From e1c538753667913799c3a4201d9055711a3dfd5b Mon Sep 17 00:00:00 2001 From: David Gauchard Date: Wed, 19 Jan 2022 15:52:09 +0100 Subject: [PATCH 01/15] apply Allman to tests/ --- tests/device/libraries/BSTest/src/BSArduino.h | 24 +- tests/device/libraries/BSTest/src/BSArgs.h | 122 +- .../device/libraries/BSTest/src/BSProtocol.h | 33 +- tests/device/libraries/BSTest/src/BSStdio.h | 9 +- tests/device/libraries/BSTest/src/BSTest.h | 48 +- tests/device/libraries/BSTest/test/test.cpp | 10 +- tests/device/test_libc/libm_string.c | 1031 +++++++++-------- tests/device/test_libc/memcpy-1.c | 230 ++-- tests/device/test_libc/memmove1.c | 256 ++-- tests/device/test_libc/strcmp-1.c | 388 ++++--- tests/device/test_libc/tstring.c | 542 ++++----- tests/host/common/Arduino.cpp | 41 +- tests/host/common/ArduinoCatch.cpp | 24 +- tests/host/common/ArduinoMain.cpp | 532 +++++---- tests/host/common/ArduinoMainLittlefs.cpp | 14 +- tests/host/common/ArduinoMainSpiffs.cpp | 14 +- tests/host/common/ArduinoMainUdp.cpp | 98 +- tests/host/common/ClientContextSocket.cpp | 314 ++--- tests/host/common/ClientContextTools.cpp | 80 +- tests/host/common/EEPROM.h | 125 +- tests/host/common/HostWiring.cpp | 92 +- tests/host/common/MockDigital.cpp | 80 +- tests/host/common/MockEEPROM.cpp | 114 +- tests/host/common/MockEsp.cpp | 227 ++-- tests/host/common/MockSPI.cpp | 64 +- tests/host/common/MockTools.cpp | 158 ++- tests/host/common/MockUART.cpp | 896 +++++++------- tests/host/common/MockWiFiServer.cpp | 82 +- tests/host/common/MockWiFiServerSocket.cpp | 202 ++-- tests/host/common/MocklwIP.cpp | 102 +- tests/host/common/MocklwIP.h | 2 +- tests/host/common/UdpContextSocket.cpp | 376 +++--- tests/host/common/WMath.cpp | 69 +- tests/host/common/c_types.h | 47 +- tests/host/common/flash_hal_mock.cpp | 15 +- tests/host/common/include/ClientContext.h | 101 +- tests/host/common/include/UdpContext.h | 13 +- tests/host/common/littlefs_mock.cpp | 48 +- tests/host/common/littlefs_mock.h | 39 +- tests/host/common/md5.c | 272 ++--- tests/host/common/mock.h | 109 +- tests/host/common/noniso.c | 72 +- tests/host/common/pins_arduino.h | 26 +- tests/host/common/queue.h | 261 ++--- tests/host/common/sdfs_mock.cpp | 20 +- tests/host/common/sdfs_mock.h | 35 +- tests/host/common/spiffs_mock.cpp | 48 +- tests/host/common/spiffs_mock.h | 33 +- tests/host/common/user_interface.cpp | 20 +- tests/host/core/test_PolledTimeout.cpp | 312 ++--- tests/host/core/test_Print.cpp | 22 +- tests/host/core/test_Updater.cpp | 22 +- tests/host/core/test_md5builder.cpp | 53 +- tests/host/core/test_pgmspace.cpp | 27 +- tests/host/core/test_string.cpp | 554 ++++----- tests/host/fs/test_fs.cpp | 35 +- tests/host/sys/pgmspace.h | 40 +- tests/restyle.sh | 1 + 58 files changed, 4555 insertions(+), 4069 deletions(-) diff --git a/tests/device/libraries/BSTest/src/BSArduino.h b/tests/device/libraries/BSTest/src/BSArduino.h index 2fd4dc66e0..b9483244a0 100644 --- a/tests/device/libraries/BSTest/src/BSArduino.h +++ b/tests/device/libraries/BSTest/src/BSArduino.h @@ -19,9 +19,11 @@ class ArduinoIOHelper char* buffer = temp; size_t len = vsnprintf(temp, sizeof(temp), format, arg); va_end(arg); - if (len > sizeof(temp) - 1) { + if (len > sizeof(temp) - 1) + { buffer = new char[len + 1]; - if (!buffer) { + if (!buffer) + { return 0; } va_start(arg, format); @@ -29,7 +31,8 @@ class ArduinoIOHelper va_end(arg); } len = m_stream.write((const uint8_t*) buffer, len); - if (buffer != temp) { + if (buffer != temp) + { delete[] buffer; } return len; @@ -40,16 +43,20 @@ class ArduinoIOHelper size_t len = 0; // Can't use Stream::readBytesUntil here because it can't tell the // difference between timing out and receiving the terminator. - while (len < dest_size - 1) { + while (len < dest_size - 1) + { int c = m_stream.read(); - if (c < 0) { + if (c < 0) + { delay(1); continue; } - if (c == '\r') { + if (c == '\r') + { continue; } - if (c == '\n') { + if (c == '\n') + { dest[len] = 0; break; } @@ -64,7 +71,8 @@ class ArduinoIOHelper typedef ArduinoIOHelper IOHelper; -inline void fatal() { +inline void fatal() +{ ESP.restart(); } diff --git a/tests/device/libraries/BSTest/src/BSArgs.h b/tests/device/libraries/BSTest/src/BSArgs.h index 060bcdf18c..ba970f60bc 100644 --- a/tests/device/libraries/BSTest/src/BSArgs.h +++ b/tests/device/libraries/BSTest/src/BSArgs.h @@ -1,8 +1,8 @@ -/* Splitting string into tokens, taking quotes and escape sequences into account. - * From https://github.com/espressif/esp-idf/blob/master/components/console/split_argv.c - * Copyright 2016-2017 Espressif Systems (Shanghai) PTE LTD - * Licensed under the Apache License 2.0. - */ +/* Splitting string into tokens, taking quotes and escape sequences into account. + From https://github.com/espressif/esp-idf/blob/master/components/console/split_argv.c + Copyright 2016-2017 Espressif Systems (Shanghai) PTE LTD + Licensed under the Apache License 2.0. +*/ #ifndef BS_ARGS_H #define BS_ARGS_H @@ -18,7 +18,8 @@ namespace protocol #define SS_FLAG_ESCAPE 0x8 -typedef enum { +typedef enum +{ /* parsing the space between arguments */ SS_SPACE = 0x0, /* parsing an argument which isn't quoted */ @@ -40,29 +41,29 @@ typedef enum { /** - * @brief Split command line into arguments in place - * - * - This function finds whitespace-separated arguments in the given input line. - * - * 'abc def 1 20 .3' -> [ 'abc', 'def', '1', '20', '.3' ] - * - * - Argument which include spaces may be surrounded with quotes. In this case - * spaces are preserved and quotes are stripped. - * - * 'abc "123 456" def' -> [ 'abc', '123 456', 'def' ] - * - * - Escape sequences may be used to produce backslash, double quote, and space: - * - * 'a\ b\\c\"' -> [ 'a b\c"' ] - * - * Pointers to at most argv_size - 1 arguments are returned in argv array. - * The pointer after the last one (i.e. argv[argc]) is set to NULL. - * - * @param line pointer to buffer to parse; it is modified in place - * @param argv array where the pointers to arguments are written - * @param argv_size number of elements in argv_array (max. number of arguments will be argv_size - 1) - * @return number of arguments found (argc) - */ + @brief Split command line into arguments in place + + - This function finds whitespace-separated arguments in the given input line. + + 'abc def 1 20 .3' -> [ 'abc', 'def', '1', '20', '.3' ] + + - Argument which include spaces may be surrounded with quotes. In this case + spaces are preserved and quotes are stripped. + + 'abc "123 456" def' -> [ 'abc', '123 456', 'def' ] + + - Escape sequences may be used to produce backslash, double quote, and space: + + 'a\ b\\c\"' -> [ 'a b\c"' ] + + Pointers to at most argv_size - 1 arguments are returned in argv array. + The pointer after the last one (i.e. argv[argc]) is set to NULL. + + @param line pointer to buffer to parse; it is modified in place + @param argv array where the pointers to arguments are written + @param argv_size number of elements in argv_array (max. number of arguments will be argv_size - 1) + @return number of arguments found (argc) +*/ inline size_t split_args(char *line, char **argv, size_t argv_size) { const int QUOTE = '"'; @@ -72,24 +73,34 @@ inline size_t split_args(char *line, char **argv, size_t argv_size) size_t argc = 0; char *next_arg_start = line; char *out_ptr = line; - for (char *in_ptr = line; argc < argv_size - 1; ++in_ptr) { - int char_in = (unsigned char) *in_ptr; - if (char_in == 0) { + for (char *in_ptr = line; argc < argv_size - 1; ++in_ptr) + { + int char_in = (unsigned char) * in_ptr; + if (char_in == 0) + { break; } int char_out = -1; - switch (state) { + switch (state) + { case SS_SPACE: - if (char_in == SPACE) { + if (char_in == SPACE) + { /* skip space */ - } else if (char_in == QUOTE) { + } + else if (char_in == QUOTE) + { next_arg_start = out_ptr; state = SS_QUOTED_ARG; - } else if (char_in == ESCAPE) { + } + else if (char_in == ESCAPE) + { next_arg_start = out_ptr; state = SS_ARG_ESCAPED; - } else { + } + else + { next_arg_start = out_ptr; state = SS_ARG; char_out = char_in; @@ -97,37 +108,51 @@ inline size_t split_args(char *line, char **argv, size_t argv_size) break; case SS_QUOTED_ARG: - if (char_in == QUOTE) { + if (char_in == QUOTE) + { END_ARG(); - } else if (char_in == ESCAPE) { + } + else if (char_in == ESCAPE) + { state = SS_QUOTED_ARG_ESCAPED; - } else { + } + else + { char_out = char_in; } break; case SS_ARG_ESCAPED: case SS_QUOTED_ARG_ESCAPED: - if (char_in == ESCAPE || char_in == QUOTE || char_in == SPACE) { + if (char_in == ESCAPE || char_in == QUOTE || char_in == SPACE) + { char_out = char_in; - } else { + } + else + { /* unrecognized escape character, skip */ } - state = (split_state_t) (state & (~SS_FLAG_ESCAPE)); + state = (split_state_t)(state & (~SS_FLAG_ESCAPE)); break; case SS_ARG: - if (char_in == SPACE) { + if (char_in == SPACE) + { END_ARG(); - } else if (char_in == ESCAPE) { + } + else if (char_in == ESCAPE) + { state = SS_ARG_ESCAPED; - } else { + } + else + { char_out = char_in; } break; } /* need to output anything? */ - if (char_out >= 0) { + if (char_out >= 0) + { *out_ptr = char_out; ++out_ptr; } @@ -135,7 +160,8 @@ inline size_t split_args(char *line, char **argv, size_t argv_size) /* make sure the final argument is terminated */ *out_ptr = 0; /* finalize the last argument */ - if (state != SS_SPACE && argc < argv_size - 1) { + if (state != SS_SPACE && argc < argv_size - 1) + { argv[argc++] = next_arg_start; } /* add a NULL at the end of argv */ diff --git a/tests/device/libraries/BSTest/src/BSProtocol.h b/tests/device/libraries/BSTest/src/BSProtocol.h index 05a874f956..afb8bfb023 100644 --- a/tests/device/libraries/BSTest/src/BSProtocol.h +++ b/tests/device/libraries/BSTest/src/BSProtocol.h @@ -24,7 +24,7 @@ void output_check_failure(IO& io, size_t line) } template -void output_test_end(IO& io, bool success, size_t checks, size_t failed_checks, size_t line=0) +void output_test_end(IO& io, bool success, size_t checks, size_t failed_checks, size_t line = 0) { io.printf(BS_LINE_PREFIX "end line=%d result=%d checks=%d failed_checks=%d\n", line, success, checks, failed_checks); } @@ -63,23 +63,27 @@ void output_getenv_result(IO& io, const char* key, const char* value) template void output_pretest_result(IO& io, bool res) { - io.printf(BS_LINE_PREFIX "pretest result=%d\n", res?1:0); + io.printf(BS_LINE_PREFIX "pretest result=%d\n", res ? 1 : 0); } template bool input_handle(IO& io, char* line_buf, size_t line_buf_size, int& test_num) { int cb_read = io.read_line(line_buf, line_buf_size); - if (cb_read == 0 || line_buf[0] == '\n') { + if (cb_read == 0 || line_buf[0] == '\n') + { return false; } char* argv[4]; - size_t argc = split_args(line_buf, argv, sizeof(argv)/sizeof(argv[0])); - if (argc == 0) { + size_t argc = split_args(line_buf, argv, sizeof(argv) / sizeof(argv[0])); + if (argc == 0) + { return false; } - if (strcmp(argv[0], "setenv") == 0) { - if (argc != 3) { + if (strcmp(argv[0], "setenv") == 0) + { + if (argc != 3) + { return false; } setenv(argv[1], argv[2], 1); @@ -87,16 +91,20 @@ bool input_handle(IO& io, char* line_buf, size_t line_buf_size, int& test_num) test_num = -1; return false; /* we didn't get the test number yet, so return false */ } - if (strcmp(argv[0], "getenv") == 0) { - if (argc != 2) { + if (strcmp(argv[0], "getenv") == 0) + { + if (argc != 2) + { return false; } const char* value = getenv(argv[1]); output_getenv_result(io, argv[1], (value != NULL) ? value : ""); return false; } - if (strcmp(argv[0], "pretest") == 0) { - if (argc != 1) { + if (strcmp(argv[0], "pretest") == 0) + { + if (argc != 1) + { return false; } bool res = ::pretest(); @@ -106,7 +114,8 @@ bool input_handle(IO& io, char* line_buf, size_t line_buf_size, int& test_num) /* not one of the commands, try to parse as test number */ char* endptr; test_num = (int) strtol(argv[0], &endptr, 10); - if (endptr != argv[0] + strlen(argv[0])) { + if (endptr != argv[0] + strlen(argv[0])) + { return false; } return true; diff --git a/tests/device/libraries/BSTest/src/BSStdio.h b/tests/device/libraries/BSTest/src/BSStdio.h index 4d1bfb56f0..f804f9750b 100644 --- a/tests/device/libraries/BSTest/src/BSStdio.h +++ b/tests/device/libraries/BSTest/src/BSStdio.h @@ -25,11 +25,13 @@ class StdIOHelper size_t read_line(char* dest, size_t dest_size) { char* res = fgets(dest, dest_size, stdin); - if (res == NULL) { + if (res == NULL) + { return 0; } size_t len = strlen(dest); - if (dest[len - 1] == '\n') { + if (dest[len - 1] == '\n') + { dest[len - 1] = 0; len--; } @@ -39,7 +41,8 @@ class StdIOHelper typedef StdIOHelper IOHelper; -inline void fatal() { +inline void fatal() +{ throw std::runtime_error("fatal error"); } diff --git a/tests/device/libraries/BSTest/src/BSTest.h b/tests/device/libraries/BSTest/src/BSTest.h index 11b4ee9f6e..6de198cb0c 100644 --- a/tests/device/libraries/BSTest/src/BSTest.h +++ b/tests/device/libraries/BSTest/src/BSTest.h @@ -28,7 +28,8 @@ class TestCase TestCase(TestCase* prev, test_case_func_t func, const char* file, size_t line, const char* name, const char* desc) : m_func(func), m_file(file), m_line(line), m_name(name), m_desc(desc) { - if (prev) { + if (prev) + { prev->m_next = this; } } @@ -60,7 +61,7 @@ class TestCase const char* desc() const { - return (m_desc)?m_desc:""; + return (m_desc) ? m_desc : ""; } protected: @@ -72,11 +73,13 @@ class TestCase const char* m_desc; }; -struct Registry { +struct Registry +{ void add(test_case_func_t func, const char* file, size_t line, const char* name, const char* desc) { TestCase* tc = new TestCase(m_last, func, file, line, name, desc); - if (!m_first) { + if (!m_first) + { m_first = tc; } m_last = tc; @@ -85,7 +88,8 @@ struct Registry { TestCase* m_last = nullptr; }; -struct Env { +struct Env +{ std::function m_check_pass; std::function m_check_fail; std::function m_fail; @@ -115,8 +119,9 @@ class Runner void run() { - do { - } while(do_menu()); + do + { + } while (do_menu()); } void check_pass() @@ -141,22 +146,27 @@ class Runner { protocol::output_menu_begin(m_io); int id = 1; - for (TestCase* tc = g_env.m_registry.m_first; tc; tc = tc->next(), ++id) { + for (TestCase* tc = g_env.m_registry.m_first; tc; tc = tc->next(), ++id) + { protocol::output_menu_item(m_io, id, tc->name(), tc->desc()); } protocol::output_menu_end(m_io); - while(true) { + while (true) + { int id; char line_buf[BS_LINE_BUF_SIZE]; - if (!protocol::input_handle(m_io, line_buf, sizeof(line_buf), id)) { + if (!protocol::input_handle(m_io, line_buf, sizeof(line_buf), id)) + { continue; } - if (id < 0) { + if (id < 0) + { return true; } TestCase* tc = g_env.m_registry.m_first; for (int i = 0; i != id - 1 && tc; ++i, tc = tc->next()); - if (!tc) { + if (!tc) + { bs::fatal(); } m_check_pass_count = 0; @@ -185,19 +195,25 @@ class AutoReg inline void check(bool condition, size_t line) { - if (!condition) { + if (!condition) + { g_env.m_check_fail(line); - } else { + } + else + { g_env.m_check_pass(); } } inline void require(bool condition, size_t line) { - if (!condition) { + if (!condition) + { g_env.m_check_fail(line); g_env.m_fail(line); - } else { + } + else + { g_env.m_check_pass(); } } diff --git a/tests/device/libraries/BSTest/test/test.cpp b/tests/device/libraries/BSTest/test/test.cpp index 863373e0de..25145344fb 100644 --- a/tests/device/libraries/BSTest/test/test.cpp +++ b/tests/device/libraries/BSTest/test/test.cpp @@ -6,11 +6,15 @@ BS_ENV_DECLARE(); int main() { - while(true) { - try{ + while (true) + { + try + { BS_RUN(); return 0; - }catch(...) { + } + catch (...) + { printf("Exception\n\n"); } } diff --git a/tests/device/test_libc/libm_string.c b/tests/device/test_libc/libm_string.c index 17f29098cd..715f7973b2 100644 --- a/tests/device/test_libc/libm_string.c +++ b/tests/device/test_libc/libm_string.c @@ -26,19 +26,19 @@ static int errors = 0; #define check(thing) checkit(thing, __LINE__) static void -_DEFUN(checkit,(ok,l), +_DEFUN(checkit, (ok, l), int ok _AND - int l ) + int l) { -// newfunc(it); -// line(l); - - if (!ok) - { - printf("string.c:%d %s\n", l, it); - ++errors; - } + // newfunc(it); + // line(l); + + if (!ok) + { + printf("string.c:%d %s\n", l, it); + ++errors; + } } @@ -47,17 +47,21 @@ _DEFUN(checkit,(ok,l), #define equal(a, b) funcqual(a,b,__LINE__); static void -_DEFUN(funcqual,(a,b,l), +_DEFUN(funcqual, (a, b, l), char *a _AND char *b _AND int l) { -// newfunc(it); - -// line(l); - if (a == NULL && b == NULL) return; - if (strcmp(a,b)) { - printf("string.c:%d (%s)\n", l, it); + // newfunc(it); + + // line(l); + if (a == NULL && b == NULL) + { + return; + } + if (strcmp(a, b)) + { + printf("string.c:%d (%s)\n", l, it); } } @@ -69,507 +73,510 @@ static char two[50]; void libm_test_string() { - /* Test strcmp first because we use it to test other things. */ - it = "strcmp"; - check(strcmp("", "") == 0); /* Trivial case. */ - check(strcmp("a", "a") == 0); /* Identity. */ - check(strcmp("abc", "abc") == 0); /* Multicharacter. */ - check(strcmp("abc", "abcd") < 0); /* Length mismatches. */ - check(strcmp("abcd", "abc") > 0); - check(strcmp("abcd", "abce") < 0); /* Honest miscompares. */ - check(strcmp("abce", "abcd") > 0); - check(strcmp("a\103", "a") > 0); /* Tricky if char signed. */ - check(strcmp("a\103", "a\003") > 0); - - /* Test strcpy next because we need it to set up other tests. */ - it = "strcpy"; - check(strcpy(one, "abcd") == one); /* Returned value. */ - equal(one, "abcd"); /* Basic test. */ - - (void) strcpy(one, "x"); - equal(one, "x"); /* Writeover. */ - equal(one+2, "cd"); /* Wrote too much? */ - - (void) strcpy(two, "hi there"); - (void) strcpy(one, two); - equal(one, "hi there"); /* Basic test encore. */ - equal(two, "hi there"); /* Stomped on source? */ - - (void) strcpy(one, ""); - equal(one, ""); /* Boundary condition. */ - - /* strcat. */ - it = "strcat"; - (void) strcpy(one, "ijk"); - check(strcat(one, "lmn") == one); /* Returned value. */ - equal(one, "ijklmn"); /* Basic test. */ - - (void) strcpy(one, "x"); - (void) strcat(one, "yz"); - equal(one, "xyz"); /* Writeover. */ - equal(one+4, "mn"); /* Wrote too much? */ - - (void) strcpy(one, "gh"); - (void) strcpy(two, "ef"); - (void) strcat(one, two); - equal(one, "ghef"); /* Basic test encore. */ - equal(two, "ef"); /* Stomped on source? */ - - (void) strcpy(one, ""); - (void) strcat(one, ""); - equal(one, ""); /* Boundary conditions. */ - (void) strcpy(one, "ab"); - (void) strcat(one, ""); - equal(one, "ab"); - (void) strcpy(one, ""); - (void) strcat(one, "cd"); - equal(one, "cd"); - - /* strncat - first test it as strcat, with big counts, - then test the count mechanism. */ - it = "strncat"; - (void) strcpy(one, "ijk"); - check(strncat(one, "lmn", 99) == one); /* Returned value. */ - equal(one, "ijklmn"); /* Basic test. */ - - (void) strcpy(one, "x"); - (void) strncat(one, "yz", 99); - equal(one, "xyz"); /* Writeover. */ - equal(one+4, "mn"); /* Wrote too much? */ - - (void) strcpy(one, "gh"); - (void) strcpy(two, "ef"); - (void) strncat(one, two, 99); - equal(one, "ghef"); /* Basic test encore. */ - equal(two, "ef"); /* Stomped on source? */ - - (void) strcpy(one, ""); - (void) strncat(one, "", 99); - equal(one, ""); /* Boundary conditions. */ - (void) strcpy(one, "ab"); - (void) strncat(one, "", 99); - equal(one, "ab"); - (void) strcpy(one, ""); - (void) strncat(one, "cd", 99); - equal(one, "cd"); - - (void) strcpy(one, "ab"); - (void) strncat(one, "cdef", 2); - equal(one, "abcd"); /* Count-limited. */ - - (void) strncat(one, "gh", 0); - equal(one, "abcd"); /* Zero count. */ - - (void) strncat(one, "gh", 2); - equal(one, "abcdgh"); /* Count _AND length equal. */ - it = "strncmp"; - /* strncmp - first test as strcmp with big counts";*/ - check(strncmp("", "", 99) == 0); /* Trivial case. */ - check(strncmp("a", "a", 99) == 0); /* Identity. */ - check(strncmp("abc", "abc", 99) == 0); /* Multicharacter. */ - check(strncmp("abc", "abcd", 99) < 0); /* Length unequal. */ - check(strncmp("abcd", "abc",99) > 0); - check(strncmp("abcd", "abce", 99) < 0); /* Honestly unequal. */ - check(strncmp("abce", "abcd",99)>0); - check(strncmp("abce", "abcd", 3) == 0); /* Count limited. */ - check(strncmp("abce", "abc", 3) == 0); /* Count == length. */ - check(strncmp("abcd", "abce", 4) < 0); /* Nudging limit. */ - check(strncmp("abc", "def", 0) == 0); /* Zero count. */ - - /* strncpy - testing is a bit different because of odd semantics. */ - it = "strncpy"; - check(strncpy(one, "abc", 4) == one); /* Returned value. */ - equal(one, "abc"); /* Did the copy go right? */ - - (void) strcpy(one, "abcdefgh"); - (void) strncpy(one, "xyz", 2); - equal(one, "xycdefgh"); /* Copy cut by count. */ - - (void) strcpy(one, "abcdefgh"); - (void) strncpy(one, "xyz", 3); /* Copy cut just before NUL. */ - equal(one, "xyzdefgh"); - - (void) strcpy(one, "abcdefgh"); - (void) strncpy(one, "xyz", 4); /* Copy just includes NUL. */ - equal(one, "xyz"); - equal(one+4, "efgh"); /* Wrote too much? */ - - (void) strcpy(one, "abcdefgh"); - (void) strncpy(one, "xyz", 5); /* Copy includes padding. */ - equal(one, "xyz"); - equal(one+4, ""); - equal(one+5, "fgh"); - - (void) strcpy(one, "abc"); - (void) strncpy(one, "xyz", 0); /* Zero-length copy. */ - equal(one, "abc"); - - (void) strncpy(one, "", 2); /* Zero-length source. */ - equal(one, ""); - equal(one+1, ""); - equal(one+2, "c"); - - (void) strcpy(one, "hi there"); - (void) strncpy(two, one, 9); - equal(two, "hi there"); /* Just paranoia. */ - equal(one, "hi there"); /* Stomped on source? */ - - /* strlen. */ - it = "strlen"; - check(strlen("") == 0); /* Empty. */ - check(strlen("a") == 1); /* Single char. */ - check(strlen("abcd") == 4); /* Multiple chars. */ - - /* strchr. */ - it = "strchr"; - check(strchr("abcd", 'z') == NULL); /* Not found. */ - (void) strcpy(one, "abcd"); - check(strchr(one, 'c') == one+2); /* Basic test. */ - check(strchr(one, 'd') == one+3); /* End of string. */ - check(strchr(one, 'a') == one); /* Beginning. */ - check(strchr(one, '\0') == one+4); /* Finding NUL. */ - (void) strcpy(one, "ababa"); - check(strchr(one, 'b') == one+1); /* Finding first. */ - (void) strcpy(one, ""); - check(strchr(one, 'b') == NULL); /* Empty string. */ - check(strchr(one, '\0') == one); /* NUL in empty string. */ - - /* index - just like strchr. */ - it = "index"; - check(index("abcd", 'z') == NULL); /* Not found. */ - (void) strcpy(one, "abcd"); - check(index(one, 'c') == one+2); /* Basic test. */ - check(index(one, 'd') == one+3); /* End of string. */ - check(index(one, 'a') == one); /* Beginning. */ - check(index(one, '\0') == one+4); /* Finding NUL. */ - (void) strcpy(one, "ababa"); - check(index(one, 'b') == one+1); /* Finding first. */ - (void) strcpy(one, ""); - check(index(one, 'b') == NULL); /* Empty string. */ - check(index(one, '\0') == one); /* NUL in empty string. */ - - /* strrchr. */ - it = "strrchr"; - check(strrchr("abcd", 'z') == NULL); /* Not found. */ - (void) strcpy(one, "abcd"); - check(strrchr(one, 'c') == one+2); /* Basic test. */ - check(strrchr(one, 'd') == one+3); /* End of string. */ - check(strrchr(one, 'a') == one); /* Beginning. */ - check(strrchr(one, '\0') == one+4); /* Finding NUL. */ - (void) strcpy(one, "ababa"); - check(strrchr(one, 'b') == one+3); /* Finding last. */ - (void) strcpy(one, ""); - check(strrchr(one, 'b') == NULL); /* Empty string. */ - check(strrchr(one, '\0') == one); /* NUL in empty string. */ - - /* rindex - just like strrchr. */ - it = "rindex"; - check(rindex("abcd", 'z') == NULL); /* Not found. */ - (void) strcpy(one, "abcd"); - check(rindex(one, 'c') == one+2); /* Basic test. */ - check(rindex(one, 'd') == one+3); /* End of string. */ - check(rindex(one, 'a') == one); /* Beginning. */ - check(rindex(one, '\0') == one+4); /* Finding NUL. */ - (void) strcpy(one, "ababa"); - check(rindex(one, 'b') == one+3); /* Finding last. */ - (void) strcpy(one, ""); - check(rindex(one, 'b') == NULL); /* Empty string. */ - check(rindex(one, '\0') == one); /* NUL in empty string. */ - - /* strpbrk - somewhat like strchr. */ - it = "strpbrk"; - check(strpbrk("abcd", "z") == NULL); /* Not found. */ - (void) strcpy(one, "abcd"); - check(strpbrk(one, "c") == one+2); /* Basic test. */ - check(strpbrk(one, "d") == one+3); /* End of string. */ - check(strpbrk(one, "a") == one); /* Beginning. */ - check(strpbrk(one, "") == NULL); /* Empty search list. */ - check(strpbrk(one, "cb") == one+1); /* Multiple search. */ - (void) strcpy(one, "abcabdea"); - check(strpbrk(one, "b") == one+1); /* Finding first. */ - check(strpbrk(one, "cb") == one+1); /* With multiple search. */ - check(strpbrk(one, "db") == one+1); /* Another variant. */ - (void) strcpy(one, ""); - check(strpbrk(one, "bc") == NULL); /* Empty string. */ - check(strpbrk(one, "") == NULL); /* Both strings empty. */ - - /* strstr - somewhat like strchr. */ - it = "strstr"; - check(strstr("z", "abcd") == NULL); /* Not found. */ - check(strstr("abx", "abcd") == NULL); /* Dead end. */ - (void) strcpy(one, "abcd"); - check(strstr(one,"c") == one+2); /* Basic test. */ - check(strstr(one, "bc") == one+1); /* Multichar. */ - check(strstr(one,"d") == one+3); /* End of string. */ - check(strstr(one,"cd") == one+2); /* Tail of string. */ - check(strstr(one,"abc") == one); /* Beginning. */ - check(strstr(one,"abcd") == one); /* Exact match. */ - check(strstr(one,"de") == NULL); /* Past end. */ - check(strstr(one,"") == one); /* Finding empty. */ - (void) strcpy(one, "ababa"); - check(strstr(one,"ba") == one+1); /* Finding first. */ - (void) strcpy(one, ""); - check(strstr(one, "b") == NULL); /* Empty string. */ - check(strstr(one,"") == one); /* Empty in empty string. */ - (void) strcpy(one, "bcbca"); - check(strstr(one,"bca") == one+2); /* False start. */ - (void) strcpy(one, "bbbcabbca"); - check(strstr(one,"bbca") == one+1); /* With overlap. */ - - /* strspn. */ - it = "strspn"; - check(strspn("abcba", "abc") == 5); /* Whole string. */ - check(strspn("abcba", "ab") == 2); /* Partial. */ - check(strspn("abc", "qx") == 0); /* None. */ - check(strspn("", "ab") == 0); /* Null string. */ - check(strspn("abc", "") == 0); /* Null search list. */ - - /* strcspn. */ - it = "strcspn"; - check(strcspn("abcba", "qx") == 5); /* Whole string. */ - check(strcspn("abcba", "cx") == 2); /* Partial. */ - check(strcspn("abc", "abc") == 0); /* None. */ - check(strcspn("", "ab") == 0); /* Null string. */ - check(strcspn("abc", "") == 3); /* Null search list. */ - - /* strtok - the hard one. */ - it = "strtok"; - (void) strcpy(one, "first, second, third"); - equal(strtok(one, ", "), "first"); /* Basic test. */ - equal(one, "first"); - equal(strtok((char *)NULL, ", "), "second"); - equal(strtok((char *)NULL, ", "), "third"); - check(strtok((char *)NULL, ", ") == NULL); - (void) strcpy(one, ", first, "); - equal(strtok(one, ", "), "first"); /* Extra delims, 1 tok. */ - check(strtok((char *)NULL, ", ") == NULL); - (void) strcpy(one, "1a, 1b; 2a, 2b"); - equal(strtok(one, ", "), "1a"); /* Changing delim lists. */ - equal(strtok((char *)NULL, "; "), "1b"); - equal(strtok((char *)NULL, ", "), "2a"); - (void) strcpy(two, "x-y"); - equal(strtok(two, "-"), "x"); /* New string before done. */ - equal(strtok((char *)NULL, "-"), "y"); - check(strtok((char *)NULL, "-") == NULL); - (void) strcpy(one, "a,b, c,, ,d"); - equal(strtok(one, ", "), "a"); /* Different separators. */ - equal(strtok((char *)NULL, ", "), "b"); - equal(strtok((char *)NULL, " ,"), "c"); /* Permute list too. */ - equal(strtok((char *)NULL, " ,"), "d"); - check(strtok((char *)NULL, ", ") == NULL); - check(strtok((char *)NULL, ", ") == NULL); /* Persistence. */ - (void) strcpy(one, ", "); - check(strtok(one, ", ") == NULL); /* No tokens. */ - (void) strcpy(one, ""); - check(strtok(one, ", ") == NULL); /* Empty string. */ - (void) strcpy(one, "abc"); - equal(strtok(one, ", "), "abc"); /* No delimiters. */ - check(strtok((char *)NULL, ", ") == NULL); - (void) strcpy(one, "abc"); - equal(strtok(one, ""), "abc"); /* Empty delimiter list. */ - check(strtok((char *)NULL, "") == NULL); - (void) strcpy(one, "abcdefgh"); - (void) strcpy(one, "a,b,c"); - equal(strtok(one, ","), "a"); /* Basics again... */ - equal(strtok((char *)NULL, ","), "b"); - equal(strtok((char *)NULL, ","), "c"); - check(strtok((char *)NULL, ",") == NULL); - equal(one+6, "gh"); /* Stomped past end? */ - equal(one, "a"); /* Stomped old tokens? */ - equal(one+2, "b"); - equal(one+4, "c"); - - /* memcmp. */ - it = "memcmp"; - check(memcmp("a", "a", 1) == 0); /* Identity. */ - check(memcmp("abc", "abc", 3) == 0); /* Multicharacter. */ - check(memcmp("abcd", "abce", 4) < 0); /* Honestly unequal. */ - check(memcmp("abce", "abcd",4)); - check(memcmp("alph", "beta", 4) < 0); - check(memcmp("abce", "abcd", 3) == 0); /* Count limited. */ - check(memcmp("abc", "def", 0) == 0); /* Zero count. */ - - /* memcmp should test strings as unsigned */ - one[0] = 0xfe; - two[0] = 0x03; - check(memcmp(one, two,1) > 0); - - - /* memchr. */ - it = "memchr"; - check(memchr("abcd", 'z', 4) == NULL); /* Not found. */ - (void) strcpy(one, "abcd"); - check(memchr(one, 'c', 4) == one+2); /* Basic test. */ - check(memchr(one, 'd', 4) == one+3); /* End of string. */ - check(memchr(one, 'a', 4) == one); /* Beginning. */ - check(memchr(one, '\0', 5) == one+4); /* Finding NUL. */ - (void) strcpy(one, "ababa"); - check(memchr(one, 'b', 5) == one+1); /* Finding first. */ - check(memchr(one, 'b', 0) == NULL); /* Zero count. */ - check(memchr(one, 'a', 1) == one); /* Singleton case. */ - (void) strcpy(one, "a\203b"); - check(memchr(one, 0203, 3) == one+1); /* Unsignedness. */ - - /* memcpy - need not work for overlap. */ - it = "memcpy"; - check(memcpy(one, "abc", 4) == one); /* Returned value. */ - equal(one, "abc"); /* Did the copy go right? */ - - (void) strcpy(one, "abcdefgh"); - (void) memcpy(one+1, "xyz", 2); - equal(one, "axydefgh"); /* Basic test. */ - - (void) strcpy(one, "abc"); - (void) memcpy(one, "xyz", 0); - equal(one, "abc"); /* Zero-length copy. */ - - (void) strcpy(one, "hi there"); - (void) strcpy(two, "foo"); - (void) memcpy(two, one, 9); - equal(two, "hi there"); /* Just paranoia. */ - equal(one, "hi there"); /* Stomped on source? */ + /* Test strcmp first because we use it to test other things. */ + it = "strcmp"; + check(strcmp("", "") == 0); /* Trivial case. */ + check(strcmp("a", "a") == 0); /* Identity. */ + check(strcmp("abc", "abc") == 0); /* Multicharacter. */ + check(strcmp("abc", "abcd") < 0); /* Length mismatches. */ + check(strcmp("abcd", "abc") > 0); + check(strcmp("abcd", "abce") < 0); /* Honest miscompares. */ + check(strcmp("abce", "abcd") > 0); + check(strcmp("a\103", "a") > 0); /* Tricky if char signed. */ + check(strcmp("a\103", "a\003") > 0); + + /* Test strcpy next because we need it to set up other tests. */ + it = "strcpy"; + check(strcpy(one, "abcd") == one); /* Returned value. */ + equal(one, "abcd"); /* Basic test. */ + + (void) strcpy(one, "x"); + equal(one, "x"); /* Writeover. */ + equal(one + 2, "cd"); /* Wrote too much? */ + + (void) strcpy(two, "hi there"); + (void) strcpy(one, two); + equal(one, "hi there"); /* Basic test encore. */ + equal(two, "hi there"); /* Stomped on source? */ + + (void) strcpy(one, ""); + equal(one, ""); /* Boundary condition. */ + + /* strcat. */ + it = "strcat"; + (void) strcpy(one, "ijk"); + check(strcat(one, "lmn") == one); /* Returned value. */ + equal(one, "ijklmn"); /* Basic test. */ + + (void) strcpy(one, "x"); + (void) strcat(one, "yz"); + equal(one, "xyz"); /* Writeover. */ + equal(one + 4, "mn"); /* Wrote too much? */ + + (void) strcpy(one, "gh"); + (void) strcpy(two, "ef"); + (void) strcat(one, two); + equal(one, "ghef"); /* Basic test encore. */ + equal(two, "ef"); /* Stomped on source? */ + + (void) strcpy(one, ""); + (void) strcat(one, ""); + equal(one, ""); /* Boundary conditions. */ + (void) strcpy(one, "ab"); + (void) strcat(one, ""); + equal(one, "ab"); + (void) strcpy(one, ""); + (void) strcat(one, "cd"); + equal(one, "cd"); + + /* strncat - first test it as strcat, with big counts, + then test the count mechanism. */ + it = "strncat"; + (void) strcpy(one, "ijk"); + check(strncat(one, "lmn", 99) == one); /* Returned value. */ + equal(one, "ijklmn"); /* Basic test. */ + + (void) strcpy(one, "x"); + (void) strncat(one, "yz", 99); + equal(one, "xyz"); /* Writeover. */ + equal(one + 4, "mn"); /* Wrote too much? */ + + (void) strcpy(one, "gh"); + (void) strcpy(two, "ef"); + (void) strncat(one, two, 99); + equal(one, "ghef"); /* Basic test encore. */ + equal(two, "ef"); /* Stomped on source? */ + + (void) strcpy(one, ""); + (void) strncat(one, "", 99); + equal(one, ""); /* Boundary conditions. */ + (void) strcpy(one, "ab"); + (void) strncat(one, "", 99); + equal(one, "ab"); + (void) strcpy(one, ""); + (void) strncat(one, "cd", 99); + equal(one, "cd"); + + (void) strcpy(one, "ab"); + (void) strncat(one, "cdef", 2); + equal(one, "abcd"); /* Count-limited. */ + + (void) strncat(one, "gh", 0); + equal(one, "abcd"); /* Zero count. */ + + (void) strncat(one, "gh", 2); + equal(one, "abcdgh"); /* Count _AND length equal. */ + it = "strncmp"; + /* strncmp - first test as strcmp with big counts";*/ + check(strncmp("", "", 99) == 0); /* Trivial case. */ + check(strncmp("a", "a", 99) == 0); /* Identity. */ + check(strncmp("abc", "abc", 99) == 0); /* Multicharacter. */ + check(strncmp("abc", "abcd", 99) < 0); /* Length unequal. */ + check(strncmp("abcd", "abc", 99) > 0); + check(strncmp("abcd", "abce", 99) < 0); /* Honestly unequal. */ + check(strncmp("abce", "abcd", 99) > 0); + check(strncmp("abce", "abcd", 3) == 0); /* Count limited. */ + check(strncmp("abce", "abc", 3) == 0); /* Count == length. */ + check(strncmp("abcd", "abce", 4) < 0); /* Nudging limit. */ + check(strncmp("abc", "def", 0) == 0); /* Zero count. */ + + /* strncpy - testing is a bit different because of odd semantics. */ + it = "strncpy"; + check(strncpy(one, "abc", 4) == one); /* Returned value. */ + equal(one, "abc"); /* Did the copy go right? */ + + (void) strcpy(one, "abcdefgh"); + (void) strncpy(one, "xyz", 2); + equal(one, "xycdefgh"); /* Copy cut by count. */ + + (void) strcpy(one, "abcdefgh"); + (void) strncpy(one, "xyz", 3); /* Copy cut just before NUL. */ + equal(one, "xyzdefgh"); + + (void) strcpy(one, "abcdefgh"); + (void) strncpy(one, "xyz", 4); /* Copy just includes NUL. */ + equal(one, "xyz"); + equal(one + 4, "efgh"); /* Wrote too much? */ + + (void) strcpy(one, "abcdefgh"); + (void) strncpy(one, "xyz", 5); /* Copy includes padding. */ + equal(one, "xyz"); + equal(one + 4, ""); + equal(one + 5, "fgh"); + + (void) strcpy(one, "abc"); + (void) strncpy(one, "xyz", 0); /* Zero-length copy. */ + equal(one, "abc"); + + (void) strncpy(one, "", 2); /* Zero-length source. */ + equal(one, ""); + equal(one + 1, ""); + equal(one + 2, "c"); + + (void) strcpy(one, "hi there"); + (void) strncpy(two, one, 9); + equal(two, "hi there"); /* Just paranoia. */ + equal(one, "hi there"); /* Stomped on source? */ + + /* strlen. */ + it = "strlen"; + check(strlen("") == 0); /* Empty. */ + check(strlen("a") == 1); /* Single char. */ + check(strlen("abcd") == 4); /* Multiple chars. */ + + /* strchr. */ + it = "strchr"; + check(strchr("abcd", 'z') == NULL); /* Not found. */ + (void) strcpy(one, "abcd"); + check(strchr(one, 'c') == one + 2); /* Basic test. */ + check(strchr(one, 'd') == one + 3); /* End of string. */ + check(strchr(one, 'a') == one); /* Beginning. */ + check(strchr(one, '\0') == one + 4); /* Finding NUL. */ + (void) strcpy(one, "ababa"); + check(strchr(one, 'b') == one + 1); /* Finding first. */ + (void) strcpy(one, ""); + check(strchr(one, 'b') == NULL); /* Empty string. */ + check(strchr(one, '\0') == one); /* NUL in empty string. */ + + /* index - just like strchr. */ + it = "index"; + check(index("abcd", 'z') == NULL); /* Not found. */ + (void) strcpy(one, "abcd"); + check(index(one, 'c') == one + 2); /* Basic test. */ + check(index(one, 'd') == one + 3); /* End of string. */ + check(index(one, 'a') == one); /* Beginning. */ + check(index(one, '\0') == one + 4); /* Finding NUL. */ + (void) strcpy(one, "ababa"); + check(index(one, 'b') == one + 1); /* Finding first. */ + (void) strcpy(one, ""); + check(index(one, 'b') == NULL); /* Empty string. */ + check(index(one, '\0') == one); /* NUL in empty string. */ + + /* strrchr. */ + it = "strrchr"; + check(strrchr("abcd", 'z') == NULL); /* Not found. */ + (void) strcpy(one, "abcd"); + check(strrchr(one, 'c') == one + 2); /* Basic test. */ + check(strrchr(one, 'd') == one + 3); /* End of string. */ + check(strrchr(one, 'a') == one); /* Beginning. */ + check(strrchr(one, '\0') == one + 4); /* Finding NUL. */ + (void) strcpy(one, "ababa"); + check(strrchr(one, 'b') == one + 3); /* Finding last. */ + (void) strcpy(one, ""); + check(strrchr(one, 'b') == NULL); /* Empty string. */ + check(strrchr(one, '\0') == one); /* NUL in empty string. */ + + /* rindex - just like strrchr. */ + it = "rindex"; + check(rindex("abcd", 'z') == NULL); /* Not found. */ + (void) strcpy(one, "abcd"); + check(rindex(one, 'c') == one + 2); /* Basic test. */ + check(rindex(one, 'd') == one + 3); /* End of string. */ + check(rindex(one, 'a') == one); /* Beginning. */ + check(rindex(one, '\0') == one + 4); /* Finding NUL. */ + (void) strcpy(one, "ababa"); + check(rindex(one, 'b') == one + 3); /* Finding last. */ + (void) strcpy(one, ""); + check(rindex(one, 'b') == NULL); /* Empty string. */ + check(rindex(one, '\0') == one); /* NUL in empty string. */ + + /* strpbrk - somewhat like strchr. */ + it = "strpbrk"; + check(strpbrk("abcd", "z") == NULL); /* Not found. */ + (void) strcpy(one, "abcd"); + check(strpbrk(one, "c") == one + 2); /* Basic test. */ + check(strpbrk(one, "d") == one + 3); /* End of string. */ + check(strpbrk(one, "a") == one); /* Beginning. */ + check(strpbrk(one, "") == NULL); /* Empty search list. */ + check(strpbrk(one, "cb") == one + 1); /* Multiple search. */ + (void) strcpy(one, "abcabdea"); + check(strpbrk(one, "b") == one + 1); /* Finding first. */ + check(strpbrk(one, "cb") == one + 1); /* With multiple search. */ + check(strpbrk(one, "db") == one + 1); /* Another variant. */ + (void) strcpy(one, ""); + check(strpbrk(one, "bc") == NULL); /* Empty string. */ + check(strpbrk(one, "") == NULL); /* Both strings empty. */ + + /* strstr - somewhat like strchr. */ + it = "strstr"; + check(strstr("z", "abcd") == NULL); /* Not found. */ + check(strstr("abx", "abcd") == NULL); /* Dead end. */ + (void) strcpy(one, "abcd"); + check(strstr(one, "c") == one + 2); /* Basic test. */ + check(strstr(one, "bc") == one + 1); /* Multichar. */ + check(strstr(one, "d") == one + 3); /* End of string. */ + check(strstr(one, "cd") == one + 2); /* Tail of string. */ + check(strstr(one, "abc") == one); /* Beginning. */ + check(strstr(one, "abcd") == one); /* Exact match. */ + check(strstr(one, "de") == NULL); /* Past end. */ + check(strstr(one, "") == one); /* Finding empty. */ + (void) strcpy(one, "ababa"); + check(strstr(one, "ba") == one + 1); /* Finding first. */ + (void) strcpy(one, ""); + check(strstr(one, "b") == NULL); /* Empty string. */ + check(strstr(one, "") == one); /* Empty in empty string. */ + (void) strcpy(one, "bcbca"); + check(strstr(one, "bca") == one + 2); /* False start. */ + (void) strcpy(one, "bbbcabbca"); + check(strstr(one, "bbca") == one + 1); /* With overlap. */ + + /* strspn. */ + it = "strspn"; + check(strspn("abcba", "abc") == 5); /* Whole string. */ + check(strspn("abcba", "ab") == 2); /* Partial. */ + check(strspn("abc", "qx") == 0); /* None. */ + check(strspn("", "ab") == 0); /* Null string. */ + check(strspn("abc", "") == 0); /* Null search list. */ + + /* strcspn. */ + it = "strcspn"; + check(strcspn("abcba", "qx") == 5); /* Whole string. */ + check(strcspn("abcba", "cx") == 2); /* Partial. */ + check(strcspn("abc", "abc") == 0); /* None. */ + check(strcspn("", "ab") == 0); /* Null string. */ + check(strcspn("abc", "") == 3); /* Null search list. */ + + /* strtok - the hard one. */ + it = "strtok"; + (void) strcpy(one, "first, second, third"); + equal(strtok(one, ", "), "first"); /* Basic test. */ + equal(one, "first"); + equal(strtok((char *)NULL, ", "), "second"); + equal(strtok((char *)NULL, ", "), "third"); + check(strtok((char *)NULL, ", ") == NULL); + (void) strcpy(one, ", first, "); + equal(strtok(one, ", "), "first"); /* Extra delims, 1 tok. */ + check(strtok((char *)NULL, ", ") == NULL); + (void) strcpy(one, "1a, 1b; 2a, 2b"); + equal(strtok(one, ", "), "1a"); /* Changing delim lists. */ + equal(strtok((char *)NULL, "; "), "1b"); + equal(strtok((char *)NULL, ", "), "2a"); + (void) strcpy(two, "x-y"); + equal(strtok(two, "-"), "x"); /* New string before done. */ + equal(strtok((char *)NULL, "-"), "y"); + check(strtok((char *)NULL, "-") == NULL); + (void) strcpy(one, "a,b, c,, ,d"); + equal(strtok(one, ", "), "a"); /* Different separators. */ + equal(strtok((char *)NULL, ", "), "b"); + equal(strtok((char *)NULL, " ,"), "c"); /* Permute list too. */ + equal(strtok((char *)NULL, " ,"), "d"); + check(strtok((char *)NULL, ", ") == NULL); + check(strtok((char *)NULL, ", ") == NULL); /* Persistence. */ + (void) strcpy(one, ", "); + check(strtok(one, ", ") == NULL); /* No tokens. */ + (void) strcpy(one, ""); + check(strtok(one, ", ") == NULL); /* Empty string. */ + (void) strcpy(one, "abc"); + equal(strtok(one, ", "), "abc"); /* No delimiters. */ + check(strtok((char *)NULL, ", ") == NULL); + (void) strcpy(one, "abc"); + equal(strtok(one, ""), "abc"); /* Empty delimiter list. */ + check(strtok((char *)NULL, "") == NULL); + (void) strcpy(one, "abcdefgh"); + (void) strcpy(one, "a,b,c"); + equal(strtok(one, ","), "a"); /* Basics again... */ + equal(strtok((char *)NULL, ","), "b"); + equal(strtok((char *)NULL, ","), "c"); + check(strtok((char *)NULL, ",") == NULL); + equal(one + 6, "gh"); /* Stomped past end? */ + equal(one, "a"); /* Stomped old tokens? */ + equal(one + 2, "b"); + equal(one + 4, "c"); + + /* memcmp. */ + it = "memcmp"; + check(memcmp("a", "a", 1) == 0); /* Identity. */ + check(memcmp("abc", "abc", 3) == 0); /* Multicharacter. */ + check(memcmp("abcd", "abce", 4) < 0); /* Honestly unequal. */ + check(memcmp("abce", "abcd", 4)); + check(memcmp("alph", "beta", 4) < 0); + check(memcmp("abce", "abcd", 3) == 0); /* Count limited. */ + check(memcmp("abc", "def", 0) == 0); /* Zero count. */ + + /* memcmp should test strings as unsigned */ + one[0] = 0xfe; + two[0] = 0x03; + check(memcmp(one, two, 1) > 0); + + + /* memchr. */ + it = "memchr"; + check(memchr("abcd", 'z', 4) == NULL); /* Not found. */ + (void) strcpy(one, "abcd"); + check(memchr(one, 'c', 4) == one + 2); /* Basic test. */ + check(memchr(one, 'd', 4) == one + 3); /* End of string. */ + check(memchr(one, 'a', 4) == one); /* Beginning. */ + check(memchr(one, '\0', 5) == one + 4); /* Finding NUL. */ + (void) strcpy(one, "ababa"); + check(memchr(one, 'b', 5) == one + 1); /* Finding first. */ + check(memchr(one, 'b', 0) == NULL); /* Zero count. */ + check(memchr(one, 'a', 1) == one); /* Singleton case. */ + (void) strcpy(one, "a\203b"); + check(memchr(one, 0203, 3) == one + 1); /* Unsignedness. */ + + /* memcpy - need not work for overlap. */ + it = "memcpy"; + check(memcpy(one, "abc", 4) == one); /* Returned value. */ + equal(one, "abc"); /* Did the copy go right? */ + + (void) strcpy(one, "abcdefgh"); + (void) memcpy(one + 1, "xyz", 2); + equal(one, "axydefgh"); /* Basic test. */ + + (void) strcpy(one, "abc"); + (void) memcpy(one, "xyz", 0); + equal(one, "abc"); /* Zero-length copy. */ + + (void) strcpy(one, "hi there"); + (void) strcpy(two, "foo"); + (void) memcpy(two, one, 9); + equal(two, "hi there"); /* Just paranoia. */ + equal(one, "hi there"); /* Stomped on source? */ #if 0 - /* memmove - must work on overlap. */ - it = "memmove"; - check(memmove(one, "abc", 4) == one); /* Returned value. */ - equal(one, "abc"); /* Did the copy go right? */ - - (void) strcpy(one, "abcdefgh"); - (void) memmove(one+1, "xyz", 2); - equal(one, "axydefgh"); /* Basic test. */ - - (void) strcpy(one, "abc"); - (void) memmove(one, "xyz", 0); - equal(one, "abc"); /* Zero-length copy. */ - - (void) strcpy(one, "hi there"); - (void) strcpy(two, "foo"); - (void) memmove(two, one, 9); - equal(two, "hi there"); /* Just paranoia. */ - equal(one, "hi there"); /* Stomped on source? */ - - (void) strcpy(one, "abcdefgh"); - (void) memmove(one+1, one, 9); - equal(one, "aabcdefgh"); /* Overlap, right-to-left. */ - - (void) strcpy(one, "abcdefgh"); - (void) memmove(one+1, one+2, 7); - equal(one, "acdefgh"); /* Overlap, left-to-right. */ - - (void) strcpy(one, "abcdefgh"); - (void) memmove(one, one, 9); - equal(one, "abcdefgh"); /* 100% overlap. */ + /* memmove - must work on overlap. */ + it = "memmove"; + check(memmove(one, "abc", 4) == one); /* Returned value. */ + equal(one, "abc"); /* Did the copy go right? */ + + (void) strcpy(one, "abcdefgh"); + (void) memmove(one + 1, "xyz", 2); + equal(one, "axydefgh"); /* Basic test. */ + + (void) strcpy(one, "abc"); + (void) memmove(one, "xyz", 0); + equal(one, "abc"); /* Zero-length copy. */ + + (void) strcpy(one, "hi there"); + (void) strcpy(two, "foo"); + (void) memmove(two, one, 9); + equal(two, "hi there"); /* Just paranoia. */ + equal(one, "hi there"); /* Stomped on source? */ + + (void) strcpy(one, "abcdefgh"); + (void) memmove(one + 1, one, 9); + equal(one, "aabcdefgh"); /* Overlap, right-to-left. */ + + (void) strcpy(one, "abcdefgh"); + (void) memmove(one + 1, one + 2, 7); + equal(one, "acdefgh"); /* Overlap, left-to-right. */ + + (void) strcpy(one, "abcdefgh"); + (void) memmove(one, one, 9); + equal(one, "abcdefgh"); /* 100% overlap. */ #endif #if 0 - /* memccpy - first test like memcpy, then the search part - The SVID, the only place where memccpy is mentioned, says - overlap might fail, so we don't try it. Besides, it's hard - to see the rationale for a non-left-to-right memccpy. */ - it = "memccpy"; - check(memccpy(one, "abc", 'q', 4) == NULL); /* Returned value. */ - equal(one, "abc"); /* Did the copy go right? */ - - (void) strcpy(one, "abcdefgh"); - (void) memccpy(one+1, "xyz", 'q', 2); - equal(one, "axydefgh"); /* Basic test. */ - - (void) strcpy(one, "abc"); - (void) memccpy(one, "xyz", 'q', 0); - equal(one, "abc"); /* Zero-length copy. */ - - (void) strcpy(one, "hi there"); - (void) strcpy(two, "foo"); - (void) memccpy(two, one, 'q', 9); - equal(two, "hi there"); /* Just paranoia. */ - equal(one, "hi there"); /* Stomped on source? */ - - (void) strcpy(one, "abcdefgh"); - (void) strcpy(two, "horsefeathers"); - check(memccpy(two, one, 'f', 9) == two+6); /* Returned value. */ - equal(one, "abcdefgh"); /* Source intact? */ - equal(two, "abcdefeathers"); /* Copy correct? */ - - (void) strcpy(one, "abcd"); - (void) strcpy(two, "bumblebee"); - check(memccpy(two, one, 'a', 4) == two+1); /* First char. */ - equal(two, "aumblebee"); - check(memccpy(two, one, 'd', 4) == two+4); /* Last char. */ - equal(two, "abcdlebee"); - (void) strcpy(one, "xyz"); - check(memccpy(two, one, 'x', 1) == two+1); /* Singleton. */ - equal(two, "xbcdlebee"); + /* memccpy - first test like memcpy, then the search part + The SVID, the only place where memccpy is mentioned, says + overlap might fail, so we don't try it. Besides, it's hard + to see the rationale for a non-left-to-right memccpy. */ + it = "memccpy"; + check(memccpy(one, "abc", 'q', 4) == NULL); /* Returned value. */ + equal(one, "abc"); /* Did the copy go right? */ + + (void) strcpy(one, "abcdefgh"); + (void) memccpy(one + 1, "xyz", 'q', 2); + equal(one, "axydefgh"); /* Basic test. */ + + (void) strcpy(one, "abc"); + (void) memccpy(one, "xyz", 'q', 0); + equal(one, "abc"); /* Zero-length copy. */ + + (void) strcpy(one, "hi there"); + (void) strcpy(two, "foo"); + (void) memccpy(two, one, 'q', 9); + equal(two, "hi there"); /* Just paranoia. */ + equal(one, "hi there"); /* Stomped on source? */ + + (void) strcpy(one, "abcdefgh"); + (void) strcpy(two, "horsefeathers"); + check(memccpy(two, one, 'f', 9) == two + 6); /* Returned value. */ + equal(one, "abcdefgh"); /* Source intact? */ + equal(two, "abcdefeathers"); /* Copy correct? */ + + (void) strcpy(one, "abcd"); + (void) strcpy(two, "bumblebee"); + check(memccpy(two, one, 'a', 4) == two + 1); /* First char. */ + equal(two, "aumblebee"); + check(memccpy(two, one, 'd', 4) == two + 4); /* Last char. */ + equal(two, "abcdlebee"); + (void) strcpy(one, "xyz"); + check(memccpy(two, one, 'x', 1) == two + 1); /* Singleton. */ + equal(two, "xbcdlebee"); #endif - /* memset. */ - it = "memset"; - (void) strcpy(one, "abcdefgh"); - check(memset(one+1, 'x', 3) == one+1); /* Return value. */ - equal(one, "axxxefgh"); /* Basic test. */ - - (void) memset(one+2, 'y', 0); - equal(one, "axxxefgh"); /* Zero-length set. */ - - (void) memset(one+5, 0, 1); - equal(one, "axxxe"); /* Zero fill. */ - equal(one+6, "gh"); /* _AND the leftover. */ - - (void) memset(one+2, 010045, 1); - equal(one, "ax\045xe"); /* Unsigned char convert. */ - - /* bcopy - much like memcpy. - Berklix manual is silent about overlap, so don't test it. */ - it = "bcopy"; - (void) bcopy("abc", one, 4); - equal(one, "abc"); /* Simple copy. */ - - (void) strcpy(one, "abcdefgh"); - (void) bcopy("xyz", one+1, 2); - equal(one, "axydefgh"); /* Basic test. */ - - (void) strcpy(one, "abc"); - (void) bcopy("xyz", one, 0); - equal(one, "abc"); /* Zero-length copy. */ - - (void) strcpy(one, "hi there"); - (void) strcpy(two, "foo"); - (void) bcopy(one, two, 9); - equal(two, "hi there"); /* Just paranoia. */ - equal(one, "hi there"); /* Stomped on source? */ - - /* bzero. */ - it = "bzero"; - (void) strcpy(one, "abcdef"); - bzero(one+2, 2); - equal(one, "ab"); /* Basic test. */ - equal(one+3, ""); - equal(one+4, "ef"); - - (void) strcpy(one, "abcdef"); - bzero(one+2, 0); - equal(one, "abcdef"); /* Zero-length copy. */ - - /* bcmp - somewhat like memcmp. */ - it = "bcmp"; - check(bcmp("a", "a", 1) == 0); /* Identity. */ - check(bcmp("abc", "abc", 3) == 0); /* Multicharacter. */ - check(bcmp("abcd", "abce", 4) != 0); /* Honestly unequal. */ - check(bcmp("abce", "abcd",4)); - check(bcmp("alph", "beta", 4) != 0); - check(bcmp("abce", "abcd", 3) == 0); /* Count limited. */ - check(bcmp("abc", "def", 0) == 0); /* Zero count. */ - - if (errors) abort(); - printf("ok\n"); + /* memset. */ + it = "memset"; + (void) strcpy(one, "abcdefgh"); + check(memset(one + 1, 'x', 3) == one + 1); /* Return value. */ + equal(one, "axxxefgh"); /* Basic test. */ + + (void) memset(one + 2, 'y', 0); + equal(one, "axxxefgh"); /* Zero-length set. */ + + (void) memset(one + 5, 0, 1); + equal(one, "axxxe"); /* Zero fill. */ + equal(one + 6, "gh"); /* _AND the leftover. */ + + (void) memset(one + 2, 010045, 1); + equal(one, "ax\045xe"); /* Unsigned char convert. */ + + /* bcopy - much like memcpy. + Berklix manual is silent about overlap, so don't test it. */ + it = "bcopy"; + (void) bcopy("abc", one, 4); + equal(one, "abc"); /* Simple copy. */ + + (void) strcpy(one, "abcdefgh"); + (void) bcopy("xyz", one + 1, 2); + equal(one, "axydefgh"); /* Basic test. */ + + (void) strcpy(one, "abc"); + (void) bcopy("xyz", one, 0); + equal(one, "abc"); /* Zero-length copy. */ + + (void) strcpy(one, "hi there"); + (void) strcpy(two, "foo"); + (void) bcopy(one, two, 9); + equal(two, "hi there"); /* Just paranoia. */ + equal(one, "hi there"); /* Stomped on source? */ + + /* bzero. */ + it = "bzero"; + (void) strcpy(one, "abcdef"); + bzero(one + 2, 2); + equal(one, "ab"); /* Basic test. */ + equal(one + 3, ""); + equal(one + 4, "ef"); + + (void) strcpy(one, "abcdef"); + bzero(one + 2, 0); + equal(one, "abcdef"); /* Zero-length copy. */ + + /* bcmp - somewhat like memcmp. */ + it = "bcmp"; + check(bcmp("a", "a", 1) == 0); /* Identity. */ + check(bcmp("abc", "abc", 3) == 0); /* Multicharacter. */ + check(bcmp("abcd", "abce", 4) != 0); /* Honestly unequal. */ + check(bcmp("abce", "abcd", 4)); + check(bcmp("alph", "beta", 4) != 0); + check(bcmp("abce", "abcd", 3) == 0); /* Count limited. */ + check(bcmp("abc", "def", 0) == 0); /* Zero count. */ + + if (errors) + { + abort(); + } + printf("ok\n"); #if 0 /* strerror - VERY system-dependent. */ -{ - extern CONST unsigned int _sys_nerr; - extern CONST char *CONST _sys_errlist[]; - int f; - it = "strerror"; - f = open("/", O_WRONLY); /* Should always fail. */ - check(f < 0 && errno > 0 && errno < _sys_nerr); - equal(strerror(errno), _sys_errlist[errno]); -} + { + extern CONST unsigned int _sys_nerr; + extern CONST char *CONST _sys_errlist[]; + int f; + it = "strerror"; + f = open("/", O_WRONLY); /* Should always fail. */ + check(f < 0 && errno > 0 && errno < _sys_nerr); + equal(strerror(errno), _sys_errlist[errno]); + } #endif } diff --git a/tests/device/test_libc/memcpy-1.c b/tests/device/test_libc/memcpy-1.c index 2485af0923..4e14bb5810 100644 --- a/tests/device/test_libc/memcpy-1.c +++ b/tests/device/test_libc/memcpy-1.c @@ -1,30 +1,30 @@ /* - * Copyright (c) 2011 ARM Ltd - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. The name of the company may not be used to endorse or promote - * products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY ARM LTD ``AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL ARM LTD BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ + Copyright (c) 2011 ARM Ltd + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. The name of the company may not be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY ARM LTD ``AS IS'' AND ANY EXPRESS OR IMPLIED + WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + IN NO EVENT SHALL ARM LTD BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ #include #include @@ -70,105 +70,109 @@ static int errors = 0; static void -print_error (char const* msg, ...) -{ - errors++; - if (errors == TOO_MANY_ERRORS) +print_error(char const* msg, ...) +{ + errors++; + if (errors == TOO_MANY_ERRORS) { - fprintf (stderr, "Too many errors.\n"); + fprintf(stderr, "Too many errors.\n"); } - else if (errors < TOO_MANY_ERRORS) + else if (errors < TOO_MANY_ERRORS) { - va_list ap; - va_start (ap, msg); - vfprintf (stderr, msg, ap); - va_end (ap); + va_list ap; + va_start(ap, msg); + vfprintf(stderr, msg, ap); + va_end(ap); } - else + else { - /* Further errors omitted. */ + /* Further errors omitted. */ } } extern int rand_seed; void memcpy_main(void) { - /* Allocate buffers to read and write from. */ - char src[BUFF_SIZE], dest[BUFF_SIZE], backup_src[BUFF_SIZE]; - - /* Fill the source buffer with non-null values, reproducible random data. */ - srand (rand_seed); - int i, j; - unsigned sa; - unsigned da; - unsigned n; - for (i = 0; i < BUFF_SIZE; i++) + /* Allocate buffers to read and write from. */ + char src[BUFF_SIZE], dest[BUFF_SIZE], backup_src[BUFF_SIZE]; + + /* Fill the source buffer with non-null values, reproducible random data. */ + srand(rand_seed); + int i, j; + unsigned sa; + unsigned da; + unsigned n; + for (i = 0; i < BUFF_SIZE; i++) + { + src[i] = (char)rand() | 1; + backup_src[i] = src[i]; + } + + /* Make calls to memcpy with block sizes ranging between 1 and + MAX_BLOCK_SIZE bytes, aligned and misaligned source and destination. */ + for (sa = 0; sa <= MAX_OFFSET; sa++) + for (da = 0; da <= MAX_OFFSET; da++) + for (n = 1; n <= MAX_BLOCK_SIZE; n++) + { + //printf ("."); + /* Zero dest so we can check it properly after the copying. */ + for (j = 0; j < BUFF_SIZE; j++) + { + dest[j] = 0; + } + + void *ret = memcpy(dest + START_COPY + da, src + sa, n); + + /* Check return value. */ + if (ret != (dest + START_COPY + da)) + print_error("\nFailed: wrong return value in memcpy of %u bytes " + "with src_align %u and dst_align %u. " + "Return value and dest should be the same" + "(ret is %p, dest is %p)\n", + n, sa, da, ret, dest + START_COPY + da); + + /* Check that content of the destination buffer + is the same as the source buffer, and + memory outside destination buffer is not modified. */ + for (j = 0; j < BUFF_SIZE; j++) + if ((unsigned)j < START_COPY + da) + { + if (dest[j] != 0) + print_error("\nFailed: after memcpy of %u bytes " + "with src_align %u and dst_align %u, " + "byte %u before the start of dest is not 0.\n", + n, sa, da, START_COPY - j); + } + else if ((unsigned)j < START_COPY + da + n) + { + i = j - START_COPY - da; + if (dest[j] != (src + sa)[i]) + print_error("\nFailed: after memcpy of %u bytes " + "with src_align %u and dst_align %u, " + "byte %u in dest and src are not the same.\n", + n, sa, da, i); + } + else if (dest[j] != 0) + { + print_error("\nFailed: after memcpy of %u bytes " + "with src_align %u and dst_align %u, " + "byte %u after the end of dest is not 0.\n", + n, sa, da, j - START_COPY - da - n); + } + + /* Check src is not modified. */ + for (j = 0; j < BUFF_SIZE; j++) + if (src[i] != backup_src[i]) + print_error("\nFailed: after memcpy of %u bytes " + "with src_align %u and dst_align %u, " + "byte %u of src is modified.\n", + n, sa, da, j); + } + + if (errors != 0) { - src[i] = (char)rand () | 1; - backup_src[i] = src[i]; + abort(); } - /* Make calls to memcpy with block sizes ranging between 1 and - MAX_BLOCK_SIZE bytes, aligned and misaligned source and destination. */ - for (sa = 0; sa <= MAX_OFFSET; sa++) - for (da = 0; da <= MAX_OFFSET; da++) - for (n = 1; n <= MAX_BLOCK_SIZE; n++) - { - //printf ("."); - /* Zero dest so we can check it properly after the copying. */ - for (j = 0; j < BUFF_SIZE; j++) - dest[j] = 0; - - void *ret = memcpy (dest + START_COPY + da, src + sa, n); - - /* Check return value. */ - if (ret != (dest + START_COPY + da)) - print_error ("\nFailed: wrong return value in memcpy of %u bytes " - "with src_align %u and dst_align %u. " - "Return value and dest should be the same" - "(ret is %p, dest is %p)\n", - n, sa, da, ret, dest + START_COPY + da); - - /* Check that content of the destination buffer - is the same as the source buffer, and - memory outside destination buffer is not modified. */ - for (j = 0; j < BUFF_SIZE; j++) - if ((unsigned)j < START_COPY + da) - { - if (dest[j] != 0) - print_error ("\nFailed: after memcpy of %u bytes " - "with src_align %u and dst_align %u, " - "byte %u before the start of dest is not 0.\n", - n, sa, da, START_COPY - j); - } - else if ((unsigned)j < START_COPY + da + n) - { - i = j - START_COPY - da; - if (dest[j] != (src + sa)[i]) - print_error ("\nFailed: after memcpy of %u bytes " - "with src_align %u and dst_align %u, " - "byte %u in dest and src are not the same.\n", - n, sa, da, i); - } - else if (dest[j] != 0) - { - print_error ("\nFailed: after memcpy of %u bytes " - "with src_align %u and dst_align %u, " - "byte %u after the end of dest is not 0.\n", - n, sa, da, j - START_COPY - da - n); - } - - /* Check src is not modified. */ - for (j = 0; j < BUFF_SIZE; j++) - if (src[i] != backup_src[i]) - print_error ("\nFailed: after memcpy of %u bytes " - "with src_align %u and dst_align %u, " - "byte %u of src is modified.\n", - n, sa, da, j); - } - - if (errors != 0) - abort (); - - printf("ok\n"); + printf("ok\n"); } diff --git a/tests/device/test_libc/memmove1.c b/tests/device/test_libc/memmove1.c index f64feae759..573b476765 100644 --- a/tests/device/test_libc/memmove1.c +++ b/tests/device/test_libc/memmove1.c @@ -1,38 +1,38 @@ -/* A minor test-program for memmove. - Copyright (C) 2005 Axis Communications. - All rights reserved. +/* A minor test-program for memmove. + Copyright (C) 2005 Axis Communications. + All rights reserved. - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: - 1. Redistributions of source code must retain the above copyright + 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - 2. Neither the name of Axis Communications nor the names of its + 2. Neither the name of Axis Communications nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - THIS SOFTWARE IS PROVIDED BY AXIS COMMUNICATIONS AND ITS CONTRIBUTORS - ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL AXIS - COMMUNICATIONS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, - STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING - IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. */ - -/* Test moves of 0..MAX bytes; overlapping-src-higher, - overlapping-src-lower and non-overlapping. The overlap varies with - 1..N where N is the size moved. This means an order of MAX**2 - iterations. The size of an octet may seem appropriate for MAX and - makes an upper limit for simple testing. For the CRIS simulator, - making this 256 added 90s to the test-run (2GHz P4) while 64 (4s) was - enough to spot the bugs that had crept in, hence the number chosen. */ + THIS SOFTWARE IS PROVIDED BY AXIS COMMUNICATIONS AND ITS CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL AXIS + COMMUNICATIONS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. */ + +/* Test moves of 0..MAX bytes; overlapping-src-higher, + overlapping-src-lower and non-overlapping. The overlap varies with + 1..N where N is the size moved. This means an order of MAX**2 + iterations. The size of an octet may seem appropriate for MAX and + makes an upper limit for simple testing. For the CRIS simulator, + making this 256 added 90s to the test-run (2GHz P4) while 64 (4s) was + enough to spot the bugs that had crept in, hence the number chosen. */ #define MAX 64 #include @@ -64,131 +64,139 @@ int errors = 0; /* A safe target-independent memmove. */ void -mymemmove (unsigned char *dest, unsigned char *src, size_t n) +mymemmove(unsigned char *dest, unsigned char *src, size_t n) { - if ((src <= dest && src + n <= dest) - || src >= dest) - while (n-- > 0) - *dest++ = *src++; - else + if ((src <= dest && src + n <= dest) + || src >= dest) + while (n-- > 0) + { + *dest++ = *src++; + } + else { - dest += n; - src += n; - while (n-- > 0) - *--dest = *--src; + dest += n; + src += n; + while (n-- > 0) + { + *--dest = *--src; + } } } -/* It's either the noinline attribute or forcing the test framework to - pass -fno-builtin-memmove. */ +/* It's either the noinline attribute or forcing the test framework to + pass -fno-builtin-memmove. */ void -xmemmove (unsigned char *dest, unsigned char *src, size_t n) - __attribute__ ((__noinline__)); +xmemmove(unsigned char *dest, unsigned char *src, size_t n) +__attribute__((__noinline__)); void -xmemmove (unsigned char *dest, unsigned char *src, size_t n) +xmemmove(unsigned char *dest, unsigned char *src, size_t n) { - void *retp; - retp = memmove (dest, src, n); + void *retp; + retp = memmove(dest, src, n); - if (retp != dest) + if (retp != dest) { - errors++; - DEBUGP ("memmove of n bytes returned %p instead of dest=%p\n", - retp, dest); + errors++; + DEBUGP("memmove of n bytes returned %p instead of dest=%p\n", + retp, dest); } } -/* Fill the array with something we can associate with a position, but - not exactly the same as the position index. */ +/* Fill the array with something we can associate with a position, but + not exactly the same as the position index. */ void -fill (unsigned char dest[MAX*3]) +fill(unsigned char dest[MAX * 3]) { - size_t i; - for (i = 0; i < MAX*3; i++) - dest[i] = (10 + i) % MAX; + size_t i; + for (i = 0; i < MAX * 3; i++) + { + dest[i] = (10 + i) % MAX; + } } void memmove_main(void) { - size_t i; - int errors = 0; - - /* Leave some room before and after the area tested, so we can detect - overwrites of up to N bytes, N being the amount tested. If you - want to test using valgrind, make these malloced instead. */ - unsigned char from_test[MAX*3]; - unsigned char to_test[MAX*3]; - unsigned char from_known[MAX*3]; - unsigned char to_known[MAX*3]; - - /* Non-overlap. */ - for (i = 0; i < MAX; i++) + size_t i; + int errors = 0; + + /* Leave some room before and after the area tested, so we can detect + overwrites of up to N bytes, N being the amount tested. If you + want to test using valgrind, make these malloced instead. */ + unsigned char from_test[MAX * 3]; + unsigned char to_test[MAX * 3]; + unsigned char from_known[MAX * 3]; + unsigned char to_known[MAX * 3]; + + /* Non-overlap. */ + for (i = 0; i < MAX; i++) { - /* Do the memmove first before setting the known array, so we know - it didn't change any of the known array. */ - fill (from_test); - fill (to_test); - xmemmove (to_test + MAX, 1 + from_test + MAX, i); - - fill (from_known); - fill (to_known); - mymemmove (to_known + MAX, 1 + from_known + MAX, i); - - if (memcmp (to_known, to_test, sizeof (to_known)) != 0) - { - errors++; - DEBUGP ("memmove failed non-overlap test for %d bytes\n", i); - } + /* Do the memmove first before setting the known array, so we know + it didn't change any of the known array. */ + fill(from_test); + fill(to_test); + xmemmove(to_test + MAX, 1 + from_test + MAX, i); + + fill(from_known); + fill(to_known); + mymemmove(to_known + MAX, 1 + from_known + MAX, i); + + if (memcmp(to_known, to_test, sizeof(to_known)) != 0) + { + errors++; + DEBUGP("memmove failed non-overlap test for %d bytes\n", i); + } } - /* Overlap-from-before. */ - for (i = 0; i < MAX; i++) + /* Overlap-from-before. */ + for (i = 0; i < MAX; i++) { - size_t j; - for (j = 0; j < i; j++) - { - fill (to_test); - xmemmove (to_test + MAX * 2 - i, to_test + MAX * 2 - i - j, i); - - fill (to_known); - mymemmove (to_known + MAX * 2 - i, to_known + MAX * 2 - i - j, i); - - if (memcmp (to_known, to_test, sizeof (to_known)) != 0) - { - errors++; - DEBUGP ("memmove failed for %d bytes," - " with src %d bytes before dest\n", - i, j); - } - } + size_t j; + for (j = 0; j < i; j++) + { + fill(to_test); + xmemmove(to_test + MAX * 2 - i, to_test + MAX * 2 - i - j, i); + + fill(to_known); + mymemmove(to_known + MAX * 2 - i, to_known + MAX * 2 - i - j, i); + + if (memcmp(to_known, to_test, sizeof(to_known)) != 0) + { + errors++; + DEBUGP("memmove failed for %d bytes," + " with src %d bytes before dest\n", + i, j); + } + } } - /* Overlap-from-after. */ - for (i = 0; i < MAX; i++) + /* Overlap-from-after. */ + for (i = 0; i < MAX; i++) { - size_t j; - for (j = 0; j < i; j++) - { - fill (to_test); - xmemmove (to_test + MAX, to_test + MAX + j, i); - - fill (to_known); - mymemmove (to_known + MAX, to_known + MAX + j, i); - - if (memcmp (to_known, to_test, sizeof (to_known)) != 0) - { - errors++; - DEBUGP ("memmove failed when moving %d bytes," - " with src %d bytes after dest\n", - i, j); - } - } + size_t j; + for (j = 0; j < i; j++) + { + fill(to_test); + xmemmove(to_test + MAX, to_test + MAX + j, i); + + fill(to_known); + mymemmove(to_known + MAX, to_known + MAX + j, i); + + if (memcmp(to_known, to_test, sizeof(to_known)) != 0) + { + errors++; + DEBUGP("memmove failed when moving %d bytes," + " with src %d bytes after dest\n", + i, j); + } + } } - if (errors != 0) - abort (); - printf("ok\n"); + if (errors != 0) + { + abort(); + } + printf("ok\n"); } diff --git a/tests/device/test_libc/strcmp-1.c b/tests/device/test_libc/strcmp-1.c index 7c1883a085..b2b3649762 100644 --- a/tests/device/test_libc/strcmp-1.c +++ b/tests/device/test_libc/strcmp-1.c @@ -1,30 +1,30 @@ /* - * Copyright (c) 2011 ARM Ltd - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. The name of the company may not be used to endorse or promote - * products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY ARM LTD ``AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL ARM LTD BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ + Copyright (c) 2011 ARM Ltd + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. The name of the company may not be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY ARM LTD ``AS IS'' AND ANY EXPRESS OR IMPLIED + WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + IN NO EVENT SHALL ARM LTD BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ #include #include @@ -47,8 +47,8 @@ #define BUFF_SIZE 256 -/* The macro LONG_TEST controls whether a short or a more comprehensive test - of strcmp should be performed. */ +/* The macro LONG_TEST controls whether a short or a more comprehensive test + of strcmp should be performed. */ #ifdef LONG_TEST #ifndef BUFF_SIZE #define BUFF_SIZE 1024 @@ -113,23 +113,23 @@ static int errors = 0; const char *testname = "strcmp"; static void -print_error (char const* msg, ...) +print_error(char const* msg, ...) { - errors++; - if (errors == TOO_MANY_ERRORS) + errors++; + if (errors == TOO_MANY_ERRORS) { - fprintf (stderr, "Too many errors.\n"); + fprintf(stderr, "Too many errors.\n"); } - else if (errors < TOO_MANY_ERRORS) + else if (errors < TOO_MANY_ERRORS) { - va_list ap; - va_start (ap, msg); - vfprintf (stderr, msg, ap); - va_end (ap); + va_list ap; + va_start(ap, msg); + vfprintf(stderr, msg, ap); + va_end(ap); } - else + else { - /* Further errors omitted. */ + /* Further errors omitted. */ } } @@ -137,155 +137,167 @@ print_error (char const* msg, ...) extern int rand_seed; void strcmp_main(void) { - /* Allocate buffers to read and write from. */ - char src[BUFF_SIZE], dest[BUFF_SIZE]; - - /* Fill the source buffer with non-null values, reproducible random data. */ - srand (rand_seed); - int i, j, zeros; - unsigned sa; - unsigned da; - unsigned n, m, len; - char *p; - int ret; - - /* Make calls to strcmp with block sizes ranging between 1 and - MAX_BLOCK_SIZE bytes, aligned and misaligned source and destination. */ - for (sa = 0; sa <= MAX_OFFSET; sa++) - for (da = 0; da <= MAX_OFFSET; da++) - for (n = 1; n <= MAX_BLOCK_SIZE; n++) - { - for (m = 1; m < n + MAX_DIFF; m++) - for (len = 0; len < MAX_LEN; len++) - for (zeros = 1; zeros < MAX_ZEROS; zeros++) - { - if (n - m > MAX_DIFF) - continue; - /* Make a copy of the source. */ - for (i = 0; i < BUFF_SIZE; i++) - { - src[i] = 'A' + (i % 26); - dest[i] = src[i]; - } - delay(0); - memcpy (dest + da, src + sa, n); - - /* Make src 0-terminated. */ - p = src + sa + n - 1; - for (i = 0; i < zeros; i++) - { - *p++ = '\0'; - } - - /* Modify dest. */ - p = dest + da + m - 1; - for (j = 0; j < (int)len; j++) - *p++ = 'x'; - /* Make dest 0-terminated. */ - *p = '\0'; - - ret = strcmp (src + sa, dest + da); - - /* Check return value. */ - if (n == m) - { - if (len == 0) - { - if (ret != 0) - { - print_error ("\nFailed: after %s of %u bytes " - "with src_align %u and dst_align %u, " - "dest after %d bytes is modified for %d bytes, " - "return value is %d, expected 0.\n", - testname, n, sa, da, m, len, ret); - } - } - else - { - if (ret >= 0) - print_error ("\nFailed: after %s of %u bytes " - "with src_align %u and dst_align %u, " - "dest after %d bytes is modified for %d bytes, " - "return value is %d, expected negative.\n", - testname, n, sa, da, m, len, ret); - } - } - else if (m > n) - { - if (ret >= 0) - { - print_error ("\nFailed: after %s of %u bytes " - "with src_align %u and dst_align %u, " - "dest after %d bytes is modified for %d bytes, " - "return value is %d, expected negative.\n", - testname, n, sa, da, m, len, ret); - } - } - else /* m < n */ - { - if (len == 0) - { - if (ret <= 0) - print_error ("\nFailed: after %s of %u bytes " - "with src_align %u and dst_align %u, " - "dest after %d bytes is modified for %d bytes, " - "return value is %d, expected positive.\n", - testname, n, sa, da, m, len, ret); - } - else - { - if (ret >= 0) - print_error ("\nFailed: after %s of %u bytes " - "with src_align %u and dst_align %u, " - "dest after %d bytes is modified for %d bytes, " - "return value is %d, expected negative.\n", - testname, n, sa, da, m, len, ret); - } - } - } - } - - /* Check some corner cases. */ - src[1] = 'A'; - dest[1] = 'A'; - src[2] = 'B'; - dest[2] = 'B'; - src[3] = 'C'; - dest[3] = 'C'; - src[4] = '\0'; - dest[4] = '\0'; - - src[0] = 0xc1; - dest[0] = 0x41; - ret = strcmp (src, dest); - if (ret <= 0) - print_error ("\nFailed: expected positive, return %d\n", ret); - - src[0] = 0x01; - dest[0] = 0x82; - ret = strcmp (src, dest); - if (ret >= 0) - print_error ("\nFailed: expected negative, return %d\n", ret); - - dest[0] = src[0] = 'D'; - src[3] = 0xc1; - dest[3] = 0x41; - ret = strcmp (src, dest); - if (ret <= 0) - print_error ("\nFailed: expected positive, return %d\n", ret); - - src[3] = 0x01; - dest[3] = 0x82; - ret = strcmp (src, dest); - if (ret >= 0) - print_error ("\nFailed: expected negative, return %d\n", ret); - - //printf ("\n"); - if (errors != 0) + /* Allocate buffers to read and write from. */ + char src[BUFF_SIZE], dest[BUFF_SIZE]; + + /* Fill the source buffer with non-null values, reproducible random data. */ + srand(rand_seed); + int i, j, zeros; + unsigned sa; + unsigned da; + unsigned n, m, len; + char *p; + int ret; + + /* Make calls to strcmp with block sizes ranging between 1 and + MAX_BLOCK_SIZE bytes, aligned and misaligned source and destination. */ + for (sa = 0; sa <= MAX_OFFSET; sa++) + for (da = 0; da <= MAX_OFFSET; da++) + for (n = 1; n <= MAX_BLOCK_SIZE; n++) + { + for (m = 1; m < n + MAX_DIFF; m++) + for (len = 0; len < MAX_LEN; len++) + for (zeros = 1; zeros < MAX_ZEROS; zeros++) + { + if (n - m > MAX_DIFF) + { + continue; + } + /* Make a copy of the source. */ + for (i = 0; i < BUFF_SIZE; i++) + { + src[i] = 'A' + (i % 26); + dest[i] = src[i]; + } + delay(0); + memcpy(dest + da, src + sa, n); + + /* Make src 0-terminated. */ + p = src + sa + n - 1; + for (i = 0; i < zeros; i++) + { + *p++ = '\0'; + } + + /* Modify dest. */ + p = dest + da + m - 1; + for (j = 0; j < (int)len; j++) + { + *p++ = 'x'; + } + /* Make dest 0-terminated. */ + *p = '\0'; + + ret = strcmp(src + sa, dest + da); + + /* Check return value. */ + if (n == m) + { + if (len == 0) + { + if (ret != 0) + { + print_error("\nFailed: after %s of %u bytes " + "with src_align %u and dst_align %u, " + "dest after %d bytes is modified for %d bytes, " + "return value is %d, expected 0.\n", + testname, n, sa, da, m, len, ret); + } + } + else + { + if (ret >= 0) + print_error("\nFailed: after %s of %u bytes " + "with src_align %u and dst_align %u, " + "dest after %d bytes is modified for %d bytes, " + "return value is %d, expected negative.\n", + testname, n, sa, da, m, len, ret); + } + } + else if (m > n) + { + if (ret >= 0) + { + print_error("\nFailed: after %s of %u bytes " + "with src_align %u and dst_align %u, " + "dest after %d bytes is modified for %d bytes, " + "return value is %d, expected negative.\n", + testname, n, sa, da, m, len, ret); + } + } + else /* m < n */ + { + if (len == 0) + { + if (ret <= 0) + print_error("\nFailed: after %s of %u bytes " + "with src_align %u and dst_align %u, " + "dest after %d bytes is modified for %d bytes, " + "return value is %d, expected positive.\n", + testname, n, sa, da, m, len, ret); + } + else + { + if (ret >= 0) + print_error("\nFailed: after %s of %u bytes " + "with src_align %u and dst_align %u, " + "dest after %d bytes is modified for %d bytes, " + "return value is %d, expected negative.\n", + testname, n, sa, da, m, len, ret); + } + } + } + } + + /* Check some corner cases. */ + src[1] = 'A'; + dest[1] = 'A'; + src[2] = 'B'; + dest[2] = 'B'; + src[3] = 'C'; + dest[3] = 'C'; + src[4] = '\0'; + dest[4] = '\0'; + + src[0] = 0xc1; + dest[0] = 0x41; + ret = strcmp(src, dest); + if (ret <= 0) { - printf ("ERROR. FAILED.\n"); - abort (); + print_error("\nFailed: expected positive, return %d\n", ret); } - //exit (0); - printf("ok\n"); + + src[0] = 0x01; + dest[0] = 0x82; + ret = strcmp(src, dest); + if (ret >= 0) + { + print_error("\nFailed: expected negative, return %d\n", ret); + } + + dest[0] = src[0] = 'D'; + src[3] = 0xc1; + dest[3] = 0x41; + ret = strcmp(src, dest); + if (ret <= 0) + { + print_error("\nFailed: expected positive, return %d\n", ret); + } + + src[3] = 0x01; + dest[3] = 0x82; + ret = strcmp(src, dest); + if (ret >= 0) + { + print_error("\nFailed: expected negative, return %d\n", ret); + } + + //printf ("\n"); + if (errors != 0) + { + printf("ERROR. FAILED.\n"); + abort(); + } + //exit (0); + printf("ok\n"); } diff --git a/tests/device/test_libc/tstring.c b/tests/device/test_libc/tstring.c index 7e806b1027..c2f2f4075a 100644 --- a/tests/device/test_libc/tstring.c +++ b/tests/device/test_libc/tstring.c @@ -1,9 +1,9 @@ /* - * Copyright (C) 2002 by Red Hat, Incorporated. All rights reserved. - * - * Permission to use, copy, modify, and distribute this software - * is freely granted, provided that this notice is preserved. - */ + Copyright (C) 2002 by Red Hat, Incorporated. All rights reserved. + + Permission to use, copy, modify, and distribute this software + is freely granted, provided that this notice is preserved. +*/ #include #include @@ -26,336 +26,342 @@ #define MAX_2 (2 * MAX_1 + MAX_1 / 10) -void eprintf (int line, char *result, char *expected, int size) +void eprintf(int line, char *result, char *expected, int size) { - if (size != 0) - printf ("Failure at line %d, result is <%.*s>, should be <%s> of size %d\n", - line, size, result, expected, size); - else - printf ("Failure at line %d, result is <%s>, should be <%s>\n", - line, result, expected); + if (size != 0) + printf("Failure at line %d, result is <%.*s>, should be <%s> of size %d\n", + line, size, result, expected, size); + else + printf("Failure at line %d, result is <%s>, should be <%s>\n", + line, result, expected); } -void mycopy (char *target, char *source, int size) +void mycopy(char *target, char *source, int size) { - int i; + int i; - for (i = 0; i < size; ++i) + for (i = 0; i < size; ++i) { - target[i] = source[i]; + target[i] = source[i]; } } -void myset (char *target, char ch, int size) +void myset(char *target, char ch, int size) { - int i; - - for (i = 0; i < size; ++i) + int i; + + for (i = 0; i < size; ++i) { - target[i] = ch; + target[i] = ch; } } void tstring_main(void) { - char target[MAX_1] = "A"; - char first_char; - char second_char; - char array[] = "abcdefghijklmnopqrstuvwxz"; - char array2[] = "0123456789!@#$%^&*("; - char buffer2[MAX_1]; - char buffer3[MAX_1]; - char buffer4[MAX_1]; - char buffer5[MAX_2]; - char buffer6[MAX_2]; - char buffer7[MAX_2]; - char expected[MAX_1]; - char *tmp1, *tmp2, *tmp3, *tmp4, *tmp5, *tmp6, *tmp7; - int i, j, k, x, z, align_test_iterations; - z = 0; - - int test_failed = 0; - - tmp1 = target; - tmp2 = buffer2; - tmp3 = buffer3; - tmp4 = buffer4; - tmp5 = buffer5; - tmp6 = buffer6; - tmp7 = buffer7; - - tmp2[0] = 'Z'; - tmp2[1] = '\0'; - - if (memset (target, 'X', 0) != target || - memcpy (target, "Y", 0) != target || - memmove (target, "K", 0) != target || - strncpy (tmp2, "4", 0) != tmp2 || - strncat (tmp2, "123", 0) != tmp2 || - strcat (target, "") != target) + char target[MAX_1] = "A"; + char first_char; + char second_char; + char array[] = "abcdefghijklmnopqrstuvwxz"; + char array2[] = "0123456789!@#$%^&*("; + char buffer2[MAX_1]; + char buffer3[MAX_1]; + char buffer4[MAX_1]; + char buffer5[MAX_2]; + char buffer6[MAX_2]; + char buffer7[MAX_2]; + char expected[MAX_1]; + char *tmp1, *tmp2, *tmp3, *tmp4, *tmp5, *tmp6, *tmp7; + int i, j, k, x, z, align_test_iterations; + z = 0; + + int test_failed = 0; + + tmp1 = target; + tmp2 = buffer2; + tmp3 = buffer3; + tmp4 = buffer4; + tmp5 = buffer5; + tmp6 = buffer6; + tmp7 = buffer7; + + tmp2[0] = 'Z'; + tmp2[1] = '\0'; + + if (memset(target, 'X', 0) != target || + memcpy(target, "Y", 0) != target || + memmove(target, "K", 0) != target || + strncpy(tmp2, "4", 0) != tmp2 || + strncat(tmp2, "123", 0) != tmp2 || + strcat(target, "") != target) { - eprintf (__LINE__, target, "A", 0); - test_failed = 1; + eprintf(__LINE__, target, "A", 0); + test_failed = 1; } - if (strcmp (target, "A") || strlen(target) != 1 || memchr (target, 'A', 0) != NULL - || memcmp (target, "J", 0) || strncmp (target, "A", 1) || strncmp (target, "J", 0) || - tmp2[0] != 'Z' || tmp2[1] != '\0') + if (strcmp(target, "A") || strlen(target) != 1 || memchr(target, 'A', 0) != NULL + || memcmp(target, "J", 0) || strncmp(target, "A", 1) || strncmp(target, "J", 0) || + tmp2[0] != 'Z' || tmp2[1] != '\0') { - eprintf (__LINE__, target, "A", 0); - test_failed = 1; + eprintf(__LINE__, target, "A", 0); + test_failed = 1; } - tmp2[2] = 'A'; - if (strcpy (target, "") != target || - strncpy (tmp2, "", 4) != tmp2 || - strcat (target, "") != target) + tmp2[2] = 'A'; + if (strcpy(target, "") != target || + strncpy(tmp2, "", 4) != tmp2 || + strcat(target, "") != target) { - eprintf (__LINE__, target, "", 0); - test_failed = 1; + eprintf(__LINE__, target, "", 0); + test_failed = 1; } - if (target[0] != '\0' || strncmp (target, "", 1) || - memcmp (tmp2, "\0\0\0\0", 4)) + if (target[0] != '\0' || strncmp(target, "", 1) || + memcmp(tmp2, "\0\0\0\0", 4)) { - eprintf (__LINE__, target, "", 0); - test_failed = 1; + eprintf(__LINE__, target, "", 0); + test_failed = 1; } - tmp2[2] = 'A'; - if (strncat (tmp2, "1", 3) != tmp2 || - memcmp (tmp2, "1\0A", 3)) + tmp2[2] = 'A'; + if (strncat(tmp2, "1", 3) != tmp2 || + memcmp(tmp2, "1\0A", 3)) { - eprintf (__LINE__, tmp2, "1\0A", 3); - test_failed = 1; + eprintf(__LINE__, tmp2, "1\0A", 3); + test_failed = 1; } - if (strcpy (tmp3, target) != tmp3 || - strcat (tmp3, "X") != tmp3 || - strncpy (tmp2, "X", 2) != tmp2 || - memset (target, tmp2[0], 1) != target) + if (strcpy(tmp3, target) != tmp3 || + strcat(tmp3, "X") != tmp3 || + strncpy(tmp2, "X", 2) != tmp2 || + memset(target, tmp2[0], 1) != target) { - eprintf (__LINE__, target, "X", 0); - test_failed = 1; + eprintf(__LINE__, target, "X", 0); + test_failed = 1; } - if (strcmp (target, "X") || strlen (target) != 1 || - memchr (target, 'X', 2) != target || - strchr (target, 'X') != target || - memchr (target, 'Y', 2) != NULL || - strchr (target, 'Y') != NULL || - strcmp (tmp3, target) || - strncmp (tmp3, target, 2) || - memcmp (target, "K", 0) || - strncmp (target, tmp3, 3)) + if (strcmp(target, "X") || strlen(target) != 1 || + memchr(target, 'X', 2) != target || + strchr(target, 'X') != target || + memchr(target, 'Y', 2) != NULL || + strchr(target, 'Y') != NULL || + strcmp(tmp3, target) || + strncmp(tmp3, target, 2) || + memcmp(target, "K", 0) || + strncmp(target, tmp3, 3)) { - eprintf (__LINE__, target, "X", 0); - test_failed = 1; + eprintf(__LINE__, target, "X", 0); + test_failed = 1; } - if (strcpy (tmp3, "Y") != tmp3 || - strcat (tmp3, "Y") != tmp3 || - memset (target, 'Y', 2) != target) + if (strcpy(tmp3, "Y") != tmp3 || + strcat(tmp3, "Y") != tmp3 || + memset(target, 'Y', 2) != target) { - eprintf (__LINE__, target, "Y", 0); - test_failed = 1; + eprintf(__LINE__, target, "Y", 0); + test_failed = 1; } - target[2] = '\0'; - if (memcmp (target, "YY", 2) || strcmp (target, "YY") || - strlen (target) != 2 || memchr (target, 'Y', 2) != target || - strcmp (tmp3, target) || - strncmp (target, tmp3, 3) || - strncmp (target, tmp3, 4) || - strncmp (target, tmp3, 2) || - strchr (target, 'Y') != target) + target[2] = '\0'; + if (memcmp(target, "YY", 2) || strcmp(target, "YY") || + strlen(target) != 2 || memchr(target, 'Y', 2) != target || + strcmp(tmp3, target) || + strncmp(target, tmp3, 3) || + strncmp(target, tmp3, 4) || + strncmp(target, tmp3, 2) || + strchr(target, 'Y') != target) { - eprintf (__LINE__, target, "YY", 2); - test_failed = 1; + eprintf(__LINE__, target, "YY", 2); + test_failed = 1; } - strcpy (target, "WW"); - if (memcmp (target, "WW", 2) || strcmp (target, "WW") || - strlen (target) != 2 || memchr (target, 'W', 2) != target || - strchr (target, 'W') != target) + strcpy(target, "WW"); + if (memcmp(target, "WW", 2) || strcmp(target, "WW") || + strlen(target) != 2 || memchr(target, 'W', 2) != target || + strchr(target, 'W') != target) { - eprintf (__LINE__, target, "WW", 2); - test_failed = 1; + eprintf(__LINE__, target, "WW", 2); + test_failed = 1; } - if (strncpy (target, "XX", 16) != target || - memcmp (target, "XX\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16)) + if (strncpy(target, "XX", 16) != target || + memcmp(target, "XX\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16)) { - eprintf (__LINE__, target, "XX\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16); - test_failed = 1; + eprintf(__LINE__, target, "XX\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16); + test_failed = 1; } - if (strcpy (tmp3, "ZZ") != tmp3 || - strcat (tmp3, "Z") != tmp3 || - memcpy (tmp4, "Z", 2) != tmp4 || - strcat (tmp4, "ZZ") != tmp4 || - memset (target, 'Z', 3) != target) + if (strcpy(tmp3, "ZZ") != tmp3 || + strcat(tmp3, "Z") != tmp3 || + memcpy(tmp4, "Z", 2) != tmp4 || + strcat(tmp4, "ZZ") != tmp4 || + memset(target, 'Z', 3) != target) { - eprintf (__LINE__, target, "ZZZ", 3); - test_failed = 1; + eprintf(__LINE__, target, "ZZZ", 3); + test_failed = 1; } - target[3] = '\0'; - tmp5[0] = '\0'; - strncat (tmp5, "123", 2); - if (memcmp (target, "ZZZ", 3) || strcmp (target, "ZZZ") || - strcmp (tmp3, target) || strcmp (tmp4, target) || - strncmp (target, "ZZZ", 4) || strncmp (target, "ZZY", 3) <= 0 || - strncmp ("ZZY", target, 4) >= 0 || - memcmp (tmp5, "12", 3) || - strlen (target) != 3) + target[3] = '\0'; + tmp5[0] = '\0'; + strncat(tmp5, "123", 2); + if (memcmp(target, "ZZZ", 3) || strcmp(target, "ZZZ") || + strcmp(tmp3, target) || strcmp(tmp4, target) || + strncmp(target, "ZZZ", 4) || strncmp(target, "ZZY", 3) <= 0 || + strncmp("ZZY", target, 4) >= 0 || + memcmp(tmp5, "12", 3) || + strlen(target) != 3) { - eprintf (__LINE__, target, "ZZZ", 3); - test_failed = 1; + eprintf(__LINE__, target, "ZZZ", 3); + test_failed = 1; } - target[2] = 'K'; - if (memcmp (target, "ZZZ", 2) || strcmp (target, "ZZZ") >= 0 || - memcmp (target, "ZZZ", 3) >= 0 || strlen (target) != 3 || - memchr (target, 'K', 3) != target + 2 || - strncmp (target, "ZZZ", 2) || strncmp (target, "ZZZ", 4) >= 0 || - strchr (target, 'K') != target + 2) + target[2] = 'K'; + if (memcmp(target, "ZZZ", 2) || strcmp(target, "ZZZ") >= 0 || + memcmp(target, "ZZZ", 3) >= 0 || strlen(target) != 3 || + memchr(target, 'K', 3) != target + 2 || + strncmp(target, "ZZZ", 2) || strncmp(target, "ZZZ", 4) >= 0 || + strchr(target, 'K') != target + 2) { - eprintf (__LINE__, target, "ZZK", 3); - test_failed = 1; + eprintf(__LINE__, target, "ZZK", 3); + test_failed = 1; } - - strcpy (target, "AAA"); - if (memcmp (target, "AAA", 3) || strcmp (target, "AAA") || - strncmp (target, "AAA", 3) || - strlen (target) != 3) + + strcpy(target, "AAA"); + if (memcmp(target, "AAA", 3) || strcmp(target, "AAA") || + strncmp(target, "AAA", 3) || + strlen(target) != 3) { - eprintf (__LINE__, target, "AAA", 3); - test_failed = 1; + eprintf(__LINE__, target, "AAA", 3); + test_failed = 1; } - - j = 5; - while (j < MAX_1) + + j = 5; + while (j < MAX_1) { - for (i = j-1; i <= j+1; ++i) + for (i = j - 1; i <= j + 1; ++i) { - /* don't bother checking unaligned data in the larger - sizes since it will waste time without performing additional testing */ - if ((size_t)i <= 16 * sizeof(long)) - { - align_test_iterations = 2*sizeof(long); - if ((size_t)i <= 2 * sizeof(long) + 1) - z = 2; - else - z = 2 * sizeof(long); + /* don't bother checking unaligned data in the larger + sizes since it will waste time without performing additional testing */ + if ((size_t)i <= 16 * sizeof(long)) + { + align_test_iterations = 2 * sizeof(long); + if ((size_t)i <= 2 * sizeof(long) + 1) + { + z = 2; + } + else + { + z = 2 * sizeof(long); + } } - else + else { - align_test_iterations = 1; + align_test_iterations = 1; } - for (x = 0; x < align_test_iterations; ++x) - { - tmp1 = target + x; - tmp2 = buffer2 + x; - tmp3 = buffer3 + x; - tmp4 = buffer4 + x; - tmp5 = buffer5 + x; - tmp6 = buffer6 + x; - - first_char = array[i % (sizeof(array) - 1)]; - second_char = array2[i % (sizeof(array2) - 1)]; - memset (tmp1, first_char, i); - mycopy (tmp2, tmp1, i); - myset (tmp2 + z, second_char, i - z - 1); - if (memcpy (tmp1 + z, tmp2 + z, i - z - 1) != tmp1 + z) - { - printf ("error at line %d\n", __LINE__); - test_failed = 1; - } - - tmp1[i] = '\0'; - tmp2[i] = '\0'; - if (strcpy (expected, tmp2) != expected) - { - printf ("error at line %d\n", __LINE__); - test_failed = 1; - } - tmp2[i-z] = first_char + 1; - if (memmove (tmp2 + z + 1, tmp2 + z, i - z - 1) != tmp2 + z + 1 || - memset (tmp3, first_char, i) != tmp3) - { - printf ("error at line %d\n", __LINE__); - test_failed = 1; - } - - myset (tmp4, first_char, i); - tmp5[0] = '\0'; - if (strncpy (tmp5, tmp1, i+1) != tmp5 || - strcat (tmp5, tmp1) != tmp5) - { - printf ("error at line %d\n", __LINE__); - test_failed = 1; - } - mycopy (tmp6, tmp1, i); - mycopy (tmp6 + i, tmp1, i + 1); - - tmp7[2*i+z] = second_char; - strcpy (tmp7, tmp1); - - (void)strchr (tmp1, second_char); - - if (memcmp (tmp1, expected, i) || strcmp (tmp1, expected) || - strncmp (tmp1, expected, i) || - strncmp (tmp1, expected, i+1) || - strcmp (tmp1, tmp2) >= 0 || memcmp (tmp1, tmp2, i) >= 0 || - strncmp (tmp1, tmp2, i+1) >= 0 || - (int)strlen (tmp1) != i || memchr (tmp1, first_char, i) != tmp1 || - strchr (tmp1, first_char) != tmp1 || - memchr (tmp1, second_char, i) != tmp1 + z || - strchr (tmp1, second_char) != tmp1 + z || - strcmp (tmp5, tmp6) || - strncat (tmp7, tmp1, i+2) != tmp7 || - strcmp (tmp7, tmp6) || - tmp7[2*i+z] != second_char) - { - eprintf (__LINE__, tmp1, expected, 0); - printf ("x is %d\n",x); - printf ("i is %d\n", i); - printf ("tmp1 is <%p>\n", tmp1); - printf ("tmp5 is <%p> <%s>\n", tmp5, tmp5); - printf ("tmp6 is <%p> <%s>\n", tmp6, tmp6); - test_failed = 1; - } - - for (k = 1; k <= align_test_iterations && k <= i; ++k) - { - if (memcmp (tmp3, tmp4, i - k + 1) != 0 || - strncmp (tmp3, tmp4, i - k + 1) != 0) - { - printf ("Failure at line %d, comparing %.*s with %.*s\n", - __LINE__, i, tmp3, i, tmp4); - test_failed = 1; - } - tmp4[i-k] = first_char + 1; - if (memcmp (tmp3, tmp4, i) >= 0 || - strncmp (tmp3, tmp4, i) >= 0 || - memcmp (tmp4, tmp3, i) <= 0 || - strncmp (tmp4, tmp3, i) <= 0) - { - printf ("Failure at line %d, comparing %.*s with %.*s\n", - __LINE__, i, tmp3, i, tmp4); - test_failed = 1; - } - tmp4[i-k] = first_char; - } - } + for (x = 0; x < align_test_iterations; ++x) + { + tmp1 = target + x; + tmp2 = buffer2 + x; + tmp3 = buffer3 + x; + tmp4 = buffer4 + x; + tmp5 = buffer5 + x; + tmp6 = buffer6 + x; + + first_char = array[i % (sizeof(array) - 1)]; + second_char = array2[i % (sizeof(array2) - 1)]; + memset(tmp1, first_char, i); + mycopy(tmp2, tmp1, i); + myset(tmp2 + z, second_char, i - z - 1); + if (memcpy(tmp1 + z, tmp2 + z, i - z - 1) != tmp1 + z) + { + printf("error at line %d\n", __LINE__); + test_failed = 1; + } + + tmp1[i] = '\0'; + tmp2[i] = '\0'; + if (strcpy(expected, tmp2) != expected) + { + printf("error at line %d\n", __LINE__); + test_failed = 1; + } + tmp2[i - z] = first_char + 1; + if (memmove(tmp2 + z + 1, tmp2 + z, i - z - 1) != tmp2 + z + 1 || + memset(tmp3, first_char, i) != tmp3) + { + printf("error at line %d\n", __LINE__); + test_failed = 1; + } + + myset(tmp4, first_char, i); + tmp5[0] = '\0'; + if (strncpy(tmp5, tmp1, i + 1) != tmp5 || + strcat(tmp5, tmp1) != tmp5) + { + printf("error at line %d\n", __LINE__); + test_failed = 1; + } + mycopy(tmp6, tmp1, i); + mycopy(tmp6 + i, tmp1, i + 1); + + tmp7[2 * i + z] = second_char; + strcpy(tmp7, tmp1); + + (void)strchr(tmp1, second_char); + + if (memcmp(tmp1, expected, i) || strcmp(tmp1, expected) || + strncmp(tmp1, expected, i) || + strncmp(tmp1, expected, i + 1) || + strcmp(tmp1, tmp2) >= 0 || memcmp(tmp1, tmp2, i) >= 0 || + strncmp(tmp1, tmp2, i + 1) >= 0 || + (int)strlen(tmp1) != i || memchr(tmp1, first_char, i) != tmp1 || + strchr(tmp1, first_char) != tmp1 || + memchr(tmp1, second_char, i) != tmp1 + z || + strchr(tmp1, second_char) != tmp1 + z || + strcmp(tmp5, tmp6) || + strncat(tmp7, tmp1, i + 2) != tmp7 || + strcmp(tmp7, tmp6) || + tmp7[2 * i + z] != second_char) + { + eprintf(__LINE__, tmp1, expected, 0); + printf("x is %d\n", x); + printf("i is %d\n", i); + printf("tmp1 is <%p>\n", tmp1); + printf("tmp5 is <%p> <%s>\n", tmp5, tmp5); + printf("tmp6 is <%p> <%s>\n", tmp6, tmp6); + test_failed = 1; + } + + for (k = 1; k <= align_test_iterations && k <= i; ++k) + { + if (memcmp(tmp3, tmp4, i - k + 1) != 0 || + strncmp(tmp3, tmp4, i - k + 1) != 0) + { + printf("Failure at line %d, comparing %.*s with %.*s\n", + __LINE__, i, tmp3, i, tmp4); + test_failed = 1; + } + tmp4[i - k] = first_char + 1; + if (memcmp(tmp3, tmp4, i) >= 0 || + strncmp(tmp3, tmp4, i) >= 0 || + memcmp(tmp4, tmp3, i) <= 0 || + strncmp(tmp4, tmp3, i) <= 0) + { + printf("Failure at line %d, comparing %.*s with %.*s\n", + __LINE__, i, tmp3, i, tmp4); + test_failed = 1; + } + tmp4[i - k] = first_char; + } + } } - j = ((2 * j) >> 2) << 2; + j = ((2 * j) >> 2) << 2; } - if (test_failed) - abort(); + if (test_failed) + { + abort(); + } - printf("ok\n"); + printf("ok\n"); } diff --git a/tests/host/common/Arduino.cpp b/tests/host/common/Arduino.cpp index 1c651e7e1f..3ca0670ae1 100644 --- a/tests/host/common/Arduino.cpp +++ b/tests/host/common/Arduino.cpp @@ -1,16 +1,16 @@ /* - Arduino.cpp - Mocks for common Arduino APIs - Copyright © 2016 Ivan Grokhotkov - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. + Arduino.cpp - Mocks for common Arduino APIs + Copyright © 2016 Ivan Grokhotkov + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. */ #include @@ -28,7 +28,9 @@ extern "C" unsigned long millis() timeval time; gettimeofday(&time, NULL); if (gtod0.tv_sec == 0) + { memcpy(>od0, &time, sizeof gtod0); + } return ((time.tv_sec - gtod0.tv_sec) * 1000) + ((time.tv_usec - gtod0.tv_usec) / 1000); } @@ -37,7 +39,9 @@ extern "C" unsigned long micros() timeval time; gettimeofday(&time, NULL); if (gtod0.tv_sec == 0) + { memcpy(>od0, &time, sizeof gtod0); + } return ((time.tv_sec - gtod0.tv_sec) * 1000000) + time.tv_usec - gtod0.tv_usec; } @@ -58,7 +62,7 @@ extern "C" bool can_yield() return true; } -extern "C" void optimistic_yield (uint32_t interval_us) +extern "C" void optimistic_yield(uint32_t interval_us) { (void)interval_us; } @@ -75,21 +79,24 @@ extern "C" void esp_yield() { } -extern "C" void esp_delay (unsigned long ms) +extern "C" void esp_delay(unsigned long ms) { usleep(ms * 1000); } -bool esp_try_delay(const uint32_t start_ms, const uint32_t timeout_ms, const uint32_t intvl_ms) { +bool esp_try_delay(const uint32_t start_ms, const uint32_t timeout_ms, const uint32_t intvl_ms) +{ uint32_t expired = millis() - start_ms; - if (expired >= timeout_ms) { + if (expired >= timeout_ms) + { return true; } esp_delay(std::min((timeout_ms - expired), intvl_ms)); return false; } -extern "C" void __panic_func(const char* file, int line, const char* func) { +extern "C" void __panic_func(const char* file, int line, const char* func) +{ (void)file; (void)line; (void)func; diff --git a/tests/host/common/ArduinoCatch.cpp b/tests/host/common/ArduinoCatch.cpp index 6a1e3cca23..1f09607f7b 100644 --- a/tests/host/common/ArduinoCatch.cpp +++ b/tests/host/common/ArduinoCatch.cpp @@ -1,16 +1,16 @@ /* - Arduino.cpp - Mocks for common Arduino APIs - Copyright © 2016 Ivan Grokhotkov - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. + Arduino.cpp - Mocks for common Arduino APIs + Copyright © 2016 Ivan Grokhotkov + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. */ #define CATCH_CONFIG_MAIN diff --git a/tests/host/common/ArduinoMain.cpp b/tests/host/common/ArduinoMain.cpp index ddda929d46..e4c966e29b 100644 --- a/tests/host/common/ArduinoMain.cpp +++ b/tests/host/common/ArduinoMain.cpp @@ -1,32 +1,32 @@ /* - Arduino emulator main loop - Copyright (c) 2018 david gauchard. All rights reserved. - - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the "Software"), - to deal with the Software without restriction, including without limitation - the rights to use, copy, modify, merge, publish, distribute, sublicense, - and/or sell copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following conditions: - - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimers. - - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimers in the - documentation and/or other materials provided with the distribution. - - - The names of its contributors may not be used to endorse or promote - products derived from this Software without specific prior written - permission. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS WITH THE SOFTWARE. + Arduino emulator main loop + Copyright (c) 2018 david gauchard. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal with the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + - The names of its contributors may not be used to endorse or promote + products derived from this Software without specific prior written + permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. */ #include @@ -56,265 +56,287 @@ const char* fspath = nullptr; static struct termios initial_settings; -int mockverbose (const char* fmt, ...) +int mockverbose(const char* fmt, ...) { - va_list ap; - va_start(ap, fmt); - if (mockdebug) - return fprintf(stderr, MOCK) + vfprintf(stderr, fmt, ap); - return 0; + va_list ap; + va_start(ap, fmt); + if (mockdebug) + { + return fprintf(stderr, MOCK) + vfprintf(stderr, fmt, ap); + } + return 0; } static int mock_start_uart(void) { - struct termios settings; - - if (!isatty(STDIN)) - { - perror("setting tty in raw mode: isatty(STDIN)"); - return -1; - } - if (tcgetattr(STDIN, &initial_settings) < 0) - { - perror("setting tty in raw mode: tcgetattr(STDIN)"); - return -1; - } - settings = initial_settings; - settings.c_lflag &= ~(ignore_sigint ? ISIG : 0); - settings.c_lflag &= ~(ECHO | ICANON); - settings.c_iflag &= ~(ICRNL | INLCR | ISTRIP | IXON); - settings.c_oflag |= (ONLCR); - settings.c_cc[VMIN] = 0; - settings.c_cc[VTIME] = 0; - if (tcsetattr(STDIN, TCSANOW, &settings) < 0) - { - perror("setting tty in raw mode: tcsetattr(STDIN)"); - return -1; - } - restore_tty = true; - return 0; + struct termios settings; + + if (!isatty(STDIN)) + { + perror("setting tty in raw mode: isatty(STDIN)"); + return -1; + } + if (tcgetattr(STDIN, &initial_settings) < 0) + { + perror("setting tty in raw mode: tcgetattr(STDIN)"); + return -1; + } + settings = initial_settings; + settings.c_lflag &= ~(ignore_sigint ? ISIG : 0); + settings.c_lflag &= ~(ECHO | ICANON); + settings.c_iflag &= ~(ICRNL | INLCR | ISTRIP | IXON); + settings.c_oflag |= (ONLCR); + settings.c_cc[VMIN] = 0; + settings.c_cc[VTIME] = 0; + if (tcsetattr(STDIN, TCSANOW, &settings) < 0) + { + perror("setting tty in raw mode: tcsetattr(STDIN)"); + return -1; + } + restore_tty = true; + return 0; } static int mock_stop_uart(void) { - if (!restore_tty) return 0; - if (!isatty(STDIN)) { - perror("restoring tty: isatty(STDIN)"); - return -1; - } - if (tcsetattr(STDIN, TCSANOW, &initial_settings) < 0) - { - perror("restoring tty: tcsetattr(STDIN)"); - return -1; - } - printf("\e[?25h"); // show cursor - return (0); + if (!restore_tty) + { + return 0; + } + if (!isatty(STDIN)) + { + perror("restoring tty: isatty(STDIN)"); + return -1; + } + if (tcsetattr(STDIN, TCSANOW, &initial_settings) < 0) + { + perror("restoring tty: tcsetattr(STDIN)"); + return -1; + } + printf("\e[?25h"); // show cursor + return (0); } static uint8_t mock_read_uart(void) { - uint8_t ch = 0; - return (read(STDIN, &ch, 1) == 1) ? ch : 0; + uint8_t ch = 0; + return (read(STDIN, &ch, 1) == 1) ? ch : 0; } -void help (const char* argv0, int exitcode) +void help(const char* argv0, int exitcode) { - printf( - "%s - compiled with esp8266/arduino emulator\n" - "options:\n" - "\t-h\n" - "\tnetwork:\n" - "\t-i - use this interface for IP address\n" - "\t-l - bind tcp/udp servers to interface only (not 0.0.0.0)\n" - "\t-s - port shifter (default: %d, when root: 0)\n" + printf( + "%s - compiled with esp8266/arduino emulator\n" + "options:\n" + "\t-h\n" + "\tnetwork:\n" + "\t-i - use this interface for IP address\n" + "\t-l - bind tcp/udp servers to interface only (not 0.0.0.0)\n" + "\t-s - port shifter (default: %d, when root: 0)\n" "\tterminal:\n" - "\t-b - blocking tty/mocked-uart (default: not blocking tty)\n" - "\t-T - show timestamp on output\n" - "\tFS:\n" - "\t-P - path for fs-persistent files (default: %s-)\n" - "\t-S - spiffs size in KBytes (default: %zd)\n" - "\t-L - littlefs size in KBytes (default: %zd)\n" - "\t (spiffs, littlefs: negative value will force mismatched size)\n" + "\t-b - blocking tty/mocked-uart (default: not blocking tty)\n" + "\t-T - show timestamp on output\n" + "\tFS:\n" + "\t-P - path for fs-persistent files (default: %s-)\n" + "\t-S - spiffs size in KBytes (default: %zd)\n" + "\t-L - littlefs size in KBytes (default: %zd)\n" + "\t (spiffs, littlefs: negative value will force mismatched size)\n" "\tgeneral:\n" - "\t-c - ignore CTRL-C (send it via Serial)\n" - "\t-f - no throttle (possibly 100%%CPU)\n" - "\t-1 - run loop once then exit (for host testing)\n" - "\t-v - verbose\n" - , argv0, MOCK_PORT_SHIFTER, argv0, spiffs_kb, littlefs_kb); - exit(exitcode); + "\t-c - ignore CTRL-C (send it via Serial)\n" + "\t-f - no throttle (possibly 100%%CPU)\n" + "\t-1 - run loop once then exit (for host testing)\n" + "\t-v - verbose\n" + , argv0, MOCK_PORT_SHIFTER, argv0, spiffs_kb, littlefs_kb); + exit(exitcode); } static struct option options[] = { - { "help", no_argument, NULL, 'h' }, - { "fast", no_argument, NULL, 'f' }, - { "local", no_argument, NULL, 'l' }, - { "sigint", no_argument, NULL, 'c' }, - { "blockinguart", no_argument, NULL, 'b' }, - { "verbose", no_argument, NULL, 'v' }, - { "timestamp", no_argument, NULL, 'T' }, - { "interface", required_argument, NULL, 'i' }, - { "fspath", required_argument, NULL, 'P' }, - { "spiffskb", required_argument, NULL, 'S' }, - { "littlefskb", required_argument, NULL, 'L' }, - { "portshifter", required_argument, NULL, 's' }, - { "once", no_argument, NULL, '1' }, + { "help", no_argument, NULL, 'h' }, + { "fast", no_argument, NULL, 'f' }, + { "local", no_argument, NULL, 'l' }, + { "sigint", no_argument, NULL, 'c' }, + { "blockinguart", no_argument, NULL, 'b' }, + { "verbose", no_argument, NULL, 'v' }, + { "timestamp", no_argument, NULL, 'T' }, + { "interface", required_argument, NULL, 'i' }, + { "fspath", required_argument, NULL, 'P' }, + { "spiffskb", required_argument, NULL, 'S' }, + { "littlefskb", required_argument, NULL, 'L' }, + { "portshifter", required_argument, NULL, 's' }, + { "once", no_argument, NULL, '1' }, }; -void cleanup () +void cleanup() { - mock_stop_spiffs(); - mock_stop_littlefs(); - mock_stop_uart(); + mock_stop_spiffs(); + mock_stop_littlefs(); + mock_stop_uart(); } -void make_fs_filename (String& name, const char* fspath, const char* argv0) +void make_fs_filename(String& name, const char* fspath, const char* argv0) { - name.clear(); - if (fspath) - { - int lastSlash = -1; - for (int i = 0; argv0[i]; i++) - if (argv0[i] == '/') - lastSlash = i; - name = fspath; - name += '/'; - name += &argv0[lastSlash + 1]; - } - else - name = argv0; + name.clear(); + if (fspath) + { + int lastSlash = -1; + for (int i = 0; argv0[i]; i++) + if (argv0[i] == '/') + { + lastSlash = i; + } + name = fspath; + name += '/'; + name += &argv0[lastSlash + 1]; + } + else + { + name = argv0; + } } -void control_c (int sig) +void control_c(int sig) { - (void)sig; - - if (user_exit) - { - fprintf(stderr, MOCK "stuck, killing\n"); - cleanup(); - exit(1); - } - user_exit = true; + (void)sig; + + if (user_exit) + { + fprintf(stderr, MOCK "stuck, killing\n"); + cleanup(); + exit(1); + } + user_exit = true; } -int main (int argc, char* const argv []) +int main(int argc, char* const argv []) { - bool fast = false; - blocking_uart = false; // global - - signal(SIGINT, control_c); - signal(SIGTERM, control_c); - if (geteuid() == 0) - mock_port_shifter = 0; - else - mock_port_shifter = MOCK_PORT_SHIFTER; - - for (;;) - { - int n = getopt_long(argc, argv, "hlcfbvTi:S:s:L:P:1", options, NULL); - if (n < 0) - break; - switch (n) - { - case 'h': - help(argv[0], EXIT_SUCCESS); - break; - case 'i': - host_interface = optarg; - break; - case 'l': - global_ipv4_netfmt = NO_GLOBAL_BINDING; - break; - case 's': - mock_port_shifter = atoi(optarg); - break; - case 'c': - ignore_sigint = true; - break; - case 'f': - fast = true; - break; - case 'S': - spiffs_kb = atoi(optarg); - break; - case 'L': - littlefs_kb = atoi(optarg); - break; - case 'P': - fspath = optarg; - break; - case 'b': - blocking_uart = true; - break; - case 'v': - mockdebug = true; - break; - case 'T': - serial_timestamp = true; - break; - case '1': - run_once = true; - break; - default: - help(argv[0], EXIT_FAILURE); - } - } - - mockverbose("server port shifter: %d\n", mock_port_shifter); - - if (spiffs_kb) - { - String name; - make_fs_filename(name, fspath, argv[0]); - name += "-spiffs"; - name += String(spiffs_kb > 0? spiffs_kb: -spiffs_kb, DEC); - name += "KB"; - mock_start_spiffs(name, spiffs_kb); - } - - if (littlefs_kb) - { - String name; - make_fs_filename(name, fspath, argv[0]); - name += "-littlefs"; - name += String(littlefs_kb > 0? littlefs_kb: -littlefs_kb, DEC); - name += "KB"; - mock_start_littlefs(name, littlefs_kb); - } - - // setup global global_ipv4_netfmt - wifi_get_ip_info(0, nullptr); - - if (!blocking_uart) - { - // set stdin to non blocking mode - mock_start_uart(); - } - - // install exit handler in case Esp.restart() is called - atexit(cleanup); - - // first call to millis(): now is millis() and micros() beginning - millis(); - - setup(); - while (!user_exit) - { - uint8_t data = mock_read_uart(); - - if (data) - uart_new_data(UART0, data); - if (!fast) - usleep(1000); // not 100% cpu, ~1000 loops per second - loop(); - loop_end(); - check_incoming_udp(); - - if (run_once) - user_exit = true; - } - cleanup(); - - return 0; + bool fast = false; + blocking_uart = false; // global + + signal(SIGINT, control_c); + signal(SIGTERM, control_c); + if (geteuid() == 0) + { + mock_port_shifter = 0; + } + else + { + mock_port_shifter = MOCK_PORT_SHIFTER; + } + + for (;;) + { + int n = getopt_long(argc, argv, "hlcfbvTi:S:s:L:P:1", options, NULL); + if (n < 0) + { + break; + } + switch (n) + { + case 'h': + help(argv[0], EXIT_SUCCESS); + break; + case 'i': + host_interface = optarg; + break; + case 'l': + global_ipv4_netfmt = NO_GLOBAL_BINDING; + break; + case 's': + mock_port_shifter = atoi(optarg); + break; + case 'c': + ignore_sigint = true; + break; + case 'f': + fast = true; + break; + case 'S': + spiffs_kb = atoi(optarg); + break; + case 'L': + littlefs_kb = atoi(optarg); + break; + case 'P': + fspath = optarg; + break; + case 'b': + blocking_uart = true; + break; + case 'v': + mockdebug = true; + break; + case 'T': + serial_timestamp = true; + break; + case '1': + run_once = true; + break; + default: + help(argv[0], EXIT_FAILURE); + } + } + + mockverbose("server port shifter: %d\n", mock_port_shifter); + + if (spiffs_kb) + { + String name; + make_fs_filename(name, fspath, argv[0]); + name += "-spiffs"; + name += String(spiffs_kb > 0 ? spiffs_kb : -spiffs_kb, DEC); + name += "KB"; + mock_start_spiffs(name, spiffs_kb); + } + + if (littlefs_kb) + { + String name; + make_fs_filename(name, fspath, argv[0]); + name += "-littlefs"; + name += String(littlefs_kb > 0 ? littlefs_kb : -littlefs_kb, DEC); + name += "KB"; + mock_start_littlefs(name, littlefs_kb); + } + + // setup global global_ipv4_netfmt + wifi_get_ip_info(0, nullptr); + + if (!blocking_uart) + { + // set stdin to non blocking mode + mock_start_uart(); + } + + // install exit handler in case Esp.restart() is called + atexit(cleanup); + + // first call to millis(): now is millis() and micros() beginning + millis(); + + setup(); + while (!user_exit) + { + uint8_t data = mock_read_uart(); + + if (data) + { + uart_new_data(UART0, data); + } + if (!fast) + { + usleep(1000); // not 100% cpu, ~1000 loops per second + } + loop(); + loop_end(); + check_incoming_udp(); + + if (run_once) + { + user_exit = true; + } + } + cleanup(); + + return 0; } diff --git a/tests/host/common/ArduinoMainLittlefs.cpp b/tests/host/common/ArduinoMainLittlefs.cpp index bf040a2fc5..36a685e50e 100644 --- a/tests/host/common/ArduinoMainLittlefs.cpp +++ b/tests/host/common/ArduinoMainLittlefs.cpp @@ -3,15 +3,17 @@ LittleFSMock* littlefs_mock = nullptr; -void mock_start_littlefs (const String& fname, size_t size_kb, size_t block_kb, size_t page_b) +void mock_start_littlefs(const String& fname, size_t size_kb, size_t block_kb, size_t page_b) { - littlefs_mock = new LittleFSMock(size_kb * 1024, block_kb * 1024, page_b, fname); + littlefs_mock = new LittleFSMock(size_kb * 1024, block_kb * 1024, page_b, fname); } -void mock_stop_littlefs () +void mock_stop_littlefs() { - if (littlefs_mock) - delete littlefs_mock; - littlefs_mock = nullptr; + if (littlefs_mock) + { + delete littlefs_mock; + } + littlefs_mock = nullptr; } diff --git a/tests/host/common/ArduinoMainSpiffs.cpp b/tests/host/common/ArduinoMainSpiffs.cpp index 1e5099d0ff..27e34baee7 100644 --- a/tests/host/common/ArduinoMainSpiffs.cpp +++ b/tests/host/common/ArduinoMainSpiffs.cpp @@ -3,15 +3,17 @@ SpiffsMock* spiffs_mock = nullptr; -void mock_start_spiffs (const String& fname, size_t size_kb, size_t block_kb, size_t page_b) +void mock_start_spiffs(const String& fname, size_t size_kb, size_t block_kb, size_t page_b) { - spiffs_mock = new SpiffsMock(size_kb * 1024, block_kb * 1024, page_b, fname); + spiffs_mock = new SpiffsMock(size_kb * 1024, block_kb * 1024, page_b, fname); } -void mock_stop_spiffs () +void mock_stop_spiffs() { - if (spiffs_mock) - delete spiffs_mock; - spiffs_mock = nullptr; + if (spiffs_mock) + { + delete spiffs_mock; + } + spiffs_mock = nullptr; } diff --git a/tests/host/common/ArduinoMainUdp.cpp b/tests/host/common/ArduinoMainUdp.cpp index 6c4a034d2a..2c0bb90841 100644 --- a/tests/host/common/ArduinoMainUdp.cpp +++ b/tests/host/common/ArduinoMainUdp.cpp @@ -1,60 +1,64 @@ /* - Arduino emulator main loop - Copyright (c) 2018 david gauchard. All rights reserved. - - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the "Software"), - to deal with the Software without restriction, including without limitation - the rights to use, copy, modify, merge, publish, distribute, sublicense, - and/or sell copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following conditions: - - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimers. - - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimers in the - documentation and/or other materials provided with the distribution. - - - The names of its contributors may not be used to endorse or promote - products derived from this Software without specific prior written - permission. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS WITH THE SOFTWARE. + Arduino emulator main loop + Copyright (c) 2018 david gauchard. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal with the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + - The names of its contributors may not be used to endorse or promote + products derived from this Software without specific prior written + permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. */ #include #include #include -std::map udps; +std::map udps; -void register_udp (int sock, UdpContext* udp) +void register_udp(int sock, UdpContext* udp) { - if (udp) - udps[sock] = udp; - else - udps.erase(sock); + if (udp) + { + udps[sock] = udp; + } + else + { + udps.erase(sock); + } } -void check_incoming_udp () +void check_incoming_udp() { - // check incoming udp - for (auto& udp: udps) - { - pollfd p; - p.fd = udp.first; - p.events = POLLIN; - if (poll(&p, 1, 0) && p.revents == POLLIN) - { - mockverbose("UDP poll(%d) -> cb\r", p.fd); - udp.second->mock_cb(); - } - } + // check incoming udp + for (auto& udp : udps) + { + pollfd p; + p.fd = udp.first; + p.events = POLLIN; + if (poll(&p, 1, 0) && p.revents == POLLIN) + { + mockverbose("UDP poll(%d) -> cb\r", p.fd); + udp.second->mock_cb(); + } + } } diff --git a/tests/host/common/ClientContextSocket.cpp b/tests/host/common/ClientContextSocket.cpp index 2d1d7c6e83..063952ce24 100644 --- a/tests/host/common/ClientContextSocket.cpp +++ b/tests/host/common/ClientContextSocket.cpp @@ -1,33 +1,33 @@ /* - Arduino emulation - socket part of ClientContext - Copyright (c) 2018 david gauchard. All rights reserved. - - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the "Software"), - to deal with the Software without restriction, including without limitation - the rights to use, copy, modify, merge, publish, distribute, sublicense, - and/or sell copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following conditions: - - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimers. - - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimers in the - documentation and/or other materials provided with the distribution. - - - The names of its contributors may not be used to endorse or promote - products derived from this Software without specific prior written - permission. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS WITH THE SOFTWARE. + Arduino emulation - socket part of ClientContext + Copyright (c) 2018 david gauchard. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal with the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + - The names of its contributors may not be used to endorse or promote + products derived from this Software without specific prior written + permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. */ // separated from lwIP to avoid type conflicts @@ -39,168 +39,176 @@ #include #include -int mockSockSetup (int sock) +int mockSockSetup(int sock) { - if (fcntl(sock, F_SETFL, O_NONBLOCK) == -1) - { - perror("socket fcntl(O_NONBLOCK)"); - close(sock); - return -1; - } + if (fcntl(sock, F_SETFL, O_NONBLOCK) == -1) + { + perror("socket fcntl(O_NONBLOCK)"); + close(sock); + return -1; + } #ifndef MSG_NOSIGNAL - int i = 1; - if (setsockopt(sock, SOL_SOCKET, SO_NOSIGPIPE, &i, sizeof i) == -1) - { - perror("sockopt(SO_NOSIGPIPE)(macOS)"); - close(sock); - return -1; - } + int i = 1; + if (setsockopt(sock, SOL_SOCKET, SO_NOSIGPIPE, &i, sizeof i) == -1) + { + perror("sockopt(SO_NOSIGPIPE)(macOS)"); + close(sock); + return -1; + } #endif - return sock; + return sock; } -int mockConnect (uint32_t ipv4, int& sock, int port) +int mockConnect(uint32_t ipv4, int& sock, int port) { - struct sockaddr_in server; - if ((sock = ::socket(AF_INET, SOCK_STREAM, 0)) == -1) - { - perror(MOCK "ClientContext:connect: ::socket()"); - return 0; - } - server.sin_family = AF_INET; - server.sin_port = htons(port); - memcpy(&server.sin_addr, &ipv4, 4); - if (::connect(sock, (struct sockaddr*)&server, sizeof(server)) == -1) - { - perror(MOCK "ClientContext::connect: ::connect()"); - return 0; - } - - return mockSockSetup(sock) == -1? 0: 1; + struct sockaddr_in server; + if ((sock = ::socket(AF_INET, SOCK_STREAM, 0)) == -1) + { + perror(MOCK "ClientContext:connect: ::socket()"); + return 0; + } + server.sin_family = AF_INET; + server.sin_port = htons(port); + memcpy(&server.sin_addr, &ipv4, 4); + if (::connect(sock, (struct sockaddr*)&server, sizeof(server)) == -1) + { + perror(MOCK "ClientContext::connect: ::connect()"); + return 0; + } + + return mockSockSetup(sock) == -1 ? 0 : 1; } -ssize_t mockFillInBuf (int sock, char* ccinbuf, size_t& ccinbufsize) +ssize_t mockFillInBuf(int sock, char* ccinbuf, size_t& ccinbufsize) { - size_t maxread = CCBUFSIZE - ccinbufsize; - ssize_t ret = ::read(sock, ccinbuf + ccinbufsize, maxread); - - if (ret == 0) - { - // connection closed - // nothing is read - return 0; - } - - if (ret == -1) - { - if (errno != EAGAIN) - { - fprintf(stderr, MOCK "ClientContext::(read/peek fd=%i): filling buffer for %zd bytes: %s\n", sock, maxread, strerror(errno)); + size_t maxread = CCBUFSIZE - ccinbufsize; + ssize_t ret = ::read(sock, ccinbuf + ccinbufsize, maxread); + + if (ret == 0) + { + // connection closed + // nothing is read + return 0; + } + + if (ret == -1) + { + if (errno != EAGAIN) + { + fprintf(stderr, MOCK "ClientContext::(read/peek fd=%i): filling buffer for %zd bytes: %s\n", sock, maxread, strerror(errno)); // error - return -1; - } - ret = 0; - } + return -1; + } + ret = 0; + } - ccinbufsize += ret; - return ret; + ccinbufsize += ret; + return ret; } -ssize_t mockPeekBytes (int sock, char* dst, size_t usersize, int timeout_ms, char* ccinbuf, size_t& ccinbufsize) +ssize_t mockPeekBytes(int sock, char* dst, size_t usersize, int timeout_ms, char* ccinbuf, size_t& ccinbufsize) { // usersize==0: peekAvailable() - if (usersize > CCBUFSIZE) - mockverbose("CCBUFSIZE(%d) should be increased by %zd bytes (-> %zd)\n", CCBUFSIZE, usersize - CCBUFSIZE, usersize); - - struct pollfd p; - size_t retsize = 0; - do - { - if (usersize && usersize <= ccinbufsize) - { - // data already buffered - retsize = usersize; - break; - } - - // check incoming data data - if (mockFillInBuf(sock, ccinbuf, ccinbufsize) < 0) - { - return -1; - } + if (usersize > CCBUFSIZE) + { + mockverbose("CCBUFSIZE(%d) should be increased by %zd bytes (-> %zd)\n", CCBUFSIZE, usersize - CCBUFSIZE, usersize); + } + + struct pollfd p; + size_t retsize = 0; + do + { + if (usersize && usersize <= ccinbufsize) + { + // data already buffered + retsize = usersize; + break; + } + + // check incoming data data + if (mockFillInBuf(sock, ccinbuf, ccinbufsize) < 0) + { + return -1; + } if (usersize == 0 && ccinbufsize) // peekAvailable + { return ccinbufsize; + } + + if (usersize <= ccinbufsize) + { + // data just received + retsize = usersize; + break; + } + + // wait for more data until timeout + p.fd = sock; + p.events = POLLIN; + } while (poll(&p, 1, timeout_ms) == 1); - if (usersize <= ccinbufsize) - { - // data just received - retsize = usersize; - break; - } - - // wait for more data until timeout - p.fd = sock; - p.events = POLLIN; - } while (poll(&p, 1, timeout_ms) == 1); - if (dst) { memcpy(dst, ccinbuf, retsize); } - return retsize; + return retsize; } -ssize_t mockRead (int sock, char* dst, size_t size, int timeout_ms, char* ccinbuf, size_t& ccinbufsize) +ssize_t mockRead(int sock, char* dst, size_t size, int timeout_ms, char* ccinbuf, size_t& ccinbufsize) { - ssize_t copied = mockPeekBytes(sock, dst, size, timeout_ms, ccinbuf, ccinbufsize); - if (copied < 0) - return -1; - // swallow (XXX use a circular buffer) - memmove(ccinbuf, ccinbuf + copied, ccinbufsize - copied); - ccinbufsize -= copied; - return copied; + ssize_t copied = mockPeekBytes(sock, dst, size, timeout_ms, ccinbuf, ccinbufsize); + if (copied < 0) + { + return -1; + } + // swallow (XXX use a circular buffer) + memmove(ccinbuf, ccinbuf + copied, ccinbufsize - copied); + ccinbufsize -= copied; + return copied; } - -ssize_t mockWrite (int sock, const uint8_t* data, size_t size, int timeout_ms) + +ssize_t mockWrite(int sock, const uint8_t* data, size_t size, int timeout_ms) { - size_t sent = 0; - while (sent < size) - { - - struct pollfd p; - p.fd = sock; - p.events = POLLOUT; - int ret = poll(&p, 1, timeout_ms); - if (ret == -1) - { - fprintf(stderr, MOCK "ClientContext::write(%d): %s\n", sock, strerror(errno)); - return -1; - } - if (ret) - { + size_t sent = 0; + while (sent < size) + { + + struct pollfd p; + p.fd = sock; + p.events = POLLOUT; + int ret = poll(&p, 1, timeout_ms); + if (ret == -1) + { + fprintf(stderr, MOCK "ClientContext::write(%d): %s\n", sock, strerror(errno)); + return -1; + } + if (ret) + { #ifndef MSG_NOSIGNAL - ret = ::write(sock, data + sent, size - sent); + ret = ::write(sock, data + sent, size - sent); #else - ret = ::send(sock, data + sent, size - sent, MSG_NOSIGNAL); + ret = ::send(sock, data + sent, size - sent, MSG_NOSIGNAL); #endif - if (ret == -1) - { - fprintf(stderr, MOCK "ClientContext::write/send(%d): %s\n", sock, strerror(errno)); - return -1; - } - sent += ret; - if (sent < size) - fprintf(stderr, MOCK "ClientContext::write: sent %d bytes (%zd / %zd)\n", ret, sent, size); - } - } + if (ret == -1) + { + fprintf(stderr, MOCK "ClientContext::write/send(%d): %s\n", sock, strerror(errno)); + return -1; + } + sent += ret; + if (sent < size) + { + fprintf(stderr, MOCK "ClientContext::write: sent %d bytes (%zd / %zd)\n", ret, sent, size); + } + } + } #ifdef DEBUG_ESP_WIFI mockverbose(MOCK "ClientContext::write: total sent %zd bytes\n", sent); #endif - return sent; + return sent; } diff --git a/tests/host/common/ClientContextTools.cpp b/tests/host/common/ClientContextTools.cpp index ccc06b56d9..bf4bc348c0 100644 --- a/tests/host/common/ClientContextTools.cpp +++ b/tests/host/common/ClientContextTools.cpp @@ -1,32 +1,32 @@ /* - Arduino emulation - part of ClientContext - Copyright (c) 2018 david gauchard. All rights reserved. - - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the "Software"), - to deal with the Software without restriction, including without limitation - the rights to use, copy, modify, merge, publish, distribute, sublicense, - and/or sell copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following conditions: - - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimers. - - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimers in the - documentation and/or other materials provided with the distribution. - - - The names of its contributors may not be used to endorse or promote - products derived from this Software without specific prior written - permission. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS WITH THE SOFTWARE. + Arduino emulation - part of ClientContext + Copyright (c) 2018 david gauchard. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal with the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + - The names of its contributors may not be used to endorse or promote + products derived from this Software without specific prior written + permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. */ #include @@ -39,19 +39,21 @@ err_t dns_gethostbyname(const char *hostname, ip_addr_t *addr, dns_found_callback found, void *callback_arg) { - (void)callback_arg; - (void)found; - struct hostent* hbn = gethostbyname(hostname); - if (!hbn) - return ERR_TIMEOUT; - addr->addr = *(uint32_t*)hbn->h_addr_list[0]; - return ERR_OK; + (void)callback_arg; + (void)found; + struct hostent* hbn = gethostbyname(hostname); + if (!hbn) + { + return ERR_TIMEOUT; + } + addr->addr = *(uint32_t*)hbn->h_addr_list[0]; + return ERR_OK; } static struct tcp_pcb mock_tcp_pcb; -tcp_pcb* tcp_new (void) +tcp_pcb* tcp_new(void) { - // this is useless - // ClientContext is setting the source port and we don't care here - return &mock_tcp_pcb; + // this is useless + // ClientContext is setting the source port and we don't care here + return &mock_tcp_pcb; } diff --git a/tests/host/common/EEPROM.h b/tests/host/common/EEPROM.h index a1e47546de..2e91bc10c1 100644 --- a/tests/host/common/EEPROM.h +++ b/tests/host/common/EEPROM.h @@ -1,77 +1,92 @@ /* - Arduino EEPROM emulation - Copyright (c) 2018 david gauchard. All rights reserved. + Arduino EEPROM emulation + Copyright (c) 2018 david gauchard. All rights reserved. - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the "Software"), - to deal with the Software without restriction, including without limitation - the rights to use, copy, modify, merge, publish, distribute, sublicense, - and/or sell copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal with the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimers. + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimers in the - documentation and/or other materials provided with the distribution. + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. - - The names of its contributors may not be used to endorse or promote - products derived from this Software without specific prior written - permission. + - The names of its contributors may not be used to endorse or promote + products derived from this Software without specific prior written + permission. - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS WITH THE SOFTWARE. + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. */ #ifndef EEPROM_MOCK #define EEPROM_MOCK -class EEPROMClass { +class EEPROMClass +{ public: - EEPROMClass(uint32_t sector); - EEPROMClass(void); - ~EEPROMClass(); + EEPROMClass(uint32_t sector); + EEPROMClass(void); + ~EEPROMClass(); - void begin(size_t size); - uint8_t read(int address); - void write(int address, uint8_t val); - bool commit(); - void end(); + void begin(size_t size); + uint8_t read(int address); + void write(int address, uint8_t val); + bool commit(); + void end(); - template - T& get(int const address, T& t) - { - if (address < 0 || address + sizeof(T) > _size) - return t; - for (size_t i = 0; i < sizeof(T); i++) - ((uint8_t*)&t)[i] = read(i); - return t; - } + template + T& get(int const address, T& t) + { + if (address < 0 || address + sizeof(T) > _size) + { + return t; + } + for (size_t i = 0; i < sizeof(T); i++) + { + ((uint8_t*)&t)[i] = read(i); + } + return t; + } - template - const T& put(int const address, const T& t) - { - if (address < 0 || address + sizeof(T) > _size) - return t; - for (size_t i = 0; i < sizeof(T); i++) - write(i, ((uint8_t*)&t)[i]); - return t; - } + template + const T& put(int const address, const T& t) + { + if (address < 0 || address + sizeof(T) > _size) + { + return t; + } + for (size_t i = 0; i < sizeof(T); i++) + { + write(i, ((uint8_t*)&t)[i]); + } + return t; + } - size_t length() { return _size; } + size_t length() + { + return _size; + } - //uint8_t& operator[](int const address) { return read(address); } - uint8_t operator[] (int address) { return read(address); } + //uint8_t& operator[](int const address) { return read(address); } + uint8_t operator[](int address) + { + return read(address); + } protected: - size_t _size = 0; - int _fd = -1; + size_t _size = 0; + int _fd = -1; }; #if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_EEPROM) diff --git a/tests/host/common/HostWiring.cpp b/tests/host/common/HostWiring.cpp index 765d4297b6..e5c84a40a6 100644 --- a/tests/host/common/HostWiring.cpp +++ b/tests/host/common/HostWiring.cpp @@ -1,32 +1,32 @@ /* - Arduino: wire emulation - Copyright (c) 2018 david gauchard. All rights reserved. + Arduino: wire emulation + Copyright (c) 2018 david gauchard. All rights reserved. - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the "Software"), - to deal with the Software without restriction, including without limitation - the rights to use, copy, modify, merge, publish, distribute, sublicense, - and/or sell copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal with the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimers. + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimers in the - documentation and/or other materials provided with the distribution. + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. - - The names of its contributors may not be used to endorse or promote - products derived from this Software without specific prior written - permission. + - The names of its contributors may not be used to endorse or promote + products derived from this Software without specific prior written + permission. - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS WITH THE SOFTWARE. + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. */ #include @@ -37,49 +37,49 @@ #define VERBOSE(x...) mockverbose(x) #endif -void pinMode (uint8_t pin, uint8_t mode) +void pinMode(uint8_t pin, uint8_t mode) { - #define xxx(mode) case mode: m=STRHELPER(mode); break - const char* m; - switch (mode) - { - case INPUT: m="INPUT"; break; - case OUTPUT: m="OUTPUT"; break; - case INPUT_PULLUP: m="INPUT_PULLUP"; break; - case OUTPUT_OPEN_DRAIN: m="OUTPUT_OPEN_DRAIN"; break; - case INPUT_PULLDOWN_16: m="INPUT_PULLDOWN_16"; break; - case WAKEUP_PULLUP: m="WAKEUP_PULLUP"; break; - case WAKEUP_PULLDOWN: m="WAKEUP_PULLDOWN"; break; - default: m="(special)"; - } - VERBOSE("gpio%d: mode='%s'\n", pin, m); +#define xxx(mode) case mode: m=STRHELPER(mode); break + const char* m; + switch (mode) + { + case INPUT: m = "INPUT"; break; + case OUTPUT: m = "OUTPUT"; break; + case INPUT_PULLUP: m = "INPUT_PULLUP"; break; + case OUTPUT_OPEN_DRAIN: m = "OUTPUT_OPEN_DRAIN"; break; + case INPUT_PULLDOWN_16: m = "INPUT_PULLDOWN_16"; break; + case WAKEUP_PULLUP: m = "WAKEUP_PULLUP"; break; + case WAKEUP_PULLDOWN: m = "WAKEUP_PULLDOWN"; break; + default: m = "(special)"; + } + VERBOSE("gpio%d: mode='%s'\n", pin, m); } void digitalWrite(uint8_t pin, uint8_t val) { - VERBOSE("digitalWrite(pin=%d val=%d)\n", pin, val); + VERBOSE("digitalWrite(pin=%d val=%d)\n", pin, val); } void analogWrite(uint8_t pin, int val) { - VERBOSE("analogWrite(pin=%d, val=%d\n", pin, val); + VERBOSE("analogWrite(pin=%d, val=%d\n", pin, val); } int analogRead(uint8_t pin) { - (void)pin; - return 512; + (void)pin; + return 512; } void analogWriteRange(uint32_t range) { - VERBOSE("analogWriteRange(range=%d)\n", range); + VERBOSE("analogWriteRange(range=%d)\n", range); } int digitalRead(uint8_t pin) { - VERBOSE("digitalRead(%d)\n", pin); + VERBOSE("digitalRead(%d)\n", pin); - // pin 0 is most likely a low active input - return pin ? 0 : 1; + // pin 0 is most likely a low active input + return pin ? 0 : 1; } diff --git a/tests/host/common/MockDigital.cpp b/tests/host/common/MockDigital.cpp index aa04527ab5..a94e6f2f20 100644 --- a/tests/host/common/MockDigital.cpp +++ b/tests/host/common/MockDigital.cpp @@ -1,22 +1,22 @@ /* - digital.c - wiring digital implementation for esp8266 + digital.c - wiring digital implementation for esp8266 - Copyright (c) 2015 Hristo Gochkov. All rights reserved. - This file is part of the esp8266 core for Arduino environment. + Copyright (c) 2015 Hristo Gochkov. All rights reserved. + This file is part of the esp8266 core for Arduino environment. - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #define ARDUINO_MAIN #include "wiring_private.h" @@ -30,27 +30,35 @@ extern "C" { -static uint8_t _mode[17]; -static uint8_t _gpio[17]; - -extern void pinMode(uint8_t pin, uint8_t mode) { - if (pin < 17) { - _mode[pin] = mode; - } -} - -extern void digitalWrite(uint8_t pin, uint8_t val) { - if (pin < 17) { - _gpio[pin] = val; - } -} - -extern int digitalRead(uint8_t pin) { - if (pin < 17) { - return _gpio[pin] != 0; - } else { - return 0; - } -} + static uint8_t _mode[17]; + static uint8_t _gpio[17]; + + extern void pinMode(uint8_t pin, uint8_t mode) + { + if (pin < 17) + { + _mode[pin] = mode; + } + } + + extern void digitalWrite(uint8_t pin, uint8_t val) + { + if (pin < 17) + { + _gpio[pin] = val; + } + } + + extern int digitalRead(uint8_t pin) + { + if (pin < 17) + { + return _gpio[pin] != 0; + } + else + { + return 0; + } + } }; diff --git a/tests/host/common/MockEEPROM.cpp b/tests/host/common/MockEEPROM.cpp index 6357c73dd2..a4d7e4ac43 100644 --- a/tests/host/common/MockEEPROM.cpp +++ b/tests/host/common/MockEEPROM.cpp @@ -1,32 +1,32 @@ /* - Arduino emulation - EEPROM - Copyright (c) 2018 david gauchard. All rights reserved. - - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the "Software"), - to deal with the Software without restriction, including without limitation - the rights to use, copy, modify, merge, publish, distribute, sublicense, - and/or sell copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following conditions: - - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimers. - - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimers in the - documentation and/or other materials provided with the distribution. - - - The names of its contributors may not be used to endorse or promote - products derived from this Software without specific prior written - permission. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS WITH THE SOFTWARE. + Arduino emulation - EEPROM + Copyright (c) 2018 david gauchard. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal with the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + - The names of its contributors may not be used to endorse or promote + products derived from this Software without specific prior written + permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. */ #ifndef __EEPROM_H @@ -42,52 +42,62 @@ #define EEPROM_FILE_NAME "eeprom" -EEPROMClass::EEPROMClass () +EEPROMClass::EEPROMClass() { } -EEPROMClass::~EEPROMClass () +EEPROMClass::~EEPROMClass() { - if (_fd >= 0) - close(_fd); + if (_fd >= 0) + { + close(_fd); + } } void EEPROMClass::begin(size_t size) { - _size = size; - if ( (_fd = open(EEPROM_FILE_NAME, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1 - || ftruncate(_fd, size) == -1) - { - fprintf(stderr, MOCK "EEPROM: cannot open/create '%s' for r/w: %s\n\r", EEPROM_FILE_NAME, strerror(errno)); - _fd = -1; - } + _size = size; + if ((_fd = open(EEPROM_FILE_NAME, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1 + || ftruncate(_fd, size) == -1) + { + fprintf(stderr, MOCK "EEPROM: cannot open/create '%s' for r/w: %s\n\r", EEPROM_FILE_NAME, strerror(errno)); + _fd = -1; + } } void EEPROMClass::end() { - if (_fd != -1) - close(_fd); + if (_fd != -1) + { + close(_fd); + } } bool EEPROMClass::commit() { - return true; + return true; } -uint8_t EEPROMClass::read (int x) +uint8_t EEPROMClass::read(int x) { - char c = 0; - if (pread(_fd, &c, 1, x) != 1) - fprintf(stderr, MOCK "eeprom: %s\n\r", strerror(errno)); - return c; + char c = 0; + if (pread(_fd, &c, 1, x) != 1) + { + fprintf(stderr, MOCK "eeprom: %s\n\r", strerror(errno)); + } + return c; } -void EEPROMClass::write (int x, uint8_t c) +void EEPROMClass::write(int x, uint8_t c) { - if (x > (int)_size) - fprintf(stderr, MOCK "### eeprom beyond\r\n"); - else if (pwrite(_fd, &c, 1, x) != 1) - fprintf(stderr, MOCK "eeprom: %s\n\r", strerror(errno)); + if (x > (int)_size) + { + fprintf(stderr, MOCK "### eeprom beyond\r\n"); + } + else if (pwrite(_fd, &c, 1, x) != 1) + { + fprintf(stderr, MOCK "eeprom: %s\n\r", strerror(errno)); + } } #if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_EEPROM) diff --git a/tests/host/common/MockEsp.cpp b/tests/host/common/MockEsp.cpp index d11a39e940..09e6c9d000 100644 --- a/tests/host/common/MockEsp.cpp +++ b/tests/host/common/MockEsp.cpp @@ -1,32 +1,32 @@ /* - Arduino emulation - esp8266's core - Copyright (c) 2018 david gauchard. All rights reserved. - - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the "Software"), - to deal with the Software without restriction, including without limitation - the rights to use, copy, modify, merge, publish, distribute, sublicense, - and/or sell copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following conditions: - - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimers. - - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimers in the - documentation and/or other materials provided with the distribution. - - - The names of its contributors may not be used to endorse or promote - products derived from this Software without specific prior written - permission. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS WITH THE SOFTWARE. + Arduino emulation - esp8266's core + Copyright (c) 2018 david gauchard. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal with the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + - The names of its contributors may not be used to endorse or promote + products derived from this Software without specific prior written + permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. */ #include @@ -36,195 +36,216 @@ #include -unsigned long long operator"" _kHz(unsigned long long x) { +unsigned long long operator"" _kHz(unsigned long long x) +{ return x * 1000; } -unsigned long long operator"" _MHz(unsigned long long x) { +unsigned long long operator"" _MHz(unsigned long long x) +{ return x * 1000 * 1000; } -unsigned long long operator"" _GHz(unsigned long long x) { +unsigned long long operator"" _GHz(unsigned long long x) +{ return x * 1000 * 1000 * 1000; } -unsigned long long operator"" _kBit(unsigned long long x) { +unsigned long long operator"" _kBit(unsigned long long x) +{ return x * 1024; } -unsigned long long operator"" _MBit(unsigned long long x) { +unsigned long long operator"" _MBit(unsigned long long x) +{ return x * 1024 * 1024; } -unsigned long long operator"" _GBit(unsigned long long x) { +unsigned long long operator"" _GBit(unsigned long long x) +{ return x * 1024 * 1024 * 1024; } -unsigned long long operator"" _kB(unsigned long long x) { +unsigned long long operator"" _kB(unsigned long long x) +{ return x * 1024; } -unsigned long long operator"" _MB(unsigned long long x) { +unsigned long long operator"" _MB(unsigned long long x) +{ return x * 1024 * 1024; } -unsigned long long operator"" _GB(unsigned long long x) { +unsigned long long operator"" _GB(unsigned long long x) +{ return x * 1024 * 1024 * 1024; } uint32_t _SPIFFS_start; -void eboot_command_write (struct eboot_command* cmd) +void eboot_command_write(struct eboot_command* cmd) { - (void)cmd; + (void)cmd; } EspClass ESP; -void EspClass::restart () +void EspClass::restart() { - mockverbose("Esp.restart(): exiting\n"); - exit(EXIT_SUCCESS); + mockverbose("Esp.restart(): exiting\n"); + exit(EXIT_SUCCESS); } uint32_t EspClass::getChipId() { - return 0xee1337; + return 0xee1337; } bool EspClass::checkFlashConfig(bool needsEquals) { - (void) needsEquals; - return true; + (void) needsEquals; + return true; } uint32_t EspClass::getSketchSize() { - return 400000; + return 400000; } uint32_t EspClass::getFreeHeap() { - return 30000; + return 30000; } uint32_t EspClass::getMaxFreeBlockSize() { - return 20000; + return 20000; } String EspClass::getResetReason() { - return "Power on"; + return "Power on"; } uint32_t EspClass::getFreeSketchSpace() { - return 4 * 1024 * 1024; + return 4 * 1024 * 1024; } const char *EspClass::getSdkVersion() { - return "2.5.0"; + return "2.5.0"; } uint32_t EspClass::getFlashChipSpeed() { - return 40; + return 40; } -void EspClass::getHeapStats(uint32_t* hfree, uint16_t* hmax, uint8_t* hfrag) { - uint32_t hf = 10 * 1024; - float hm = 1 * 1024; +void EspClass::getHeapStats(uint32_t* hfree, uint16_t* hmax, uint8_t* hfrag) +{ + uint32_t hf = 10 * 1024; + float hm = 1 * 1024; - if (hfree) *hfree = hf; - if (hmax) *hmax = hm; - if (hfrag) *hfrag = 100 - (sqrt(hm) * 100) / hf; + if (hfree) + { + *hfree = hf; + } + if (hmax) + { + *hmax = hm; + } + if (hfrag) + { + *hfrag = 100 - (sqrt(hm) * 100) / hf; + } } bool EspClass::flashEraseSector(uint32_t sector) { - (void) sector; - return true; + (void) sector; + return true; } FlashMode_t EspClass::getFlashChipMode() { - return FM_DOUT; + return FM_DOUT; } FlashMode_t EspClass::magicFlashChipMode(uint8_t byte) { - (void) byte; - return FM_DOUT; + (void) byte; + return FM_DOUT; } bool EspClass::flashWrite(uint32_t offset, const uint32_t *data, size_t size) { - (void)offset; - (void)data; - (void)size; - return true; + (void)offset; + (void)data; + (void)size; + return true; } bool EspClass::flashWrite(uint32_t offset, const uint8_t *data, size_t size) { - (void)offset; - (void)data; - (void)size; - return true; + (void)offset; + (void)data; + (void)size; + return true; } bool EspClass::flashRead(uint32_t offset, uint32_t *data, size_t size) { - (void)offset; - (void)data; - (void)size; - return true; + (void)offset; + (void)data; + (void)size; + return true; } bool EspClass::flashRead(uint32_t offset, uint8_t *data, size_t size) { - (void)offset; - (void)data; - (void)size; - return true; -} - -uint32_t EspClass::magicFlashChipSize(uint8_t byte) { - switch(byte & 0x0F) { - case 0x0: // 4 Mbit (512KB) - return (512_kB); - case 0x1: // 2 MBit (256KB) - return (256_kB); - case 0x2: // 8 MBit (1MB) - return (1_MB); - case 0x3: // 16 MBit (2MB) - return (2_MB); - case 0x4: // 32 MBit (4MB) - return (4_MB); - case 0x8: // 64 MBit (8MB) - return (8_MB); - case 0x9: // 128 MBit (16MB) - return (16_MB); - default: // fail? - return 0; + (void)offset; + (void)data; + (void)size; + return true; +} + +uint32_t EspClass::magicFlashChipSize(uint8_t byte) +{ + switch (byte & 0x0F) + { + case 0x0: // 4 Mbit (512KB) + return (512_kB); + case 0x1: // 2 MBit (256KB) + return (256_kB); + case 0x2: // 8 MBit (1MB) + return (1_MB); + case 0x3: // 16 MBit (2MB) + return (2_MB); + case 0x4: // 32 MBit (4MB) + return (4_MB); + case 0x8: // 64 MBit (8MB) + return (8_MB); + case 0x9: // 128 MBit (16MB) + return (16_MB); + default: // fail? + return 0; } } uint32_t EspClass::getFlashChipRealSize(void) { - return magicFlashChipSize(4); + return magicFlashChipSize(4); } uint32_t EspClass::getFlashChipSize(void) { - return magicFlashChipSize(4); + return magicFlashChipSize(4); } -String EspClass::getFullVersion () +String EspClass::getFullVersion() { - return "emulation-on-host"; + return "emulation-on-host"; } uint32_t EspClass::getFreeContStack() diff --git a/tests/host/common/MockSPI.cpp b/tests/host/common/MockSPI.cpp index 251cad914a..3efef67ac9 100644 --- a/tests/host/common/MockSPI.cpp +++ b/tests/host/common/MockSPI.cpp @@ -1,32 +1,32 @@ /* - Arduino emulation - spi - Copyright (c) 2018 david gauchard. All rights reserved. - - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the "Software"), - to deal with the Software without restriction, including without limitation - the rights to use, copy, modify, merge, publish, distribute, sublicense, - and/or sell copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following conditions: - - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimers. - - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimers in the - documentation and/or other materials provided with the distribution. - - - The names of its contributors may not be used to endorse or promote - products derived from this Software without specific prior written - permission. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS WITH THE SOFTWARE. + Arduino emulation - spi + Copyright (c) 2018 david gauchard. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal with the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + - The names of its contributors may not be used to endorse or promote + products derived from this Software without specific prior written + permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. */ #include @@ -35,13 +35,13 @@ SPIClass SPI; #endif -SPIClass::SPIClass () +SPIClass::SPIClass() { } uint8_t SPIClass::transfer(uint8_t data) { - return data; + return data; } void SPIClass::begin() @@ -54,10 +54,10 @@ void SPIClass::end() void SPIClass::setFrequency(uint32_t freq) { - (void)freq; + (void)freq; } void SPIClass::setHwCs(bool use) { - (void)use; + (void)use; } diff --git a/tests/host/common/MockTools.cpp b/tests/host/common/MockTools.cpp index 5eb7969de7..a41b7521bc 100644 --- a/tests/host/common/MockTools.cpp +++ b/tests/host/common/MockTools.cpp @@ -1,32 +1,32 @@ /* - Arduino emulation - tools - Copyright (c) 2018 david gauchard. All rights reserved. - - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the "Software"), - to deal with the Software without restriction, including without limitation - the rights to use, copy, modify, merge, publish, distribute, sublicense, - and/or sell copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following conditions: - - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimers. - - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimers in the - documentation and/or other materials provided with the distribution. - - - The names of its contributors may not be used to endorse or promote - products derived from this Software without specific prior written - permission. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS WITH THE SOFTWARE. + Arduino emulation - tools + Copyright (c) 2018 david gauchard. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal with the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + - The names of its contributors may not be used to endorse or promote + products derived from this Software without specific prior written + permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. */ #include @@ -35,46 +35,82 @@ extern "C" { -uint32_t lwip_htonl (uint32_t hostlong) { return htonl(hostlong); } -uint16_t lwip_htons (uint16_t hostshort) { return htons(hostshort); } -uint32_t lwip_ntohl (uint32_t netlong) { return ntohl(netlong); } -uint16_t lwip_ntohs (uint16_t netshort) { return ntohs(netshort); } - -char* ets_strcpy (char* d, const char* s) { return strcpy(d, s); } -char* ets_strncpy (char* d, const char* s, size_t n) { return strncpy(d, s, n); } -size_t ets_strlen (const char* s) { return strlen(s); } - -int ets_printf (const char* fmt, ...) -{ + uint32_t lwip_htonl(uint32_t hostlong) + { + return htonl(hostlong); + } + uint16_t lwip_htons(uint16_t hostshort) + { + return htons(hostshort); + } + uint32_t lwip_ntohl(uint32_t netlong) + { + return ntohl(netlong); + } + uint16_t lwip_ntohs(uint16_t netshort) + { + return ntohs(netshort); + } + + char* ets_strcpy(char* d, const char* s) + { + return strcpy(d, s); + } + char* ets_strncpy(char* d, const char* s, size_t n) + { + return strncpy(d, s, n); + } + size_t ets_strlen(const char* s) + { + return strlen(s); + } + + int ets_printf(const char* fmt, ...) + { va_list ap; va_start(ap, fmt); - int len = vprintf(fmt, ap); - va_end(ap); - return len; -} - -void stack_thunk_add_ref() { } -void stack_thunk_del_ref() { } -void stack_thunk_repaint() { } - -uint32_t stack_thunk_get_refcnt() { return 0; } -uint32_t stack_thunk_get_stack_top() { return 0; } -uint32_t stack_thunk_get_stack_bot() { return 0; } -uint32_t stack_thunk_get_cont_sp() { return 0; } -uint32_t stack_thunk_get_max_usage() { return 0; } -void stack_thunk_dump_stack() { } - -// Thunking macro + int len = vprintf(fmt, ap); + va_end(ap); + return len; + } + + void stack_thunk_add_ref() { } + void stack_thunk_del_ref() { } + void stack_thunk_repaint() { } + + uint32_t stack_thunk_get_refcnt() + { + return 0; + } + uint32_t stack_thunk_get_stack_top() + { + return 0; + } + uint32_t stack_thunk_get_stack_bot() + { + return 0; + } + uint32_t stack_thunk_get_cont_sp() + { + return 0; + } + uint32_t stack_thunk_get_max_usage() + { + return 0; + } + void stack_thunk_dump_stack() { } + + // Thunking macro #define make_stack_thunk(fcnToThunk) }; void configTime(int timezone, int daylightOffset_sec, - const char* server1, const char* server2, const char* server3) + const char* server1, const char* server2, const char* server3) { - (void)server1; - (void)server2; - (void)server3; + (void)server1; + (void)server2; + (void)server3; - mockverbose("configTime: TODO (tz=%dH offset=%dS) (time will be host's)\n", timezone, daylightOffset_sec); + mockverbose("configTime: TODO (tz=%dH offset=%dS) (time will be host's)\n", timezone, daylightOffset_sec); } diff --git a/tests/host/common/MockUART.cpp b/tests/host/common/MockUART.cpp index dc6514ae40..19d234cbb9 100644 --- a/tests/host/common/MockUART.cpp +++ b/tests/host/common/MockUART.cpp @@ -1,32 +1,32 @@ /* - MockUART.cpp - esp8266 UART HAL EMULATION + MockUART.cpp - esp8266 UART HAL EMULATION - Copyright (c) 2019 Clemens Kirchgatterer. All rights reserved. - This file is part of the esp8266 core for Arduino environment. + Copyright (c) 2019 Clemens Kirchgatterer. All rights reserved. + This file is part of the esp8266 core for Arduino environment. - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ /* - This UART driver is directly derived from the ESP8266 UART HAL driver - Copyright (c) 2014 Ivan Grokhotkov. It provides the same API as the - original driver and was striped from all HW dependent interfaces. + This UART driver is directly derived from the ESP8266 UART HAL driver + Copyright (c) 2014 Ivan Grokhotkov. It provides the same API as the + original driver and was striped from all HW dependent interfaces. - UART0 writes got to stdout, while UART1 writes got to stderr. The user - is responsible for feeding the RX FIFO new data by calling uart_new_data(). - */ + UART0 writes got to stdout, while UART1 writes got to stderr. The user + is responsible for feeding the RX FIFO new data by calling uart_new_data(). +*/ #include // write #include // gettimeofday @@ -39,464 +39,526 @@ extern "C" { -bool blocking_uart = true; // system default + bool blocking_uart = true; // system default -static int s_uart_debug_nr = UART1; + static int s_uart_debug_nr = UART1; -static uart_t *UART[2] = { NULL, NULL }; + static uart_t *UART[2] = { NULL, NULL }; -struct uart_rx_buffer_ -{ - size_t size; - size_t rpos; - size_t wpos; - uint8_t * buffer; -}; - -struct uart_ -{ - int uart_nr; - int baud_rate; - bool rx_enabled; - bool tx_enabled; - bool rx_overrun; - struct uart_rx_buffer_ * rx_buffer; -}; - -bool serial_timestamp = false; + struct uart_rx_buffer_ + { + size_t size; + size_t rpos; + size_t wpos; + uint8_t * buffer; + }; -// write one byte to the emulated UART -static void -uart_do_write_char(const int uart_nr, char c) -{ - static bool w = false; - - if (uart_nr >= UART0 && uart_nr <= UART1) - { - if (serial_timestamp && (c == '\n' || c == '\r')) - { - if (w) - { - FILE* out = uart_nr == UART0? stdout: stderr; - timeval tv; - gettimeofday(&tv, nullptr); - const tm* tm = localtime(&tv.tv_sec); - fprintf(out, "\r\n%d:%02d:%02d.%06d: ", tm->tm_hour, tm->tm_min, tm->tm_sec, (int)tv.tv_usec); - fflush(out); - w = false; - } - } - else - { + struct uart_ + { + int uart_nr; + int baud_rate; + bool rx_enabled; + bool tx_enabled; + bool rx_overrun; + struct uart_rx_buffer_ * rx_buffer; + }; + + bool serial_timestamp = false; + + // write one byte to the emulated UART + static void + uart_do_write_char(const int uart_nr, char c) + { + static bool w = false; + + if (uart_nr >= UART0 && uart_nr <= UART1) + { + if (serial_timestamp && (c == '\n' || c == '\r')) + { + if (w) + { + FILE* out = uart_nr == UART0 ? stdout : stderr; + timeval tv; + gettimeofday(&tv, nullptr); + const tm* tm = localtime(&tv.tv_sec); + fprintf(out, "\r\n%d:%02d:%02d.%06d: ", tm->tm_hour, tm->tm_min, tm->tm_sec, (int)tv.tv_usec); + fflush(out); + w = false; + } + } + else + { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-result" - write(uart_nr + 1, &c, 1); + write(uart_nr + 1, &c, 1); #pragma GCC diagnostic pop - w = true; - } - } -} + w = true; + } + } + } -// write a new byte into the RX FIFO buffer -static void -uart_handle_data(uart_t* uart, uint8_t data) -{ - struct uart_rx_buffer_ *rx_buffer = uart->rx_buffer; + // write a new byte into the RX FIFO buffer + static void + uart_handle_data(uart_t* uart, uint8_t data) + { + struct uart_rx_buffer_ *rx_buffer = uart->rx_buffer; - size_t nextPos = (rx_buffer->wpos + 1) % rx_buffer->size; - if(nextPos == rx_buffer->rpos) - { - uart->rx_overrun = true; + size_t nextPos = (rx_buffer->wpos + 1) % rx_buffer->size; + if (nextPos == rx_buffer->rpos) + { + uart->rx_overrun = true; #ifdef UART_DISCARD_NEWEST - return; + return; #else - if (++rx_buffer->rpos == rx_buffer->size) - rx_buffer->rpos = 0; + if (++rx_buffer->rpos == rx_buffer->size) + { + rx_buffer->rpos = 0; + } #endif - } - rx_buffer->buffer[rx_buffer->wpos] = data; - rx_buffer->wpos = nextPos; -} + } + rx_buffer->buffer[rx_buffer->wpos] = data; + rx_buffer->wpos = nextPos; + } -// insert a new byte into the RX FIFO nuffer -void -uart_new_data(const int uart_nr, uint8_t data) -{ - uart_t* uart = UART[uart_nr]; + // insert a new byte into the RX FIFO nuffer + void + uart_new_data(const int uart_nr, uint8_t data) + { + uart_t* uart = UART[uart_nr]; - if(uart == NULL || !uart->rx_enabled) { - return; - } + if (uart == NULL || !uart->rx_enabled) + { + return; + } - uart_handle_data(uart, data); -} + uart_handle_data(uart, data); + } -static size_t -uart_rx_available_unsafe(const struct uart_rx_buffer_ * rx_buffer) -{ - size_t ret = rx_buffer->wpos - rx_buffer->rpos; + static size_t + uart_rx_available_unsafe(const struct uart_rx_buffer_ * rx_buffer) + { + size_t ret = rx_buffer->wpos - rx_buffer->rpos; - if(rx_buffer->wpos < rx_buffer->rpos) - ret = (rx_buffer->wpos + rx_buffer->size) - rx_buffer->rpos; + if (rx_buffer->wpos < rx_buffer->rpos) + { + ret = (rx_buffer->wpos + rx_buffer->size) - rx_buffer->rpos; + } - return ret; -} + return ret; + } -// taking data straight from fifo, only needed in uart_resize_rx_buffer() -static int -uart_read_char_unsafe(uart_t* uart) -{ - if (uart_rx_available_unsafe(uart->rx_buffer)) - { - // take oldest sw data - int ret = uart->rx_buffer->buffer[uart->rx_buffer->rpos]; - uart->rx_buffer->rpos = (uart->rx_buffer->rpos + 1) % uart->rx_buffer->size; - return ret; - } - // unavailable - return -1; -} + // taking data straight from fifo, only needed in uart_resize_rx_buffer() + static int + uart_read_char_unsafe(uart_t* uart) + { + if (uart_rx_available_unsafe(uart->rx_buffer)) + { + // take oldest sw data + int ret = uart->rx_buffer->buffer[uart->rx_buffer->rpos]; + uart->rx_buffer->rpos = (uart->rx_buffer->rpos + 1) % uart->rx_buffer->size; + return ret; + } + // unavailable + return -1; + } -/**********************************************************/ -/************ UART API FUNCTIONS **************************/ -/**********************************************************/ + /**********************************************************/ + /************ UART API FUNCTIONS **************************/ + /**********************************************************/ -size_t -uart_rx_available(uart_t* uart) -{ - if(uart == NULL || !uart->rx_enabled) - return 0; + size_t + uart_rx_available(uart_t* uart) + { + if (uart == NULL || !uart->rx_enabled) + { + return 0; + } - return uart_rx_available_unsafe(uart->rx_buffer); -} + return uart_rx_available_unsafe(uart->rx_buffer); + } -int -uart_peek_char(uart_t* uart) -{ - if(uart == NULL || !uart->rx_enabled) - return -1; + int + uart_peek_char(uart_t* uart) + { + if (uart == NULL || !uart->rx_enabled) + { + return -1; + } - if (!uart_rx_available_unsafe(uart->rx_buffer)) - return -1; + if (!uart_rx_available_unsafe(uart->rx_buffer)) + { + return -1; + } - return uart->rx_buffer->buffer[uart->rx_buffer->rpos]; -} + return uart->rx_buffer->buffer[uart->rx_buffer->rpos]; + } -int -uart_read_char(uart_t* uart) -{ - uint8_t ret; - return uart_read(uart, (char*)&ret, 1) ? ret : -1; -} + int + uart_read_char(uart_t* uart) + { + uint8_t ret; + return uart_read(uart, (char*)&ret, 1) ? ret : -1; + } -size_t -uart_read(uart_t* uart, char* userbuffer, size_t usersize) -{ - if(uart == NULL || !uart->rx_enabled) - return 0; - - if (!blocking_uart) - { - char c; - if (read(0, &c, 1) == 1) - uart_new_data(0, c); - } - - size_t ret = 0; - while (ret < usersize && uart_rx_available_unsafe(uart->rx_buffer)) - { - // pour sw buffer to user's buffer - // get largest linear length from sw buffer - size_t chunk = uart->rx_buffer->rpos < uart->rx_buffer->wpos ? - uart->rx_buffer->wpos - uart->rx_buffer->rpos : - uart->rx_buffer->size - uart->rx_buffer->rpos; - if (ret + chunk > usersize) - chunk = usersize - ret; - memcpy(userbuffer + ret, uart->rx_buffer->buffer + uart->rx_buffer->rpos, chunk); - uart->rx_buffer->rpos = (uart->rx_buffer->rpos + chunk) % uart->rx_buffer->size; - ret += chunk; - } - return ret; -} + size_t + uart_read(uart_t* uart, char* userbuffer, size_t usersize) + { + if (uart == NULL || !uart->rx_enabled) + { + return 0; + } + + if (!blocking_uart) + { + char c; + if (read(0, &c, 1) == 1) + { + uart_new_data(0, c); + } + } + + size_t ret = 0; + while (ret < usersize && uart_rx_available_unsafe(uart->rx_buffer)) + { + // pour sw buffer to user's buffer + // get largest linear length from sw buffer + size_t chunk = uart->rx_buffer->rpos < uart->rx_buffer->wpos ? + uart->rx_buffer->wpos - uart->rx_buffer->rpos : + uart->rx_buffer->size - uart->rx_buffer->rpos; + if (ret + chunk > usersize) + { + chunk = usersize - ret; + } + memcpy(userbuffer + ret, uart->rx_buffer->buffer + uart->rx_buffer->rpos, chunk); + uart->rx_buffer->rpos = (uart->rx_buffer->rpos + chunk) % uart->rx_buffer->size; + ret += chunk; + } + return ret; + } -size_t -uart_resize_rx_buffer(uart_t* uart, size_t new_size) -{ - if(uart == NULL || !uart->rx_enabled) - return 0; - - if(uart->rx_buffer->size == new_size) - return uart->rx_buffer->size; - - uint8_t * new_buf = (uint8_t*)malloc(new_size); - if(!new_buf) - return uart->rx_buffer->size; - - size_t new_wpos = 0; - // if uart_rx_available_unsafe() returns non-0, uart_read_char_unsafe() can't return -1 - while(uart_rx_available_unsafe(uart->rx_buffer) && new_wpos < new_size) - new_buf[new_wpos++] = uart_read_char_unsafe(uart); - if (new_wpos == new_size) - new_wpos = 0; - - uint8_t * old_buf = uart->rx_buffer->buffer; - uart->rx_buffer->rpos = 0; - uart->rx_buffer->wpos = new_wpos; - uart->rx_buffer->size = new_size; - uart->rx_buffer->buffer = new_buf; - free(old_buf); - return uart->rx_buffer->size; -} + size_t + uart_resize_rx_buffer(uart_t* uart, size_t new_size) + { + if (uart == NULL || !uart->rx_enabled) + { + return 0; + } + + if (uart->rx_buffer->size == new_size) + { + return uart->rx_buffer->size; + } + + uint8_t * new_buf = (uint8_t*)malloc(new_size); + if (!new_buf) + { + return uart->rx_buffer->size; + } + + size_t new_wpos = 0; + // if uart_rx_available_unsafe() returns non-0, uart_read_char_unsafe() can't return -1 + while (uart_rx_available_unsafe(uart->rx_buffer) && new_wpos < new_size) + { + new_buf[new_wpos++] = uart_read_char_unsafe(uart); + } + if (new_wpos == new_size) + { + new_wpos = 0; + } + + uint8_t * old_buf = uart->rx_buffer->buffer; + uart->rx_buffer->rpos = 0; + uart->rx_buffer->wpos = new_wpos; + uart->rx_buffer->size = new_size; + uart->rx_buffer->buffer = new_buf; + free(old_buf); + return uart->rx_buffer->size; + } -size_t -uart_get_rx_buffer_size(uart_t* uart) -{ - return uart && uart->rx_enabled ? uart->rx_buffer->size : 0; -} + size_t + uart_get_rx_buffer_size(uart_t* uart) + { + return uart && uart->rx_enabled ? uart->rx_buffer->size : 0; + } -size_t -uart_write_char(uart_t* uart, char c) -{ - if(uart == NULL || !uart->tx_enabled) - return 0; + size_t + uart_write_char(uart_t* uart, char c) + { + if (uart == NULL || !uart->tx_enabled) + { + return 0; + } - uart_do_write_char(uart->uart_nr, c); + uart_do_write_char(uart->uart_nr, c); - return 1; -} + return 1; + } -size_t -uart_write(uart_t* uart, const char* buf, size_t size) -{ - if(uart == NULL || !uart->tx_enabled) - return 0; + size_t + uart_write(uart_t* uart, const char* buf, size_t size) + { + if (uart == NULL || !uart->tx_enabled) + { + return 0; + } + + size_t ret = size; + const int uart_nr = uart->uart_nr; + while (size--) + { + uart_do_write_char(uart_nr, *buf++); + } + + return ret; + } - size_t ret = size; - const int uart_nr = uart->uart_nr; - while (size--) - uart_do_write_char(uart_nr, *buf++); + size_t + uart_tx_free(uart_t* uart) + { + if (uart == NULL || !uart->tx_enabled) + { + return 0; + } - return ret; -} + return UART_TX_FIFO_SIZE; + } -size_t -uart_tx_free(uart_t* uart) -{ - if(uart == NULL || !uart->tx_enabled) - return 0; + void + uart_wait_tx_empty(uart_t* uart) + { + (void) uart; + } - return UART_TX_FIFO_SIZE; -} + void + uart_flush(uart_t* uart) + { + if (uart == NULL) + { + return; + } + + if (uart->rx_enabled) + { + uart->rx_buffer->rpos = 0; + uart->rx_buffer->wpos = 0; + } + } -void -uart_wait_tx_empty(uart_t* uart) -{ - (void) uart; -} + void + uart_set_baudrate(uart_t* uart, int baud_rate) + { + if (uart == NULL) + { + return; + } -void -uart_flush(uart_t* uart) -{ - if(uart == NULL) - return; - - if(uart->rx_enabled) - { - uart->rx_buffer->rpos = 0; - uart->rx_buffer->wpos = 0; - } -} + uart->baud_rate = baud_rate; + } -void -uart_set_baudrate(uart_t* uart, int baud_rate) -{ - if(uart == NULL) - return; + int + uart_get_baudrate(uart_t* uart) + { + if (uart == NULL) + { + return 0; + } - uart->baud_rate = baud_rate; -} + return uart->baud_rate; + } -int -uart_get_baudrate(uart_t* uart) -{ - if(uart == NULL) - return 0; + uint8_t + uart_get_bit_length(const int uart_nr) + { + uint8_t width = ((uart_nr % 16) >> 2) + 5; + uint8_t parity = (uart_nr >> 5) + 1; + uint8_t stop = uart_nr % 4; + return (width + parity + stop + 1); + } - return uart->baud_rate; -} + uart_t* + uart_init(int uart_nr, int baudrate, int config, int mode, int tx_pin, size_t rx_size, bool invert) + { + (void) config; + (void) tx_pin; + (void) invert; + uart_t* uart = (uart_t*) malloc(sizeof(uart_t)); + if (uart == NULL) + { + return NULL; + } + + uart->uart_nr = uart_nr; + uart->rx_overrun = false; + + switch (uart->uart_nr) + { + case UART0: + uart->rx_enabled = (mode != UART_TX_ONLY); + uart->tx_enabled = (mode != UART_RX_ONLY); + if (uart->rx_enabled) + { + struct uart_rx_buffer_ * rx_buffer = (struct uart_rx_buffer_ *)malloc(sizeof(struct uart_rx_buffer_)); + if (rx_buffer == NULL) + { + free(uart); + return NULL; + } + rx_buffer->size = rx_size;//var this + rx_buffer->rpos = 0; + rx_buffer->wpos = 0; + rx_buffer->buffer = (uint8_t *)malloc(rx_buffer->size); + if (rx_buffer->buffer == NULL) + { + free(rx_buffer); + free(uart); + return NULL; + } + uart->rx_buffer = rx_buffer; + } + break; + + case UART1: + // Note: uart_interrupt_handler does not support RX on UART 1. + uart->rx_enabled = false; + uart->tx_enabled = (mode != UART_RX_ONLY); + break; + + case UART_NO: + default: + // big fail! + free(uart); + return NULL; + } + + uart_set_baudrate(uart, baudrate); + + UART[uart_nr] = uart; + + return uart; + } -uint8_t -uart_get_bit_length(const int uart_nr) -{ - uint8_t width = ((uart_nr % 16) >> 2) + 5; - uint8_t parity = (uart_nr >> 5) + 1; - uint8_t stop = uart_nr % 4; - return (width + parity + stop + 1); -} + void + uart_uninit(uart_t* uart) + { + if (uart == NULL) + { + return; + } + + if (uart->rx_enabled) + { + free(uart->rx_buffer->buffer); + free(uart->rx_buffer); + } + free(uart); + } -uart_t* -uart_init(int uart_nr, int baudrate, int config, int mode, int tx_pin, size_t rx_size, bool invert) -{ - (void) config; - (void) tx_pin; - (void) invert; - uart_t* uart = (uart_t*) malloc(sizeof(uart_t)); - if(uart == NULL) - return NULL; - - uart->uart_nr = uart_nr; - uart->rx_overrun = false; - - switch(uart->uart_nr) - { - case UART0: - uart->rx_enabled = (mode != UART_TX_ONLY); - uart->tx_enabled = (mode != UART_RX_ONLY); - if(uart->rx_enabled) - { - struct uart_rx_buffer_ * rx_buffer = (struct uart_rx_buffer_ *)malloc(sizeof(struct uart_rx_buffer_)); - if(rx_buffer == NULL) - { - free(uart); - return NULL; - } - rx_buffer->size = rx_size;//var this - rx_buffer->rpos = 0; - rx_buffer->wpos = 0; - rx_buffer->buffer = (uint8_t *)malloc(rx_buffer->size); - if(rx_buffer->buffer == NULL) - { - free(rx_buffer); - free(uart); - return NULL; - } - uart->rx_buffer = rx_buffer; - } - break; - - case UART1: - // Note: uart_interrupt_handler does not support RX on UART 1. - uart->rx_enabled = false; - uart->tx_enabled = (mode != UART_RX_ONLY); - break; - - case UART_NO: - default: - // big fail! - free(uart); - return NULL; - } - - uart_set_baudrate(uart, baudrate); - - UART[uart_nr] = uart; - - return uart; -} + bool + uart_swap(uart_t* uart, int tx_pin) + { + (void) uart; + (void) tx_pin; + return true; + } -void -uart_uninit(uart_t* uart) -{ - if(uart == NULL) - return; - - if(uart->rx_enabled) { - free(uart->rx_buffer->buffer); - free(uart->rx_buffer); - } - free(uart); -} + bool + uart_set_tx(uart_t* uart, int tx_pin) + { + (void) uart; + (void) tx_pin; + return true; + } -bool -uart_swap(uart_t* uart, int tx_pin) -{ - (void) uart; - (void) tx_pin; - return true; -} + bool + uart_set_pins(uart_t* uart, int tx, int rx) + { + (void) uart; + (void) tx; + (void) rx; + return true; + } -bool -uart_set_tx(uart_t* uart, int tx_pin) -{ - (void) uart; - (void) tx_pin; - return true; -} + bool + uart_tx_enabled(uart_t* uart) + { + if (uart == NULL) + { + return false; + } -bool -uart_set_pins(uart_t* uart, int tx, int rx) -{ - (void) uart; - (void) tx; - (void) rx; - return true; -} + return uart->tx_enabled; + } -bool -uart_tx_enabled(uart_t* uart) -{ - if(uart == NULL) - return false; + bool + uart_rx_enabled(uart_t* uart) + { + if (uart == NULL) + { + return false; + } - return uart->tx_enabled; -} + return uart->rx_enabled; + } -bool -uart_rx_enabled(uart_t* uart) -{ - if(uart == NULL) - return false; + bool + uart_has_overrun(uart_t* uart) + { + if (uart == NULL || !uart->rx_overrun) + { + return false; + } + + // clear flag + uart->rx_overrun = false; + return true; + } - return uart->rx_enabled; -} + bool + uart_has_rx_error(uart_t* uart) + { + (void) uart; + return false; + } -bool -uart_has_overrun(uart_t* uart) -{ - if(uart == NULL || !uart->rx_overrun) - return false; + void + uart_set_debug(int uart_nr) + { + (void)uart_nr; + } - // clear flag - uart->rx_overrun = false; - return true; -} + int + uart_get_debug() + { + return s_uart_debug_nr; + } -bool -uart_has_rx_error(uart_t* uart) -{ - (void) uart; - return false; -} + void + uart_start_detect_baudrate(int uart_nr) + { + (void) uart_nr; + } -void -uart_set_debug(int uart_nr) -{ - (void)uart_nr; -} + int + uart_detect_baudrate(int uart_nr) + { + (void) uart_nr; + return 115200; + } -int -uart_get_debug() +}; + + +size_t uart_peek_available(uart_t* uart) { - return s_uart_debug_nr; + return 0; } - -void -uart_start_detect_baudrate(int uart_nr) +const char* uart_peek_buffer(uart_t* uart) { - (void) uart_nr; + return nullptr; } - -int -uart_detect_baudrate(int uart_nr) +void uart_peek_consume(uart_t* uart, size_t consume) { - (void) uart_nr; - return 115200; + (void)uart; + (void)consume; } -}; - - -size_t uart_peek_available (uart_t* uart) { return 0; } -const char* uart_peek_buffer (uart_t* uart) { return nullptr; } -void uart_peek_consume (uart_t* uart, size_t consume) { (void)uart; (void)consume; } - diff --git a/tests/host/common/MockWiFiServer.cpp b/tests/host/common/MockWiFiServer.cpp index dba66362d3..3c74927af0 100644 --- a/tests/host/common/MockWiFiServer.cpp +++ b/tests/host/common/MockWiFiServer.cpp @@ -1,32 +1,32 @@ /* - Arduino emulation - WiFiServer - Copyright (c) 2018 david gauchard. All rights reserved. - - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the "Software"), - to deal with the Software without restriction, including without limitation - the rights to use, copy, modify, merge, publish, distribute, sublicense, - and/or sell copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following conditions: - - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimers. - - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimers in the - documentation and/or other materials provided with the distribution. - - - The names of its contributors may not be used to endorse or promote - products derived from this Software without specific prior written - permission. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS WITH THE SOFTWARE. + Arduino emulation - WiFiServer + Copyright (c) 2018 david gauchard. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal with the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + - The names of its contributors may not be used to endorse or promote + products derived from this Software without specific prior written + permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. */ #include @@ -44,28 +44,30 @@ extern "C" const ip_addr_t ip_addr_any = IPADDR4_INIT(IPADDR_ANY); // lwIP API side of WiFiServer -WiFiServer::WiFiServer (const IPAddress& addr, uint16_t port) +WiFiServer::WiFiServer(const IPAddress& addr, uint16_t port) { - (void)addr; - _port = port; + (void)addr; + _port = port; } -WiFiServer::WiFiServer (uint16_t port) +WiFiServer::WiFiServer(uint16_t port) { - _port = port; + _port = port; } -WiFiClient WiFiServer::available (uint8_t* status) +WiFiClient WiFiServer::available(uint8_t* status) { - (void)status; - return accept(); + (void)status; + return accept(); } -WiFiClient WiFiServer::accept () +WiFiClient WiFiServer::accept() { - if (hasClient()) - return WiFiClient(new ClientContext(serverAccept(pcb2int(_listen_pcb)))); - return WiFiClient(); + if (hasClient()) + { + return WiFiClient(new ClientContext(serverAccept(pcb2int(_listen_pcb)))); + } + return WiFiClient(); } // static declaration diff --git a/tests/host/common/MockWiFiServerSocket.cpp b/tests/host/common/MockWiFiServerSocket.cpp index 9ab344bf50..3eff34bfff 100644 --- a/tests/host/common/MockWiFiServerSocket.cpp +++ b/tests/host/common/MockWiFiServerSocket.cpp @@ -1,32 +1,32 @@ /* - Arduino emulation - WiFiServer socket side - Copyright (c) 2018 david gauchard. All rights reserved. - - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the "Software"), - to deal with the Software without restriction, including without limitation - the rights to use, copy, modify, merge, publish, distribute, sublicense, - and/or sell copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following conditions: - - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimers. - - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimers in the - documentation and/or other materials provided with the distribution. - - - The names of its contributors may not be used to endorse or promote - products derived from this Software without specific prior written - permission. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS WITH THE SOFTWARE. + Arduino emulation - WiFiServer socket side + Copyright (c) 2018 david gauchard. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal with the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + - The names of its contributors may not be used to endorse or promote + products derived from this Software without specific prior written + permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. */ #include @@ -44,102 +44,108 @@ // host socket internal side of WiFiServer -int serverAccept (int srvsock) +int serverAccept(int srvsock) { - int clisock; - socklen_t n; - struct sockaddr_in client; - n = sizeof(client); - if ((clisock = accept(srvsock, (struct sockaddr*)&client, &n)) == -1) - { - perror(MOCK "accept()"); - exit(EXIT_FAILURE); - } - return mockSockSetup(clisock); + int clisock; + socklen_t n; + struct sockaddr_in client; + n = sizeof(client); + if ((clisock = accept(srvsock, (struct sockaddr*)&client, &n)) == -1) + { + perror(MOCK "accept()"); + exit(EXIT_FAILURE); + } + return mockSockSetup(clisock); } -void WiFiServer::begin (uint16_t port) +void WiFiServer::begin(uint16_t port) { return begin(port, !0); } -void WiFiServer::begin (uint16_t port, uint8_t backlog) +void WiFiServer::begin(uint16_t port, uint8_t backlog) { if (!backlog) + { return; + } _port = port; return begin(); } -void WiFiServer::begin () +void WiFiServer::begin() { - int sock; - int mockport; - struct sockaddr_in server; - - mockport = _port; - if (mockport < 1024 && mock_port_shifter) - { - mockport += mock_port_shifter; - fprintf(stderr, MOCK "=====> WiFiServer port: %d shifted to %d (use option -s) <=====\n", _port, mockport); - } - else - fprintf(stderr, MOCK "=====> WiFiServer port: %d <=====\n", mockport); - - if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) - { - perror(MOCK "socket()"); - exit(EXIT_FAILURE); - } - - int optval = 1; - if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval)) == -1) - { - perror(MOCK "reuseport"); - exit(EXIT_FAILURE); - } - - server.sin_family = AF_INET; - server.sin_port = htons(mockport); - server.sin_addr.s_addr = htonl(global_source_address); - if (bind(sock, (struct sockaddr*)&server, sizeof(server)) == -1) - { - perror(MOCK "bind()"); - exit(EXIT_FAILURE); - } - - if (listen(sock, 1) == -1) - { - perror(MOCK "listen()"); - exit(EXIT_FAILURE); - } - - - // store int into pointer - _listen_pcb = int2pcb(sock); + int sock; + int mockport; + struct sockaddr_in server; + + mockport = _port; + if (mockport < 1024 && mock_port_shifter) + { + mockport += mock_port_shifter; + fprintf(stderr, MOCK "=====> WiFiServer port: %d shifted to %d (use option -s) <=====\n", _port, mockport); + } + else + { + fprintf(stderr, MOCK "=====> WiFiServer port: %d <=====\n", mockport); + } + + if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) + { + perror(MOCK "socket()"); + exit(EXIT_FAILURE); + } + + int optval = 1; + if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval)) == -1) + { + perror(MOCK "reuseport"); + exit(EXIT_FAILURE); + } + + server.sin_family = AF_INET; + server.sin_port = htons(mockport); + server.sin_addr.s_addr = htonl(global_source_address); + if (bind(sock, (struct sockaddr*)&server, sizeof(server)) == -1) + { + perror(MOCK "bind()"); + exit(EXIT_FAILURE); + } + + if (listen(sock, 1) == -1) + { + perror(MOCK "listen()"); + exit(EXIT_FAILURE); + } + + + // store int into pointer + _listen_pcb = int2pcb(sock); } -bool WiFiServer::hasClient () +bool WiFiServer::hasClient() { - struct pollfd p; - p.fd = pcb2int(_listen_pcb); - p.events = POLLIN; - return poll(&p, 1, 0) && p.revents == POLLIN; + struct pollfd p; + p.fd = pcb2int(_listen_pcb); + p.events = POLLIN; + return poll(&p, 1, 0) && p.revents == POLLIN; } -void WiFiServer::close () +void WiFiServer::close() { - if (pcb2int(_listen_pcb) >= 0) - ::close(pcb2int(_listen_pcb)); - _listen_pcb = int2pcb(-1); + if (pcb2int(_listen_pcb) >= 0) + { + ::close(pcb2int(_listen_pcb)); + } + _listen_pcb = int2pcb(-1); } -void WiFiServer::stop () +void WiFiServer::stop() { close(); } -size_t WiFiServer::hasClientData () +size_t WiFiServer::hasClientData() { // Trivial Mocking: // There is no waiting list of clients in this trivial mocking code, @@ -149,7 +155,7 @@ size_t WiFiServer::hasClientData () return 0; } -bool WiFiServer::hasMaxPendingClients () +bool WiFiServer::hasMaxPendingClients() { // Mocking code does not consider the waiting client list, // so it will return ::hasClient() here meaning: diff --git a/tests/host/common/MocklwIP.cpp b/tests/host/common/MocklwIP.cpp index 1e19f20fc7..0b98243217 100644 --- a/tests/host/common/MocklwIP.cpp +++ b/tests/host/common/MocklwIP.cpp @@ -8,57 +8,57 @@ esp8266::AddressListImplementation::AddressList addrList; extern "C" { -extern netif netif0; - -netif* netif_list = &netif0; - -err_t dhcp_renew(struct netif *netif) -{ - (void)netif; - return ERR_OK; -} - -void sntp_setserver(u8_t, const ip_addr_t) -{ -} - -const ip_addr_t* sntp_getserver(u8_t) -{ - return IP_ADDR_ANY; -} - -err_t etharp_request(struct netif *netif, const ip4_addr_t *ipaddr) -{ - (void)netif; - (void)ipaddr; - return ERR_OK; -} - -err_t igmp_start(struct netif* netif) -{ - (void)netif; - return ERR_OK; -} - -err_t igmp_joingroup_netif(struct netif *netif, const ip4_addr_t *groupaddr) -{ - (void)netif; - (void)groupaddr; - return ERR_OK; -} - -err_t igmp_leavegroup_netif(struct netif *netif, const ip4_addr_t *groupaddr) -{ - (void)netif; - (void)groupaddr; - return ERR_OK; -} - -struct netif* netif_get_by_index(u8_t idx) -{ - (void)idx; - return &netif0; -} + extern netif netif0; + + netif* netif_list = &netif0; + + err_t dhcp_renew(struct netif *netif) + { + (void)netif; + return ERR_OK; + } + + void sntp_setserver(u8_t, const ip_addr_t) + { + } + + const ip_addr_t* sntp_getserver(u8_t) + { + return IP_ADDR_ANY; + } + + err_t etharp_request(struct netif *netif, const ip4_addr_t *ipaddr) + { + (void)netif; + (void)ipaddr; + return ERR_OK; + } + + err_t igmp_start(struct netif* netif) + { + (void)netif; + return ERR_OK; + } + + err_t igmp_joingroup_netif(struct netif *netif, const ip4_addr_t *groupaddr) + { + (void)netif; + (void)groupaddr; + return ERR_OK; + } + + err_t igmp_leavegroup_netif(struct netif *netif, const ip4_addr_t *groupaddr) + { + (void)netif; + (void)groupaddr; + return ERR_OK; + } + + struct netif* netif_get_by_index(u8_t idx) + { + (void)idx; + return &netif0; + } } // extern "C" diff --git a/tests/host/common/MocklwIP.h b/tests/host/common/MocklwIP.h index e7fead4cb7..47c3d06c6e 100644 --- a/tests/host/common/MocklwIP.h +++ b/tests/host/common/MocklwIP.h @@ -8,7 +8,7 @@ extern "C" #include #include -extern netif netif0; + extern netif netif0; } // extern "C" diff --git a/tests/host/common/UdpContextSocket.cpp b/tests/host/common/UdpContextSocket.cpp index 4212bb0ee4..23f2883c11 100644 --- a/tests/host/common/UdpContextSocket.cpp +++ b/tests/host/common/UdpContextSocket.cpp @@ -1,32 +1,32 @@ /* - Arduino emulation - UdpContext emulation - socket part - Copyright (c) 2018 david gauchard. All rights reserved. - - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the "Software"), - to deal with the Software without restriction, including without limitation - the rights to use, copy, modify, merge, publish, distribute, sublicense, - and/or sell copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following conditions: - - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimers. - - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimers in the - documentation and/or other materials provided with the distribution. - - - The names of its contributors may not be used to endorse or promote - products derived from this Software without specific prior written - permission. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS WITH THE SOFTWARE. + Arduino emulation - UdpContext emulation - socket part + Copyright (c) 2018 david gauchard. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal with the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + - The names of its contributors may not be used to endorse or promote + products derived from this Software without specific prior written + permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. */ #include @@ -39,176 +39,198 @@ #include #include -int mockUDPSocket () +int mockUDPSocket() { - int s; - if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1 || fcntl(s, F_SETFL, O_NONBLOCK) == -1) - { - fprintf(stderr, MOCK "UDP socket: %s", strerror(errno)); - exit(EXIT_FAILURE); - } - return s; + int s; + if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1 || fcntl(s, F_SETFL, O_NONBLOCK) == -1) + { + fprintf(stderr, MOCK "UDP socket: %s", strerror(errno)); + exit(EXIT_FAILURE); + } + return s; } -bool mockUDPListen (int sock, uint32_t dstaddr, uint16_t port, uint32_t mcast) +bool mockUDPListen(int sock, uint32_t dstaddr, uint16_t port, uint32_t mcast) { - int optval; - int mockport; - - mockport = port; - if (mockport < 1024 && mock_port_shifter) - { - mockport += mock_port_shifter; - fprintf(stderr, MOCK "=====> UdpServer port: %d shifted to %d (use option -s) <=====\n", port, mockport); - } - else - fprintf(stderr, MOCK "=====> UdpServer port: %d <=====\n", mockport); - - optval = 1; - if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval)) == -1) - fprintf(stderr, MOCK "SO_REUSEPORT failed\n"); - optval = 1; - if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) == -1) - fprintf(stderr, MOCK "SO_REUSEADDR failed\n"); - - struct sockaddr_in servaddr; - memset(&servaddr, 0, sizeof(servaddr)); - - // Filling server information - servaddr.sin_family = AF_INET; - (void) dstaddr; - //servaddr.sin_addr.s_addr = htonl(global_source_address); - servaddr.sin_addr.s_addr = htonl(INADDR_ANY); - servaddr.sin_port = htons(mockport); - - // Bind the socket with the server address - if (bind(sock, (const struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) - { - fprintf(stderr, MOCK "UDP bind on port %d failed: %s\n", mockport, strerror(errno)); - return false; - } - else - mockverbose("UDP server on port %d (sock=%d)\n", mockport, sock); - - if (!mcast) - mcast = inet_addr("224.0.0.1"); // all hosts group - if (mcast) - { - // https://web.cs.wpi.edu/~claypool/courses/4514-B99/samples/multicast.c - // https://stackoverflow.com/questions/12681097/c-choose-interface-for-udp-multicast-socket - - struct ip_mreq mreq; - mreq.imr_multiaddr.s_addr = mcast; - //mreq.imr_interface.s_addr = htonl(global_source_address); - mreq.imr_interface.s_addr = htonl(INADDR_ANY); - - if (host_interface) - { + int optval; + int mockport; + + mockport = port; + if (mockport < 1024 && mock_port_shifter) + { + mockport += mock_port_shifter; + fprintf(stderr, MOCK "=====> UdpServer port: %d shifted to %d (use option -s) <=====\n", port, mockport); + } + else + { + fprintf(stderr, MOCK "=====> UdpServer port: %d <=====\n", mockport); + } + + optval = 1; + if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval)) == -1) + { + fprintf(stderr, MOCK "SO_REUSEPORT failed\n"); + } + optval = 1; + if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) == -1) + { + fprintf(stderr, MOCK "SO_REUSEADDR failed\n"); + } + + struct sockaddr_in servaddr; + memset(&servaddr, 0, sizeof(servaddr)); + + // Filling server information + servaddr.sin_family = AF_INET; + (void) dstaddr; + //servaddr.sin_addr.s_addr = htonl(global_source_address); + servaddr.sin_addr.s_addr = htonl(INADDR_ANY); + servaddr.sin_port = htons(mockport); + + // Bind the socket with the server address + if (bind(sock, (const struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) + { + fprintf(stderr, MOCK "UDP bind on port %d failed: %s\n", mockport, strerror(errno)); + return false; + } + else + { + mockverbose("UDP server on port %d (sock=%d)\n", mockport, sock); + } + + if (!mcast) + { + mcast = inet_addr("224.0.0.1"); // all hosts group + } + if (mcast) + { + // https://web.cs.wpi.edu/~claypool/courses/4514-B99/samples/multicast.c + // https://stackoverflow.com/questions/12681097/c-choose-interface-for-udp-multicast-socket + + struct ip_mreq mreq; + mreq.imr_multiaddr.s_addr = mcast; + //mreq.imr_interface.s_addr = htonl(global_source_address); + mreq.imr_interface.s_addr = htonl(INADDR_ANY); + + if (host_interface) + { #if __APPLE__ - int idx = if_nametoindex(host_interface); - if (setsockopt(sock, IPPROTO_TCP, IP_BOUND_IF, &idx, sizeof(idx)) == -1) + int idx = if_nametoindex(host_interface); + if (setsockopt(sock, IPPROTO_TCP, IP_BOUND_IF, &idx, sizeof(idx)) == -1) #else - if (setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, host_interface, strlen(host_interface)) == -1) + if (setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, host_interface, strlen(host_interface)) == -1) #endif - fprintf(stderr, MOCK "UDP multicast: can't setup bind/output on interface %s: %s\n", host_interface, strerror(errno)); - if (setsockopt(sock, IPPROTO_IP, IP_MULTICAST_IF, &mreq.imr_interface, sizeof(struct in_addr)) == -1) - fprintf(stderr, MOCK "UDP multicast: can't setup bind/input on interface %s: %s\n", host_interface, strerror(errno)); - } - - if (setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) - { - fprintf(stderr, MOCK "can't join multicast group addr %08x\n", (int)mcast); - return false; - } - else - mockverbose("joined multicast group addr %08lx\n", (long)ntohl(mcast)); - } - - return true; + fprintf(stderr, MOCK "UDP multicast: can't setup bind/output on interface %s: %s\n", host_interface, strerror(errno)); + if (setsockopt(sock, IPPROTO_IP, IP_MULTICAST_IF, &mreq.imr_interface, sizeof(struct in_addr)) == -1) + { + fprintf(stderr, MOCK "UDP multicast: can't setup bind/input on interface %s: %s\n", host_interface, strerror(errno)); + } + } + + if (setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) + { + fprintf(stderr, MOCK "can't join multicast group addr %08x\n", (int)mcast); + return false; + } + else + { + mockverbose("joined multicast group addr %08lx\n", (long)ntohl(mcast)); + } + } + + return true; } -size_t mockUDPFillInBuf (int sock, char* ccinbuf, size_t& ccinbufsize, uint8_t& addrsize, uint8_t addr[16], uint16_t& port) +size_t mockUDPFillInBuf(int sock, char* ccinbuf, size_t& ccinbufsize, uint8_t& addrsize, uint8_t addr[16], uint16_t& port) { - struct sockaddr_storage addrbuf; - socklen_t addrbufsize = std::min((socklen_t)sizeof(addrbuf), (socklen_t)16); - - size_t maxread = CCBUFSIZE - ccinbufsize; - ssize_t ret = ::recvfrom(sock, ccinbuf + ccinbufsize, maxread, 0/*flags*/, (sockaddr*)&addrbuf, &addrbufsize); - if (ret == -1) - { - if (errno != EAGAIN) - fprintf(stderr, MOCK "UDPContext::(read/peek): filling buffer for %zd bytes: %s\n", maxread, strerror(errno)); - ret = 0; - } - - if (ret > 0) - { - port = ntohs(((sockaddr_in*)&addrbuf)->sin_port); - if (addrbuf.ss_family == AF_INET) - memcpy(&addr[0], &(((sockaddr_in*)&addrbuf)->sin_addr.s_addr), addrsize = 4); - else - { - fprintf(stderr, MOCK "TODO UDP+IPv6\n"); - exit(EXIT_FAILURE); - } - } - - return ccinbufsize += ret; + struct sockaddr_storage addrbuf; + socklen_t addrbufsize = std::min((socklen_t)sizeof(addrbuf), (socklen_t)16); + + size_t maxread = CCBUFSIZE - ccinbufsize; + ssize_t ret = ::recvfrom(sock, ccinbuf + ccinbufsize, maxread, 0/*flags*/, (sockaddr*)&addrbuf, &addrbufsize); + if (ret == -1) + { + if (errno != EAGAIN) + { + fprintf(stderr, MOCK "UDPContext::(read/peek): filling buffer for %zd bytes: %s\n", maxread, strerror(errno)); + } + ret = 0; + } + + if (ret > 0) + { + port = ntohs(((sockaddr_in*)&addrbuf)->sin_port); + if (addrbuf.ss_family == AF_INET) + { + memcpy(&addr[0], &(((sockaddr_in*)&addrbuf)->sin_addr.s_addr), addrsize = 4); + } + else + { + fprintf(stderr, MOCK "TODO UDP+IPv6\n"); + exit(EXIT_FAILURE); + } + } + + return ccinbufsize += ret; } -size_t mockUDPPeekBytes (int sock, char* dst, size_t usersize, int timeout_ms, char* ccinbuf, size_t& ccinbufsize) +size_t mockUDPPeekBytes(int sock, char* dst, size_t usersize, int timeout_ms, char* ccinbuf, size_t& ccinbufsize) { - (void) sock; - (void) timeout_ms; - if (usersize > CCBUFSIZE) - fprintf(stderr, MOCK "CCBUFSIZE(%d) should be increased by %zd bytes (-> %zd)\n", CCBUFSIZE, usersize - CCBUFSIZE, usersize); - - size_t retsize = 0; - if (ccinbufsize) - { - // data already buffered - retsize = usersize; - if (retsize > ccinbufsize) - retsize = ccinbufsize; - } - memcpy(dst, ccinbuf, retsize); - return retsize; + (void) sock; + (void) timeout_ms; + if (usersize > CCBUFSIZE) + { + fprintf(stderr, MOCK "CCBUFSIZE(%d) should be increased by %zd bytes (-> %zd)\n", CCBUFSIZE, usersize - CCBUFSIZE, usersize); + } + + size_t retsize = 0; + if (ccinbufsize) + { + // data already buffered + retsize = usersize; + if (retsize > ccinbufsize) + { + retsize = ccinbufsize; + } + } + memcpy(dst, ccinbuf, retsize); + return retsize; } -void mockUDPSwallow (size_t copied, char* ccinbuf, size_t& ccinbufsize) +void mockUDPSwallow(size_t copied, char* ccinbuf, size_t& ccinbufsize) { - // poor man buffer - memmove(ccinbuf, ccinbuf + copied, ccinbufsize - copied); - ccinbufsize -= copied; + // poor man buffer + memmove(ccinbuf, ccinbuf + copied, ccinbufsize - copied); + ccinbufsize -= copied; } -size_t mockUDPRead (int sock, char* dst, size_t size, int timeout_ms, char* ccinbuf, size_t& ccinbufsize) +size_t mockUDPRead(int sock, char* dst, size_t size, int timeout_ms, char* ccinbuf, size_t& ccinbufsize) { - size_t copied = mockUDPPeekBytes(sock, dst, size, timeout_ms, ccinbuf, ccinbufsize); - mockUDPSwallow(copied, ccinbuf, ccinbufsize); - return copied; + size_t copied = mockUDPPeekBytes(sock, dst, size, timeout_ms, ccinbuf, ccinbufsize); + mockUDPSwallow(copied, ccinbuf, ccinbufsize); + return copied; } -size_t mockUDPWrite (int sock, const uint8_t* data, size_t size, int timeout_ms, uint32_t ipv4, uint16_t port) +size_t mockUDPWrite(int sock, const uint8_t* data, size_t size, int timeout_ms, uint32_t ipv4, uint16_t port) { - (void) timeout_ms; - // Filling server information - struct sockaddr_in peer; - peer.sin_family = AF_INET; - peer.sin_addr.s_addr = ipv4; //XXFIXME should use lwip_htonl? - peer.sin_port = htons(port); - int ret = ::sendto(sock, data, size, 0/*flags*/, (const sockaddr*)&peer, sizeof(peer)); - if (ret == -1) - { - fprintf(stderr, MOCK "UDPContext::write: write(%d): %s\n", sock, strerror(errno)); - return 0; - } - if (ret != (int)size) - { - fprintf(stderr, MOCK "UDPContext::write: short write (%d < %zd) (TODO)\n", ret, size); - exit(EXIT_FAILURE); - } - - return ret; + (void) timeout_ms; + // Filling server information + struct sockaddr_in peer; + peer.sin_family = AF_INET; + peer.sin_addr.s_addr = ipv4; //XXFIXME should use lwip_htonl? + peer.sin_port = htons(port); + int ret = ::sendto(sock, data, size, 0/*flags*/, (const sockaddr*)&peer, sizeof(peer)); + if (ret == -1) + { + fprintf(stderr, MOCK "UDPContext::write: write(%d): %s\n", sock, strerror(errno)); + return 0; + } + if (ret != (int)size) + { + fprintf(stderr, MOCK "UDPContext::write: short write (%d < %zd) (TODO)\n", ret, size); + exit(EXIT_FAILURE); + } + + return ret; } diff --git a/tests/host/common/WMath.cpp b/tests/host/common/WMath.cpp index 4fdf07fa2e..8409941db4 100644 --- a/tests/host/common/WMath.cpp +++ b/tests/host/common/WMath.cpp @@ -1,62 +1,71 @@ /* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* - Part of the Wiring project - http://wiring.org.co - Copyright (c) 2004-06 Hernando Barragan - Modified 13 August 2006, David A. Mellis for Arduino - http://www.arduino.cc/ - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General - Public License along with this library; if not, write to the - Free Software Foundation, Inc., 59 Temple Place, Suite 330, - Boston, MA 02111-1307 USA - - $Id$ - */ + Part of the Wiring project - http://wiring.org.co + Copyright (c) 2004-06 Hernando Barragan + Modified 13 August 2006, David A. Mellis for Arduino - http://www.arduino.cc/ + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA + + $Id$ +*/ extern "C" { #include #include } -void randomSeed(unsigned long seed) { - if(seed != 0) { +void randomSeed(unsigned long seed) +{ + if (seed != 0) + { srand(seed); } } -long random(long howbig) { - if(howbig == 0) { +long random(long howbig) +{ + if (howbig == 0) + { return 0; } return (rand()) % howbig; } -long random(long howsmall, long howbig) { - if(howsmall >= howbig) { +long random(long howsmall, long howbig) +{ + if (howsmall >= howbig) + { return howsmall; } long diff = howbig - howsmall; return random(diff) + howsmall; } -long map(long x, long in_min, long in_max, long out_min, long out_max) { +long map(long x, long in_min, long in_max, long out_min, long out_max) +{ return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } -uint16_t makeWord(unsigned int w) { +uint16_t makeWord(unsigned int w) +{ return w; } -uint16_t makeWord(unsigned char h, unsigned char l) { +uint16_t makeWord(unsigned char h, unsigned char l) +{ return (h << 8) | l; } diff --git a/tests/host/common/c_types.h b/tests/host/common/c_types.h index a4c784c7fb..c57b64dd91 100644 --- a/tests/host/common/c_types.h +++ b/tests/host/common/c_types.h @@ -6,28 +6,28 @@ // diff -u common/c_types.h ../../tools/sdk/include/c_types.h /* - * ESPRESSIF MIT License - * - * Copyright (c) 2016 - * - * Permission is hereby granted for use on ESPRESSIF SYSTEMS ESP8266 only, in which case, - * it is free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the Software is furnished - * to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or - * substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ + ESPRESSIF MIT License + + Copyright (c) 2016 + + Permission is hereby granted for use on ESPRESSIF SYSTEMS ESP8266 only, in which case, + it is free of charge, to any person obtaining a copy of this software and associated + documentation files (the "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the Software is furnished + to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all copies or + substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +*/ #ifndef _C_TYPES_H_ #define _C_TYPES_H_ @@ -74,7 +74,8 @@ typedef double real64; #endif /* NULL */ /* probably should not put STATUS here */ -typedef enum { +typedef enum +{ OK = 0, FAIL, PENDING, diff --git a/tests/host/common/flash_hal_mock.cpp b/tests/host/common/flash_hal_mock.cpp index 5304d7553a..10b9dba023 100644 --- a/tests/host/common/flash_hal_mock.cpp +++ b/tests/host/common/flash_hal_mock.cpp @@ -12,24 +12,29 @@ extern "C" uint8_t* s_phys_data = nullptr; } -int32_t flash_hal_read(uint32_t addr, uint32_t size, uint8_t *dst) { +int32_t flash_hal_read(uint32_t addr, uint32_t size, uint8_t *dst) +{ memcpy(dst, s_phys_data + addr, size); return 0; } -int32_t flash_hal_write(uint32_t addr, uint32_t size, const uint8_t *src) { +int32_t flash_hal_write(uint32_t addr, uint32_t size, const uint8_t *src) +{ memcpy(s_phys_data + addr, src, size); return 0; } -int32_t flash_hal_erase(uint32_t addr, uint32_t size) { +int32_t flash_hal_erase(uint32_t addr, uint32_t size) +{ if ((size & (FLASH_SECTOR_SIZE - 1)) != 0 || - (addr & (FLASH_SECTOR_SIZE - 1)) != 0) { + (addr & (FLASH_SECTOR_SIZE - 1)) != 0) + { abort(); } const uint32_t sector = addr / FLASH_SECTOR_SIZE; const uint32_t sectorCount = size / FLASH_SECTOR_SIZE; - for (uint32_t i = 0; i < sectorCount; ++i) { + for (uint32_t i = 0; i < sectorCount; ++i) + { memset(s_phys_data + (sector + i) * FLASH_SECTOR_SIZE, 0xff, FLASH_SECTOR_SIZE); } return 0; diff --git a/tests/host/common/include/ClientContext.h b/tests/host/common/include/ClientContext.h index bd9c9b80a5..0c06c889ff 100644 --- a/tests/host/common/include/ClientContext.h +++ b/tests/host/common/include/ClientContext.h @@ -1,23 +1,23 @@ /* - ClientContext.h - emulation of TCP connection handling on top of lwIP + ClientContext.h - emulation of TCP connection handling on top of lwIP - Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. - This file is part of the esp8266 core for Arduino environment. + Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. + This file is part of the esp8266 core for Arduino environment. - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ #ifndef CLIENTCONTEXT_H #define CLIENTCONTEXT_H @@ -26,7 +26,7 @@ class WiFiClient; #include -bool getDefaultPrivateGlobalSyncValue (); +bool getDefaultPrivateGlobalSyncValue(); typedef void (*discard_cb_t)(void*, ClientContext*); @@ -39,19 +39,19 @@ class ClientContext { (void)pcb; } - - ClientContext (int sock) : + + ClientContext(int sock) : _discard_cb(nullptr), _discard_cb_arg(nullptr), _refcnt(0), _next(nullptr), _sync(::getDefaultPrivateGlobalSyncValue()), _sock(sock) { } - + err_t abort() { if (_sock >= 0) { ::close(_sock); - mockverbose("socket %d closed\n", _sock); + mockverbose("socket %d closed\n", _sock); } _sock = -1; return ERR_ABRT; @@ -88,11 +88,14 @@ class ClientContext void unref() { DEBUGV(":ur %d\r\n", _refcnt); - if(--_refcnt == 0) { + if (--_refcnt == 0) + { discard_received(); close(); if (_discard_cb) - _discard_cb(_discard_cb_arg, this); + { + _discard_cb(_discard_cb_arg, this); + } DEBUGV(":del\r\n"); delete this; } @@ -157,9 +160,13 @@ class ClientContext size_t getSize() { if (_sock < 0) + { return 0; + } if (_inbufsize) + { return _inbufsize; + } ssize_t ret = mockFillInBuf(_sock, _inbuf, _inbufsize); if (ret < 0) { @@ -172,10 +179,10 @@ class ClientContext int read() { char c; - return read(&c, 1)? (unsigned char)c: -1; + return read(&c, 1) ? (unsigned char)c : -1; } - size_t read (char* dst, size_t size) + size_t read(char* dst, size_t size) { ssize_t ret = mockRead(_sock, dst, size, 0, _inbuf, _inbufsize); if (ret < 0) @@ -189,7 +196,7 @@ class ClientContext int peek() { char c; - return peekBytes(&c, 1)? c: -1; + return peekBytes(&c, 1) ? c : -1; } size_t peekBytes(char *dst, size_t size) @@ -216,22 +223,22 @@ class ClientContext uint8_t state() { - (void)getSize(); // read on socket to force detect closed peer - return _sock >= 0? ESTABLISHED: CLOSED; + (void)getSize(); // read on socket to force detect closed peer + return _sock >= 0 ? ESTABLISHED : CLOSED; } size_t write(const char* data, size_t size) { - ssize_t ret = mockWrite(_sock, (const uint8_t*)data, size, _timeout_ms); - if (ret < 0) - { - abort(); - return 0; - } - return ret; + ssize_t ret = mockWrite(_sock, (const uint8_t*)data, size, _timeout_ms); + if (ret < 0) + { + abort(); + return 0; + } + return ret; } - void keepAlive (uint16_t idle_sec = TCP_DEFAULT_KEEPALIVE_IDLE_SEC, uint16_t intv_sec = TCP_DEFAULT_KEEPALIVE_INTERVAL_SEC, uint8_t count = TCP_DEFAULT_KEEPALIVE_COUNT) + void keepAlive(uint16_t idle_sec = TCP_DEFAULT_KEEPALIVE_IDLE_SEC, uint16_t intv_sec = TCP_DEFAULT_KEEPALIVE_INTERVAL_SEC, uint8_t count = TCP_DEFAULT_KEEPALIVE_COUNT) { (void) idle_sec; (void) intv_sec; @@ -239,37 +246,37 @@ class ClientContext mockverbose("TODO ClientContext::keepAlive()\n"); } - bool isKeepAliveEnabled () const + bool isKeepAliveEnabled() const { mockverbose("TODO ClientContext::isKeepAliveEnabled()\n"); return false; } - uint16_t getKeepAliveIdle () const + uint16_t getKeepAliveIdle() const { mockverbose("TODO ClientContext::getKeepAliveIdle()\n"); return 0; } - uint16_t getKeepAliveInterval () const + uint16_t getKeepAliveInterval() const { mockverbose("TODO ClientContext::getKeepAliveInternal()\n"); return 0; } - uint8_t getKeepAliveCount () const + uint8_t getKeepAliveCount() const { mockverbose("TODO ClientContext::getKeepAliveCount()\n"); return 0; } - bool getSync () const + bool getSync() const { mockverbose("TODO ClientContext::getSync()\n"); return _sync; } - void setSync (bool sync) + void setSync(bool sync) { mockverbose("TODO ClientContext::setSync()\n"); _sync = sync; @@ -277,13 +284,13 @@ class ClientContext // return a pointer to available data buffer (size = peekAvailable()) // semantic forbids any kind of read() before calling peekConsume() - const char* peekBuffer () + const char* peekBuffer() { return _inbuf; } // return number of byte accessible by peekBuffer() - size_t peekAvailable () + size_t peekAvailable() { ssize_t ret = mockPeekBytes(_sock, nullptr, 0, 0, _inbuf, _inbufsize); if (ret < 0) @@ -295,7 +302,7 @@ class ClientContext } // consume bytes after use (see peekBuffer) - void peekConsume (size_t consume) + void peekConsume(size_t consume) { assert(consume <= _inbufsize); memmove(_inbuf, _inbuf + consume, _inbufsize - consume); @@ -309,11 +316,11 @@ class ClientContext int8_t _refcnt; ClientContext* _next; - + bool _sync; - + // MOCK - + int _sock = -1; int _timeout_ms = 5000; diff --git a/tests/host/common/include/UdpContext.h b/tests/host/common/include/UdpContext.h index bf104bc40f..725ce89ca1 100644 --- a/tests/host/common/include/UdpContext.h +++ b/tests/host/common/include/UdpContext.h @@ -222,7 +222,9 @@ class UdpContext size_t wrt = mockUDPWrite(_sock, (const uint8_t*)_outbuf, _outbufsize, _timeout_ms, dst, dstport); err_t ret = _outbufsize ? ERR_OK : ERR_ABRT; if (!keepBuffer || wrt == _outbufsize) + { cancelBuffer(); + } return ret; } @@ -242,15 +244,22 @@ class UdpContext err_t err; esp8266::polledTimeout::oneShotFastMs timeout(timeoutMs); while (((err = trySend(addr, port)) != ERR_OK) && !timeout) + { delay(0); + } if (err != ERR_OK) + { cancelBuffer(); + } return err == ERR_OK; } void mock_cb(void) { - if (_on_rx) _on_rx(); + if (_on_rx) + { + _on_rx(); + } } public: @@ -270,7 +279,9 @@ class UdpContext //ip4_addr_set_u32(&ip_2_ip4(_dst), *(uint32_t*)addr); } else + { mockverbose("TODO unhandled udp address of size %d\n", (int)addrsize); + } } int _sock = -1; diff --git a/tests/host/common/littlefs_mock.cpp b/tests/host/common/littlefs_mock.cpp index 0d99e82b1e..8377eb3b80 100644 --- a/tests/host/common/littlefs_mock.cpp +++ b/tests/host/common/littlefs_mock.cpp @@ -1,19 +1,19 @@ /* - littlefs_mock.cpp - LittleFS mock for host side testing - Copyright © 2019 Earle F. Philhower, III + littlefs_mock.cpp - LittleFS mock for host side testing + Copyright © 2019 Earle F. Philhower, III - Based off spiffs_mock.cpp: - Copyright © 2016 Ivan Grokhotkov + Based off spiffs_mock.cpp: + Copyright © 2016 Ivan Grokhotkov - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. */ @@ -42,7 +42,9 @@ LittleFSMock::LittleFSMock(ssize_t fs_size, size_t fs_block, size_t fs_page, con { m_storage = storage; if ((m_overwrite = (fs_size < 0))) + { fs_size = -fs_size; + } fprintf(stderr, "LittleFS: %zd bytes\n", fs_size); @@ -73,26 +75,28 @@ LittleFSMock::~LittleFSMock() LittleFS = FS(FSImplPtr(nullptr)); } -void LittleFSMock::load () +void LittleFSMock::load() { if (!m_fs.size() || !m_storage.length()) + { return; - + } + int fs = ::open(m_storage.c_str(), O_RDONLY); if (fs == -1) { fprintf(stderr, "LittleFS: loading '%s': %s\n", m_storage.c_str(), strerror(errno)); return; } - + off_t flen = lseek(fs, 0, SEEK_END); - if (flen == (off_t)-1) + if (flen == (off_t) -1) { fprintf(stderr, "LittleFS: checking size of '%s': %s\n", m_storage.c_str(), strerror(errno)); return; } lseek(fs, 0, SEEK_SET); - + if (flen != (off_t)m_fs.size()) { fprintf(stderr, "LittleFS: size of '%s': %d does not match requested size %zd\n", m_storage.c_str(), (int)flen, m_fs.size()); @@ -108,15 +112,19 @@ void LittleFSMock::load () fprintf(stderr, "LittleFS: loading %zi bytes from '%s'\n", m_fs.size(), m_storage.c_str()); ssize_t r = ::read(fs, m_fs.data(), m_fs.size()); if (r != (ssize_t)m_fs.size()) + { fprintf(stderr, "LittleFS: reading %zi bytes: returned %zd: %s\n", m_fs.size(), r, strerror(errno)); + } } ::close(fs); } -void LittleFSMock::save () +void LittleFSMock::save() { if (!m_fs.size() || !m_storage.length()) + { return; + } int fs = ::open(m_storage.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644); if (fs == -1) @@ -127,7 +135,11 @@ void LittleFSMock::save () fprintf(stderr, "LittleFS: saving %zi bytes to '%s'\n", m_fs.size(), m_storage.c_str()); if (::write(fs, m_fs.data(), m_fs.size()) != (ssize_t)m_fs.size()) + { fprintf(stderr, "LittleFS: writing %zi bytes: %s\n", m_fs.size(), strerror(errno)); + } if (::close(fs) == -1) + { fprintf(stderr, "LittleFS: closing %s: %s\n", m_storage.c_str(), strerror(errno)); + } } diff --git a/tests/host/common/littlefs_mock.h b/tests/host/common/littlefs_mock.h index 0905fa9322..283a61f1b5 100644 --- a/tests/host/common/littlefs_mock.h +++ b/tests/host/common/littlefs_mock.h @@ -1,19 +1,19 @@ /* - littlefs_mock.h - LittleFS HAL mock for host side testing - Copyright © 2019 Earle F. Philhower, III - - Based on spiffs_mock: - Copyright © 2016 Ivan Grokhotkov - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. + littlefs_mock.h - LittleFS HAL mock for host side testing + Copyright © 2019 Earle F. Philhower, III + + Based on spiffs_mock: + Copyright © 2016 Ivan Grokhotkov + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. */ #ifndef littlefs_mock_hpp @@ -27,15 +27,16 @@ #define DEFAULT_LITTLEFS_FILE_NAME "littlefs.bin" -class LittleFSMock { +class LittleFSMock +{ public: LittleFSMock(ssize_t fs_size, size_t fs_block, size_t fs_page, const String& storage = emptyString); void reset(); ~LittleFSMock(); - + protected: - void load (); - void save (); + void load(); + void save(); std::vector m_fs; String m_storage; diff --git a/tests/host/common/md5.c b/tests/host/common/md5.c index 4b58f261f3..195ffa0785 100644 --- a/tests/host/common/md5.c +++ b/tests/host/common/md5.c @@ -1,36 +1,36 @@ /* - * Copyright (c) 2007, Cameron Rich - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * * Neither the name of the axTLS project nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ + Copyright (c) 2007, Cameron Rich + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + * * Neither the name of the axTLS project nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ /** - * This file implements the MD5 algorithm as defined in RFC1321 - */ + This file implements the MD5 algorithm as defined in RFC1321 +*/ #include #include @@ -39,18 +39,18 @@ #define EXP_FUNC extern #define STDCALL -#define MD5_SIZE 16 +#define MD5_SIZE 16 -typedef struct +typedef struct { - uint32_t state[4]; /* state (ABCD) */ - uint32_t count[2]; /* number of bits, modulo 2^64 (lsb first) */ - uint8_t buffer[64]; /* input buffer */ + uint32_t state[4]; /* state (ABCD) */ + uint32_t count[2]; /* number of bits, modulo 2^64 (lsb first) */ + uint8_t buffer[64]; /* input buffer */ } MD5_CTX; -/* Constants for MD5Transform routine. - */ +/* Constants for MD5Transform routine. +*/ #define S11 7 #define S12 12 #define S13 17 @@ -73,15 +73,15 @@ static void MD5Transform(uint32_t state[4], const uint8_t block[64]); static void Encode(uint8_t *output, uint32_t *input, uint32_t len); static void Decode(uint32_t *output, const uint8_t *input, uint32_t len); -static const uint8_t PADDING[64] = +static const uint8_t PADDING[64] = { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; -/* F, G, H and I are basic MD5 functions. - */ +/* F, G, H and I are basic MD5 functions. +*/ #define F(x, y, z) (((x) & (y)) | ((~x) & (z))) #define G(x, y, z) (((x) & (z)) | ((y) & (~z))) #define H(x, y, z) ((x) ^ (y) ^ (z)) @@ -90,8 +90,8 @@ static const uint8_t PADDING[64] = /* ROTATE_LEFT rotates x left n bits. */ #define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n)))) -/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. - Rotation is separate from addition to prevent recomputation. */ +/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. + Rotation is separate from addition to prevent recomputation. */ #define FF(a, b, c, d, x, s, ac) { \ (a) += F ((b), (c), (d)) + (x) + (uint32_t)(ac); \ (a) = ROTATE_LEFT ((a), (s)); \ @@ -114,14 +114,14 @@ static const uint8_t PADDING[64] = } /** - * MD5 initialization - begins an MD5 operation, writing a new ctx. - */ + MD5 initialization - begins an MD5 operation, writing a new ctx. +*/ EXP_FUNC void STDCALL MD5Init(MD5_CTX *ctx) { ctx->count[0] = ctx->count[1] = 0; - /* Load magic initialization constants. - */ + /* Load magic initialization constants. + */ ctx->state[0] = 0x67452301; ctx->state[1] = 0xefcdab89; ctx->state[2] = 0x98badcfe; @@ -129,8 +129,8 @@ EXP_FUNC void STDCALL MD5Init(MD5_CTX *ctx) } /** - * Accepts an array of octets as the next portion of the message. - */ + Accepts an array of octets as the next portion of the message. +*/ EXP_FUNC void STDCALL MD5Update(MD5_CTX *ctx, const uint8_t * msg, int len) { uint32_t x; @@ -141,32 +141,38 @@ EXP_FUNC void STDCALL MD5Update(MD5_CTX *ctx, const uint8_t * msg, int len) /* Update number of bits */ if ((ctx->count[0] += ((uint32_t)len << 3)) < ((uint32_t)len << 3)) + { ctx->count[1]++; + } ctx->count[1] += ((uint32_t)len >> 29); partLen = 64 - x; /* Transform as many times as possible. */ - if (len >= partLen) + if (len >= partLen) { memcpy(&ctx->buffer[x], msg, partLen); MD5Transform(ctx->state, ctx->buffer); for (i = partLen; i + 63 < len; i += 64) + { MD5Transform(ctx->state, &msg[i]); + } x = 0; } else + { i = 0; + } /* Buffer remaining input */ - memcpy(&ctx->buffer[x], &msg[i], len-i); + memcpy(&ctx->buffer[x], &msg[i], len - i); } /** - * Return the 128-bit message digest into the user's array - */ + Return the 128-bit message digest into the user's array +*/ EXP_FUNC void STDCALL MD5Final(uint8_t *digest, MD5_CTX *ctx) { uint8_t bits[8]; @@ -175,8 +181,8 @@ EXP_FUNC void STDCALL MD5Final(uint8_t *digest, MD5_CTX *ctx) /* Save number of bits */ Encode(bits, ctx->count, 8); - /* Pad out to 56 mod 64. - */ + /* Pad out to 56 mod 64. + */ x = (uint32_t)((ctx->count[0] >> 3) & 0x3f); padLen = (x < 56) ? (56 - x) : (120 - x); MD5Update(ctx, PADDING, padLen); @@ -189,86 +195,86 @@ EXP_FUNC void STDCALL MD5Final(uint8_t *digest, MD5_CTX *ctx) } /** - * MD5 basic transformation. Transforms state based on block. - */ + MD5 basic transformation. Transforms state based on block. +*/ static void MD5Transform(uint32_t state[4], const uint8_t block[64]) { - uint32_t a = state[0], b = state[1], c = state[2], + uint32_t a = state[0], b = state[1], c = state[2], d = state[3], x[MD5_SIZE]; Decode(x, block, 64); /* Round 1 */ - FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */ - FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */ - FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */ - FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */ - FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */ - FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */ - FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */ - FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */ - FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */ - FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */ - FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ - FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ - FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ - FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ - FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ - FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ + FF(a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */ + FF(d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */ + FF(c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */ + FF(b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */ + FF(a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */ + FF(d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */ + FF(c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */ + FF(b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */ + FF(a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */ + FF(d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */ + FF(c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ + FF(b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ + FF(a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ + FF(d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ + FF(c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ + FF(b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ /* Round 2 */ - GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */ - GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */ - GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ - GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */ - GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */ - GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */ - GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ - GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */ - GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */ - GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ - GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */ - GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */ - GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ - GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */ - GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */ - GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ + GG(a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */ + GG(d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */ + GG(c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ + GG(b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */ + GG(a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */ + GG(d, a, b, c, x[10], S22, 0x2441453); /* 22 */ + GG(c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ + GG(b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */ + GG(a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */ + GG(d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ + GG(c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */ + GG(b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */ + GG(a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ + GG(d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */ + GG(c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */ + GG(b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ /* Round 3 */ - HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */ - HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */ - HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ - HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ - HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */ - HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */ - HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */ - HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ - HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ - HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */ - HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */ - HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */ - HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */ - HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ - HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ - HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */ + HH(a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */ + HH(d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */ + HH(c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ + HH(b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ + HH(a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */ + HH(d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */ + HH(c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */ + HH(b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ + HH(a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ + HH(d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */ + HH(c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */ + HH(b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */ + HH(a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */ + HH(d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ + HH(c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ + HH(b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */ /* Round 4 */ - II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */ - II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */ - II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ - II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */ - II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ - II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */ - II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ - II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */ - II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */ - II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ - II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */ - II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ - II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */ - II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ - II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */ - II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */ + II(a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */ + II(d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */ + II(c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ + II(b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */ + II(a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ + II(d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */ + II(c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ + II(b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */ + II(a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */ + II(d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ + II(c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */ + II(b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ + II(a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */ + II(d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ + II(c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */ + II(b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */ state[0] += a; state[1] += b; @@ -277,31 +283,31 @@ static void MD5Transform(uint32_t state[4], const uint8_t block[64]) } /** - * Encodes input (uint32_t) into output (uint8_t). Assumes len is - * a multiple of 4. - */ + Encodes input (uint32_t) into output (uint8_t). Assumes len is + a multiple of 4. +*/ static void Encode(uint8_t *output, uint32_t *input, uint32_t len) { uint32_t i, j; - for (i = 0, j = 0; j < len; i++, j += 4) + for (i = 0, j = 0; j < len; i++, j += 4) { output[j] = (uint8_t)(input[i] & 0xff); - output[j+1] = (uint8_t)((input[i] >> 8) & 0xff); - output[j+2] = (uint8_t)((input[i] >> 16) & 0xff); - output[j+3] = (uint8_t)((input[i] >> 24) & 0xff); + output[j + 1] = (uint8_t)((input[i] >> 8) & 0xff); + output[j + 2] = (uint8_t)((input[i] >> 16) & 0xff); + output[j + 3] = (uint8_t)((input[i] >> 24) & 0xff); } } /** - * Decodes input (uint8_t) into output (uint32_t). Assumes len is - * a multiple of 4. - */ + Decodes input (uint8_t) into output (uint32_t). Assumes len is + a multiple of 4. +*/ static void Decode(uint32_t *output, const uint8_t *input, uint32_t len) { uint32_t i, j; for (i = 0, j = 0; j < len; i++, j += 4) - output[i] = ((uint32_t)input[j]) | (((uint32_t)input[j+1]) << 8) | - (((uint32_t)input[j+2]) << 16) | (((uint32_t)input[j+3]) << 24); + output[i] = ((uint32_t)input[j]) | (((uint32_t)input[j + 1]) << 8) | + (((uint32_t)input[j + 2]) << 16) | (((uint32_t)input[j + 3]) << 24); } diff --git a/tests/host/common/mock.h b/tests/host/common/mock.h index 56919ee60a..a0af18f5b7 100644 --- a/tests/host/common/mock.h +++ b/tests/host/common/mock.h @@ -1,32 +1,32 @@ /* - Arduino emulation - common to all emulated code - Copyright (c) 2018 david gauchard. All rights reserved. - - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the "Software"), - to deal with the Software without restriction, including without limitation - the rights to use, copy, modify, merge, publish, distribute, sublicense, - and/or sell copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following conditions: - - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimers. - - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimers in the - documentation and/or other materials provided with the distribution. - - - The names of its contributors may not be used to endorse or promote - products derived from this Software without specific prior written - permission. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS WITH THE SOFTWARE. + Arduino emulation - common to all emulated code + Copyright (c) 2018 david gauchard. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal with the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + - The names of its contributors may not be used to endorse or promote + products derived from this Software without specific prior written + permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. */ #define CORE_MOCK 1 @@ -60,8 +60,8 @@ extern "C" { #endif // TODO: #include ? -char* itoa (int val, char *s, int radix); -char* ltoa (long val, char *s, int radix); +char* itoa(int val, char *s, int radix); +char* ltoa(long val, char *s, int radix); size_t strlcat(char *dst, const char *src, size_t size); @@ -100,12 +100,15 @@ uint32_t esp_get_cycle_count(); extern "C" { #endif #include -int ets_printf (const char* fmt, ...) __attribute__ ((format (printf, 1, 2))); +int ets_printf(const char* fmt, ...) __attribute__((format(printf, 1, 2))); #define os_printf_plus printf #define ets_vsnprintf vsnprintf -inline void ets_putc (char c) { putchar(c); } +inline void ets_putc(char c) +{ + putchar(c); +} -int mockverbose (const char* fmt, ...) __attribute__ ((format (printf, 1, 2))); +int mockverbose(const char* fmt, ...) __attribute__((format(printf, 1, 2))); extern const char* host_interface; // cmdline parameter extern bool serial_timestamp; @@ -140,33 +143,33 @@ void uart_new_data(const int uart_nr, uint8_t data); #endif // tcp -int mockSockSetup (int sock); -int mockConnect (uint32_t addr, int& sock, int port); -ssize_t mockFillInBuf (int sock, char* ccinbuf, size_t& ccinbufsize); -ssize_t mockPeekBytes (int sock, char* dst, size_t size, int timeout_ms, char* buf, size_t& bufsize); -ssize_t mockRead (int sock, char* dst, size_t size, int timeout_ms, char* buf, size_t& bufsize); -ssize_t mockWrite (int sock, const uint8_t* data, size_t size, int timeout_ms); -int serverAccept (int sock); +int mockSockSetup(int sock); +int mockConnect(uint32_t addr, int& sock, int port); +ssize_t mockFillInBuf(int sock, char* ccinbuf, size_t& ccinbufsize); +ssize_t mockPeekBytes(int sock, char* dst, size_t size, int timeout_ms, char* buf, size_t& bufsize); +ssize_t mockRead(int sock, char* dst, size_t size, int timeout_ms, char* buf, size_t& bufsize); +ssize_t mockWrite(int sock, const uint8_t* data, size_t size, int timeout_ms); +int serverAccept(int sock); // udp -void check_incoming_udp (); -int mockUDPSocket (); -bool mockUDPListen (int sock, uint32_t dstaddr, uint16_t port, uint32_t mcast = 0); -size_t mockUDPFillInBuf (int sock, char* ccinbuf, size_t& ccinbufsize, uint8_t& addrsize, uint8_t addr[16], uint16_t& port); -size_t mockUDPPeekBytes (int sock, char* dst, size_t usersize, int timeout_ms, char* ccinbuf, size_t& ccinbufsize); -size_t mockUDPRead (int sock, char* dst, size_t size, int timeout_ms, char* ccinbuf, size_t& ccinbufsize); -size_t mockUDPWrite (int sock, const uint8_t* data, size_t size, int timeout_ms, uint32_t ipv4, uint16_t port); -void mockUDPSwallow (size_t copied, char* ccinbuf, size_t& ccinbufsize); +void check_incoming_udp(); +int mockUDPSocket(); +bool mockUDPListen(int sock, uint32_t dstaddr, uint16_t port, uint32_t mcast = 0); +size_t mockUDPFillInBuf(int sock, char* ccinbuf, size_t& ccinbufsize, uint8_t& addrsize, uint8_t addr[16], uint16_t& port); +size_t mockUDPPeekBytes(int sock, char* dst, size_t usersize, int timeout_ms, char* ccinbuf, size_t& ccinbufsize); +size_t mockUDPRead(int sock, char* dst, size_t size, int timeout_ms, char* ccinbuf, size_t& ccinbufsize); +size_t mockUDPWrite(int sock, const uint8_t* data, size_t size, int timeout_ms, uint32_t ipv4, uint16_t port); +void mockUDPSwallow(size_t copied, char* ccinbuf, size_t& ccinbufsize); class UdpContext; -void register_udp (int sock, UdpContext* udp = nullptr); +void register_udp(int sock, UdpContext* udp = nullptr); // -void mock_start_spiffs (const String& fname, size_t size_kb, size_t block_kb = 8, size_t page_b = 512); -void mock_stop_spiffs (); -void mock_start_littlefs (const String& fname, size_t size_kb, size_t block_kb = 8, size_t page_b = 512); -void mock_stop_littlefs (); +void mock_start_spiffs(const String& fname, size_t size_kb, size_t block_kb = 8, size_t page_b = 512); +void mock_stop_spiffs(); +void mock_start_littlefs(const String& fname, size_t size_kb, size_t block_kb = 8, size_t page_b = 512); +void mock_stop_littlefs(); // diff --git a/tests/host/common/noniso.c b/tests/host/common/noniso.c index 869a4b7f8e..5ef9c85774 100644 --- a/tests/host/common/noniso.c +++ b/tests/host/common/noniso.c @@ -1,16 +1,16 @@ /* - noniso.cpp - replacements for non-ISO functions used by Arduino core - Copyright © 2016 Ivan Grokhotkov - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. + noniso.cpp - replacements for non-ISO functions used by Arduino core + Copyright © 2016 Ivan Grokhotkov + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. */ @@ -22,10 +22,12 @@ #include "stdlib_noniso.h" -void reverse(char* begin, char* end) { +void reverse(char* begin, char* end) +{ char *is = begin; char *ie = end - 1; - while(is < ie) { + while (is < ie) + { char tmp = *ie; *ie = *is; *is = tmp; @@ -34,8 +36,10 @@ void reverse(char* begin, char* end) { } } -char* utoa(unsigned value, char* result, int base) { - if(base < 2 || base > 16) { +char* utoa(unsigned value, char* result, int base) +{ + if (base < 2 || base > 16) + { *result = 0; return result; } @@ -43,56 +47,66 @@ char* utoa(unsigned value, char* result, int base) { char* out = result; unsigned quotient = value; - do { + do + { const unsigned tmp = quotient / base; *out = "0123456789abcdef"[quotient - (tmp * base)]; ++out; quotient = tmp; - } while(quotient); + } while (quotient); reverse(result, out); *out = 0; return result; } -char* itoa(int value, char* result, int base) { - if(base < 2 || base > 16) { +char* itoa(int value, char* result, int base) +{ + if (base < 2 || base > 16) + { *result = 0; return result; } - if (base != 10) { - return utoa((unsigned)value, result, base); - } + if (base != 10) + { + return utoa((unsigned)value, result, base); + } char* out = result; int quotient = abs(value); - do { + do + { const int tmp = quotient / base; *out = "0123456789abcdef"[quotient - (tmp * base)]; ++out; quotient = tmp; - } while(quotient); + } while (quotient); // Apply negative sign - if(value < 0) + if (value < 0) + { *out++ = '-'; + } reverse(result, out); *out = 0; return result; } -int atoi(const char* s) { +int atoi(const char* s) +{ return (int) atol(s); } -long atol(const char* s) { +long atol(const char* s) +{ char * tmp; return strtol(s, &tmp, 10); } -double atof(const char* s) { +double atof(const char* s) +{ char * tmp; return strtod(s, &tmp); } diff --git a/tests/host/common/pins_arduino.h b/tests/host/common/pins_arduino.h index ad051ed24a..5c33e0f119 100644 --- a/tests/host/common/pins_arduino.h +++ b/tests/host/common/pins_arduino.h @@ -1,17 +1,17 @@ /* - pins_arduino.h - Copyright © 2016 Ivan Grokhotkov - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - */ + pins_arduino.h + Copyright © 2016 Ivan Grokhotkov + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. +*/ #ifndef pins_arduino_h #define pins_arduino_h diff --git a/tests/host/common/queue.h b/tests/host/common/queue.h index af637ca030..778241d2a5 100644 --- a/tests/host/common/queue.h +++ b/tests/host/common/queue.h @@ -1,38 +1,38 @@ /* - * Copyright (c) 1991, 1993 - * 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 - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * @(#)queue.h 8.5 (Berkeley) 8/20/94 - * $FreeBSD: src/sys/sys/queue.h,v 1.48 2002/04/17 14:00:37 tmm Exp $ - */ + Copyright (c) 1991, 1993 + 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 + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. All advertising materials mentioning features or use of this software + must display the following acknowledgement: + This product includes software developed by the University of + California, Berkeley and its contributors. + 4. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + @(#)queue.h 8.5 (Berkeley) 8/20/94 + $FreeBSD: src/sys/sys/queue.h,v 1.48 2002/04/17 14:00:37 tmm Exp $ +*/ #ifndef _SYS_QUEUE_H_ #define _SYS_QUEUE_H_ @@ -40,72 +40,72 @@ #include /* for __offsetof */ /* - * This file defines four types of data structures: singly-linked lists, - * singly-linked tail queues, lists and tail queues. - * - * A singly-linked list is headed by a single forward pointer. The elements - * are singly linked for minimum space and pointer manipulation overhead at - * the expense of O(n) removal for arbitrary elements. New elements can be - * added to the list after an existing element or at the head of the list. - * Elements being removed from the head of the list should use the explicit - * macro for this purpose for optimum efficiency. A singly-linked list may - * only be traversed in the forward direction. Singly-linked lists are ideal - * for applications with large datasets and few or no removals or for - * implementing a LIFO queue. - * - * A singly-linked tail queue is headed by a pair of pointers, one to the - * head of the list and the other to the tail of the list. The elements are - * singly linked for minimum space and pointer manipulation overhead at the - * expense of O(n) removal for arbitrary elements. New elements can be added - * to the list after an existing element, at the head of the list, or at the - * end of the list. Elements being removed from the head of the tail queue - * should use the explicit macro for this purpose for optimum efficiency. - * A singly-linked tail queue may only be traversed in the forward direction. - * Singly-linked tail queues are ideal for applications with large datasets - * and few or no removals or for implementing a FIFO queue. - * - * A list is headed by a single forward pointer (or an array of forward - * pointers for a hash table header). The elements are doubly linked - * so that an arbitrary element can be removed without a need to - * traverse the list. New elements can be added to the list before - * or after an existing element or at the head of the list. A list - * may only be traversed in the forward direction. - * - * A tail queue is headed by a pair of pointers, one to the head of the - * list and the other to the tail of the list. The elements are doubly - * linked so that an arbitrary element can be removed without a need to - * traverse the list. New elements can be added to the list before or - * after an existing element, at the head of the list, or at the end of - * the list. A tail queue may be traversed in either direction. - * - * For details on the use of these macros, see the queue(3) manual page. - * - * - * SLIST LIST STAILQ TAILQ - * _HEAD + + + + - * _HEAD_INITIALIZER + + + + - * _ENTRY + + + + - * _INIT + + + + - * _EMPTY + + + + - * _FIRST + + + + - * _NEXT + + + + - * _PREV - - - + - * _LAST - - + + - * _FOREACH + + + + - * _FOREACH_REVERSE - - - + - * _INSERT_HEAD + + + + - * _INSERT_BEFORE - + - + - * _INSERT_AFTER + + + + - * _INSERT_TAIL - - + + - * _CONCAT - - + + - * _REMOVE_HEAD + - + - - * _REMOVE + + + + - * - */ + This file defines four types of data structures: singly-linked lists, + singly-linked tail queues, lists and tail queues. + + A singly-linked list is headed by a single forward pointer. The elements + are singly linked for minimum space and pointer manipulation overhead at + the expense of O(n) removal for arbitrary elements. New elements can be + added to the list after an existing element or at the head of the list. + Elements being removed from the head of the list should use the explicit + macro for this purpose for optimum efficiency. A singly-linked list may + only be traversed in the forward direction. Singly-linked lists are ideal + for applications with large datasets and few or no removals or for + implementing a LIFO queue. + + A singly-linked tail queue is headed by a pair of pointers, one to the + head of the list and the other to the tail of the list. The elements are + singly linked for minimum space and pointer manipulation overhead at the + expense of O(n) removal for arbitrary elements. New elements can be added + to the list after an existing element, at the head of the list, or at the + end of the list. Elements being removed from the head of the tail queue + should use the explicit macro for this purpose for optimum efficiency. + A singly-linked tail queue may only be traversed in the forward direction. + Singly-linked tail queues are ideal for applications with large datasets + and few or no removals or for implementing a FIFO queue. + + A list is headed by a single forward pointer (or an array of forward + pointers for a hash table header). The elements are doubly linked + so that an arbitrary element can be removed without a need to + traverse the list. New elements can be added to the list before + or after an existing element or at the head of the list. A list + may only be traversed in the forward direction. + + A tail queue is headed by a pair of pointers, one to the head of the + list and the other to the tail of the list. The elements are doubly + linked so that an arbitrary element can be removed without a need to + traverse the list. New elements can be added to the list before or + after an existing element, at the head of the list, or at the end of + the list. A tail queue may be traversed in either direction. + + For details on the use of these macros, see the queue(3) manual page. + + + SLIST LIST STAILQ TAILQ + _HEAD + + + + + _HEAD_INITIALIZER + + + + + _ENTRY + + + + + _INIT + + + + + _EMPTY + + + + + _FIRST + + + + + _NEXT + + + + + _PREV - - - + + _LAST - - + + + _FOREACH + + + + + _FOREACH_REVERSE - - - + + _INSERT_HEAD + + + + + _INSERT_BEFORE - + - + + _INSERT_AFTER + + + + + _INSERT_TAIL - - + + + _CONCAT - - + + + _REMOVE_HEAD + - + - + _REMOVE + + + + + +*/ /* - * Singly-linked List declarations. - */ + Singly-linked List declarations. +*/ #define SLIST_HEAD(name, type) \ struct name { \ struct type *slh_first; /* first element */ \ @@ -113,15 +113,15 @@ struct name { \ #define SLIST_HEAD_INITIALIZER(head) \ { NULL } - + #define SLIST_ENTRY(type) \ struct { \ struct type *sle_next; /* next element */ \ } - + /* - * Singly-linked List functions. - */ + Singly-linked List functions. +*/ #define SLIST_EMPTY(head) ((head)->slh_first == NULL) #define SLIST_FIRST(head) ((head)->slh_first) @@ -165,8 +165,8 @@ struct { \ } while (0) /* - * Singly-linked Tail queue declarations. - */ + Singly-linked Tail queue declarations. +*/ #define STAILQ_HEAD(name, type) \ struct name { \ struct type *stqh_first;/* first element */ \ @@ -182,8 +182,8 @@ struct { \ } /* - * Singly-linked Tail queue functions. - */ + Singly-linked Tail queue functions. +*/ #define STAILQ_CONCAT(head1, head2) do { \ if (!STAILQ_EMPTY((head2))) { \ *(head1)->stqh_last = (head2)->stqh_first; \ @@ -258,8 +258,8 @@ struct { \ } while (0) /* - * List declarations. - */ + List declarations. +*/ #define LIST_HEAD(name, type) \ struct name { \ struct type *lh_first; /* first element */ \ @@ -275,8 +275,8 @@ struct { \ } /* - * List functions. - */ + List functions. +*/ #define LIST_EMPTY(head) ((head)->lh_first == NULL) @@ -323,8 +323,8 @@ struct { \ } while (0) /* - * Tail queue declarations. - */ + Tail queue declarations. +*/ #define TAILQ_HEAD(name, type) \ struct name { \ struct type *tqh_first; /* first element */ \ @@ -341,8 +341,8 @@ struct { \ } /* - * Tail queue functions. - */ + Tail queue functions. +*/ #define TAILQ_CONCAT(head1, head2, field) do { \ if (!TAILQ_EMPTY(head2)) { \ *(head1)->tqh_last = (head2)->tqh_first; \ @@ -426,13 +426,14 @@ struct { \ #ifdef _KERNEL /* - * XXX insque() and remque() are an old way of handling certain queues. - * They bogusly assumes that all queue heads look alike. - */ + XXX insque() and remque() are an old way of handling certain queues. + They bogusly assumes that all queue heads look alike. +*/ -struct quehead { - struct quehead *qh_link; - struct quehead *qh_rlink; +struct quehead +{ + struct quehead *qh_link; + struct quehead *qh_rlink; }; #ifdef __GNUC__ @@ -440,23 +441,23 @@ struct quehead { static __inline void insque(void *a, void *b) { - struct quehead *element = (struct quehead *)a, - *head = (struct quehead *)b; + struct quehead *element = (struct quehead *)a, + *head = (struct quehead *)b; - element->qh_link = head->qh_link; - element->qh_rlink = head; - head->qh_link = element; - element->qh_link->qh_rlink = element; + element->qh_link = head->qh_link; + element->qh_rlink = head; + head->qh_link = element; + element->qh_link->qh_rlink = element; } static __inline void remque(void *a) { - struct quehead *element = (struct quehead *)a; + struct quehead *element = (struct quehead *)a; - element->qh_link->qh_rlink = element->qh_rlink; - element->qh_rlink->qh_link = element->qh_link; - element->qh_rlink = 0; + element->qh_link->qh_rlink = element->qh_rlink; + element->qh_rlink->qh_link = element->qh_link; + element->qh_rlink = 0; } #else /* !__GNUC__ */ diff --git a/tests/host/common/sdfs_mock.cpp b/tests/host/common/sdfs_mock.cpp index ef2ae44152..2673ab318f 100644 --- a/tests/host/common/sdfs_mock.cpp +++ b/tests/host/common/sdfs_mock.cpp @@ -1,16 +1,16 @@ /* - sdfs_mock.cpp - SDFS HAL mock for host side testing - Copyright (c) 2019 Earle F. Philhower, III + sdfs_mock.cpp - SDFS HAL mock for host side testing + Copyright (c) 2019 Earle F. Philhower, III - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. */ #include "sdfs_mock.h" diff --git a/tests/host/common/sdfs_mock.h b/tests/host/common/sdfs_mock.h index 611474701a..08a196a846 100644 --- a/tests/host/common/sdfs_mock.h +++ b/tests/host/common/sdfs_mock.h @@ -1,16 +1,16 @@ /* - sdfs.h - SDFS mock for host side testing - Copyright (c) 2019 Earle F. Philhower, III - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. + sdfs.h - SDFS mock for host side testing + Copyright (c) 2019 Earle F. Philhower, III + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. */ #ifndef sdfs_mock_hpp @@ -21,9 +21,16 @@ #include #include -class SDFSMock { +class SDFSMock +{ public: - SDFSMock(ssize_t fs_size, size_t fs_block, size_t fs_page, const String& storage = emptyString) { (void)fs_size; (void)fs_block; (void)fs_page; (void)storage; } + SDFSMock(ssize_t fs_size, size_t fs_block, size_t fs_page, const String& storage = emptyString) + { + (void)fs_size; + (void)fs_block; + (void)fs_page; + (void)storage; + } void reset() { } ~SDFSMock() { } }; diff --git a/tests/host/common/spiffs_mock.cpp b/tests/host/common/spiffs_mock.cpp index c7f9f53aba..716b84b60f 100644 --- a/tests/host/common/spiffs_mock.cpp +++ b/tests/host/common/spiffs_mock.cpp @@ -1,16 +1,16 @@ /* - spiffs_mock.cpp - SPIFFS HAL mock for host side testing - Copyright © 2016 Ivan Grokhotkov - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. + spiffs_mock.cpp - SPIFFS HAL mock for host side testing + Copyright © 2016 Ivan Grokhotkov + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. */ @@ -41,7 +41,9 @@ SpiffsMock::SpiffsMock(ssize_t fs_size, size_t fs_block, size_t fs_page, const S { m_storage = storage; if ((m_overwrite = (fs_size < 0))) + { fs_size = -fs_size; + } fprintf(stderr, "SPIFFS: %zd bytes\n", fs_size); @@ -72,26 +74,28 @@ SpiffsMock::~SpiffsMock() SPIFFS = FS(FSImplPtr(nullptr)); } -void SpiffsMock::load () +void SpiffsMock::load() { if (!m_fs.size() || !m_storage.length()) + { return; - + } + int fs = ::open(m_storage.c_str(), O_RDONLY); if (fs == -1) { fprintf(stderr, "SPIFFS: loading '%s': %s\n", m_storage.c_str(), strerror(errno)); return; } - + off_t flen = lseek(fs, 0, SEEK_END); - if (flen == (off_t)-1) + if (flen == (off_t) -1) { fprintf(stderr, "SPIFFS: checking size of '%s': %s\n", m_storage.c_str(), strerror(errno)); return; } lseek(fs, 0, SEEK_SET); - + if (flen != (off_t)m_fs.size()) { fprintf(stderr, "SPIFFS: size of '%s': %d does not match requested size %zd\n", m_storage.c_str(), (int)flen, m_fs.size()); @@ -107,15 +111,19 @@ void SpiffsMock::load () fprintf(stderr, "SPIFFS: loading %zi bytes from '%s'\n", m_fs.size(), m_storage.c_str()); ssize_t r = ::read(fs, m_fs.data(), m_fs.size()); if (r != (ssize_t)m_fs.size()) + { fprintf(stderr, "SPIFFS: reading %zi bytes: returned %zd: %s\n", m_fs.size(), r, strerror(errno)); + } } ::close(fs); } -void SpiffsMock::save () +void SpiffsMock::save() { if (!m_fs.size() || !m_storage.length()) + { return; + } int fs = ::open(m_storage.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644); if (fs == -1) @@ -126,9 +134,13 @@ void SpiffsMock::save () fprintf(stderr, "SPIFFS: saving %zi bytes to '%s'\n", m_fs.size(), m_storage.c_str()); if (::write(fs, m_fs.data(), m_fs.size()) != (ssize_t)m_fs.size()) + { fprintf(stderr, "SPIFFS: writing %zi bytes: %s\n", m_fs.size(), strerror(errno)); + } if (::close(fs) == -1) + { fprintf(stderr, "SPIFFS: closing %s: %s\n", m_storage.c_str(), strerror(errno)); + } } #pragma GCC diagnostic pop diff --git a/tests/host/common/spiffs_mock.h b/tests/host/common/spiffs_mock.h index 4c265964f5..12a97f2851 100644 --- a/tests/host/common/spiffs_mock.h +++ b/tests/host/common/spiffs_mock.h @@ -1,16 +1,16 @@ /* - spiffs_mock.h - SPIFFS HAL mock for host side testing - Copyright © 2016 Ivan Grokhotkov - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. + spiffs_mock.h - SPIFFS HAL mock for host side testing + Copyright © 2016 Ivan Grokhotkov + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. */ #ifndef spiffs_mock_hpp @@ -24,15 +24,16 @@ #define DEFAULT_SPIFFS_FILE_NAME "spiffs.bin" -class SpiffsMock { +class SpiffsMock +{ public: SpiffsMock(ssize_t fs_size, size_t fs_block, size_t fs_page, const String& storage = emptyString); void reset(); ~SpiffsMock(); - + protected: - void load (); - void save (); + void load(); + void save(); std::vector m_fs; String m_storage; diff --git a/tests/host/common/user_interface.cpp b/tests/host/common/user_interface.cpp index 4e03d77786..2c9bde2453 100644 --- a/tests/host/common/user_interface.cpp +++ b/tests/host/common/user_interface.cpp @@ -62,22 +62,22 @@ bool DhcpServer::set_dhcps_offer_option(uint8 level, void* optarg) return false; } -void DhcpServer::end () +void DhcpServer::end() { } -bool DhcpServer::begin (struct ip_info *info) +bool DhcpServer::begin(struct ip_info *info) { (void)info; return false; } -DhcpServer::DhcpServer (netif* netif) +DhcpServer::DhcpServer(netif* netif) { (void)netif; } -DhcpServer::~DhcpServer () +DhcpServer::~DhcpServer() { end(); } @@ -126,7 +126,9 @@ extern "C" strcpy((char*)config->password, "emulated-ssid-password"); config->bssid_set = 0; for (int i = 0; i < 6; i++) + { config->bssid[i] = i; + } config->threshold.rssi = 1; config->threshold.authmode = AUTH_WPA_PSK; #ifdef NONOSDK3V0 @@ -181,7 +183,9 @@ extern "C" } if (host_interface) + { mockverbose("host: looking for interface '%s':\n", host_interface); + } for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) { @@ -194,7 +198,9 @@ extern "C" mockverbose(" IPV4 (0x%08lx)", test_ipv4); if ((test_ipv4 & 0xff000000) == 0x7f000000) // 127./8 + { mockverbose(" (local, ignored)"); + } else { if (!host_interface || (host_interface && strcmp(ifa->ifa_name, host_interface) == 0)) @@ -204,7 +210,9 @@ extern "C" mask = *(uint32_t*) & ((struct sockaddr_in*)ifa->ifa_netmask)->sin_addr; mockverbose(" (selected)\n"); if (host_interface) + { global_source_address = ntohl(ipv4); + } break; } } @@ -213,14 +221,18 @@ extern "C" } if (ifAddrStruct != NULL) + { freeifaddrs(ifAddrStruct); + } (void)if_index; //if (if_index != STATION_IF) // fprintf(stderr, "we are not AP"); if (global_ipv4_netfmt == NO_GLOBAL_BINDING) + { global_ipv4_netfmt = ipv4; + } if (info) { diff --git a/tests/host/core/test_PolledTimeout.cpp b/tests/host/core/test_PolledTimeout.cpp index 37b31d8544..3645123827 100644 --- a/tests/host/core/test_PolledTimeout.cpp +++ b/tests/host/core/test_PolledTimeout.cpp @@ -9,238 +9,260 @@ template inline bool fuzzycomp(argT a, argT b) { - const argT epsilon = 10; - return (std::max(a,b) - std::min(a,b) <= epsilon); + const argT epsilon = 10; + return (std::max(a, b) - std::min(a, b) <= epsilon); } TEST_CASE("OneShot Timeout 500000000ns (0.5s)", "[polledTimeout]") { - using esp8266::polledTimeout::oneShotFastNs; - using timeType = oneShotFastNs::timeType; - timeType before, after, delta; + using esp8266::polledTimeout::oneShotFastNs; + using timeType = oneShotFastNs::timeType; + timeType before, after, delta; - Serial.println("OneShot Timeout 500000000ns (0.5s)"); + Serial.println("OneShot Timeout 500000000ns (0.5s)"); - oneShotFastNs timeout(500000000); - before = micros(); - while(!timeout.expired()) - yield(); - after = micros(); + oneShotFastNs timeout(500000000); + before = micros(); + while (!timeout.expired()) + { + yield(); + } + after = micros(); - delta = after - before; - Serial.printf("delta = %u\n", delta); + delta = after - before; + Serial.printf("delta = %u\n", delta); - REQUIRE(fuzzycomp(delta/1000, (timeType)500)); + REQUIRE(fuzzycomp(delta / 1000, (timeType)500)); - Serial.print("reset\n"); + Serial.print("reset\n"); - timeout.reset(); - before = micros(); - while(!timeout) - yield(); - after = micros(); + timeout.reset(); + before = micros(); + while (!timeout) + { + yield(); + } + after = micros(); - delta = after - before; - Serial.printf("delta = %u\n", delta); + delta = after - before; + Serial.printf("delta = %u\n", delta); - REQUIRE(fuzzycomp(delta/1000, (timeType)500)); + REQUIRE(fuzzycomp(delta / 1000, (timeType)500)); } TEST_CASE("OneShot Timeout 3000000us", "[polledTimeout]") { - using esp8266::polledTimeout::oneShotFastUs; - using timeType = oneShotFastUs::timeType; - timeType before, after, delta; + using esp8266::polledTimeout::oneShotFastUs; + using timeType = oneShotFastUs::timeType; + timeType before, after, delta; - Serial.println("OneShot Timeout 3000000us"); + Serial.println("OneShot Timeout 3000000us"); - oneShotFastUs timeout(3000000); - before = micros(); - while(!timeout.expired()) - yield(); - after = micros(); + oneShotFastUs timeout(3000000); + before = micros(); + while (!timeout.expired()) + { + yield(); + } + after = micros(); - delta = after - before; - Serial.printf("delta = %u\n", delta); + delta = after - before; + Serial.printf("delta = %u\n", delta); - REQUIRE(fuzzycomp(delta/1000, (timeType)3000)); + REQUIRE(fuzzycomp(delta / 1000, (timeType)3000)); - Serial.print("reset\n"); + Serial.print("reset\n"); - timeout.reset(); - before = micros(); - while(!timeout) - yield(); - after = micros(); + timeout.reset(); + before = micros(); + while (!timeout) + { + yield(); + } + after = micros(); - delta = after - before; - Serial.printf("delta = %u\n", delta); + delta = after - before; + Serial.printf("delta = %u\n", delta); - REQUIRE(fuzzycomp(delta/1000, (timeType)3000)); + REQUIRE(fuzzycomp(delta / 1000, (timeType)3000)); } TEST_CASE("OneShot Timeout 3000ms", "[polledTimeout]") { - using esp8266::polledTimeout::oneShotMs; - using timeType = oneShotMs::timeType; - timeType before, after, delta; + using esp8266::polledTimeout::oneShotMs; + using timeType = oneShotMs::timeType; + timeType before, after, delta; - Serial.println("OneShot Timeout 3000ms"); + Serial.println("OneShot Timeout 3000ms"); - oneShotMs timeout(3000); - before = millis(); - while(!timeout.expired()) - yield(); - after = millis(); + oneShotMs timeout(3000); + before = millis(); + while (!timeout.expired()) + { + yield(); + } + after = millis(); - delta = after - before; - Serial.printf("delta = %lu\n", delta); + delta = after - before; + Serial.printf("delta = %lu\n", delta); - REQUIRE(fuzzycomp(delta, (timeType)3000)); + REQUIRE(fuzzycomp(delta, (timeType)3000)); - Serial.print("reset\n"); + Serial.print("reset\n"); - timeout.reset(); - before = millis(); - while(!timeout) - yield(); - after = millis(); + timeout.reset(); + before = millis(); + while (!timeout) + { + yield(); + } + after = millis(); - delta = after - before; - Serial.printf("delta = %lu\n", delta); + delta = after - before; + Serial.printf("delta = %lu\n", delta); - REQUIRE(fuzzycomp(delta, (timeType)3000)); + REQUIRE(fuzzycomp(delta, (timeType)3000)); } TEST_CASE("OneShot Timeout 3000ms reset to 1000ms", "[polledTimeout]") { - using esp8266::polledTimeout::oneShotMs; - using timeType = oneShotMs::timeType; - timeType before, after, delta; + using esp8266::polledTimeout::oneShotMs; + using timeType = oneShotMs::timeType; + timeType before, after, delta; - Serial.println("OneShot Timeout 3000ms"); + Serial.println("OneShot Timeout 3000ms"); - oneShotMs timeout(3000); - before = millis(); - while(!timeout.expired()) - yield(); - after = millis(); + oneShotMs timeout(3000); + before = millis(); + while (!timeout.expired()) + { + yield(); + } + after = millis(); - delta = after - before; - Serial.printf("delta = %lu\n", delta); + delta = after - before; + Serial.printf("delta = %lu\n", delta); - REQUIRE(fuzzycomp(delta, (timeType)3000)); + REQUIRE(fuzzycomp(delta, (timeType)3000)); - Serial.print("reset\n"); + Serial.print("reset\n"); - timeout.reset(1000); - before = millis(); - while(!timeout) - yield(); - after = millis(); + timeout.reset(1000); + before = millis(); + while (!timeout) + { + yield(); + } + after = millis(); - delta = after - before; - Serial.printf("delta = %lu\n", delta); + delta = after - before; + Serial.printf("delta = %lu\n", delta); - REQUIRE(fuzzycomp(delta, (timeType)1000)); + REQUIRE(fuzzycomp(delta, (timeType)1000)); } TEST_CASE("Periodic Timeout 1T 3000ms", "[polledTimeout]") { - using esp8266::polledTimeout::periodicMs; - using timeType = periodicMs::timeType; - timeType before, after, delta; + using esp8266::polledTimeout::periodicMs; + using timeType = periodicMs::timeType; + timeType before, after, delta; - Serial.println("Periodic Timeout 1T 3000ms"); + Serial.println("Periodic Timeout 1T 3000ms"); - periodicMs timeout(3000); - before = millis(); - while(!timeout) - yield(); - after = millis(); + periodicMs timeout(3000); + before = millis(); + while (!timeout) + { + yield(); + } + after = millis(); - delta = after - before; - Serial.printf("delta = %lu\n", delta); + delta = after - before; + Serial.printf("delta = %lu\n", delta); - REQUIRE(fuzzycomp(delta, (timeType)3000)); + REQUIRE(fuzzycomp(delta, (timeType)3000)); - Serial.print("no reset needed\n"); + Serial.print("no reset needed\n"); - before = millis(); - while(!timeout) - yield(); - after = millis(); + before = millis(); + while (!timeout) + { + yield(); + } + after = millis(); - delta = after - before; - Serial.printf("delta = %lu\n", delta); + delta = after - before; + Serial.printf("delta = %lu\n", delta); - REQUIRE(fuzzycomp(delta, (timeType)3000)); + REQUIRE(fuzzycomp(delta, (timeType)3000)); } TEST_CASE("Periodic Timeout 10T 1000ms", "[polledTimeout]") { - using esp8266::polledTimeout::periodicMs; - using timeType = periodicMs::timeType; - timeType before, after, delta; + using esp8266::polledTimeout::periodicMs; + using timeType = periodicMs::timeType; + timeType before, after, delta; - Serial.println("Periodic 10T Timeout 1000ms"); + Serial.println("Periodic 10T Timeout 1000ms"); - int counter = 10; + int counter = 10; - periodicMs timeout(1000); - before = millis(); - while(1) - { - if(timeout) + periodicMs timeout(1000); + before = millis(); + while (1) { - Serial.print("*"); - if(!--counter) - break; - yield(); + if (timeout) + { + Serial.print("*"); + if (!--counter) + { + break; + } + yield(); + } } - } - after = millis(); + after = millis(); - delta = after - before; - Serial.printf("\ndelta = %lu\n", delta); - REQUIRE(fuzzycomp(delta, (timeType)10000)); + delta = after - before; + Serial.printf("\ndelta = %lu\n", delta); + REQUIRE(fuzzycomp(delta, (timeType)10000)); } TEST_CASE("OneShot Timeout 3000ms reset to 1000ms custom yield", "[polledTimeout]") { - using YieldOrSkipPolicy = esp8266::polledTimeout::YieldPolicy::YieldOrSkip; - using oneShotMsYield = esp8266::polledTimeout::timeoutTemplate; - using timeType = oneShotMsYield::timeType; - timeType before, after, delta; + using YieldOrSkipPolicy = esp8266::polledTimeout::YieldPolicy::YieldOrSkip; + using oneShotMsYield = esp8266::polledTimeout::timeoutTemplate; + using timeType = oneShotMsYield::timeType; + timeType before, after, delta; - Serial.println("OneShot Timeout 3000ms"); + Serial.println("OneShot Timeout 3000ms"); - oneShotMsYield timeout(3000); - before = millis(); - while(!timeout.expired()); - after = millis(); + oneShotMsYield timeout(3000); + before = millis(); + while (!timeout.expired()); + after = millis(); - delta = after - before; - Serial.printf("delta = %lu\n", delta); + delta = after - before; + Serial.printf("delta = %lu\n", delta); - REQUIRE(fuzzycomp(delta, (timeType)3000)); + REQUIRE(fuzzycomp(delta, (timeType)3000)); - Serial.print("reset\n"); + Serial.print("reset\n"); - timeout.reset(1000); - before = millis(); - while(!timeout); - after = millis(); + timeout.reset(1000); + before = millis(); + while (!timeout); + after = millis(); - delta = after - before; - Serial.printf("delta = %lu\n", delta); + delta = after - before; + Serial.printf("delta = %lu\n", delta); - REQUIRE(fuzzycomp(delta, (timeType)1000)); + REQUIRE(fuzzycomp(delta, (timeType)1000)); } diff --git a/tests/host/core/test_Print.cpp b/tests/host/core/test_Print.cpp index e58539c59e..33baead1b0 100644 --- a/tests/host/core/test_Print.cpp +++ b/tests/host/core/test_Print.cpp @@ -1,17 +1,17 @@ /* - test_pgmspace.cpp - pgmspace tests - Copyright © 2016 Ivan Grokhotkov + test_pgmspace.cpp - pgmspace tests + Copyright © 2016 Ivan Grokhotkov - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - */ + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. +*/ #include #include diff --git a/tests/host/core/test_Updater.cpp b/tests/host/core/test_Updater.cpp index f3b850e130..ab8941694b 100644 --- a/tests/host/core/test_Updater.cpp +++ b/tests/host/core/test_Updater.cpp @@ -1,17 +1,17 @@ /* - test_Updater.cpp - Updater tests - Copyright © 2019 Earle F. Philhower, III + test_Updater.cpp - Updater tests + Copyright © 2019 Earle F. Philhower, III - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - */ + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. +*/ #include #include diff --git a/tests/host/core/test_md5builder.cpp b/tests/host/core/test_md5builder.cpp index 0041c2eb72..6f8075fe93 100644 --- a/tests/host/core/test_md5builder.cpp +++ b/tests/host/core/test_md5builder.cpp @@ -1,17 +1,17 @@ /* - test_md5builder.cpp - MD5Builder tests - Copyright © 2016 Ivan Grokhotkov + test_md5builder.cpp - MD5Builder tests + Copyright © 2016 Ivan Grokhotkov - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - */ + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. +*/ #include #include @@ -35,25 +35,28 @@ TEST_CASE("MD5Builder::add works as expected", "[core][MD5Builder]") TEST_CASE("MD5Builder::addHexString works as expected", "[core][MD5Builder]") { - WHEN("A char array is parsed"){ - MD5Builder builder; - builder.begin(); - const char * myPayload = "1234567890abcdeffedcba98765432106469676974616c7369676e61747572656170706c69636174696F6e73"; - builder.addHexString(myPayload); - builder.calculate(); - REQUIRE(builder.toString() == "47b937a6f9f12a4c389fa5854e023efb"); + WHEN("A char array is parsed") + { + MD5Builder builder; + builder.begin(); + const char * myPayload = "1234567890abcdeffedcba98765432106469676974616c7369676e61747572656170706c69636174696F6e73"; + builder.addHexString(myPayload); + builder.calculate(); + REQUIRE(builder.toString() == "47b937a6f9f12a4c389fa5854e023efb"); } - WHEN("A Arduino String is parsed"){ - MD5Builder builder; - builder.begin(); - builder.addHexString(String("1234567890abcdeffedcba98765432106469676974616c7369676e61747572656170706c69636174696f6e73")); - builder.calculate(); - REQUIRE(builder.toString() == "47b937a6f9f12a4c389fa5854e023efb"); + WHEN("A Arduino String is parsed") + { + MD5Builder builder; + builder.begin(); + builder.addHexString(String("1234567890abcdeffedcba98765432106469676974616c7369676e61747572656170706c69636174696f6e73")); + builder.calculate(); + REQUIRE(builder.toString() == "47b937a6f9f12a4c389fa5854e023efb"); } } -TEST_CASE("MD5Builder::addStream works", "[core][MD5Builder]"){ +TEST_CASE("MD5Builder::addStream works", "[core][MD5Builder]") +{ MD5Builder builder; const char* str = "MD5Builder::addStream_works_longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglong"; { diff --git a/tests/host/core/test_pgmspace.cpp b/tests/host/core/test_pgmspace.cpp index f44221c2b4..28fa6ca0f1 100644 --- a/tests/host/core/test_pgmspace.cpp +++ b/tests/host/core/test_pgmspace.cpp @@ -1,17 +1,17 @@ /* - test_pgmspace.cpp - pgmspace tests - Copyright © 2016 Ivan Grokhotkov + test_pgmspace.cpp - pgmspace tests + Copyright © 2016 Ivan Grokhotkov - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - */ + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. +*/ #include #include @@ -19,7 +19,8 @@ TEST_CASE("strstr_P works as strstr", "[core][pgmspace]") { - auto t = [](const char* h, const char* n) { + auto t = [](const char* h, const char* n) + { const char* strstr_P_result = strstr_P(h, n); const char* strstr_result = strstr(h, n); REQUIRE(strstr_P_result == strstr_result); @@ -27,7 +28,7 @@ TEST_CASE("strstr_P works as strstr", "[core][pgmspace]") // Test case data is from avr-libc, original copyright (c) 2007 Dmitry Xmelkov // See avr-libc/tests/simulate/pmstring/strstr_P.c - t ("", ""); + t("", ""); t("12345", ""); t("ababac", "abac"); t("", "a"); diff --git a/tests/host/core/test_string.cpp b/tests/host/core/test_string.cpp index cd844545d0..e2eaba3a99 100644 --- a/tests/host/core/test_string.cpp +++ b/tests/host/core/test_string.cpp @@ -1,17 +1,17 @@ /* - test_string.cpp - String tests - Copyright © 2018 Earle F. Philhower, III + test_string.cpp - String tests + Copyright © 2018 Earle F. Philhower, III - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - */ + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. +*/ #include #include @@ -52,10 +52,10 @@ TEST_CASE("String::replace", "[core][String]") TEST_CASE("String(value, base)", "[core][String]") { - String strbase2(9999,2); - String strbase8(9999,8); - String strbase10(9999,10); - String strbase16(9999,16); + String strbase2(9999, 2); + String strbase8(9999, 8); + String strbase10(9999, 10); + String strbase16(9999, 16); REQUIRE(strbase2 == "10011100001111"); REQUIRE(strbase8 == "23417"); REQUIRE(strbase10 == "9999"); @@ -64,7 +64,7 @@ TEST_CASE("String(value, base)", "[core][String]") String strnegf(-2.123, 3); REQUIRE(strnegi == "-9999"); REQUIRE(strnegf == "-2.123"); - String strbase16l((long)999999,16); + String strbase16l((long)999999, 16); REQUIRE(strbase16l == "f423f"); } @@ -78,7 +78,7 @@ TEST_CASE("String constructors", "[core][String]") REQUIRE(ib == "3e7"); String lb((unsigned long)3000000000, 8); REQUIRE(lb == "26264057000"); - String sl1((long)-2000000000, 10); + String sl1((long) -2000000000, 10); REQUIRE(sl1 == "-2000000000"); String s1("abcd"); String s2(s1); @@ -124,11 +124,11 @@ TEST_CASE("String concantenation", "[core][String]") REQUIRE(str == "abcdeabcde9872147483647-214748364869"); str += (unsigned int)1969; REQUIRE(str == "abcdeabcde9872147483647-2147483648691969"); - str += (long)-123; + str += (long) -123; REQUIRE(str == "abcdeabcde9872147483647-2147483648691969-123"); str += (unsigned long)321; REQUIRE(str == "abcdeabcde9872147483647-2147483648691969-123321"); - str += (float)-1.01; + str += (float) -1.01; REQUIRE(str == "abcdeabcde9872147483647-2147483648691969-123321-1.01"); str += (double)1.01; REQUIRE(str == "abcdeabcde9872147483647-2147483648691969-123321-1.011.01"); @@ -146,13 +146,13 @@ TEST_CASE("String concantenation", "[core][String]") REQUIRE(str.concat(str) == true); REQUIRE(str == "cleanclean"); // non-decimal negative #s should be as if they were unsigned - str = String((int)-100, 16); + str = String((int) -100, 16); REQUIRE(str == "ffffff9c"); - str = String((long)-101, 16); + str = String((long) -101, 16); REQUIRE(str == "ffffff9b"); - str = String((int)-100, 10); + str = String((int) -100, 10); REQUIRE(str == "-100"); - str = String((long)-100, 10); + str = String((long) -100, 10); REQUIRE(str == "-100"); // Non-zero-terminated array concatenation const char buff[] = "abcdefg"; @@ -161,12 +161,16 @@ TEST_CASE("String concantenation", "[core][String]") n = "1"; // Overwrite [1] with 0, but leave old junk in SSO space still n.concat(buff, 3); REQUIRE(n == "1abc"); // Ensure the trailing 0 is always present even w/this funky concat - for (int i=0; i<20; i++) - n.concat(buff, 1); // Add 20 'a's to go from SSO to normal string + for (int i = 0; i < 20; i++) + { + n.concat(buff, 1); // Add 20 'a's to go from SSO to normal string + } REQUIRE(n == "1abcaaaaaaaaaaaaaaaaaaaa"); n = ""; - for (int i=0; i<=5; i++) + for (int i = 0; i <= 5; i++) + { n.concat(buff, i); + } REQUIRE(n == "aababcabcdabcde"); n.concat(buff, 0); // And check no add'n REQUIRE(n == "aababcabcdabcde"); @@ -224,7 +228,7 @@ TEST_CASE("String conversion", "[core][String]") REQUIRE(l == INT_MIN); s = "3.14159"; float f = s.toFloat(); - REQUIRE( fabs(f - 3.14159) < 0.0001 ); + REQUIRE(fabs(f - 3.14159) < 0.0001); } TEST_CASE("String case", "[core][String]") @@ -246,7 +250,7 @@ TEST_CASE("String nulls", "[core][String]") s.trim(); s.toUpperCase(); s.toLowerCase(); - s.remove(1,1); + s.remove(1, 1); s.remove(10); s.replace("taco", "burrito"); s.replace('a', 'b'); @@ -268,7 +272,7 @@ TEST_CASE("String nulls", "[core][String]") REQUIRE(s == ""); REQUIRE(s.length() == 0); s.setCharAt(1, 't'); - REQUIRE(s.startsWith("abc",0) == false); + REQUIRE(s.startsWith("abc", 0) == false); REQUIRE(s.startsWith("def") == false); REQUIRE(s.equalsConstantTime("def") == false); REQUIRE(s.equalsConstantTime("") == true); @@ -299,125 +303,128 @@ TEST_CASE("String sizes near 8b", "[core][String]") String s15("12345678901234"); String s16("123456789012345"); String s17("1234567890123456"); - REQUIRE(!strcmp(s7.c_str(),"123456")); - REQUIRE(!strcmp(s8.c_str(),"1234567")); - REQUIRE(!strcmp(s9.c_str(),"12345678")); - REQUIRE(!strcmp(s15.c_str(),"12345678901234")); - REQUIRE(!strcmp(s16.c_str(),"123456789012345")); - REQUIRE(!strcmp(s17.c_str(),"1234567890123456")); + REQUIRE(!strcmp(s7.c_str(), "123456")); + REQUIRE(!strcmp(s8.c_str(), "1234567")); + REQUIRE(!strcmp(s9.c_str(), "12345678")); + REQUIRE(!strcmp(s15.c_str(), "12345678901234")); + REQUIRE(!strcmp(s16.c_str(), "123456789012345")); + REQUIRE(!strcmp(s17.c_str(), "1234567890123456")); s7 += '_'; s8 += '_'; s9 += '_'; s15 += '_'; s16 += '_'; s17 += '_'; - REQUIRE(!strcmp(s7.c_str(),"123456_")); - REQUIRE(!strcmp(s8.c_str(),"1234567_")); - REQUIRE(!strcmp(s9.c_str(),"12345678_")); - REQUIRE(!strcmp(s15.c_str(),"12345678901234_")); - REQUIRE(!strcmp(s16.c_str(),"123456789012345_")); - REQUIRE(!strcmp(s17.c_str(),"1234567890123456_")); + REQUIRE(!strcmp(s7.c_str(), "123456_")); + REQUIRE(!strcmp(s8.c_str(), "1234567_")); + REQUIRE(!strcmp(s9.c_str(), "12345678_")); + REQUIRE(!strcmp(s15.c_str(), "12345678901234_")); + REQUIRE(!strcmp(s16.c_str(), "123456789012345_")); + REQUIRE(!strcmp(s17.c_str(), "1234567890123456_")); } TEST_CASE("String SSO works", "[core][String]") { - // This test assumes that SSO_SIZE==8, if that changes the test must as well - String s; - s += "0"; - REQUIRE(s == "0"); - REQUIRE(s.length() == 1); - const char *savesso = s.c_str(); - s += 1; - REQUIRE(s.c_str() == savesso); - REQUIRE(s == "01"); - REQUIRE(s.length() == 2); - s += "2"; - REQUIRE(s.c_str() == savesso); - REQUIRE(s == "012"); - REQUIRE(s.length() == 3); - s += 3; - REQUIRE(s.c_str() == savesso); - REQUIRE(s == "0123"); - REQUIRE(s.length() == 4); - s += "4"; - REQUIRE(s.c_str() == savesso); - REQUIRE(s == "01234"); - REQUIRE(s.length() == 5); - s += "5"; - REQUIRE(s.c_str() == savesso); - REQUIRE(s == "012345"); - REQUIRE(s.length() == 6); - s += "6"; - REQUIRE(s.c_str() == savesso); - REQUIRE(s == "0123456"); - REQUIRE(s.length() == 7); - s += "7"; - REQUIRE(s.c_str() == savesso); - REQUIRE(s == "01234567"); - REQUIRE(s.length() == 8); - s += "8"; - REQUIRE(s.c_str() == savesso); - REQUIRE(s == "012345678"); - REQUIRE(s.length() == 9); - s += "9"; - REQUIRE(s.c_str() == savesso); - REQUIRE(s == "0123456789"); - REQUIRE(s.length() == 10); - if (sizeof(savesso) == 4) { - s += "a"; - REQUIRE(s.c_str() != savesso); - REQUIRE(s == "0123456789a"); - REQUIRE(s.length() == 11); - s += "b"; - REQUIRE(s.c_str() != savesso); - REQUIRE(s == "0123456789ab"); - REQUIRE(s.length() == 12); - s += "c"; - REQUIRE(s.c_str() != savesso); - REQUIRE(s == "0123456789abc"); - REQUIRE(s.length() == 13); - } else { - s += "a"; + // This test assumes that SSO_SIZE==8, if that changes the test must as well + String s; + s += "0"; + REQUIRE(s == "0"); + REQUIRE(s.length() == 1); + const char *savesso = s.c_str(); + s += 1; + REQUIRE(s.c_str() == savesso); + REQUIRE(s == "01"); + REQUIRE(s.length() == 2); + s += "2"; + REQUIRE(s.c_str() == savesso); + REQUIRE(s == "012"); + REQUIRE(s.length() == 3); + s += 3; + REQUIRE(s.c_str() == savesso); + REQUIRE(s == "0123"); + REQUIRE(s.length() == 4); + s += "4"; + REQUIRE(s.c_str() == savesso); + REQUIRE(s == "01234"); + REQUIRE(s.length() == 5); + s += "5"; + REQUIRE(s.c_str() == savesso); + REQUIRE(s == "012345"); + REQUIRE(s.length() == 6); + s += "6"; + REQUIRE(s.c_str() == savesso); + REQUIRE(s == "0123456"); + REQUIRE(s.length() == 7); + s += "7"; + REQUIRE(s.c_str() == savesso); + REQUIRE(s == "01234567"); + REQUIRE(s.length() == 8); + s += "8"; REQUIRE(s.c_str() == savesso); - REQUIRE(s == "0123456789a"); - REQUIRE(s.length() == 11); - s += "bcde"; + REQUIRE(s == "012345678"); + REQUIRE(s.length() == 9); + s += "9"; REQUIRE(s.c_str() == savesso); - REQUIRE(s == "0123456789abcde"); - REQUIRE(s.length() == 15); - s += "fghi"; - REQUIRE(s.c_str() != savesso); - REQUIRE(s == "0123456789abcdefghi"); - REQUIRE(s.length() == 19); - s += "j"; - REQUIRE(s.c_str() != savesso); - REQUIRE(s == "0123456789abcdefghij"); - REQUIRE(s.length() == 20); - s += "k"; - REQUIRE(s.c_str() != savesso); - REQUIRE(s == "0123456789abcdefghijk"); - REQUIRE(s.length() == 21); - s += "l"; - REQUIRE(s.c_str() != savesso); - REQUIRE(s == "0123456789abcdefghijkl"); - REQUIRE(s.length() == 22); - s += "m"; - REQUIRE(s.c_str() != savesso); - REQUIRE(s == "0123456789abcdefghijklm"); - REQUIRE(s.length() == 23); - s += "nopq"; - REQUIRE(s.c_str() != savesso); - REQUIRE(s == "0123456789abcdefghijklmnopq"); - REQUIRE(s.length() == 27); - s += "rstu"; - REQUIRE(s.c_str() != savesso); - REQUIRE(s == "0123456789abcdefghijklmnopqrstu"); - REQUIRE(s.length() == 31); - } - s = "0123456789abcde"; - s = s.substring(s.indexOf('a')); - REQUIRE(s == "abcde"); - REQUIRE(s.length() == 5); + REQUIRE(s == "0123456789"); + REQUIRE(s.length() == 10); + if (sizeof(savesso) == 4) + { + s += "a"; + REQUIRE(s.c_str() != savesso); + REQUIRE(s == "0123456789a"); + REQUIRE(s.length() == 11); + s += "b"; + REQUIRE(s.c_str() != savesso); + REQUIRE(s == "0123456789ab"); + REQUIRE(s.length() == 12); + s += "c"; + REQUIRE(s.c_str() != savesso); + REQUIRE(s == "0123456789abc"); + REQUIRE(s.length() == 13); + } + else + { + s += "a"; + REQUIRE(s.c_str() == savesso); + REQUIRE(s == "0123456789a"); + REQUIRE(s.length() == 11); + s += "bcde"; + REQUIRE(s.c_str() == savesso); + REQUIRE(s == "0123456789abcde"); + REQUIRE(s.length() == 15); + s += "fghi"; + REQUIRE(s.c_str() != savesso); + REQUIRE(s == "0123456789abcdefghi"); + REQUIRE(s.length() == 19); + s += "j"; + REQUIRE(s.c_str() != savesso); + REQUIRE(s == "0123456789abcdefghij"); + REQUIRE(s.length() == 20); + s += "k"; + REQUIRE(s.c_str() != savesso); + REQUIRE(s == "0123456789abcdefghijk"); + REQUIRE(s.length() == 21); + s += "l"; + REQUIRE(s.c_str() != savesso); + REQUIRE(s == "0123456789abcdefghijkl"); + REQUIRE(s.length() == 22); + s += "m"; + REQUIRE(s.c_str() != savesso); + REQUIRE(s == "0123456789abcdefghijklm"); + REQUIRE(s.length() == 23); + s += "nopq"; + REQUIRE(s.c_str() != savesso); + REQUIRE(s == "0123456789abcdefghijklmnopq"); + REQUIRE(s.length() == 27); + s += "rstu"; + REQUIRE(s.c_str() != savesso); + REQUIRE(s == "0123456789abcdefghijklmnopqrstu"); + REQUIRE(s.length() == 31); + } + s = "0123456789abcde"; + s = s.substring(s.indexOf('a')); + REQUIRE(s == "abcde"); + REQUIRE(s.length() == 5); } #include @@ -429,64 +436,64 @@ void repl(const String& key, const String& val, String& s, boolean useURLencode) TEST_CASE("String SSO handles junk in memory", "[core][String]") { - // We fill the SSO space with garbage then construct an object in it and check consistency - // This is NOT how you want to use Strings outside of this testing! - unsigned char space[64]; - String *s = (String*)space; - memset(space, 0xff, 64); - new(s) String; - REQUIRE(*s == ""); - s->~String(); - - // Tests from #5883 - bool useURLencode = false; - const char euro[4] = {(char)0xe2, (char)0x82, (char)0xac, 0}; // Unicode euro symbol - const char yen[3] = {(char)0xc2, (char)0xa5, 0}; // Unicode yen symbol - - memset(space, 0xff, 64); - new(s) String("%ssid%"); - repl(("%ssid%"), "MikroTik", *s, useURLencode); - REQUIRE(*s == "MikroTik"); - s->~String(); - - memset(space, 0xff, 64); - new(s) String("{E}"); - repl(("{E}"), euro, *s, useURLencode); - REQUIRE(*s == "€"); - s->~String(); - memset(space, 0xff, 64); - new(s) String("€"); - repl(("€"), euro, *s, useURLencode); - REQUIRE(*s == "€"); - s->~String(); - memset(space, 0xff, 64); - new(s) String("{Y}"); - repl(("{Y}"), yen, *s, useURLencode); - REQUIRE(*s == "¥"); - s->~String(); - memset(space, 0xff, 64); - new(s) String("¥"); - repl(("¥"), yen, *s, useURLencode); - REQUIRE(*s == "¥"); - s->~String(); - - memset(space, 0xff, 64); - new(s) String("%sysname%"); - repl(("%sysname%"), "CO2_defect", *s, useURLencode); - REQUIRE(*s == "CO2_defect"); - s->~String(); + // We fill the SSO space with garbage then construct an object in it and check consistency + // This is NOT how you want to use Strings outside of this testing! + unsigned char space[64]; + String *s = (String*)space; + memset(space, 0xff, 64); + new (s) String; + REQUIRE(*s == ""); + s->~String(); + + // Tests from #5883 + bool useURLencode = false; + const char euro[4] = {(char)0xe2, (char)0x82, (char)0xac, 0}; // Unicode euro symbol + const char yen[3] = {(char)0xc2, (char)0xa5, 0}; // Unicode yen symbol + + memset(space, 0xff, 64); + new (s) String("%ssid%"); + repl(("%ssid%"), "MikroTik", *s, useURLencode); + REQUIRE(*s == "MikroTik"); + s->~String(); + + memset(space, 0xff, 64); + new (s) String("{E}"); + repl(("{E}"), euro, *s, useURLencode); + REQUIRE(*s == "€"); + s->~String(); + memset(space, 0xff, 64); + new (s) String("€"); + repl(("€"), euro, *s, useURLencode); + REQUIRE(*s == "€"); + s->~String(); + memset(space, 0xff, 64); + new (s) String("{Y}"); + repl(("{Y}"), yen, *s, useURLencode); + REQUIRE(*s == "¥"); + s->~String(); + memset(space, 0xff, 64); + new (s) String("¥"); + repl(("¥"), yen, *s, useURLencode); + REQUIRE(*s == "¥"); + s->~String(); + + memset(space, 0xff, 64); + new (s) String("%sysname%"); + repl(("%sysname%"), "CO2_defect", *s, useURLencode); + REQUIRE(*s == "CO2_defect"); + s->~String(); } TEST_CASE("Issue #5949 - Overlapping src/dest in replace", "[core][String]") { - String blah = "blah"; - blah.replace("xx", "y"); - REQUIRE(blah == "blah"); - blah.replace("x", "yy"); - REQUIRE(blah == "blah"); - blah.replace(blah, blah); - REQUIRE(blah == "blah"); + String blah = "blah"; + blah.replace("xx", "y"); + REQUIRE(blah == "blah"); + blah.replace("x", "yy"); + REQUIRE(blah == "blah"); + blah.replace(blah, blah); + REQUIRE(blah == "blah"); } @@ -502,97 +509,100 @@ TEST_CASE("Issue #2736 - StreamString SSO fix", "[core][StreamString]") TEST_CASE("Strings with NULs", "[core][String]") { - // The following should never be done in a real app! This is only to inject 0s in the middle of a string. - // Fits in SSO... - String str("01234567"); - REQUIRE(str.length() == 8); - char *ptr = (char *)str.c_str(); - ptr[3] = 0; - String str2; - str2 = str; - REQUIRE(str2.length() == 8); - // Needs a buffer pointer - str = "0123456789012345678901234567890123456789"; - ptr = (char *)str.c_str(); - ptr[3] = 0; - str2 = str; - REQUIRE(str2.length() == 40); - String str3("a"); - ptr = (char *)str3.c_str(); - *ptr = 0; - REQUIRE(str3.length() == 1); - str3 += str3; - REQUIRE(str3.length() == 2); - str3 += str3; - REQUIRE(str3.length() == 4); - str3 += str3; - REQUIRE(str3.length() == 8); - str3 += str3; - REQUIRE(str3.length() == 16); - str3 += str3; - REQUIRE(str3.length() == 32); - str3 += str3; - REQUIRE(str3.length() == 64); - static char zeros[64] = {0}; - const char *p = str3.c_str(); - REQUIRE(!memcmp(p, zeros, 64)); + // The following should never be done in a real app! This is only to inject 0s in the middle of a string. + // Fits in SSO... + String str("01234567"); + REQUIRE(str.length() == 8); + char *ptr = (char *)str.c_str(); + ptr[3] = 0; + String str2; + str2 = str; + REQUIRE(str2.length() == 8); + // Needs a buffer pointer + str = "0123456789012345678901234567890123456789"; + ptr = (char *)str.c_str(); + ptr[3] = 0; + str2 = str; + REQUIRE(str2.length() == 40); + String str3("a"); + ptr = (char *)str3.c_str(); + *ptr = 0; + REQUIRE(str3.length() == 1); + str3 += str3; + REQUIRE(str3.length() == 2); + str3 += str3; + REQUIRE(str3.length() == 4); + str3 += str3; + REQUIRE(str3.length() == 8); + str3 += str3; + REQUIRE(str3.length() == 16); + str3 += str3; + REQUIRE(str3.length() == 32); + str3 += str3; + REQUIRE(str3.length() == 64); + static char zeros[64] = {0}; + const char *p = str3.c_str(); + REQUIRE(!memcmp(p, zeros, 64)); } TEST_CASE("Replace and string expansion", "[core][String]") { - String s, l; - // Make these large enough to span SSO and non SSO - String whole = "#123456789012345678901234567890"; - const char *res = "abcde123456789012345678901234567890"; - for (size_t i=1; i < whole.length(); i++) { - s = whole.substring(0, i); - l = s; - l.replace("#", "abcde"); - char buff[64]; - strcpy(buff, res); - buff[5 + i-1] = 0; - REQUIRE(!strcmp(l.c_str(), buff)); - REQUIRE(l.length() == strlen(buff)); - } + String s, l; + // Make these large enough to span SSO and non SSO + String whole = "#123456789012345678901234567890"; + const char *res = "abcde123456789012345678901234567890"; + for (size_t i = 1; i < whole.length(); i++) + { + s = whole.substring(0, i); + l = s; + l.replace("#", "abcde"); + char buff[64]; + strcpy(buff, res); + buff[5 + i - 1] = 0; + REQUIRE(!strcmp(l.c_str(), buff)); + REQUIRE(l.length() == strlen(buff)); + } } TEST_CASE("String chaining", "[core][String]") { - const char* chunks[] { - "~12345", - "67890", - "qwertyuiopasdfghjkl", - "zxcvbnm" - }; - - String all; - for (auto* chunk : chunks) { - all += chunk; - } - - // make sure we can chain a combination of things to form a String - REQUIRE((String(chunks[0]) + String(chunks[1]) + String(chunks[2]) + String(chunks[3])) == all); - REQUIRE((chunks[0] + String(chunks[1]) + F(chunks[2]) + chunks[3]) == all); - REQUIRE((String(chunks[0]) + F(chunks[1]) + F(chunks[2]) + String(chunks[3])) == all); - REQUIRE(('~' + String(&chunks[0][0] + 1) + chunks[1] + String(chunks[2]) + F(chunks[3])) == all); - REQUIRE((String(chunks[0]) + '6' + (&chunks[1][0] + 1) + String(chunks[2]) + F(chunks[3])) == all); - - // these are still invalid (and also cannot compile at all): - // - `F(...)` + `F(...)` - // - `F(...)` + `const char*` - // - `const char*` + `F(...)` - // we need `String()` as either rhs or lhs - - // ensure chaining reuses the buffer - // (internal details...) - { - String tmp(chunks[3]); - tmp.reserve(2 * all.length()); - auto* ptr = tmp.c_str(); - String result("~1" + String(&chunks[0][0] + 2) + F(chunks[1]) + chunks[2] + std::move(tmp)); - REQUIRE(result == all); - REQUIRE(static_cast(result.c_str()) == static_cast(ptr)); - } + const char* chunks[] + { + "~12345", + "67890", + "qwertyuiopasdfghjkl", + "zxcvbnm" + }; + + String all; + for (auto* chunk : chunks) + { + all += chunk; + } + + // make sure we can chain a combination of things to form a String + REQUIRE((String(chunks[0]) + String(chunks[1]) + String(chunks[2]) + String(chunks[3])) == all); + REQUIRE((chunks[0] + String(chunks[1]) + F(chunks[2]) + chunks[3]) == all); + REQUIRE((String(chunks[0]) + F(chunks[1]) + F(chunks[2]) + String(chunks[3])) == all); + REQUIRE(('~' + String(&chunks[0][0] + 1) + chunks[1] + String(chunks[2]) + F(chunks[3])) == all); + REQUIRE((String(chunks[0]) + '6' + (&chunks[1][0] + 1) + String(chunks[2]) + F(chunks[3])) == all); + + // these are still invalid (and also cannot compile at all): + // - `F(...)` + `F(...)` + // - `F(...)` + `const char*` + // - `const char*` + `F(...)` + // we need `String()` as either rhs or lhs + + // ensure chaining reuses the buffer + // (internal details...) + { + String tmp(chunks[3]); + tmp.reserve(2 * all.length()); + auto* ptr = tmp.c_str(); + String result("~1" + String(&chunks[0][0] + 2) + F(chunks[1]) + chunks[2] + std::move(tmp)); + REQUIRE(result == all); + REQUIRE(static_cast(result.c_str()) == static_cast(ptr)); + } } TEST_CASE("String concat OOB #8198", "[core][String]") diff --git a/tests/host/fs/test_fs.cpp b/tests/host/fs/test_fs.cpp index fb73a6a271..dad26483a6 100644 --- a/tests/host/fs/test_fs.cpp +++ b/tests/host/fs/test_fs.cpp @@ -1,16 +1,16 @@ /* - test_fs.cpp - host side file system tests - Copyright © 2016 Ivan Grokhotkov - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. + test_fs.cpp - host side file system tests + Copyright © 2016 Ivan Grokhotkov + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. */ #include @@ -25,7 +25,8 @@ #include "../../../libraries/SD/src/SD.h" -namespace spiffs_test { +namespace spiffs_test +{ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" @@ -62,7 +63,8 @@ TEST_CASE("SPIFFS checks the config object passed in", "[fs]") }; -namespace littlefs_test { +namespace littlefs_test +{ #define FSTYPE LittleFS #define TESTPRE "LittleFS - " #define TESTPAT "[lfs]" @@ -95,7 +97,8 @@ TEST_CASE("LittleFS checks the config object passed in", "[fs]") }; -namespace sdfs_test { +namespace sdfs_test +{ #define FSTYPE SDFS #define TESTPRE "SDFS - " #define TESTPAT "[sdfs]" @@ -142,7 +145,7 @@ TEST_CASE("SD.h FILE_WRITE macro is append", "[fs]") f.write(65); f.write("bbcc"); f.write("theend", 6); - char block[3]={'x','y','z'}; + char block[3] = {'x', 'y', 'z'}; f.write(block, 3); uint32_t bigone = 0x40404040; f.write((const uint8_t*)&bigone, 4); diff --git a/tests/host/sys/pgmspace.h b/tests/host/sys/pgmspace.h index ecc4558351..5426685bf8 100644 --- a/tests/host/sys/pgmspace.h +++ b/tests/host/sys/pgmspace.h @@ -27,17 +27,17 @@ #endif #ifdef __cplusplus - #define pgm_read_byte(addr) (*reinterpret_cast(addr)) - #define pgm_read_word(addr) (*reinterpret_cast(addr)) - #define pgm_read_dword(addr) (*reinterpret_cast(addr)) - #define pgm_read_float(addr) (*reinterpret_cast(addr)) - #define pgm_read_ptr(addr) (*reinterpret_cast(addr)) +#define pgm_read_byte(addr) (*reinterpret_cast(addr)) +#define pgm_read_word(addr) (*reinterpret_cast(addr)) +#define pgm_read_dword(addr) (*reinterpret_cast(addr)) +#define pgm_read_float(addr) (*reinterpret_cast(addr)) +#define pgm_read_ptr(addr) (*reinterpret_cast(addr)) #else - #define pgm_read_byte(addr) (*(const uint8_t*)(addr)) - #define pgm_read_word(addr) (*(const uint16_t*)(addr)) - #define pgm_read_dword(addr) (*(const uint32_t*)(addr)) - #define pgm_read_float(addr) (*(const float)(addr)) - #define pgm_read_ptr(addr) (*(const void* const *)(addr)) +#define pgm_read_byte(addr) (*(const uint8_t*)(addr)) +#define pgm_read_word(addr) (*(const uint16_t*)(addr)) +#define pgm_read_dword(addr) (*(const uint32_t*)(addr)) +#define pgm_read_float(addr) (*(const float)(addr)) +#define pgm_read_ptr(addr) (*(const void* const *)(addr)) #endif #define pgm_read_byte_near(addr) pgm_read_byte(addr) @@ -54,10 +54,22 @@ // Wrapper inlines for _P functions #include #include -inline const char *strstr_P(const char *haystack, const char *needle) { return strstr(haystack, needle); } -inline char *strcpy_P(char *dest, const char *src) { return strcpy(dest, src); } -inline size_t strlen_P(const char *s) { return strlen(s); } -inline int vsnprintf_P(char *str, size_t size, const char *format, va_list ap) { return vsnprintf(str, size, format, ap); } +inline const char *strstr_P(const char *haystack, const char *needle) +{ + return strstr(haystack, needle); +} +inline char *strcpy_P(char *dest, const char *src) +{ + return strcpy(dest, src); +} +inline size_t strlen_P(const char *s) +{ + return strlen(s); +} +inline int vsnprintf_P(char *str, size_t size, const char *format, va_list ap) +{ + return vsnprintf(str, size, format, ap); +} #define memcpy_P memcpy #define memmove_P memmove diff --git a/tests/restyle.sh b/tests/restyle.sh index ea454069c5..e7fdbc6c28 100755 --- a/tests/restyle.sh +++ b/tests/restyle.sh @@ -20,6 +20,7 @@ cores/esp8266/core_esp8266_si2c.cpp cores/esp8266/StreamString.* cores/esp8266/StreamSend.* libraries/Netdump +tests " # core From b130c8b556b9bf3e2589807de207cfaae056c070 Mon Sep 17 00:00:00 2001 From: David Gauchard Date: Wed, 19 Jan 2022 17:55:24 +0100 Subject: [PATCH 02/15] wip: use clang-format --- .clang-format | 7 + .github/workflows/pull-request.yml | 2 +- cores/esp8266/LwipDhcpServer-NonOS.cpp | 7 +- cores/esp8266/LwipDhcpServer.cpp | 438 ++++--- cores/esp8266/LwipDhcpServer.h | 66 +- cores/esp8266/LwipIntf.cpp | 20 +- cores/esp8266/LwipIntf.h | 16 +- cores/esp8266/LwipIntfCB.cpp | 16 +- cores/esp8266/LwipIntfDev.h | 107 +- cores/esp8266/StreamSend.cpp | 22 +- cores/esp8266/StreamString.h | 87 +- cores/esp8266/core_esp8266_si2c.cpp | 373 +++--- cores/esp8266/debug.cpp | 4 +- cores/esp8266/debug.h | 44 +- libraries/ESP8266mDNS/src/ESP8266mDNS.cpp | 1 - libraries/ESP8266mDNS/src/ESP8266mDNS.h | 6 +- libraries/ESP8266mDNS/src/LEAmDNS.cpp | 531 ++++----- libraries/ESP8266mDNS/src/LEAmDNS.h | 358 +++--- libraries/ESP8266mDNS/src/LEAmDNS_Control.cpp | 839 ++++++------- libraries/ESP8266mDNS/src/LEAmDNS_Helpers.cpp | 275 ++--- libraries/ESP8266mDNS/src/LEAmDNS_Priv.h | 62 +- libraries/ESP8266mDNS/src/LEAmDNS_Structs.cpp | 619 ++++------ .../ESP8266mDNS/src/LEAmDNS_Transfer.cpp | 1033 ++++++++--------- libraries/ESP8266mDNS/src/LEAmDNS_lwIPdefs.h | 2 +- .../Netdump/examples/Netdump/Netdump.ino | 66 +- libraries/Netdump/src/Netdump.cpp | 57 +- libraries/Netdump/src/Netdump.h | 23 +- libraries/Netdump/src/NetdumpIP.cpp | 162 ++- libraries/Netdump/src/NetdumpIP.h | 34 +- libraries/Netdump/src/NetdumpPacket.cpp | 209 ++-- libraries/Netdump/src/NetdumpPacket.h | 40 +- libraries/Netdump/src/PacketType.cpp | 58 +- libraries/Netdump/src/PacketType.h | 9 +- libraries/SoftwareSerial | 2 +- libraries/Wire/Wire.cpp | 12 +- libraries/Wire/Wire.h | 15 +- libraries/lwIP_PPP/src/PPPServer.cpp | 120 +- libraries/lwIP_PPP/src/PPPServer.h | 10 +- libraries/lwIP_enc28j60/src/ENC28J60lwIP.h | 2 +- .../lwIP_enc28j60/src/utility/enc28j60.cpp | 146 ++- .../lwIP_enc28j60/src/utility/enc28j60.h | 23 +- libraries/lwIP_w5100/src/W5100lwIP.h | 2 +- libraries/lwIP_w5100/src/utility/w5100.cpp | 43 +- libraries/lwIP_w5100/src/utility/w5100.h | 163 ++- libraries/lwIP_w5500/src/W5500lwIP.h | 2 +- libraries/lwIP_w5500/src/utility/w5500.cpp | 31 +- libraries/lwIP_w5500/src/utility/w5500.h | 115 +- tests/device/libraries/BSTest/src/BSArduino.h | 15 +- tests/device/libraries/BSTest/src/BSArgs.h | 162 +-- .../device/libraries/BSTest/src/BSProtocol.h | 32 +- tests/device/libraries/BSTest/src/BSStdio.h | 8 +- tests/device/libraries/BSTest/src/BSTest.h | 58 +- tests/device/libraries/BSTest/test/test.cpp | 8 +- tests/device/test_libc/libm_string.c | 499 ++++---- tests/device/test_libc/memcpy-1.c | 56 +- tests/device/test_libc/memmove1.c | 44 +- tests/device/test_libc/strcmp-1.c | 72 +- tests/device/test_libc/tstring.c | 143 ++- tests/host/common/Arduino.cpp | 3 +- tests/host/common/ArduinoCatch.cpp | 3 +- tests/host/common/ArduinoMain.cpp | 136 +-- tests/host/common/ArduinoMainLittlefs.cpp | 1 - tests/host/common/ArduinoMainSpiffs.cpp | 1 - tests/host/common/ClientContextSocket.cpp | 13 +- tests/host/common/ClientContextTools.cpp | 10 +- tests/host/common/EEPROM.h | 8 +- tests/host/common/HostWiring.cpp | 36 +- tests/host/common/MockDigital.cpp | 13 +- tests/host/common/MockEEPROM.cpp | 9 +- tests/host/common/MockEsp.cpp | 48 +- tests/host/common/MockTools.cpp | 13 +- tests/host/common/MockUART.cpp | 131 +-- tests/host/common/MockWiFiServer.cpp | 1 - tests/host/common/MockWiFiServerSocket.cpp | 9 +- tests/host/common/MocklwIP.cpp | 12 +- tests/host/common/MocklwIP.h | 7 +- tests/host/common/UdpContextSocket.cpp | 31 +- tests/host/common/WMath.cpp | 5 +- tests/host/common/c_types.h | 77 +- tests/host/common/flash_hal_mock.cpp | 6 +- tests/host/common/flash_hal_mock.h | 4 +- tests/host/common/include/ClientContext.h | 29 +- tests/host/common/include/UdpContext.h | 33 +- tests/host/common/littlefs_mock.cpp | 31 +- tests/host/common/littlefs_mock.h | 8 +- tests/host/common/md5.c | 210 ++-- tests/host/common/mock.h | 56 +- tests/host/common/noniso.c | 19 +- tests/host/common/pins_arduino.h | 1 - tests/host/common/queue.h | 666 ++++++----- tests/host/common/sdfs_mock.cpp | 2 +- tests/host/common/sdfs_mock.h | 29 +- tests/host/common/spiffs_mock.cpp | 28 +- tests/host/common/spiffs_mock.h | 8 +- tests/host/common/strl.cpp | 30 +- tests/host/common/user_interface.cpp | 73 +- tests/host/core/test_PolledTimeout.cpp | 17 +- tests/host/core/test_Print.cpp | 28 +- tests/host/core/test_Updater.cpp | 5 +- tests/host/core/test_md5builder.cpp | 7 +- tests/host/core/test_pgmspace.cpp | 4 +- tests/host/core/test_string.cpp | 61 +- tests/host/fs/test_fs.cpp | 29 +- tests/host/sys/pgmspace.h | 52 +- tests/restyle.sh | 7 +- tools/sdk/lwip2/builder | 2 +- 106 files changed, 4515 insertions(+), 4873 deletions(-) create mode 100644 .clang-format diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000000..a54f0962b7 --- /dev/null +++ b/.clang-format @@ -0,0 +1,7 @@ +BasedOnStyle: Chromium +AlignTrailingComments: true +BreakBeforeBraces: Allman +ColumnLimit: 0 +IndentWidth: 4 +KeepEmptyLinesAtTheStartOfBlocks: false +SpacesBeforeTrailingComments: 2 diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 74f1b43063..2606963a83 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -242,7 +242,7 @@ jobs: TRAVIS_TAG: ${{ github.ref }} run: | sudo apt update - sudo apt install astyle + sudo apt install astyle clang-format bash ./tests/ci/style_check.sh diff --git a/cores/esp8266/LwipDhcpServer-NonOS.cpp b/cores/esp8266/LwipDhcpServer-NonOS.cpp index 0bd04ebcfe..aee22b6d5c 100644 --- a/cores/esp8266/LwipDhcpServer-NonOS.cpp +++ b/cores/esp8266/LwipDhcpServer-NonOS.cpp @@ -23,7 +23,7 @@ // these functions must exists as-is with "C" interface, // nonos-sdk calls them at boot time and later -#include // LWIP_VERSION +#include // LWIP_VERSION #include #include "LwipDhcpServer.h" @@ -35,8 +35,7 @@ DhcpServer dhcpSoftAP(&netif_git[SOFTAP_IF]); extern "C" { - - void dhcps_start(struct ip_info *info, netif* apnetif) + void dhcps_start(struct ip_info* info, netif* apnetif) { // apnetif is esp interface, replaced by lwip2's // netif_git[SOFTAP_IF] interface in constructor @@ -61,4 +60,4 @@ extern "C" dhcpSoftAP.end(); } -} // extern "C" +} // extern "C" diff --git a/cores/esp8266/LwipDhcpServer.cpp b/cores/esp8266/LwipDhcpServer.cpp index 86f8849a91..869c9350a9 100644 --- a/cores/esp8266/LwipDhcpServer.cpp +++ b/cores/esp8266/LwipDhcpServer.cpp @@ -34,23 +34,23 @@ // (better is enemy of [good = already working]) // ^^ this comment is supposed to be removed after the first commit -#include // LWIP_VERSION +#include // LWIP_VERSION -#define DHCPS_LEASE_TIME_DEF (120) +#define DHCPS_LEASE_TIME_DEF (120) #define USE_DNS -#include "lwip/inet.h" #include "lwip/err.h" +#include "lwip/inet.h" +#include "lwip/mem.h" #include "lwip/pbuf.h" #include "lwip/udp.h" -#include "lwip/mem.h" #include "osapi.h" #include "LwipDhcpServer.h" -#include "user_interface.h" #include "mem.h" +#include "user_interface.h" typedef struct dhcps_state { @@ -107,46 +107,45 @@ struct dhcps_pool uint32 lease_timer; dhcps_type_t type; dhcps_state_t state; - }; -#define DHCPS_LEASE_TIMER dhcps_lease_time //0x05A0 +#define DHCPS_LEASE_TIMER dhcps_lease_time //0x05A0 #define DHCPS_MAX_LEASE 0x64 #define BOOTP_BROADCAST 0x8000 -#define DHCP_REQUEST 1 -#define DHCP_REPLY 2 +#define DHCP_REQUEST 1 +#define DHCP_REPLY 2 #define DHCP_HTYPE_ETHERNET 1 -#define DHCP_HLEN_ETHERNET 6 -#define DHCP_MSG_LEN 236 - -#define DHCPS_SERVER_PORT 67 -#define DHCPS_CLIENT_PORT 68 - -#define DHCPDISCOVER 1 -#define DHCPOFFER 2 -#define DHCPREQUEST 3 -#define DHCPDECLINE 4 -#define DHCPACK 5 -#define DHCPNAK 6 -#define DHCPRELEASE 7 - -#define DHCP_OPTION_SUBNET_MASK 1 -#define DHCP_OPTION_ROUTER 3 -#define DHCP_OPTION_DNS_SERVER 6 -#define DHCP_OPTION_REQ_IPADDR 50 -#define DHCP_OPTION_LEASE_TIME 51 -#define DHCP_OPTION_MSG_TYPE 53 -#define DHCP_OPTION_SERVER_ID 54 +#define DHCP_HLEN_ETHERNET 6 +#define DHCP_MSG_LEN 236 + +#define DHCPS_SERVER_PORT 67 +#define DHCPS_CLIENT_PORT 68 + +#define DHCPDISCOVER 1 +#define DHCPOFFER 2 +#define DHCPREQUEST 3 +#define DHCPDECLINE 4 +#define DHCPACK 5 +#define DHCPNAK 6 +#define DHCPRELEASE 7 + +#define DHCP_OPTION_SUBNET_MASK 1 +#define DHCP_OPTION_ROUTER 3 +#define DHCP_OPTION_DNS_SERVER 6 +#define DHCP_OPTION_REQ_IPADDR 50 +#define DHCP_OPTION_LEASE_TIME 51 +#define DHCP_OPTION_MSG_TYPE 53 +#define DHCP_OPTION_SERVER_ID 54 #define DHCP_OPTION_INTERFACE_MTU 26 #define DHCP_OPTION_PERFORM_ROUTER_DISCOVERY 31 #define DHCP_OPTION_BROADCAST_ADDRESS 28 -#define DHCP_OPTION_REQ_LIST 55 -#define DHCP_OPTION_END 255 +#define DHCP_OPTION_REQ_LIST 55 +#define DHCP_OPTION_END 255 //#define USE_CLASS_B_NET 1 -#define DHCPS_DEBUG 0 -#define MAX_STATION_NUM 8 +#define DHCPS_DEBUG 0 +#define MAX_STATION_NUM 8 #define DHCPS_STATE_OFFER 1 #define DHCPS_STATE_DECLINE 2 @@ -155,25 +154,35 @@ struct dhcps_pool #define DHCPS_STATE_IDLE 5 #define DHCPS_STATE_RELEASE 6 -#define dhcps_router_enabled(offer) ((offer & OFFER_ROUTER) != 0) +#define dhcps_router_enabled(offer) ((offer & OFFER_ROUTER) != 0) #ifdef MEMLEAK_DEBUG const char mem_debug_file[] ICACHE_RODATA_ATTR = __FILE__; #endif #if DHCPS_DEBUG -#define LWIP_IS_OK(what,err) ({ int ret = 1, errval = (err); if (errval != ERR_OK) { os_printf("DHCPS ERROR: %s (lwip:%d)\n", what, errval); ret = 0; } ret; }) +#define LWIP_IS_OK(what, err) ( \ + { \ + int ret = 1, errval = (err); \ + if (errval != ERR_OK) \ + { \ + os_printf("DHCPS ERROR: %s (lwip:%d)\n", what, errval); \ + ret = 0; \ + } \ + ret; \ + }) #else -#define LWIP_IS_OK(what,err) ((err) == ERR_OK) +#define LWIP_IS_OK(what, err) ((err) == ERR_OK) #endif -const uint32 DhcpServer::magic_cookie = 0x63538263; // https://tools.ietf.org/html/rfc1497 +const uint32 DhcpServer::magic_cookie = 0x63538263; // https://tools.ietf.org/html/rfc1497 int fw_has_started_softap_dhcps = 0; //////////////////////////////////////////////////////////////////////////////////// -DhcpServer::DhcpServer(netif* netif): _netif(netif) +DhcpServer::DhcpServer(netif* netif) + : _netif(netif) { pcb_dhcps = nullptr; dns_address.addr = 0; @@ -189,13 +198,13 @@ DhcpServer::DhcpServer(netif* netif): _netif(netif) // 2. global ctor DhcpServer's `dhcpSoftAP(&netif_git[SOFTAP_IF])` is called // 3. (that's here) => begin(legacy-values) is called ip_info ip = - { - { 0x0104a8c0 }, // IP 192.168.4.1 - { 0x00ffffff }, // netmask 255.255.255.0 - { 0 } // gateway 0.0.0.0 - }; + { + {0x0104a8c0}, // IP 192.168.4.1 + {0x00ffffff}, // netmask 255.255.255.0 + {0} // gateway 0.0.0.0 + }; begin(&ip); - fw_has_started_softap_dhcps = 2; // not 1, ending initial boot sequence + fw_has_started_softap_dhcps = 2; // not 1, ending initial boot sequence } }; @@ -217,11 +226,11 @@ void DhcpServer::dhcps_set_dns(int num, const ipv4_addr_t* dns) Parameters : arg -- Additional argument to pass to the callback function Returns : none *******************************************************************************/ -void DhcpServer::node_insert_to_list(list_node **phead, list_node* pinsert) +void DhcpServer::node_insert_to_list(list_node** phead, list_node* pinsert) { - list_node *plist = nullptr; - struct dhcps_pool *pdhcps_pool = nullptr; - struct dhcps_pool *pdhcps_node = nullptr; + list_node* plist = nullptr; + struct dhcps_pool* pdhcps_pool = nullptr; + struct dhcps_pool* pdhcps_node = nullptr; if (*phead == nullptr) { *phead = pinsert; @@ -266,9 +275,9 @@ void DhcpServer::node_insert_to_list(list_node **phead, list_node* pinsert) Parameters : arg -- Additional argument to pass to the callback function Returns : none *******************************************************************************/ -void DhcpServer::node_remove_from_list(list_node **phead, list_node* pdelete) +void DhcpServer::node_remove_from_list(list_node** phead, list_node* pdelete) { - list_node *plist = nullptr; + list_node* plist = nullptr; plist = *phead; if (plist == nullptr) @@ -303,10 +312,10 @@ void DhcpServer::node_remove_from_list(list_node **phead, list_node* pdelete) Parameters : mac address Returns : true if ok and false if this mac already exist or if all ip are already reserved *******************************************************************************/ -bool DhcpServer::add_dhcps_lease(uint8 *macaddr) +bool DhcpServer::add_dhcps_lease(uint8* macaddr) { - struct dhcps_pool *pdhcps_pool = nullptr; - list_node *pback_node = nullptr; + struct dhcps_pool* pdhcps_pool = nullptr; + list_node* pback_node = nullptr; uint32 start_ip = dhcps_lease.start_ip.addr; uint32 end_ip = dhcps_lease.end_ip.addr; @@ -335,13 +344,13 @@ bool DhcpServer::add_dhcps_lease(uint8 *macaddr) return false; } - pdhcps_pool = (struct dhcps_pool *)zalloc(sizeof(struct dhcps_pool)); + pdhcps_pool = (struct dhcps_pool*)zalloc(sizeof(struct dhcps_pool)); pdhcps_pool->ip.addr = start_ip; memcpy(pdhcps_pool->mac, macaddr, sizeof(pdhcps_pool->mac)); pdhcps_pool->lease_timer = DHCPS_LEASE_TIMER; pdhcps_pool->type = DHCPS_TYPE_STATIC; pdhcps_pool->state = DHCPS_STATE_ONLINE; - pback_node = (list_node *)zalloc(sizeof(list_node)); + pback_node = (list_node*)zalloc(sizeof(list_node)); pback_node->pnode = pdhcps_pool; pback_node->pnext = nullptr; node_insert_to_list(&plist, pback_node); @@ -359,9 +368,8 @@ bool DhcpServer::add_dhcps_lease(uint8 *macaddr) @return uint8_t* DHCP msg */ /////////////////////////////////////////////////////////////////////////////////// -uint8_t* DhcpServer::add_msg_type(uint8_t *optptr, uint8_t type) +uint8_t* DhcpServer::add_msg_type(uint8_t* optptr, uint8_t type) { - *optptr++ = DHCP_OPTION_MSG_TYPE; *optptr++ = 1; *optptr++ = type; @@ -376,7 +384,7 @@ uint8_t* DhcpServer::add_msg_type(uint8_t *optptr, uint8_t type) @return uint8_t* DHCP msg */ /////////////////////////////////////////////////////////////////////////////////// -uint8_t* DhcpServer::add_offer_options(uint8_t *optptr) +uint8_t* DhcpServer::add_offer_options(uint8_t* optptr) { //struct ipv4_addr ipadd; //ipadd.addr = server_address.addr; @@ -448,19 +456,19 @@ uint8_t* DhcpServer::add_offer_options(uint8_t *optptr) *optptr++ = DHCP_OPTION_INTERFACE_MTU; *optptr++ = 2; *optptr++ = 0x05; - *optptr++ = 0xdc; // 1500 + *optptr++ = 0xdc; // 1500 *optptr++ = DHCP_OPTION_PERFORM_ROUTER_DISCOVERY; *optptr++ = 1; *optptr++ = 0x00; -#if 0 // vendor specific uninitialized (??) +#if 0 // vendor specific uninitialized (??) *optptr++ = 43; // vendor specific *optptr++ = 6; // uninitialized ? #endif -#if 0 // already set (DHCP_OPTION_SUBNET_MASK==1) (??) +#if 0 // already set (DHCP_OPTION_SUBNET_MASK==1) (??) *optptr++ = 0x01; *optptr++ = 4; *optptr++ = 0; @@ -483,15 +491,14 @@ uint8_t* DhcpServer::add_offer_options(uint8_t *optptr) @return uint8_t* DHCP msg */ /////////////////////////////////////////////////////////////////////////////////// -uint8_t* DhcpServer::add_end(uint8_t *optptr) +uint8_t* DhcpServer::add_end(uint8_t* optptr) { - *optptr++ = DHCP_OPTION_END; return optptr; } /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// -void DhcpServer::create_msg(struct dhcps_msg *m) +void DhcpServer::create_msg(struct dhcps_msg* m) { struct ipv4_addr client; @@ -504,14 +511,14 @@ void DhcpServer::create_msg(struct dhcps_msg *m) m->secs = 0; m->flags = htons(BOOTP_BROADCAST); - memcpy((char *) m->yiaddr, (char *) &client.addr, sizeof(m->yiaddr)); - memset((char *) m->ciaddr, 0, sizeof(m->ciaddr)); - memset((char *) m->siaddr, 0, sizeof(m->siaddr)); - memset((char *) m->giaddr, 0, sizeof(m->giaddr)); - memset((char *) m->sname, 0, sizeof(m->sname)); - memset((char *) m->file, 0, sizeof(m->file)); - memset((char *) m->options, 0, sizeof(m->options)); - memcpy((char *) m->options, &magic_cookie, sizeof(magic_cookie)); + memcpy((char*)m->yiaddr, (char*)&client.addr, sizeof(m->yiaddr)); + memset((char*)m->ciaddr, 0, sizeof(m->ciaddr)); + memset((char*)m->siaddr, 0, sizeof(m->siaddr)); + memset((char*)m->giaddr, 0, sizeof(m->giaddr)); + memset((char*)m->sname, 0, sizeof(m->sname)); + memset((char*)m->file, 0, sizeof(m->file)); + memset((char*)m->options, 0, sizeof(m->options)); + memcpy((char*)m->options, &magic_cookie, sizeof(magic_cookie)); } /////////////////////////////////////////////////////////////////////////////////// /* @@ -520,11 +527,11 @@ void DhcpServer::create_msg(struct dhcps_msg *m) @param -- m DHCP msg */ /////////////////////////////////////////////////////////////////////////////////// -void DhcpServer::send_offer(struct dhcps_msg *m) +void DhcpServer::send_offer(struct dhcps_msg* m) { - uint8_t *end; + uint8_t* end; struct pbuf *p, *q; - u8_t *data; + u8_t* data; u16_t cnt = 0; u16_t i; create_msg(m); @@ -539,7 +546,6 @@ void DhcpServer::send_offer(struct dhcps_msg *m) #endif if (p != nullptr) { - #if DHCPS_DEBUG os_printf("dhcps: send_offer>>pbuf_alloc succeed\n"); os_printf("dhcps: send_offer>>p->tot_len = %d\n", p->tot_len); @@ -548,10 +554,10 @@ void DhcpServer::send_offer(struct dhcps_msg *m) q = p; while (q != nullptr) { - data = (u8_t *)q->payload; + data = (u8_t*)q->payload; for (i = 0; i < q->len; i++) { - data[i] = ((u8_t *) m)[cnt++]; + data[i] = ((u8_t*)m)[cnt++]; } q = q->next; @@ -559,7 +565,6 @@ void DhcpServer::send_offer(struct dhcps_msg *m) } else { - #if DHCPS_DEBUG os_printf("dhcps: send_offer>>pbuf_alloc failed\n"); #endif @@ -586,12 +591,11 @@ void DhcpServer::send_offer(struct dhcps_msg *m) @param m DHCP msg */ /////////////////////////////////////////////////////////////////////////////////// -void DhcpServer::send_nak(struct dhcps_msg *m) +void DhcpServer::send_nak(struct dhcps_msg* m) { - - u8_t *end; + u8_t* end; struct pbuf *p, *q; - u8_t *data; + u8_t* data; u16_t cnt = 0; u16_t i; create_msg(m); @@ -605,7 +609,6 @@ void DhcpServer::send_nak(struct dhcps_msg *m) #endif if (p != nullptr) { - #if DHCPS_DEBUG os_printf("dhcps: send_nak>>pbuf_alloc succeed\n"); os_printf("dhcps: send_nak>>p->tot_len = %d\n", p->tot_len); @@ -614,10 +617,10 @@ void DhcpServer::send_nak(struct dhcps_msg *m) q = p; while (q != nullptr) { - data = (u8_t *)q->payload; + data = (u8_t*)q->payload; for (i = 0; i < q->len; i++) { - data[i] = ((u8_t *) m)[cnt++]; + data[i] = ((u8_t*)m)[cnt++]; } q = q->next; @@ -625,7 +628,6 @@ void DhcpServer::send_nak(struct dhcps_msg *m) } else { - #if DHCPS_DEBUG os_printf("dhcps: send_nak>>pbuf_alloc failed\n"); #endif @@ -647,12 +649,11 @@ void DhcpServer::send_nak(struct dhcps_msg *m) @param m DHCP msg */ /////////////////////////////////////////////////////////////////////////////////// -void DhcpServer::send_ack(struct dhcps_msg *m) +void DhcpServer::send_ack(struct dhcps_msg* m) { - - u8_t *end; + u8_t* end; struct pbuf *p, *q; - u8_t *data; + u8_t* data; u16_t cnt = 0; u16_t i; create_msg(m); @@ -667,7 +668,6 @@ void DhcpServer::send_ack(struct dhcps_msg *m) #endif if (p != nullptr) { - #if DHCPS_DEBUG os_printf("dhcps: send_ack>>pbuf_alloc succeed\n"); os_printf("dhcps: send_ack>>p->tot_len = %d\n", p->tot_len); @@ -676,10 +676,10 @@ void DhcpServer::send_ack(struct dhcps_msg *m) q = p; while (q != nullptr) { - data = (u8_t *)q->payload; + data = (u8_t*)q->payload; for (i = 0; i < q->len; i++) { - data[i] = ((u8_t *) m)[cnt++]; + data[i] = ((u8_t*)m)[cnt++]; } q = q->next; @@ -687,7 +687,6 @@ void DhcpServer::send_ack(struct dhcps_msg *m) } else { - #if DHCPS_DEBUG os_printf("dhcps: send_ack>>pbuf_alloc failed\n"); #endif @@ -718,7 +717,7 @@ void DhcpServer::send_ack(struct dhcps_msg *m) @return uint8_t* DHCP Server */ /////////////////////////////////////////////////////////////////////////////////// -uint8_t DhcpServer::parse_options(uint8_t *optptr, sint16_t len) +uint8_t DhcpServer::parse_options(uint8_t* optptr, sint16_t len) { struct ipv4_addr client; bool is_dhcp_parse_end = false; @@ -726,7 +725,7 @@ uint8_t DhcpServer::parse_options(uint8_t *optptr, sint16_t len) client.addr = client_address.addr; - u8_t *end = optptr + len; + u8_t* end = optptr + len; u16_t type = 0; s.state = DHCPS_STATE_IDLE; @@ -736,35 +735,34 @@ uint8_t DhcpServer::parse_options(uint8_t *optptr, sint16_t len) #if DHCPS_DEBUG os_printf("dhcps: (sint16_t)*optptr = %d\n", (sint16_t)*optptr); #endif - switch ((sint16_t) *optptr) + switch ((sint16_t)*optptr) { + case DHCP_OPTION_MSG_TYPE: //53 + type = *(optptr + 2); + break; - case DHCP_OPTION_MSG_TYPE: //53 - type = *(optptr + 2); - break; - - case DHCP_OPTION_REQ_IPADDR://50 - //os_printf("dhcps:0x%08x,0x%08x\n",client.addr,*(uint32*)(optptr+2)); - if (memcmp((char *) &client.addr, (char *) optptr + 2, 4) == 0) - { + case DHCP_OPTION_REQ_IPADDR: //50 + //os_printf("dhcps:0x%08x,0x%08x\n",client.addr,*(uint32*)(optptr+2)); + if (memcmp((char*)&client.addr, (char*)optptr + 2, 4) == 0) + { #if DHCPS_DEBUG - os_printf("dhcps: DHCP_OPTION_REQ_IPADDR = 0 ok\n"); + os_printf("dhcps: DHCP_OPTION_REQ_IPADDR = 0 ok\n"); #endif - s.state = DHCPS_STATE_ACK; - } - else - { + s.state = DHCPS_STATE_ACK; + } + else + { #if DHCPS_DEBUG - os_printf("dhcps: DHCP_OPTION_REQ_IPADDR != 0 err\n"); + os_printf("dhcps: DHCP_OPTION_REQ_IPADDR != 0 err\n"); #endif - s.state = DHCPS_STATE_NAK; + s.state = DHCPS_STATE_NAK; + } + break; + case DHCP_OPTION_END: + { + is_dhcp_parse_end = true; } break; - case DHCP_OPTION_END: - { - is_dhcp_parse_end = true; - } - break; } if (is_dhcp_parse_end) @@ -777,43 +775,43 @@ uint8_t DhcpServer::parse_options(uint8_t *optptr, sint16_t len) switch (type) { - case DHCPDISCOVER://1 - s.state = DHCPS_STATE_OFFER; + case DHCPDISCOVER: //1 + s.state = DHCPS_STATE_OFFER; #if DHCPS_DEBUG - os_printf("dhcps: DHCPD_STATE_OFFER\n"); + os_printf("dhcps: DHCPD_STATE_OFFER\n"); #endif - break; + break; - case DHCPREQUEST://3 - if (!(s.state == DHCPS_STATE_ACK || s.state == DHCPS_STATE_NAK)) - { - if (renew == true) + case DHCPREQUEST: //3 + if (!(s.state == DHCPS_STATE_ACK || s.state == DHCPS_STATE_NAK)) { - s.state = DHCPS_STATE_ACK; - } - else - { - s.state = DHCPS_STATE_NAK; - } + if (renew == true) + { + s.state = DHCPS_STATE_ACK; + } + else + { + s.state = DHCPS_STATE_NAK; + } #if DHCPS_DEBUG - os_printf("dhcps: DHCPD_STATE_NAK\n"); + os_printf("dhcps: DHCPD_STATE_NAK\n"); #endif - } - break; + } + break; - case DHCPDECLINE://4 - s.state = DHCPS_STATE_IDLE; + case DHCPDECLINE: //4 + s.state = DHCPS_STATE_IDLE; #if DHCPS_DEBUG - os_printf("dhcps: DHCPD_STATE_IDLE\n"); + os_printf("dhcps: DHCPD_STATE_IDLE\n"); #endif - break; + break; - case DHCPRELEASE://7 - s.state = DHCPS_STATE_RELEASE; + case DHCPRELEASE: //7 + s.state = DHCPS_STATE_RELEASE; #if DHCPS_DEBUG - os_printf("dhcps: DHCPD_STATE_IDLE\n"); + os_printf("dhcps: DHCPD_STATE_IDLE\n"); #endif - break; + break; } #if DHCPS_DEBUG os_printf("dhcps: return s.state = %d\n", s.state); @@ -822,9 +820,9 @@ uint8_t DhcpServer::parse_options(uint8_t *optptr, sint16_t len) } /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// -sint16_t DhcpServer::parse_msg(struct dhcps_msg *m, u16_t len) +sint16_t DhcpServer::parse_msg(struct dhcps_msg* m, u16_t len) { - if (memcmp((char *)m->options, + if (memcmp((char*)m->options, &magic_cookie, sizeof(magic_cookie)) == 0) { @@ -836,7 +834,7 @@ sint16_t DhcpServer::parse_msg(struct dhcps_msg *m, u16_t len) if (ret == DHCPS_STATE_RELEASE) { - dhcps_client_leave(m->chaddr, &ip, true); // force to delete + dhcps_client_leave(m->chaddr, &ip, true); // force to delete client_address.addr = ip.addr; } @@ -857,10 +855,10 @@ sint16_t DhcpServer::parse_msg(struct dhcps_msg *m, u16_t len) */ /////////////////////////////////////////////////////////////////////////////////// -void DhcpServer::S_handle_dhcp(void *arg, - struct udp_pcb *pcb, - struct pbuf *p, - const ip_addr_t *addr, +void DhcpServer::S_handle_dhcp(void* arg, + struct udp_pcb* pcb, + struct pbuf* p, + const ip_addr_t* addr, uint16_t port) { DhcpServer* instance = reinterpret_cast(arg); @@ -868,21 +866,21 @@ void DhcpServer::S_handle_dhcp(void *arg, } void DhcpServer::handle_dhcp( - struct udp_pcb *pcb, - struct pbuf *p, - const ip_addr_t *addr, + struct udp_pcb* pcb, + struct pbuf* p, + const ip_addr_t* addr, uint16_t port) { (void)pcb; (void)addr; (void)port; - struct dhcps_msg *pmsg_dhcps = nullptr; + struct dhcps_msg* pmsg_dhcps = nullptr; sint16_t tlen = 0; u16_t i = 0; u16_t dhcps_msg_cnt = 0; - u8_t *p_dhcps_msg = nullptr; - u8_t *data = nullptr; + u8_t* p_dhcps_msg = nullptr; + u8_t* data = nullptr; #if DHCPS_DEBUG os_printf("dhcps: handle_dhcp-> receive a packet\n"); @@ -892,13 +890,13 @@ void DhcpServer::handle_dhcp( return; } - pmsg_dhcps = (struct dhcps_msg *)zalloc(sizeof(struct dhcps_msg)); + pmsg_dhcps = (struct dhcps_msg*)zalloc(sizeof(struct dhcps_msg)); if (nullptr == pmsg_dhcps) { pbuf_free(p); return; } - p_dhcps_msg = (u8_t *)pmsg_dhcps; + p_dhcps_msg = (u8_t*)pmsg_dhcps; tlen = p->tot_len; data = (u8_t*)p->payload; @@ -933,31 +931,30 @@ void DhcpServer::handle_dhcp( switch (parse_msg(pmsg_dhcps, tlen - 240)) { - - case DHCPS_STATE_OFFER://1 + case DHCPS_STATE_OFFER: //1 #if DHCPS_DEBUG - os_printf("dhcps: handle_dhcp-> DHCPD_STATE_OFFER\n"); + os_printf("dhcps: handle_dhcp-> DHCPD_STATE_OFFER\n"); #endif - send_offer(pmsg_dhcps); - break; - case DHCPS_STATE_ACK://3 + send_offer(pmsg_dhcps); + break; + case DHCPS_STATE_ACK: //3 #if DHCPS_DEBUG - os_printf("dhcps: handle_dhcp-> DHCPD_STATE_ACK\n"); + os_printf("dhcps: handle_dhcp-> DHCPD_STATE_ACK\n"); #endif - send_ack(pmsg_dhcps); - if (_netif->num == SOFTAP_IF) - { - wifi_softap_set_station_info(pmsg_dhcps->chaddr, &client_address); - } - break; - case DHCPS_STATE_NAK://4 + send_ack(pmsg_dhcps); + if (_netif->num == SOFTAP_IF) + { + wifi_softap_set_station_info(pmsg_dhcps->chaddr, &client_address); + } + break; + case DHCPS_STATE_NAK: //4 #if DHCPS_DEBUG - os_printf("dhcps: handle_dhcp-> DHCPD_STATE_NAK\n"); + os_printf("dhcps: handle_dhcp-> DHCPD_STATE_NAK\n"); #endif - send_nak(pmsg_dhcps); - break; - default : - break; + send_nak(pmsg_dhcps); + break; + default: + break; } #if DHCPS_DEBUG os_printf("dhcps: handle_dhcp-> pbuf_free(p)\n"); @@ -986,8 +983,7 @@ void DhcpServer::init_dhcps_lease(uint32 ip) { /*config ip information must be in the same segment as the local ip*/ softap_ip >>= 8; - if (((start_ip >> 8 != softap_ip) || (end_ip >> 8 != softap_ip)) - || (end_ip - start_ip > DHCPS_MAX_LEASE)) + if (((start_ip >> 8 != softap_ip) || (end_ip >> 8 != softap_ip)) || (end_ip - start_ip > DHCPS_MAX_LEASE)) { dhcps_lease.enable = false; } @@ -1005,7 +1001,7 @@ void DhcpServer::init_dhcps_lease(uint32 ip) } else { - local_ip ++; + local_ip++; } bzero(&dhcps_lease, sizeof(dhcps_lease)); @@ -1020,7 +1016,7 @@ void DhcpServer::init_dhcps_lease(uint32 ip) } /////////////////////////////////////////////////////////////////////////////////// -bool DhcpServer::begin(struct ip_info *info) +bool DhcpServer::begin(struct ip_info* info) { if (pcb_dhcps != nullptr) { @@ -1053,9 +1049,9 @@ bool DhcpServer::begin(struct ip_info *info) if (_netif->num == SOFTAP_IF) { - wifi_set_ip_info(SOFTAP_IF, info); // added for lwip-git, not sure whether useful + wifi_set_ip_info(SOFTAP_IF, info); // added for lwip-git, not sure whether useful } - _netif->flags |= NETIF_FLAG_UP | NETIF_FLAG_LINK_UP; // added for lwip-git + _netif->flags |= NETIF_FLAG_UP | NETIF_FLAG_LINK_UP; // added for lwip-git return true; } @@ -1077,8 +1073,8 @@ void DhcpServer::end() pcb_dhcps = nullptr; //udp_remove(pcb_dhcps); - list_node *pnode = nullptr; - list_node *pback_node = nullptr; + list_node* pnode = nullptr; + list_node* pback_node = nullptr; struct dhcps_pool* dhcp_node = nullptr; struct ipv4_addr ip_zero; @@ -1107,7 +1103,6 @@ bool DhcpServer::isRunning() return !!_netif->state; } - /****************************************************************************** FunctionName : set_dhcps_lease Description : set the lease information of DHCP server @@ -1115,7 +1110,7 @@ bool DhcpServer::isRunning() Little-Endian. Returns : true or false *******************************************************************************/ -bool DhcpServer::set_dhcps_lease(struct dhcps_lease *please) +bool DhcpServer::set_dhcps_lease(struct dhcps_lease* please) { uint32 softap_ip = 0; uint32 start_ip = 0; @@ -1151,8 +1146,7 @@ bool DhcpServer::set_dhcps_lease(struct dhcps_lease *please) /*config ip information must be in the same segment as the local ip*/ softap_ip >>= 8; - if ((start_ip >> 8 != softap_ip) - || (end_ip >> 8 != softap_ip)) + if ((start_ip >> 8 != softap_ip) || (end_ip >> 8 != softap_ip)) { return false; } @@ -1180,7 +1174,7 @@ bool DhcpServer::set_dhcps_lease(struct dhcps_lease *please) Little-Endian. Returns : true or false *******************************************************************************/ -bool DhcpServer::get_dhcps_lease(struct dhcps_lease *please) +bool DhcpServer::get_dhcps_lease(struct dhcps_lease* please) { if (_netif->num == SOFTAP_IF) { @@ -1244,7 +1238,8 @@ void DhcpServer::kill_oldest_dhcps_pool(void) pre = p; p = p->pnext; } - minpre->pnext = minp->pnext; pdhcps_pool->state = DHCPS_STATE_OFFLINE; + minpre->pnext = minp->pnext; + pdhcps_pool->state = DHCPS_STATE_OFFLINE; free(minp->pnode); minp->pnode = nullptr; free(minp); @@ -1254,16 +1249,16 @@ void DhcpServer::kill_oldest_dhcps_pool(void) void DhcpServer::dhcps_coarse_tmr(void) { uint8 num_dhcps_pool = 0; - list_node *pback_node = nullptr; - list_node *pnode = nullptr; - struct dhcps_pool *pdhcps_pool = nullptr; + list_node* pback_node = nullptr; + list_node* pnode = nullptr; + struct dhcps_pool* pdhcps_pool = nullptr; pnode = plist; while (pnode != nullptr) { pdhcps_pool = (struct dhcps_pool*)pnode->pnode; if (pdhcps_pool->type == DHCPS_TYPE_DYNAMIC) { - pdhcps_pool->lease_timer --; + pdhcps_pool->lease_timer--; } if (pdhcps_pool->lease_timer == 0) { @@ -1277,8 +1272,8 @@ void DhcpServer::dhcps_coarse_tmr(void) } else { - pnode = pnode ->pnext; - num_dhcps_pool ++; + pnode = pnode->pnext; + num_dhcps_pool++; } } @@ -1304,13 +1299,13 @@ bool DhcpServer::set_dhcps_offer_option(uint8 level, void* optarg) switch (level) { - case OFFER_ROUTER: - offer = (*(uint8 *)optarg) & 0x01; - offer_flag = true; - break; - default : - offer_flag = false; - break; + case OFFER_ROUTER: + offer = (*(uint8*)optarg) & 0x01; + offer_flag = true; + break; + default: + offer_flag = false; + break; } return offer_flag; } @@ -1358,15 +1353,15 @@ bool DhcpServer::reset_dhcps_lease_time(void) return true; } -uint32 DhcpServer::get_dhcps_lease_time(void) // minute +uint32 DhcpServer::get_dhcps_lease_time(void) // minute { return dhcps_lease_time; } -void DhcpServer::dhcps_client_leave(u8 *bssid, struct ipv4_addr *ip, bool force) +void DhcpServer::dhcps_client_leave(u8* bssid, struct ipv4_addr* ip, bool force) { - struct dhcps_pool *pdhcps_pool = nullptr; - list_node *pback_node = nullptr; + struct dhcps_pool* pdhcps_pool = nullptr; + list_node* pback_node = nullptr; if ((bssid == nullptr) || (ip == nullptr)) { @@ -1412,12 +1407,12 @@ void DhcpServer::dhcps_client_leave(u8 *bssid, struct ipv4_addr *ip, bool force) } } -uint32 DhcpServer::dhcps_client_update(u8 *bssid, struct ipv4_addr *ip) +uint32 DhcpServer::dhcps_client_update(u8* bssid, struct ipv4_addr* ip) { - struct dhcps_pool *pdhcps_pool = nullptr; - list_node *pback_node = nullptr; - list_node *pmac_node = nullptr; - list_node *pip_node = nullptr; + struct dhcps_pool* pdhcps_pool = nullptr; + list_node* pback_node = nullptr; + list_node* pmac_node = nullptr; + list_node* pip_node = nullptr; bool flag = false; uint32 start_ip = dhcps_lease.start_ip.addr; uint32 end_ip = dhcps_lease.end_ip.addr; @@ -1501,7 +1496,7 @@ uint32 DhcpServer::dhcps_client_update(u8 *bssid, struct ipv4_addr *ip) } } - if (pmac_node != nullptr) // update new ip + if (pmac_node != nullptr) // update new ip { if (pip_node != nullptr) { @@ -1531,7 +1526,6 @@ uint32 DhcpServer::dhcps_client_update(u8 *bssid, struct ipv4_addr *ip) pdhcps_pool->lease_timer = DHCPS_LEASE_TIMER; pdhcps_pool->type = type; pdhcps_pool->state = DHCPS_STATE_ONLINE; - } else { @@ -1544,7 +1538,7 @@ uint32 DhcpServer::dhcps_client_update(u8 *bssid, struct ipv4_addr *ip) { pdhcps_pool->ip.addr = start_ip; } - else // no ip to distribute + else // no ip to distribute { return IPADDR_ANY; } @@ -1556,9 +1550,9 @@ uint32 DhcpServer::dhcps_client_update(u8 *bssid, struct ipv4_addr *ip) node_insert_to_list(&plist, pmac_node); } } - else // new station + else // new station { - if (pip_node != nullptr) // maybe ip has used + if (pip_node != nullptr) // maybe ip has used { pdhcps_pool = (struct dhcps_pool*)pip_node->pnode; if (pdhcps_pool->state != DHCPS_STATE_OFFLINE) @@ -1572,7 +1566,7 @@ uint32 DhcpServer::dhcps_client_update(u8 *bssid, struct ipv4_addr *ip) } else { - pdhcps_pool = (struct dhcps_pool *)zalloc(sizeof(struct dhcps_pool)); + pdhcps_pool = (struct dhcps_pool*)zalloc(sizeof(struct dhcps_pool)); if (ip != nullptr) { pdhcps_pool->ip.addr = ip->addr; @@ -1581,7 +1575,7 @@ uint32 DhcpServer::dhcps_client_update(u8 *bssid, struct ipv4_addr *ip) { pdhcps_pool->ip.addr = start_ip; } - else // no ip to distribute + else // no ip to distribute { free(pdhcps_pool); return IPADDR_ANY; @@ -1595,7 +1589,7 @@ uint32 DhcpServer::dhcps_client_update(u8 *bssid, struct ipv4_addr *ip) pdhcps_pool->lease_timer = DHCPS_LEASE_TIMER; pdhcps_pool->type = type; pdhcps_pool->state = DHCPS_STATE_ONLINE; - pback_node = (list_node *)zalloc(sizeof(list_node)); + pback_node = (list_node*)zalloc(sizeof(list_node)); pback_node->pnode = pdhcps_pool; pback_node->pnext = nullptr; node_insert_to_list(&plist, pback_node); diff --git a/cores/esp8266/LwipDhcpServer.h b/cores/esp8266/LwipDhcpServer.h index e93166981d..51c4bf86f9 100644 --- a/cores/esp8266/LwipDhcpServer.h +++ b/cores/esp8266/LwipDhcpServer.h @@ -31,12 +31,11 @@ #ifndef __DHCPS_H__ #define __DHCPS_H__ -#include // LWIP_VERSION +#include // LWIP_VERSION class DhcpServer { -public: - + public: DhcpServer(netif* netif); ~DhcpServer(); @@ -54,55 +53,54 @@ class DhcpServer // legacy public C structure and API to eventually turn into C++ void init_dhcps_lease(uint32 ip); - bool set_dhcps_lease(struct dhcps_lease *please); - bool get_dhcps_lease(struct dhcps_lease *please); + bool set_dhcps_lease(struct dhcps_lease* please); + bool get_dhcps_lease(struct dhcps_lease* please); bool set_dhcps_offer_option(uint8 level, void* optarg); bool set_dhcps_lease_time(uint32 minute); bool reset_dhcps_lease_time(void); uint32 get_dhcps_lease_time(void); - bool add_dhcps_lease(uint8 *macaddr); + bool add_dhcps_lease(uint8* macaddr); void dhcps_set_dns(int num, const ipv4_addr_t* dns); -protected: - + protected: // legacy C structure and API to eventually turn into C++ typedef struct _list_node { - void *pnode; - struct _list_node *pnext; + void* pnode; + struct _list_node* pnext; } list_node; - void node_insert_to_list(list_node **phead, list_node* pinsert); - void node_remove_from_list(list_node **phead, list_node* pdelete); - uint8_t* add_msg_type(uint8_t *optptr, uint8_t type); - uint8_t* add_offer_options(uint8_t *optptr); - uint8_t* add_end(uint8_t *optptr); - void create_msg(struct dhcps_msg *m); - void send_offer(struct dhcps_msg *m); - void send_nak(struct dhcps_msg *m); - void send_ack(struct dhcps_msg *m); - uint8_t parse_options(uint8_t *optptr, sint16_t len); - sint16_t parse_msg(struct dhcps_msg *m, u16_t len); - static void S_handle_dhcp(void *arg, - struct udp_pcb *pcb, - struct pbuf *p, - const ip_addr_t *addr, + void node_insert_to_list(list_node** phead, list_node* pinsert); + void node_remove_from_list(list_node** phead, list_node* pdelete); + uint8_t* add_msg_type(uint8_t* optptr, uint8_t type); + uint8_t* add_offer_options(uint8_t* optptr); + uint8_t* add_end(uint8_t* optptr); + void create_msg(struct dhcps_msg* m); + void send_offer(struct dhcps_msg* m); + void send_nak(struct dhcps_msg* m); + void send_ack(struct dhcps_msg* m); + uint8_t parse_options(uint8_t* optptr, sint16_t len); + sint16_t parse_msg(struct dhcps_msg* m, u16_t len); + static void S_handle_dhcp(void* arg, + struct udp_pcb* pcb, + struct pbuf* p, + const ip_addr_t* addr, uint16_t port); void handle_dhcp( - struct udp_pcb *pcb, - struct pbuf *p, - const ip_addr_t *addr, + struct udp_pcb* pcb, + struct pbuf* p, + const ip_addr_t* addr, uint16_t port); void kill_oldest_dhcps_pool(void); - void dhcps_coarse_tmr(void); // CURRENTLY NOT CALLED - void dhcps_client_leave(u8 *bssid, struct ipv4_addr *ip, bool force); - uint32 dhcps_client_update(u8 *bssid, struct ipv4_addr *ip); + void dhcps_coarse_tmr(void); // CURRENTLY NOT CALLED + void dhcps_client_leave(u8* bssid, struct ipv4_addr* ip, bool force); + uint32 dhcps_client_update(u8* bssid, struct ipv4_addr* ip); netif* _netif; - struct udp_pcb *pcb_dhcps; + struct udp_pcb* pcb_dhcps; ip_addr_t broadcast_dhcps; struct ipv4_addr server_address; struct ipv4_addr client_address; @@ -110,7 +108,7 @@ class DhcpServer uint32 dhcps_lease_time; struct dhcps_lease dhcps_lease; - list_node *plist; + list_node* plist; uint8 offer; bool renew; @@ -121,4 +119,4 @@ class DhcpServer extern DhcpServer dhcpSoftAP; extern "C" int fw_has_started_softap_dhcps; -#endif // __DHCPS_H__ +#endif // __DHCPS_H__ diff --git a/cores/esp8266/LwipIntf.cpp b/cores/esp8266/LwipIntf.cpp index b4a4807b9a..e549270623 100644 --- a/cores/esp8266/LwipIntf.cpp +++ b/cores/esp8266/LwipIntf.cpp @@ -1,19 +1,20 @@ -extern "C" { +extern "C" +{ +#include "lwip/dhcp.h" +#include "lwip/dns.h" #include "lwip/err.h" +#include "lwip/init.h" // LWIP_VERSION_ #include "lwip/ip_addr.h" -#include "lwip/dns.h" -#include "lwip/dhcp.h" -#include "lwip/init.h" // LWIP_VERSION_ #if LWIP_IPV6 -#include "lwip/netif.h" // struct netif +#include "lwip/netif.h" // struct netif #endif #include } -#include "debug.h" #include "LwipIntf.h" +#include "debug.h" // args | esp order arduino order // ---- + --------- ------------- @@ -24,8 +25,7 @@ extern "C" { // // result stored into gateway/netmask/dns1 -bool LwipIntf::ipAddressReorder(const IPAddress& local_ip, const IPAddress& arg1, const IPAddress& arg2, const IPAddress& arg3, - IPAddress& gateway, IPAddress& netmask, IPAddress& dns1) +bool LwipIntf::ipAddressReorder(const IPAddress& local_ip, const IPAddress& arg1, const IPAddress& arg2, const IPAddress& arg3, IPAddress& gateway, IPAddress& netmask, IPAddress& dns1) { //To allow compatibility, check first octet of 3rd arg. If 255, interpret as ESP order, otherwise Arduino order. gateway = arg1; @@ -36,7 +36,7 @@ bool LwipIntf::ipAddressReorder(const IPAddress& local_ip, const IPAddress& arg1 { //octet is not 255 => interpret as Arduino order gateway = arg2; - netmask = arg3[0] == 0 ? IPAddress(255, 255, 255, 0) : arg3; //arg order is arduino and 4th arg not given => assign it arduino default + netmask = arg3[0] == 0 ? IPAddress(255, 255, 255, 0) : arg3; //arg order is arduino and 4th arg not given => assign it arduino default dns1 = arg1; } @@ -143,7 +143,6 @@ bool LwipIntf::hostname(const char* aHostname) // harmless for AP, also compatible with ethernet adapters (to come) for (netif* intf = netif_list; intf; intf = intf->next) { - // unconditionally update all known interfaces intf->hostname = wifi_station_get_hostname(); @@ -162,4 +161,3 @@ bool LwipIntf::hostname(const char* aHostname) return ret && compliant; } - diff --git a/cores/esp8266/LwipIntf.h b/cores/esp8266/LwipIntf.h index d73c2d825a..5eef15305a 100644 --- a/cores/esp8266/LwipIntf.h +++ b/cores/esp8266/LwipIntf.h @@ -2,16 +2,15 @@ #ifndef _LWIPINTF_H #define _LWIPINTF_H -#include #include +#include #include class LwipIntf { -public: - - using CBType = std::function ; + public: + using CBType = std::function; static bool stateUpCB(LwipIntf::CBType&& cb); @@ -24,9 +23,7 @@ class LwipIntf // arg3 | dns1 netmask // // result stored into gateway/netmask/dns1 - static - bool ipAddressReorder(const IPAddress& local_ip, const IPAddress& arg1, const IPAddress& arg2, const IPAddress& arg3, - IPAddress& gateway, IPAddress& netmask, IPAddress& dns1); + static bool ipAddressReorder(const IPAddress& local_ip, const IPAddress& arg1, const IPAddress& arg2, const IPAddress& arg3, IPAddress& gateway, IPAddress& netmask, IPAddress& dns1); String hostname(); bool hostname(const String& aHostname) @@ -41,9 +38,8 @@ class LwipIntf } const char* getHostname(); -protected: - + protected: static bool stateChangeSysCB(LwipIntf::CBType&& cb); }; -#endif // _LWIPINTF_H +#endif // _LWIPINTF_H diff --git a/cores/esp8266/LwipIntfCB.cpp b/cores/esp8266/LwipIntfCB.cpp index 1e495c5fd3..7271416300 100644 --- a/cores/esp8266/LwipIntfCB.cpp +++ b/cores/esp8266/LwipIntfCB.cpp @@ -6,7 +6,7 @@ #define NETIF_STATUS_CB_SIZE 3 static int netifStatusChangeListLength = 0; -LwipIntf::CBType netifStatusChangeList [NETIF_STATUS_CB_SIZE]; +LwipIntf::CBType netifStatusChangeList[NETIF_STATUS_CB_SIZE]; extern "C" void netif_status_changed(struct netif* netif) { @@ -33,12 +33,10 @@ bool LwipIntf::stateChangeSysCB(LwipIntf::CBType&& cb) bool LwipIntf::stateUpCB(LwipIntf::CBType&& cb) { - return stateChangeSysCB([cb](netif * nif) - { - if (netif_is_up(nif)) - schedule_function([cb, nif]() - { - cb(nif); - }); - }); + return stateChangeSysCB([cb](netif* nif) + { + if (netif_is_up(nif)) + schedule_function([cb, nif]() + { cb(nif); }); + }); } diff --git a/cores/esp8266/LwipIntfDev.h b/cores/esp8266/LwipIntfDev.h index f8290d7cd6..82dd4e653f 100644 --- a/cores/esp8266/LwipIntfDev.h +++ b/cores/esp8266/LwipIntfDev.h @@ -6,19 +6,19 @@ // remove all Serial.print // unchain pbufs -#include -#include -#include -#include +#include #include #include -#include +#include +#include +#include +#include -#include // wifi_get_macaddr() +#include // wifi_get_macaddr() +#include "LwipIntf.h" #include "SPI.h" #include "Schedule.h" -#include "LwipIntf.h" #include "wl_definitions.h" #ifndef DEFAULT_MTU @@ -26,17 +26,15 @@ #endif template -class LwipIntfDev: public LwipIntf, public RawDev +class LwipIntfDev : public LwipIntf, public RawDev { - -public: - - LwipIntfDev(int8_t cs = SS, SPIClass& spi = SPI, int8_t intr = -1): - RawDev(cs, spi, intr), - _mtu(DEFAULT_MTU), - _intrPin(intr), - _started(false), - _default(false) + public: + LwipIntfDev(int8_t cs = SS, SPIClass& spi = SPI, int8_t intr = -1) + : RawDev(cs, spi, intr), + _mtu(DEFAULT_MTU), + _intrPin(intr), + _started(false), + _default(false) { memset(&_netif, 0, sizeof(_netif)); } @@ -44,22 +42,22 @@ class LwipIntfDev: public LwipIntf, public RawDev boolean config(const IPAddress& local_ip, const IPAddress& arg1, const IPAddress& arg2, const IPAddress& arg3 = IPADDR_NONE, const IPAddress& dns2 = IPADDR_NONE); // default mac-address is inferred from esp8266's STA interface - boolean begin(const uint8_t *macAddress = nullptr, const uint16_t mtu = DEFAULT_MTU); + boolean begin(const uint8_t* macAddress = nullptr, const uint16_t mtu = DEFAULT_MTU); const netif* getNetIf() const { return &_netif; } - IPAddress localIP() const + IPAddress localIP() const { return IPAddress(ip4_addr_get_u32(ip_2_ip4(&_netif.ip_addr))); } - IPAddress subnetMask() const + IPAddress subnetMask() const { return IPAddress(ip4_addr_get_u32(ip_2_ip4(&_netif.netmask))); } - IPAddress gatewayIP() const + IPAddress gatewayIP() const { return IPAddress(ip4_addr_get_u32(ip_2_ip4(&_netif.gw))); } @@ -76,28 +74,26 @@ class LwipIntfDev: public LwipIntf, public RawDev wl_status_t status(); -protected: - + protected: err_t netif_init(); - void netif_status_callback(); + void netif_status_callback(); static err_t netif_init_s(netif* netif); - static err_t linkoutput_s(netif *netif, struct pbuf *p); - static void netif_status_callback_s(netif* netif); + static err_t linkoutput_s(netif* netif, struct pbuf* p); + static void netif_status_callback_s(netif* netif); // called on a regular basis or on interrupt err_t handlePackets(); // members - netif _netif; - - uint16_t _mtu; - int8_t _intrPin; - uint8_t _macAddress[6]; - bool _started; - bool _default; + netif _netif; + uint16_t _mtu; + int8_t _intrPin; + uint8_t _macAddress[6]; + bool _started; + bool _default; }; template @@ -162,9 +158,9 @@ boolean LwipIntfDev::begin(const uint8_t* macAddress, const uint16_t mtu memset(_macAddress, 0, 6); _macAddress[0] = 0xEE; #endif - _macAddress[3] += _netif.num; // alter base mac address - _macAddress[0] &= 0xfe; // set as locally administered, unicast, per - _macAddress[0] |= 0x02; // https://en.wikipedia.org/wiki/MAC_address#Universal_vs._local + _macAddress[3] += _netif.num; // alter base mac address + _macAddress[0] &= 0xfe; // set as locally administered, unicast, per + _macAddress[0] |= 0x02; // https://en.wikipedia.org/wiki/MAC_address#Universal_vs._local } if (!RawDev::begin(_macAddress)) @@ -194,15 +190,15 @@ boolean LwipIntfDev::begin(const uint8_t* macAddress, const uint16_t mtu { switch (dhcp_start(&_netif)) { - case ERR_OK: - break; + case ERR_OK: + break; - case ERR_IF: - return false; + case ERR_IF: + return false; - default: - netif_remove(&_netif); - return false; + default: + netif_remove(&_netif); + return false; } } @@ -222,10 +218,11 @@ boolean LwipIntfDev::begin(const uint8_t* macAddress, const uint16_t mtu } if (_intrPin < 0 && !schedule_recurrent_function_us([&]() -{ - this->handlePackets(); - return true; - }, 100)) + { + this->handlePackets(); + return true; + }, + 100)) { netif_remove(&_netif); return false; @@ -241,7 +238,7 @@ wl_status_t LwipIntfDev::status() } template -err_t LwipIntfDev::linkoutput_s(netif *netif, struct pbuf *pbuf) +err_t LwipIntfDev::linkoutput_s(netif* netif, struct pbuf* pbuf) { LwipIntfDev* ths = (LwipIntfDev*)netif->state; @@ -255,7 +252,7 @@ err_t LwipIntfDev::linkoutput_s(netif *netif, struct pbuf *pbuf) #if PHY_HAS_CAPTURE if (phy_capture) { - phy_capture(ths->_netif.num, (const char*)pbuf->payload, pbuf->len, /*out*/1, /*success*/len == pbuf->len); + phy_capture(ths->_netif.num, (const char*)pbuf->payload, pbuf->len, /*out*/ 1, /*success*/ len == pbuf->len); } #endif @@ -282,10 +279,7 @@ err_t LwipIntfDev::netif_init() _netif.mtu = _mtu; _netif.chksum_flags = NETIF_CHECKSUM_ENABLE_ALL; _netif.flags = - NETIF_FLAG_ETHARP - | NETIF_FLAG_IGMP - | NETIF_FLAG_BROADCAST - | NETIF_FLAG_LINK_UP; + NETIF_FLAG_ETHARP | NETIF_FLAG_IGMP | NETIF_FLAG_BROADCAST | NETIF_FLAG_LINK_UP; // lwIP's doc: This function typically first resolves the hardware // address, then sends the packet. For ethernet physical layer, this is @@ -328,7 +322,7 @@ err_t LwipIntfDev::handlePackets() while (1) { if (++pkt == 10) - // prevent starvation + // prevent starvation { return ERR_OK; } @@ -374,7 +368,7 @@ err_t LwipIntfDev::handlePackets() #if PHY_HAS_CAPTURE if (phy_capture) { - phy_capture(_netif.num, (const char*)pbuf->payload, tot_len, /*out*/0, /*success*/err == ERR_OK); + phy_capture(_netif.num, (const char*)pbuf->payload, tot_len, /*out*/ 0, /*success*/ err == ERR_OK); } #endif @@ -384,7 +378,6 @@ err_t LwipIntfDev::handlePackets() return err; } // (else) allocated pbuf is now lwIP's responsibility - } } @@ -398,4 +391,4 @@ void LwipIntfDev::setDefault() } } -#endif // _LWIPINTFDEV_H +#endif // _LWIPINTFDEV_H diff --git a/cores/esp8266/StreamSend.cpp b/cores/esp8266/StreamSend.cpp index 693e340cff..d84a4bf961 100644 --- a/cores/esp8266/StreamSend.cpp +++ b/cores/esp8266/StreamSend.cpp @@ -19,7 +19,6 @@ parsing functions based on TextFinder library by Michael Margolis */ - #include #include @@ -32,7 +31,7 @@ size_t Stream::sendGeneric(Print* to, if (len == 0) { - return 0; // conveniently avoids timeout for no requested data + return 0; // conveniently avoids timeout for no requested data } // There are two timeouts: @@ -57,7 +56,6 @@ size_t Stream::sendGeneric(Print* to, return SendGenericRegular(to, len, timeoutMs); } - size_t Stream::SendGenericPeekBuffer(Print* to, const ssize_t len, const int readUntilChar, const esp8266::polledTimeout::oneShotFastMs::timeType timeoutMs) { // "neverExpires (default, impossible)" is translated to default timeout @@ -104,7 +102,7 @@ size_t Stream::SendGenericPeekBuffer(Print* to, const ssize_t len, const int rea { peekConsume(w); written += w; - timedOut.reset(); // something has been written + timedOut.reset(); // something has been written } if (foundChar) { @@ -186,7 +184,7 @@ size_t Stream::SendGenericRegularUntil(Print* to, const ssize_t len, const int r break; } written += 1; - timedOut.reset(); // something has been written + timedOut.reset(); // something has been written } if (timedOut) @@ -243,7 +241,7 @@ size_t Stream::SendGenericRegular(Print* to, const ssize_t len, const esp8266::p size_t w = to->availableForWrite(); if (w == 0 && !to->outputCanTimeout()) - // no more data can be written, ever + // no more data can be written, ever { break; } @@ -270,7 +268,7 @@ size_t Stream::SendGenericRegular(Print* to, const ssize_t len, const esp8266::p setReport(Report::WriteError); break; } - timedOut.reset(); // something has been written + timedOut.reset(); // something has been written } if (timedOut) @@ -305,19 +303,19 @@ size_t Stream::SendGenericRegular(Print* to, const ssize_t len, const esp8266::p return written; } -Stream& operator << (Stream& out, String& string) +Stream& operator<<(Stream& out, String& string) { StreamConstPtr(string).sendAll(out); return out; } -Stream& operator << (Stream& out, StreamString& stream) +Stream& operator<<(Stream& out, StreamString& stream) { stream.sendAll(out); return out; } -Stream& operator << (Stream& out, Stream& stream) +Stream& operator<<(Stream& out, Stream& stream) { if (stream.streamRemaining() < 0) { @@ -339,13 +337,13 @@ Stream& operator << (Stream& out, Stream& stream) return out; } -Stream& operator << (Stream& out, const char* text) +Stream& operator<<(Stream& out, const char* text) { StreamConstPtr(text, strlen_P(text)).sendAll(out); return out; } -Stream& operator << (Stream& out, const __FlashStringHelper* text) +Stream& operator<<(Stream& out, const __FlashStringHelper* text) { StreamConstPtr(text).sendAll(out); return out; diff --git a/cores/esp8266/StreamString.h b/cores/esp8266/StreamString.h index be11669a79..3f7f5dc89c 100644 --- a/cores/esp8266/StreamString.h +++ b/cores/esp8266/StreamString.h @@ -23,8 +23,8 @@ #ifndef __STREAMSTRING_H #define __STREAMSTRING_H -#include #include +#include #include "Stream.h" #include "WString.h" @@ -32,17 +32,16 @@ // S2Stream points to a String and makes it a Stream // (it is also the helper for StreamString) -class S2Stream: public Stream +class S2Stream : public Stream { -public: - - S2Stream(String& string, int peekPointer = -1): - string(&string), peekPointer(peekPointer) + public: + S2Stream(String& string, int peekPointer = -1) + : string(&string), peekPointer(peekPointer) { } - S2Stream(String* string, int peekPointer = -1): - string(string), peekPointer(peekPointer) + S2Stream(String* string, int peekPointer = -1) + : string(string), peekPointer(peekPointer) { } @@ -206,19 +205,16 @@ class S2Stream: public Stream peekPointer = pointer; } -protected: - + protected: String* string; - int peekPointer; // -1:String is consumed / >=0:resettable pointer + int peekPointer; // -1:String is consumed / >=0:resettable pointer }; - // StreamString is a S2Stream holding the String -class StreamString: public String, public S2Stream +class StreamString : public String, public S2Stream { -protected: - + protected: void resetpp() { if (peekPointer > 0) @@ -227,56 +223,69 @@ class StreamString: public String, public S2Stream } } -public: - - StreamString(StreamString&& bro): String(bro), S2Stream(this) { } - StreamString(const StreamString& bro): String(bro), S2Stream(this) { } + public: + StreamString(StreamString&& bro) + : String(bro), S2Stream(this) {} + StreamString(const StreamString& bro) + : String(bro), S2Stream(this) {} // duplicate String constructors and operator=: - StreamString(const char* text = nullptr): String(text), S2Stream(this) { } - StreamString(const String& string): String(string), S2Stream(this) { } - StreamString(const __FlashStringHelper *str): String(str), S2Stream(this) { } - StreamString(String&& string): String(string), S2Stream(this) { } - - explicit StreamString(char c): String(c), S2Stream(this) { } - explicit StreamString(unsigned char c, unsigned char base = 10): String(c, base), S2Stream(this) { } - explicit StreamString(int i, unsigned char base = 10): String(i, base), S2Stream(this) { } - explicit StreamString(unsigned int i, unsigned char base = 10): String(i, base), S2Stream(this) { } - explicit StreamString(long l, unsigned char base = 10): String(l, base), S2Stream(this) { } - explicit StreamString(unsigned long l, unsigned char base = 10): String(l, base), S2Stream(this) { } - explicit StreamString(float f, unsigned char decimalPlaces = 2): String(f, decimalPlaces), S2Stream(this) { } - explicit StreamString(double d, unsigned char decimalPlaces = 2): String(d, decimalPlaces), S2Stream(this) { } - - StreamString& operator= (const StreamString& rhs) + StreamString(const char* text = nullptr) + : String(text), S2Stream(this) {} + StreamString(const String& string) + : String(string), S2Stream(this) {} + StreamString(const __FlashStringHelper* str) + : String(str), S2Stream(this) {} + StreamString(String&& string) + : String(string), S2Stream(this) {} + + explicit StreamString(char c) + : String(c), S2Stream(this) {} + explicit StreamString(unsigned char c, unsigned char base = 10) + : String(c, base), S2Stream(this) {} + explicit StreamString(int i, unsigned char base = 10) + : String(i, base), S2Stream(this) {} + explicit StreamString(unsigned int i, unsigned char base = 10) + : String(i, base), S2Stream(this) {} + explicit StreamString(long l, unsigned char base = 10) + : String(l, base), S2Stream(this) {} + explicit StreamString(unsigned long l, unsigned char base = 10) + : String(l, base), S2Stream(this) {} + explicit StreamString(float f, unsigned char decimalPlaces = 2) + : String(f, decimalPlaces), S2Stream(this) {} + explicit StreamString(double d, unsigned char decimalPlaces = 2) + : String(d, decimalPlaces), S2Stream(this) {} + + StreamString& operator=(const StreamString& rhs) { String::operator=(rhs); resetpp(); return *this; } - StreamString& operator= (const String& rhs) + StreamString& operator=(const String& rhs) { String::operator=(rhs); resetpp(); return *this; } - StreamString& operator= (const char* cstr) + StreamString& operator=(const char* cstr) { String::operator=(cstr); resetpp(); return *this; } - StreamString& operator= (const __FlashStringHelper* str) + StreamString& operator=(const __FlashStringHelper* str) { String::operator=(str); resetpp(); return *this; } - StreamString& operator= (String&& rval) + StreamString& operator=(String&& rval) { String::operator=(rval); resetpp(); @@ -284,4 +293,4 @@ class StreamString: public String, public S2Stream } }; -#endif // __STREAMSTRING_H +#endif // __STREAMSTRING_H diff --git a/cores/esp8266/core_esp8266_si2c.cpp b/cores/esp8266/core_esp8266_si2c.cpp index e01dffe080..28b6f99f40 100644 --- a/cores/esp8266/core_esp8266_si2c.cpp +++ b/cores/esp8266/core_esp8266_si2c.cpp @@ -19,16 +19,15 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Modified January 2017 by Bjorn Hammarberg (bjoham@esp8266.com) - i2c slave support */ -#include "twi.h" +#include "PolledTimeout.h" #include "pins_arduino.h" +#include "twi.h" #include "wiring_private.h" -#include "PolledTimeout.h" - - -extern "C" { -#include "twi_util.h" +extern "C" +{ #include "ets_sys.h" +#include "twi_util.h" }; // Inline helpers @@ -57,11 +56,10 @@ static inline __attribute__((always_inline)) bool SCL_READ(const int twi_scl) return (GPI & (1 << twi_scl)) != 0; } - // Implement as a class to reduce code size by allowing access to many global variables with a single base pointer class Twi { -private: + private: unsigned int preferred_si2c_clock = 100000; uint32_t twi_dcount = 18; unsigned char twi_sda = 0; @@ -73,8 +71,26 @@ class Twi // issues about RmW on packed bytes. The int-wide variations of asm instructions are smaller than the equivalent // byte-wide ones, and since these emums are used everywhere, the difference adds up fast. There is only a single // instance of the class, though, so the extra 12 bytes of RAM used here saves a lot more IRAM. - volatile enum { TWIPM_UNKNOWN = 0, TWIPM_IDLE, TWIPM_ADDRESSED, TWIPM_WAIT} twip_mode = TWIPM_IDLE; - volatile enum { TWIP_UNKNOWN = 0, TWIP_IDLE, TWIP_START, TWIP_SEND_ACK, TWIP_WAIT_ACK, TWIP_WAIT_STOP, TWIP_SLA_W, TWIP_SLA_R, TWIP_REP_START, TWIP_READ, TWIP_STOP, TWIP_REC_ACK, TWIP_READ_ACK, TWIP_RWAIT_ACK, TWIP_WRITE, TWIP_BUS_ERR } twip_state = TWIP_IDLE; + volatile enum { TWIPM_UNKNOWN = 0, + TWIPM_IDLE, + TWIPM_ADDRESSED, + TWIPM_WAIT } twip_mode = TWIPM_IDLE; + volatile enum { TWIP_UNKNOWN = 0, + TWIP_IDLE, + TWIP_START, + TWIP_SEND_ACK, + TWIP_WAIT_ACK, + TWIP_WAIT_STOP, + TWIP_SLA_W, + TWIP_SLA_R, + TWIP_REP_START, + TWIP_READ, + TWIP_STOP, + TWIP_REC_ACK, + TWIP_READ_ACK, + TWIP_RWAIT_ACK, + TWIP_WRITE, + TWIP_BUS_ERR } twip_state = TWIP_IDLE; volatile int twip_status = TW_NO_INFO; volatile int bitCount = 0; @@ -83,7 +99,11 @@ class Twi volatile int twi_ack_rec = 0; volatile int twi_timeout_ms = 10; - volatile enum { TWI_READY = 0, TWI_MRX, TWI_MTX, TWI_SRX, TWI_STX } twi_state = TWI_READY; + volatile enum { TWI_READY = 0, + TWI_MRX, + TWI_MTX, + TWI_SRX, + TWI_STX } twi_state = TWI_READY; volatile uint8_t twi_error = 0xFF; uint8_t twi_txBuffer[TWI_BUFFER_LENGTH]; @@ -97,16 +117,25 @@ class Twi void (*twi_onSlaveReceive)(uint8_t*, size_t); // ETS queue/timer interfaces - enum { EVENTTASK_QUEUE_SIZE = 1, EVENTTASK_QUEUE_PRIO = 2 }; - enum { TWI_SIG_RANGE = 0x00000100, TWI_SIG_RX = 0x00000101, TWI_SIG_TX = 0x00000102 }; + enum + { + EVENTTASK_QUEUE_SIZE = 1, + EVENTTASK_QUEUE_PRIO = 2 + }; + enum + { + TWI_SIG_RANGE = 0x00000100, + TWI_SIG_RX = 0x00000101, + TWI_SIG_TX = 0x00000102 + }; ETSEvent eventTaskQueue[EVENTTASK_QUEUE_SIZE]; ETSTimer timer; // Event/IRQ callbacks, so they can't use "this" and need to be static static void IRAM_ATTR onSclChange(void); static void IRAM_ATTR onSdaChange(void); - static void eventTask(ETSEvent *e); - static void IRAM_ATTR onTimer(void *unused); + static void eventTask(ETSEvent* e); + static void IRAM_ATTR onTimer(void* unused); // Allow not linking in the slave code if there is no call to setAddress bool _slaveEnabled = false; @@ -126,9 +155,9 @@ class Twi { esp8266::polledTimeout::oneShotFastUs timeout(twi_clockStretchLimit); esp8266::polledTimeout::periodicFastUs yieldTimeout(5000); - while (!timeout && !SCL_READ(twi_scl)) // outer loop is stretch duration up to stretch limit + while (!timeout && !SCL_READ(twi_scl)) // outer loop is stretch duration up to stretch limit { - if (yieldTimeout) // inner loop yields every 5ms + if (yieldTimeout) // inner loop yields every 5ms { yield(); } @@ -138,12 +167,12 @@ class Twi // Generate a clock "valley" (at the end of a segment, just before a repeated start) void twi_scl_valley(void); -public: + public: void setClock(unsigned int freq); void setClockStretchLimit(uint32_t limit); void init(unsigned char sda, unsigned char scl); void setAddress(uint8_t address); - unsigned char writeTo(unsigned char address, unsigned char * buf, unsigned int len, unsigned char sendStop); + unsigned char writeTo(unsigned char address, unsigned char* buf, unsigned int len, unsigned char sendStop); unsigned char readFrom(unsigned char address, unsigned char* buf, unsigned int len, unsigned char sendStop); uint8_t status(); uint8_t transmit(const uint8_t* data, uint8_t length); @@ -175,8 +204,8 @@ void Twi::setClock(unsigned int freq) { freq = 400000; } - twi_dcount = (500000000 / freq); // half-cycle period in ns - twi_dcount = (1000 * (twi_dcount - 1120)) / 62500; // (half cycle - overhead) / busywait loop time + twi_dcount = (500000000 / freq); // half-cycle period in ns + twi_dcount = (1000 * (twi_dcount - 1120)) / 62500; // (half cycle - overhead) / busywait loop time #else @@ -184,8 +213,8 @@ void Twi::setClock(unsigned int freq) { freq = 800000; } - twi_dcount = (500000000 / freq); // half-cycle period in ns - twi_dcount = (1000 * (twi_dcount - 560)) / 31250; // (half cycle - overhead) / busywait loop time + twi_dcount = (500000000 / freq); // half-cycle period in ns + twi_dcount = (1000 * (twi_dcount - 560)) / 31250; // (half cycle - overhead) / busywait loop time #endif } @@ -195,8 +224,6 @@ void Twi::setClockStretchLimit(uint32_t limit) twi_clockStretchLimit = limit; } - - void Twi::init(unsigned char sda, unsigned char scl) { // set timer function @@ -210,7 +237,7 @@ void Twi::init(unsigned char sda, unsigned char scl) pinMode(twi_sda, INPUT_PULLUP); pinMode(twi_scl, INPUT_PULLUP); twi_setClock(preferred_si2c_clock); - twi_setClockStretchLimit(150000L); // default value is 150 mS + twi_setClockStretchLimit(150000L); // default value is 150 mS } void Twi::setAddress(uint8_t address) @@ -234,7 +261,7 @@ void IRAM_ATTR Twi::busywait(unsigned int v) unsigned int i; for (i = 0; i < v; i++) // loop time is 5 machine cycles: 31.25ns @ 160MHz, 62.5ns @ 80MHz { - __asm__ __volatile__("nop"); // minimum element to keep GCC from optimizing this function out. + __asm__ __volatile__("nop"); // minimum element to keep GCC from optimizing this function out. } } @@ -308,7 +335,7 @@ bool Twi::write_byte(unsigned char byte) write_bit(byte & 0x80); byte <<= 1; } - return !read_bit();//NACK/ACK + return !read_bit(); //NACK/ACK } unsigned char Twi::read_byte(bool nack) @@ -323,7 +350,7 @@ unsigned char Twi::read_byte(bool nack) return byte; } -unsigned char Twi::writeTo(unsigned char address, unsigned char * buf, unsigned int len, unsigned char sendStop) +unsigned char Twi::writeTo(unsigned char address, unsigned char* buf, unsigned int len, unsigned char sendStop) { unsigned int i; if (!write_start()) @@ -336,7 +363,7 @@ unsigned char Twi::writeTo(unsigned char address, unsigned char * buf, unsigned { write_stop(); } - return 2; //received NACK on transmit of address + return 2; //received NACK on transmit of address } for (i = 0; i < len; i++) { @@ -346,7 +373,7 @@ unsigned char Twi::writeTo(unsigned char address, unsigned char * buf, unsigned { write_stop(); } - return 3;//received NACK on transmit of data + return 3; //received NACK on transmit of data } } if (sendStop) @@ -381,7 +408,7 @@ unsigned char Twi::readFrom(unsigned char address, unsigned char* buf, unsigned { write_stop(); } - return 2;//received NACK on transmit of address + return 2; //received NACK on transmit of address } for (i = 0; i < (len - 1); i++) { @@ -424,12 +451,12 @@ uint8_t Twi::status() } int clockCount = 20; - while (!SDA_READ(twi_sda) && clockCount-- > 0) // if SDA low, read the bits slaves have to sent to a max + while (!SDA_READ(twi_sda) && clockCount-- > 0) // if SDA low, read the bits slaves have to sent to a max { read_bit(); if (!SCL_READ(twi_scl)) { - return I2C_SCL_HELD_LOW_AFTER_READ; // I2C bus error. SCL held low beyond slave clock stretch time + return I2C_SCL_HELD_LOW_AFTER_READ; // I2C bus error. SCL held low beyond slave clock stretch time } } if (!SDA_READ(twi_sda)) @@ -485,139 +512,137 @@ void IRAM_ATTR Twi::reply(uint8_t ack) if (ack) { //TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT) | _BV(TWEA); - SCL_HIGH(twi.twi_scl); // _BV(TWINT) - twi_ack = 1; // _BV(TWEA) + SCL_HIGH(twi.twi_scl); // _BV(TWINT) + twi_ack = 1; // _BV(TWEA) } else { //TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT); - SCL_HIGH(twi.twi_scl); // _BV(TWINT) - twi_ack = 0; // ~_BV(TWEA) + SCL_HIGH(twi.twi_scl); // _BV(TWINT) + twi_ack = 0; // ~_BV(TWEA) } } - void IRAM_ATTR Twi::releaseBus(void) { // release bus //TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT); - SCL_HIGH(twi.twi_scl); // _BV(TWINT) - twi_ack = 1; // _BV(TWEA) + SCL_HIGH(twi.twi_scl); // _BV(TWINT) + twi_ack = 1; // _BV(TWEA) SDA_HIGH(twi.twi_sda); // update twi state twi_state = TWI_READY; } - void IRAM_ATTR Twi::onTwipEvent(uint8_t status) { twip_status = status; switch (status) { - // Slave Receiver - case TW_SR_SLA_ACK: // addressed, returned ack - case TW_SR_GCALL_ACK: // addressed generally, returned ack - case TW_SR_ARB_LOST_SLA_ACK: // lost arbitration, returned ack - case TW_SR_ARB_LOST_GCALL_ACK: // lost arbitration, returned ack - // enter slave receiver mode - twi_state = TWI_SRX; - // indicate that rx buffer can be overwritten and ack - twi_rxBufferIndex = 0; - reply(1); - break; - case TW_SR_DATA_ACK: // data received, returned ack - case TW_SR_GCALL_DATA_ACK: // data received generally, returned ack - // if there is still room in the rx buffer - if (twi_rxBufferIndex < TWI_BUFFER_LENGTH) - { - // put byte in buffer and ack - twi_rxBuffer[twi_rxBufferIndex++] = twi_data; + // Slave Receiver + case TW_SR_SLA_ACK: // addressed, returned ack + case TW_SR_GCALL_ACK: // addressed generally, returned ack + case TW_SR_ARB_LOST_SLA_ACK: // lost arbitration, returned ack + case TW_SR_ARB_LOST_GCALL_ACK: // lost arbitration, returned ack + // enter slave receiver mode + twi_state = TWI_SRX; + // indicate that rx buffer can be overwritten and ack + twi_rxBufferIndex = 0; reply(1); - } - else - { - // otherwise nack - reply(0); - } - break; - case TW_SR_STOP: // stop or repeated start condition received - // put a null char after data if there's room - if (twi_rxBufferIndex < TWI_BUFFER_LENGTH) - { - twi_rxBuffer[twi_rxBufferIndex] = '\0'; - } - // callback to user-defined callback over event task to allow for non-RAM-residing code - //twi_rxBufferLock = true; // This may be necessary - ets_post(EVENTTASK_QUEUE_PRIO, TWI_SIG_RX, twi_rxBufferIndex); - - // since we submit rx buffer to "wire" library, we can reset it - twi_rxBufferIndex = 0; - break; - - case TW_SR_DATA_NACK: // data received, returned nack - case TW_SR_GCALL_DATA_NACK: // data received generally, returned nack - // nack back at master - reply(0); - break; - - // Slave Transmitter - case TW_ST_SLA_ACK: // addressed, returned ack - case TW_ST_ARB_LOST_SLA_ACK: // arbitration lost, returned ack - // enter slave transmitter mode - twi_state = TWI_STX; - // ready the tx buffer index for iteration - twi_txBufferIndex = 0; - // set tx buffer length to be zero, to verify if user changes it - twi_txBufferLength = 0; - // callback to user-defined callback over event task to allow for non-RAM-residing code - // request for txBuffer to be filled and length to be set - // note: user must call twi_transmit(bytes, length) to do this - ets_post(EVENTTASK_QUEUE_PRIO, TWI_SIG_TX, 0); - break; - - case TW_ST_DATA_ACK: // byte sent, ack returned - // copy data to output register - twi_data = twi_txBuffer[twi_txBufferIndex++]; - - bitCount = 8; - bitCount--; - if (twi_data & 0x80) - { - SDA_HIGH(twi.twi_sda); - } - else - { - SDA_LOW(twi.twi_sda); - } - twi_data <<= 1; + break; + case TW_SR_DATA_ACK: // data received, returned ack + case TW_SR_GCALL_DATA_ACK: // data received generally, returned ack + // if there is still room in the rx buffer + if (twi_rxBufferIndex < TWI_BUFFER_LENGTH) + { + // put byte in buffer and ack + twi_rxBuffer[twi_rxBufferIndex++] = twi_data; + reply(1); + } + else + { + // otherwise nack + reply(0); + } + break; + case TW_SR_STOP: // stop or repeated start condition received + // put a null char after data if there's room + if (twi_rxBufferIndex < TWI_BUFFER_LENGTH) + { + twi_rxBuffer[twi_rxBufferIndex] = '\0'; + } + // callback to user-defined callback over event task to allow for non-RAM-residing code + //twi_rxBufferLock = true; // This may be necessary + ets_post(EVENTTASK_QUEUE_PRIO, TWI_SIG_RX, twi_rxBufferIndex); - // if there is more to send, ack, otherwise nack - if (twi_txBufferIndex < twi_txBufferLength) - { - reply(1); - } - else - { + // since we submit rx buffer to "wire" library, we can reset it + twi_rxBufferIndex = 0; + break; + + case TW_SR_DATA_NACK: // data received, returned nack + case TW_SR_GCALL_DATA_NACK: // data received generally, returned nack + // nack back at master reply(0); - } - break; - case TW_ST_DATA_NACK: // received nack, we are done - case TW_ST_LAST_DATA: // received ack, but we are done already! - // leave slave receiver state - releaseBus(); - break; - - // All - case TW_NO_INFO: // no state information - break; - case TW_BUS_ERROR: // bus error, illegal stop/start - twi_error = TW_BUS_ERROR; - break; + break; + + // Slave Transmitter + case TW_ST_SLA_ACK: // addressed, returned ack + case TW_ST_ARB_LOST_SLA_ACK: // arbitration lost, returned ack + // enter slave transmitter mode + twi_state = TWI_STX; + // ready the tx buffer index for iteration + twi_txBufferIndex = 0; + // set tx buffer length to be zero, to verify if user changes it + twi_txBufferLength = 0; + // callback to user-defined callback over event task to allow for non-RAM-residing code + // request for txBuffer to be filled and length to be set + // note: user must call twi_transmit(bytes, length) to do this + ets_post(EVENTTASK_QUEUE_PRIO, TWI_SIG_TX, 0); + break; + + case TW_ST_DATA_ACK: // byte sent, ack returned + // copy data to output register + twi_data = twi_txBuffer[twi_txBufferIndex++]; + + bitCount = 8; + bitCount--; + if (twi_data & 0x80) + { + SDA_HIGH(twi.twi_sda); + } + else + { + SDA_LOW(twi.twi_sda); + } + twi_data <<= 1; + + // if there is more to send, ack, otherwise nack + if (twi_txBufferIndex < twi_txBufferLength) + { + reply(1); + } + else + { + reply(0); + } + break; + case TW_ST_DATA_NACK: // received nack, we are done + case TW_ST_LAST_DATA: // received ack, but we are done already! + // leave slave receiver state + releaseBus(); + break; + + // All + case TW_NO_INFO: // no state information + break; + case TW_BUS_ERROR: // bus error, illegal stop/start + twi_error = TW_BUS_ERROR; + break; } } -void IRAM_ATTR Twi::onTimer(void *unused) +void IRAM_ATTR Twi::onTimer(void* unused) { (void)unused; twi.releaseBus(); @@ -626,9 +651,8 @@ void IRAM_ATTR Twi::onTimer(void *unused) twi.twip_state = TWIP_BUS_ERR; } -void Twi::eventTask(ETSEvent *e) +void Twi::eventTask(ETSEvent* e) { - if (e == NULL) { return; @@ -636,26 +660,26 @@ void Twi::eventTask(ETSEvent *e) switch (e->sig) { - case TWI_SIG_TX: - twi.twi_onSlaveTransmit(); + case TWI_SIG_TX: + twi.twi_onSlaveTransmit(); - // if they didn't change buffer & length, initialize it - if (twi.twi_txBufferLength == 0) - { - twi.twi_txBufferLength = 1; - twi.twi_txBuffer[0] = 0x00; - } + // if they didn't change buffer & length, initialize it + if (twi.twi_txBufferLength == 0) + { + twi.twi_txBufferLength = 1; + twi.twi_txBuffer[0] = 0x00; + } - // Initiate transmission - twi.onTwipEvent(TW_ST_DATA_ACK); + // Initiate transmission + twi.onTwipEvent(TW_ST_DATA_ACK); - break; + break; - case TWI_SIG_RX: - // ack future responses and leave slave receiver state - twi.releaseBus(); - twi.twi_onSlaveReceive(twi.twi_rxBuffer, e->par); - break; + case TWI_SIG_RX: + // ack future responses and leave slave receiver state + twi.releaseBus(); + twi.twi_onSlaveReceive(twi.twi_rxBuffer, e->par); + break; } } @@ -663,7 +687,7 @@ void Twi::eventTask(ETSEvent *e) // compared to the logical-or of all states with the same branch. This removes the need // for a large series of straight-line compares. The biggest win is when multiple states // all have the same branch (onSdaChange), but for others there is some benefit, still. -#define S2M(x) (1<<(x)) +#define S2M(x) (1 << (x)) // Shorthand for if the state is any of the or'd bitmask x #define IFSTATE(x) if (twip_state_mask & (x)) @@ -677,7 +701,7 @@ void IRAM_ATTR Twi::onSclChange(void) sda = SDA_READ(twi.twi_sda); scl = SCL_READ(twi.twi_scl); - twi.twip_status = 0xF8; // reset TWI status + twi.twip_status = 0xF8; // reset TWI status int twip_state_mask = S2M(twi.twip_state); IFSTATE(S2M(TWIP_START) | S2M(TWIP_REP_START) | S2M(TWIP_SLA_W) | S2M(TWIP_READ)) @@ -752,7 +776,7 @@ void IRAM_ATTR Twi::onSclChange(void) } else { - SCL_LOW(twi.twi_scl); // clock stretching + SCL_LOW(twi.twi_scl); // clock stretching SDA_HIGH(twi.twi_sda); twi.twip_mode = TWIPM_ADDRESSED; if (!(twi.twi_data & 0x01)) @@ -770,7 +794,7 @@ void IRAM_ATTR Twi::onSclChange(void) } else { - SCL_LOW(twi.twi_scl); // clock stretching + SCL_LOW(twi.twi_scl); // clock stretching SDA_HIGH(twi.twi_sda); if (!twi.twi_ack) { @@ -848,7 +872,7 @@ void IRAM_ATTR Twi::onSclChange(void) } else { - SCL_LOW(twi.twi_scl); // clock stretching + SCL_LOW(twi.twi_scl); // clock stretching if (twi.twi_ack && twi.twi_ack_rec) { twi.onTwipEvent(TW_ST_DATA_ACK); @@ -875,7 +899,7 @@ void IRAM_ATTR Twi::onSdaChange(void) scl = SCL_READ(twi.twi_scl); int twip_state_mask = S2M(twi.twip_state); - if (scl) /* !DATA */ + if (scl) /* !DATA */ { IFSTATE(S2M(TWIP_IDLE)) { @@ -888,13 +912,13 @@ void IRAM_ATTR Twi::onSdaChange(void) // START twi.bitCount = 8; twi.twip_state = TWIP_START; - ets_timer_arm_new(&twi.timer, twi.twi_timeout_ms, false, true); // Once, ms + ets_timer_arm_new(&twi.timer, twi.twi_timeout_ms, false, true); // Once, ms } } else IFSTATE(S2M(TWIP_START) | S2M(TWIP_REP_START) | S2M(TWIP_SEND_ACK) | S2M(TWIP_WAIT_ACK) | S2M(TWIP_SLA_R) | S2M(TWIP_REC_ACK) | S2M(TWIP_READ_ACK) | S2M(TWIP_RWAIT_ACK) | S2M(TWIP_WRITE)) { // START or STOP - SDA_HIGH(twi.twi_sda); // Should not be necessary + SDA_HIGH(twi.twi_sda); // Should not be necessary twi.onTwipEvent(TW_BUS_ERROR); twi.twip_mode = TWIPM_WAIT; twi.twip_state = TWIP_BUS_ERR; @@ -904,7 +928,7 @@ void IRAM_ATTR Twi::onSdaChange(void) if (sda) { // STOP - SCL_LOW(twi.twi_scl); // generates a low SCL pulse after STOP + SCL_LOW(twi.twi_scl); // generates a low SCL pulse after STOP ets_timer_disarm(&twi.timer); twi.twip_state = TWIP_IDLE; twi.twip_mode = TWIPM_IDLE; @@ -921,7 +945,7 @@ void IRAM_ATTR Twi::onSdaChange(void) { twi.bitCount = 8; twi.twip_state = TWIP_REP_START; - ets_timer_arm_new(&twi.timer, twi.twi_timeout_ms, false, true); // Once, ms + ets_timer_arm_new(&twi.timer, twi.twi_timeout_ms, false, true); // Once, ms } } } @@ -938,7 +962,7 @@ void IRAM_ATTR Twi::onSdaChange(void) else { // during first bit in byte transfer - ok - SCL_LOW(twi.twi_scl); // clock stretching + SCL_LOW(twi.twi_scl); // clock stretching twi.onTwipEvent(TW_SR_STOP); if (sda) { @@ -951,7 +975,7 @@ void IRAM_ATTR Twi::onSdaChange(void) { // START twi.bitCount = 8; - ets_timer_arm_new(&twi.timer, twi.twi_timeout_ms, false, true); // Once, ms + ets_timer_arm_new(&twi.timer, twi.twi_timeout_ms, false, true); // Once, ms twi.twip_state = TWIP_REP_START; twi.twip_mode = TWIPM_IDLE; } @@ -961,8 +985,8 @@ void IRAM_ATTR Twi::onSdaChange(void) } // C wrappers for the object, since API is exposed only as C -extern "C" { - +extern "C" +{ void twi_init(unsigned char sda, unsigned char scl) { return twi.init(sda, scl); @@ -983,12 +1007,12 @@ extern "C" { twi.setClockStretchLimit(limit); } - uint8_t twi_writeTo(unsigned char address, unsigned char * buf, unsigned int len, unsigned char sendStop) + uint8_t twi_writeTo(unsigned char address, unsigned char* buf, unsigned int len, unsigned char sendStop) { return twi.writeTo(address, buf, len, sendStop); } - uint8_t twi_readFrom(unsigned char address, unsigned char * buf, unsigned int len, unsigned char sendStop) + uint8_t twi_readFrom(unsigned char address, unsigned char* buf, unsigned int len, unsigned char sendStop) { return twi.readFrom(address, buf, len, sendStop); } @@ -998,7 +1022,7 @@ extern "C" { return twi.status(); } - uint8_t twi_transmit(const uint8_t * buf, uint8_t len) + uint8_t twi_transmit(const uint8_t* buf, uint8_t len) { return twi.transmit(buf, len); } @@ -1027,5 +1051,4 @@ extern "C" { { twi.enableSlave(); } - }; diff --git a/cores/esp8266/debug.cpp b/cores/esp8266/debug.cpp index 06af1e424b..7173c29ab7 100644 --- a/cores/esp8266/debug.cpp +++ b/cores/esp8266/debug.cpp @@ -18,8 +18,8 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -#include "Arduino.h" #include "debug.h" +#include "Arduino.h" #include "osapi.h" #ifdef DEBUG_ESP_CORE @@ -30,7 +30,7 @@ void __iamslow(const char* what) #endif IRAM_ATTR -void hexdump(const void *mem, uint32_t len, uint8_t cols) +void hexdump(const void* mem, uint32_t len, uint8_t cols) { const char* src = (const char*)mem; os_printf("\n[HEXDUMP] Address: %p len: 0x%X (%d)", src, len, len); diff --git a/cores/esp8266/debug.h b/cores/esp8266/debug.h index 263d3e9149..025687a5af 100644 --- a/cores/esp8266/debug.h +++ b/cores/esp8266/debug.h @@ -5,44 +5,54 @@ #include #ifdef DEBUG_ESP_CORE -#define DEBUGV(fmt, ...) ::printf((PGM_P)PSTR(fmt), ## __VA_ARGS__) +#define DEBUGV(fmt, ...) ::printf((PGM_P)PSTR(fmt), ##__VA_ARGS__) #endif #ifndef DEBUGV -#define DEBUGV(...) do { (void)0; } while (0) +#define DEBUGV(...) \ + do \ + { \ + (void)0; \ + } while (0) #endif #ifdef __cplusplus -extern "C" void hexdump(const void *mem, uint32_t len, uint8_t cols = 16); +extern "C" void hexdump(const void* mem, uint32_t len, uint8_t cols = 16); #else -void hexdump(const void *mem, uint32_t len, uint8_t cols); +void hexdump(const void* mem, uint32_t len, uint8_t cols); #endif #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -void __unhandled_exception(const char *str) __attribute__((noreturn)); -void __panic_func(const char* file, int line, const char* func) __attribute__((noreturn)); + void __unhandled_exception(const char* str) __attribute__((noreturn)); + void __panic_func(const char* file, int line, const char* func) __attribute__((noreturn)); #define panic() __panic_func(PSTR(__FILE__), __LINE__, __func__) #ifdef DEBUG_ESP_CORE -extern void __iamslow(const char* what); -#define IAMSLOW() \ - do { \ - static bool once = false; \ - if (!once) { \ - once = true; \ + extern void __iamslow(const char* what); +#define IAMSLOW() \ + do \ + { \ + static bool once = false; \ + if (!once) \ + { \ + once = true; \ __iamslow((PGM_P)FPSTR(__FUNCTION__)); \ - } \ + } \ } while (0) #else -#define IAMSLOW() do { (void)0; } while (0) +#define IAMSLOW() \ + do \ + { \ + (void)0; \ + } while (0) #endif #ifdef __cplusplus } #endif - -#endif//ARD_DEBUG_H +#endif //ARD_DEBUG_H diff --git a/libraries/ESP8266mDNS/src/ESP8266mDNS.cpp b/libraries/ESP8266mDNS/src/ESP8266mDNS.cpp index b5d7aac277..821b7010af 100644 --- a/libraries/ESP8266mDNS/src/ESP8266mDNS.cpp +++ b/libraries/ESP8266mDNS/src/ESP8266mDNS.cpp @@ -30,4 +30,3 @@ #if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_MDNS) MDNSResponder MDNS; #endif - diff --git a/libraries/ESP8266mDNS/src/ESP8266mDNS.h b/libraries/ESP8266mDNS/src/ESP8266mDNS.h index 8b035a7986..3b6ccc6449 100644 --- a/libraries/ESP8266mDNS/src/ESP8266mDNS.h +++ b/libraries/ESP8266mDNS/src/ESP8266mDNS.h @@ -41,13 +41,13 @@ #ifndef __ESP8266MDNS_H #define __ESP8266MDNS_H -#include "LEAmDNS.h" // LEA +#include "LEAmDNS.h" // LEA #if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_MDNS) // Maps the implementation to use to the global namespace type -using MDNSResponder = esp8266::MDNSImplementation::MDNSResponder; // LEA +using MDNSResponder = esp8266::MDNSImplementation::MDNSResponder; // LEA extern MDNSResponder MDNS; #endif -#endif // __ESP8266MDNS_H +#endif // __ESP8266MDNS_H diff --git a/libraries/ESP8266mDNS/src/LEAmDNS.cpp b/libraries/ESP8266mDNS/src/LEAmDNS.cpp index 4908a67e06..c6ed0fe997 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS.cpp +++ b/libraries/ESP8266mDNS/src/LEAmDNS.cpp @@ -22,24 +22,22 @@ */ -#include #include +#include -#include "ESP8266mDNS.h" -#include "LEAmDNS_Priv.h" -#include // LwipIntf::stateUpCB() +#include // LwipIntf::stateUpCB() #include #include +#include "ESP8266mDNS.h" +#include "LEAmDNS_Priv.h" namespace esp8266 { - /* LEAmDNS */ namespace MDNSImplementation { - /** STRINGIZE */ @@ -50,7 +48,6 @@ namespace MDNSImplementation #define STRINGIZE_VALUE_OF(x) STRINGIZE(x) #endif - /** INTERFACE */ @@ -59,11 +56,11 @@ namespace MDNSImplementation MDNSResponder::MDNSResponder */ MDNSResponder::MDNSResponder(void) - : m_pServices(0), - m_pUDPContext(0), - m_pcHostname(0), - m_pServiceQueries(0), - m_fnServiceTxtCallback(0) + : m_pServices(0), + m_pUDPContext(0), + m_pcHostname(0), + m_pServiceQueries(0), + m_fnServiceTxtCallback(0) { } @@ -72,7 +69,6 @@ MDNSResponder::MDNSResponder(void) */ MDNSResponder::~MDNSResponder(void) { - _resetProbeStatus(false); _releaseServiceQueries(); _releaseHostname(); @@ -91,26 +87,24 @@ MDNSResponder::~MDNSResponder(void) */ bool MDNSResponder::begin(const char* p_pcHostname, const IPAddress& /*p_IPAddress*/, uint32_t /*p_u32TTL*/) { - bool bResult = false; + bool bResult = false; if (_setHostname(p_pcHostname)) { bResult = _restart(); } - LwipIntf::stateUpCB - ( - [this](netif * intf) - { - (void)intf; - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] new Interface '%c%c' is UP! restarting\n"), intf->name[0], intf->name[1])); - _restart(); - } - ); + LwipIntf::stateUpCB( + [this](netif* intf) + { + (void)intf; + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] new Interface '%c%c' is UP! restarting\n"), intf->name[0], intf->name[1])); + _restart(); + }); DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] begin: FAILED for '%s'!\n"), (p_pcHostname ? : "-")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] begin: FAILED for '%s'!\n"), (p_pcHostname ?: "-")); + }); return bResult; } @@ -124,12 +118,12 @@ bool MDNSResponder::begin(const char* p_pcHostname, const IPAddress& /*p_IPAddre */ bool MDNSResponder::close(void) { - bool bResult = false; + bool bResult = false; if (0 != m_pUDPContext) { _announce(false, true); - _resetProbeStatus(false); // Stop probing + _resetProbeStatus(false); // Stop probing _releaseServiceQueries(); _releaseServices(); _releaseUDPContext(); @@ -167,8 +161,7 @@ bool MDNSResponder::end(void) */ bool MDNSResponder::setHostname(const char* p_pcHostname) { - - bool bResult = false; + bool bResult = false; if (_setHostname(p_pcHostname)) { @@ -186,9 +179,9 @@ bool MDNSResponder::setHostname(const char* p_pcHostname) } } DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] setHostname: FAILED for '%s'!\n"), (p_pcHostname ? : "-")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] setHostname: FAILED for '%s'!\n"), (p_pcHostname ?: "-")); + }); return bResult; } @@ -197,11 +190,9 @@ bool MDNSResponder::setHostname(const char* p_pcHostname) */ bool MDNSResponder::setHostname(const String& p_strHostname) { - return setHostname(p_strHostname.c_str()); } - /* SERVICES */ @@ -215,37 +206,34 @@ bool MDNSResponder::setHostname(const String& p_strHostname) */ MDNSResponder::hMDNSService MDNSResponder::addService(const char* p_pcName, - const char* p_pcService, - const char* p_pcProtocol, - uint16_t p_u16Port) -{ - - hMDNSService hResult = 0; - - if (((!p_pcName) || // NO name OR - (MDNS_DOMAIN_LABEL_MAXLENGTH >= os_strlen(p_pcName))) && // Fitting name - (p_pcService) && - (MDNS_SERVICE_NAME_LENGTH >= os_strlen(p_pcService)) && - (p_pcProtocol) && - ((MDNS_SERVICE_PROTOCOL_LENGTH - 1) != os_strlen(p_pcProtocol)) && - (p_u16Port)) + const char* p_pcService, + const char* p_pcProtocol, + uint16_t p_u16Port) +{ + hMDNSService hResult = 0; + + if (((!p_pcName) || // NO name OR + (MDNS_DOMAIN_LABEL_MAXLENGTH >= os_strlen(p_pcName))) && // Fitting name + (p_pcService) && + (MDNS_SERVICE_NAME_LENGTH >= os_strlen(p_pcService)) && + (p_pcProtocol) && + ((MDNS_SERVICE_PROTOCOL_LENGTH - 1) != os_strlen(p_pcProtocol)) && + (p_u16Port)) { - - if (!_findService((p_pcName ? : m_pcHostname), p_pcService, p_pcProtocol)) // Not already used + if (!_findService((p_pcName ?: m_pcHostname), p_pcService, p_pcProtocol)) // Not already used { if (0 != (hResult = (hMDNSService)_allocService(p_pcName, p_pcService, p_pcProtocol, p_u16Port))) { - // Start probing ((stcMDNSService*)hResult)->m_ProbeInformation.m_ProbingStatus = ProbingStatus_ReadyToStart; } } - } // else: bad arguments - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] addService: %s to add '%s.%s.%s'!\n"), (hResult ? "Succeeded" : "FAILED"), (p_pcName ? : "-"), p_pcService, p_pcProtocol);); + } // else: bad arguments + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] addService: %s to add '%s.%s.%s'!\n"), (hResult ? "Succeeded" : "FAILED"), (p_pcName ?: "-"), p_pcService, p_pcProtocol);); DEBUG_EX_ERR(if (!hResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] addService: FAILED to add '%s.%s.%s'!\n"), (p_pcName ? : "-"), p_pcService, p_pcProtocol); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] addService: FAILED to add '%s.%s.%s'!\n"), (p_pcName ?: "-"), p_pcService, p_pcProtocol); + }); return hResult; } @@ -258,15 +246,14 @@ MDNSResponder::hMDNSService MDNSResponder::addService(const char* p_pcName, */ bool MDNSResponder::removeService(const MDNSResponder::hMDNSService p_hService) { - stcMDNSService* pService = 0; - bool bResult = (((pService = _findService(p_hService))) && - (_announceService(*pService, false)) && - (_releaseService(pService))); + bool bResult = (((pService = _findService(p_hService))) && + (_announceService(*pService, false)) && + (_releaseService(pService))); DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] removeService: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] removeService: FAILED!\n")); + }); return bResult; } @@ -277,8 +264,7 @@ bool MDNSResponder::removeService(const char* p_pcName, const char* p_pcService, const char* p_pcProtocol) { - - return removeService((hMDNSService)_findService((p_pcName ? : m_pcHostname), p_pcService, p_pcProtocol)); + return removeService((hMDNSService)_findService((p_pcName ?: m_pcHostname), p_pcService, p_pcProtocol)); } /* @@ -288,7 +274,6 @@ bool MDNSResponder::addService(const String& p_strService, const String& p_strProtocol, uint16_t p_u16Port) { - return (0 != addService(m_pcHostname, p_strService.c_str(), p_strProtocol.c_str(), p_u16Port)); } @@ -298,17 +283,16 @@ bool MDNSResponder::addService(const String& p_strService, bool MDNSResponder::setServiceName(const MDNSResponder::hMDNSService p_hService, const char* p_pcInstanceName) { - stcMDNSService* pService = 0; - bool bResult = (((!p_pcInstanceName) || - (MDNS_DOMAIN_LABEL_MAXLENGTH >= os_strlen(p_pcInstanceName))) && - ((pService = _findService(p_hService))) && - (pService->setName(p_pcInstanceName)) && - ((pService->m_ProbeInformation.m_ProbingStatus = ProbingStatus_ReadyToStart))); + bool bResult = (((!p_pcInstanceName) || + (MDNS_DOMAIN_LABEL_MAXLENGTH >= os_strlen(p_pcInstanceName))) && + ((pService = _findService(p_hService))) && + (pService->setName(p_pcInstanceName)) && + ((pService->m_ProbeInformation.m_ProbingStatus = ProbingStatus_ReadyToStart))); DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] setServiceName: FAILED for '%s'!\n"), (p_pcInstanceName ? : "-")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] setServiceName: FAILED for '%s'!\n"), (p_pcInstanceName ?: "-")); + }); return bResult; } @@ -323,20 +307,19 @@ bool MDNSResponder::setServiceName(const MDNSResponder::hMDNSService p_hService, */ MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - const char* p_pcValue) + const char* p_pcKey, + const char* p_pcValue) { - - hMDNSTxt hTxt = 0; + hMDNSTxt hTxt = 0; stcMDNSService* pService = _findService(p_hService); if (pService) { hTxt = (hMDNSTxt)_addServiceTxt(pService, p_pcKey, p_pcValue, false); } DEBUG_EX_ERR(if (!hTxt) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] addServiceTxt: FAILED for '%s=%s'!\n"), (p_pcKey ? : "-"), (p_pcValue ? : "-")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] addServiceTxt: FAILED for '%s=%s'!\n"), (p_pcKey ?: "-"), (p_pcValue ?: "-")); + }); return hTxt; } @@ -346,10 +329,11 @@ MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSS Formats: http://www.cplusplus.com/reference/cstdio/printf/ */ MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - uint32_t p_u32Value) + const char* p_pcKey, + uint32_t p_u32Value) { - char acBuffer[32]; *acBuffer = 0; + char acBuffer[32]; + *acBuffer = 0; sprintf(acBuffer, "%u", p_u32Value); return addServiceTxt(p_hService, p_pcKey, acBuffer); @@ -359,10 +343,11 @@ MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSS MDNSResponder::addServiceTxt (uint16_t) */ MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - uint16_t p_u16Value) + const char* p_pcKey, + uint16_t p_u16Value) { - char acBuffer[16]; *acBuffer = 0; + char acBuffer[16]; + *acBuffer = 0; sprintf(acBuffer, "%hu", p_u16Value); return addServiceTxt(p_hService, p_pcKey, acBuffer); @@ -372,10 +357,11 @@ MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSS MDNSResponder::addServiceTxt (uint8_t) */ MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - uint8_t p_u8Value) + const char* p_pcKey, + uint8_t p_u8Value) { - char acBuffer[8]; *acBuffer = 0; + char acBuffer[8]; + *acBuffer = 0; sprintf(acBuffer, "%hhu", p_u8Value); return addServiceTxt(p_hService, p_pcKey, acBuffer); @@ -385,10 +371,11 @@ MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSS MDNSResponder::addServiceTxt (int32_t) */ MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - int32_t p_i32Value) + const char* p_pcKey, + int32_t p_i32Value) { - char acBuffer[32]; *acBuffer = 0; + char acBuffer[32]; + *acBuffer = 0; sprintf(acBuffer, "%i", p_i32Value); return addServiceTxt(p_hService, p_pcKey, acBuffer); @@ -398,10 +385,11 @@ MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSS MDNSResponder::addServiceTxt (int16_t) */ MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - int16_t p_i16Value) + const char* p_pcKey, + int16_t p_i16Value) { - char acBuffer[16]; *acBuffer = 0; + char acBuffer[16]; + *acBuffer = 0; sprintf(acBuffer, "%hi", p_i16Value); return addServiceTxt(p_hService, p_pcKey, acBuffer); @@ -411,10 +399,11 @@ MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSS MDNSResponder::addServiceTxt (int8_t) */ MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - int8_t p_i8Value) + const char* p_pcKey, + int8_t p_i8Value) { - char acBuffer[8]; *acBuffer = 0; + char acBuffer[8]; + *acBuffer = 0; sprintf(acBuffer, "%hhi", p_i8Value); return addServiceTxt(p_hService, p_pcKey, acBuffer); @@ -428,22 +417,21 @@ MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSS bool MDNSResponder::removeServiceTxt(const MDNSResponder::hMDNSService p_hService, const MDNSResponder::hMDNSTxt p_hTxt) { - - bool bResult = false; + bool bResult = false; stcMDNSService* pService = _findService(p_hService); if (pService) { - stcMDNSServiceTxt* pTxt = _findServiceTxt(pService, p_hTxt); + stcMDNSServiceTxt* pTxt = _findServiceTxt(pService, p_hTxt); if (pTxt) { bResult = _releaseServiceTxt(pService, pTxt); } } DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] removeServiceTxt: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] removeServiceTxt: FAILED!\n")); + }); return bResult; } @@ -453,22 +441,21 @@ bool MDNSResponder::removeServiceTxt(const MDNSResponder::hMDNSService p_hServic bool MDNSResponder::removeServiceTxt(const MDNSResponder::hMDNSService p_hService, const char* p_pcKey) { - - bool bResult = false; + bool bResult = false; stcMDNSService* pService = _findService(p_hService); if (pService) { - stcMDNSServiceTxt* pTxt = _findServiceTxt(pService, p_pcKey); + stcMDNSServiceTxt* pTxt = _findServiceTxt(pService, p_pcKey); if (pTxt) { bResult = _releaseServiceTxt(pService, pTxt); } } DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] removeServiceTxt: FAILED for '%s'!\n"), (p_pcKey ? : "-")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] removeServiceTxt: FAILED for '%s'!\n"), (p_pcKey ?: "-")); + }); return bResult; } @@ -480,13 +467,12 @@ bool MDNSResponder::removeServiceTxt(const char* p_pcName, const char* p_pcProtocol, const char* p_pcKey) { + bool bResult = false; - bool bResult = false; - - stcMDNSService* pService = _findService((p_pcName ? : m_pcHostname), p_pcService, p_pcProtocol); + stcMDNSService* pService = _findService((p_pcName ?: m_pcHostname), p_pcService, p_pcProtocol); if (pService) { - stcMDNSServiceTxt* pTxt = _findServiceTxt(pService, p_pcKey); + stcMDNSServiceTxt* pTxt = _findServiceTxt(pService, p_pcKey); if (pTxt) { bResult = _releaseServiceTxt(pService, pTxt); @@ -503,7 +489,6 @@ bool MDNSResponder::addServiceTxt(const char* p_pcService, const char* p_pcKey, const char* p_pcValue) { - return (0 != _addServiceTxt(_findService(m_pcHostname, p_pcService, p_pcProtocol), p_pcKey, p_pcValue, false)); } @@ -515,7 +500,6 @@ bool MDNSResponder::addServiceTxt(const String& p_strService, const String& p_strKey, const String& p_strValue) { - return (0 != _addServiceTxt(_findService(m_pcHostname, p_strService.c_str(), p_strProtocol.c_str()), p_strKey.c_str(), p_strValue.c_str(), false)); } @@ -528,7 +512,6 @@ bool MDNSResponder::addServiceTxt(const String& p_strService, */ bool MDNSResponder::setDynamicServiceTxtCallback(MDNSResponder::MDNSDynamicServiceTxtCallbackFunc p_fnCallback) { - m_fnServiceTxtCallback = p_fnCallback; return true; @@ -542,10 +525,9 @@ bool MDNSResponder::setDynamicServiceTxtCallback(MDNSResponder::MDNSDynamicServi */ bool MDNSResponder::setDynamicServiceTxtCallback(MDNSResponder::hMDNSService p_hService, - MDNSResponder::MDNSDynamicServiceTxtCallbackFunc p_fnCallback) + MDNSResponder::MDNSDynamicServiceTxtCallbackFunc p_fnCallback) { - - bool bResult = false; + bool bResult = false; stcMDNSService* pService = _findService(p_hService); if (pService) @@ -555,9 +537,9 @@ bool MDNSResponder::setDynamicServiceTxtCallback(MDNSResponder::hMDNSService p_h bResult = true; } DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] setDynamicServiceTxtCallback: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] setDynamicServiceTxtCallback: FAILED!\n")); + }); return bResult; } @@ -565,12 +547,12 @@ bool MDNSResponder::setDynamicServiceTxtCallback(MDNSResponder::hMDNSService p_h MDNSResponder::addDynamicServiceTxt */ MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - const char* p_pcValue) + const char* p_pcKey, + const char* p_pcValue) { //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] addDynamicServiceTxt (%s=%s)\n"), p_pcKey, p_pcValue);); - hMDNSTxt hTxt = 0; + hMDNSTxt hTxt = 0; stcMDNSService* pService = _findService(p_hService); if (pService) @@ -578,9 +560,9 @@ MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNS hTxt = _addServiceTxt(pService, p_pcKey, p_pcValue, true); } DEBUG_EX_ERR(if (!hTxt) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] addDynamicServiceTxt: FAILED for '%s=%s'!\n"), (p_pcKey ? : "-"), (p_pcValue ? : "-")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] addDynamicServiceTxt: FAILED for '%s=%s'!\n"), (p_pcKey ?: "-"), (p_pcValue ?: "-")); + }); return hTxt; } @@ -588,11 +570,11 @@ MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNS MDNSResponder::addDynamicServiceTxt (uint32_t) */ MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - uint32_t p_u32Value) + const char* p_pcKey, + uint32_t p_u32Value) { - - char acBuffer[32]; *acBuffer = 0; + char acBuffer[32]; + *acBuffer = 0; sprintf(acBuffer, "%u", p_u32Value); return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); @@ -602,11 +584,11 @@ MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNS MDNSResponder::addDynamicServiceTxt (uint16_t) */ MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - uint16_t p_u16Value) + const char* p_pcKey, + uint16_t p_u16Value) { - - char acBuffer[16]; *acBuffer = 0; + char acBuffer[16]; + *acBuffer = 0; sprintf(acBuffer, "%hu", p_u16Value); return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); @@ -616,11 +598,11 @@ MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNS MDNSResponder::addDynamicServiceTxt (uint8_t) */ MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - uint8_t p_u8Value) + const char* p_pcKey, + uint8_t p_u8Value) { - - char acBuffer[8]; *acBuffer = 0; + char acBuffer[8]; + *acBuffer = 0; sprintf(acBuffer, "%hhu", p_u8Value); return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); @@ -630,11 +612,11 @@ MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNS MDNSResponder::addDynamicServiceTxt (int32_t) */ MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - int32_t p_i32Value) + const char* p_pcKey, + int32_t p_i32Value) { - - char acBuffer[32]; *acBuffer = 0; + char acBuffer[32]; + *acBuffer = 0; sprintf(acBuffer, "%i", p_i32Value); return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); @@ -644,11 +626,11 @@ MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNS MDNSResponder::addDynamicServiceTxt (int16_t) */ MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - int16_t p_i16Value) + const char* p_pcKey, + int16_t p_i16Value) { - - char acBuffer[16]; *acBuffer = 0; + char acBuffer[16]; + *acBuffer = 0; sprintf(acBuffer, "%hi", p_i16Value); return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); @@ -658,17 +640,16 @@ MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNS MDNSResponder::addDynamicServiceTxt (int8_t) */ MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - int8_t p_i8Value) + const char* p_pcKey, + int8_t p_i8Value) { - - char acBuffer[8]; *acBuffer = 0; + char acBuffer[8]; + *acBuffer = 0; sprintf(acBuffer, "%hhi", p_i8Value); return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); } - /** STATIC SERVICE QUERY (LEGACY) */ @@ -695,19 +676,18 @@ uint32_t MDNSResponder::queryService(const char* p_pcService, DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] queryService '%s.%s'\n"), p_pcService, p_pcProtocol);); - uint32_t u32Result = 0; + uint32_t u32Result = 0; - stcMDNSServiceQuery* pServiceQuery = 0; + stcMDNSServiceQuery* pServiceQuery = 0; if ((p_pcService) && - (os_strlen(p_pcService)) && - (p_pcProtocol) && - (os_strlen(p_pcProtocol)) && - (p_u16Timeout) && - (_removeLegacyServiceQuery()) && - ((pServiceQuery = _allocServiceQuery())) && - (_buildDomainForService(p_pcService, p_pcProtocol, pServiceQuery->m_ServiceTypeDomain))) + (os_strlen(p_pcService)) && + (p_pcProtocol) && + (os_strlen(p_pcProtocol)) && + (p_u16Timeout) && + (_removeLegacyServiceQuery()) && + ((pServiceQuery = _allocServiceQuery())) && + (_buildDomainForService(p_pcService, p_pcProtocol, pServiceQuery->m_ServiceTypeDomain))) { - pServiceQuery->m_bLegacyQuery = true; if (_sendMDNSServiceQuery(*pServiceQuery)) @@ -720,7 +700,7 @@ uint32_t MDNSResponder::queryService(const char* p_pcService, pServiceQuery->m_bAwaitingAnswers = false; u32Result = pServiceQuery->answerCount(); } - else // FAILED to send query + else // FAILED to send query { _removeServiceQuery(pServiceQuery); } @@ -740,7 +720,6 @@ uint32_t MDNSResponder::queryService(const char* p_pcService, */ bool MDNSResponder::removeQuery(void) { - return _removeLegacyServiceQuery(); } @@ -750,7 +729,6 @@ bool MDNSResponder::removeQuery(void) uint32_t MDNSResponder::queryService(const String& p_strService, const String& p_strProtocol) { - return queryService(p_strService.c_str(), p_strProtocol.c_str()); } @@ -759,16 +737,14 @@ uint32_t MDNSResponder::queryService(const String& p_strService, */ const char* MDNSResponder::answerHostname(const uint32_t p_u32AnswerIndex) { - - stcMDNSServiceQuery* pServiceQuery = _findLegacyServiceQuery(); + stcMDNSServiceQuery* pServiceQuery = _findLegacyServiceQuery(); stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); if ((pSQAnswer) && - (pSQAnswer->m_HostDomain.m_u16NameLength) && - (!pSQAnswer->m_pcHostDomain)) + (pSQAnswer->m_HostDomain.m_u16NameLength) && + (!pSQAnswer->m_pcHostDomain)) { - - char* pcHostDomain = pSQAnswer->allocHostDomain(pSQAnswer->m_HostDomain.c_strLength()); + char* pcHostDomain = pSQAnswer->allocHostDomain(pSQAnswer->m_HostDomain.c_strLength()); if (pcHostDomain) { pSQAnswer->m_HostDomain.c_str(pcHostDomain); @@ -783,10 +759,9 @@ const char* MDNSResponder::answerHostname(const uint32_t p_u32AnswerIndex) */ IPAddress MDNSResponder::answerIP(const uint32_t p_u32AnswerIndex) { - - const stcMDNSServiceQuery* pServiceQuery = _findLegacyServiceQuery(); - const stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - const stcMDNSServiceQuery::stcAnswer::stcIP4Address* pIP4Address = (((pSQAnswer) && (pSQAnswer->m_pIP4Addresses)) ? pSQAnswer->IP4AddressAtIndex(0) : 0); + const stcMDNSServiceQuery* pServiceQuery = _findLegacyServiceQuery(); + const stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); + const stcMDNSServiceQuery::stcAnswer::stcIP4Address* pIP4Address = (((pSQAnswer) && (pSQAnswer->m_pIP4Addresses)) ? pSQAnswer->IP4AddressAtIndex(0) : 0); return (pIP4Address ? pIP4Address->m_IPAddress : IPAddress()); } #endif @@ -797,10 +772,9 @@ IPAddress MDNSResponder::answerIP(const uint32_t p_u32AnswerIndex) */ IPAddress MDNSResponder::answerIP6(const uint32_t p_u32AnswerIndex) { - - const stcMDNSServiceQuery* pServiceQuery = _findLegacyServiceQuery(); - const stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - const stcMDNSServiceQuery::stcAnswer::stcIP6Address* pIP6Address = (((pSQAnswer) && (pSQAnswer->m_pIP6Addresses)) ? pSQAnswer->IP6AddressAtIndex(0) : 0); + const stcMDNSServiceQuery* pServiceQuery = _findLegacyServiceQuery(); + const stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); + const stcMDNSServiceQuery::stcAnswer::stcIP6Address* pIP6Address = (((pSQAnswer) && (pSQAnswer->m_pIP6Addresses)) ? pSQAnswer->IP6AddressAtIndex(0) : 0); return (pIP6Address ? pIP6Address->m_IPAddress : IP6Address()); } #endif @@ -810,9 +784,8 @@ IPAddress MDNSResponder::answerIP6(const uint32_t p_u32AnswerIndex) */ uint16_t MDNSResponder::answerPort(const uint32_t p_u32AnswerIndex) { - - const stcMDNSServiceQuery* pServiceQuery = _findLegacyServiceQuery(); - const stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); + const stcMDNSServiceQuery* pServiceQuery = _findLegacyServiceQuery(); + const stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); return (pSQAnswer ? pSQAnswer->m_u16Port : 0); } @@ -821,7 +794,6 @@ uint16_t MDNSResponder::answerPort(const uint32_t p_u32AnswerIndex) */ String MDNSResponder::hostname(const uint32_t p_u32AnswerIndex) { - return String(answerHostname(p_u32AnswerIndex)); } @@ -830,7 +802,6 @@ String MDNSResponder::hostname(const uint32_t p_u32AnswerIndex) */ IPAddress MDNSResponder::IP(const uint32_t p_u32AnswerIndex) { - return answerIP(p_u32AnswerIndex); } @@ -839,11 +810,9 @@ IPAddress MDNSResponder::IP(const uint32_t p_u32AnswerIndex) */ uint16_t MDNSResponder::port(const uint32_t p_u32AnswerIndex) { - return answerPort(p_u32AnswerIndex); } - /** DYNAMIC SERVICE QUERY */ @@ -862,21 +831,20 @@ uint16_t MDNSResponder::port(const uint32_t p_u32AnswerIndex) */ MDNSResponder::hMDNSServiceQuery MDNSResponder::installServiceQuery(const char* p_pcService, - const char* p_pcProtocol, - MDNSResponder::MDNSServiceQueryCallbackFunc p_fnCallback) + const char* p_pcProtocol, + MDNSResponder::MDNSServiceQueryCallbackFunc p_fnCallback) { - hMDNSServiceQuery hResult = 0; + hMDNSServiceQuery hResult = 0; - stcMDNSServiceQuery* pServiceQuery = 0; + stcMDNSServiceQuery* pServiceQuery = 0; if ((p_pcService) && - (os_strlen(p_pcService)) && - (p_pcProtocol) && - (os_strlen(p_pcProtocol)) && - (p_fnCallback) && - ((pServiceQuery = _allocServiceQuery())) && - (_buildDomainForService(p_pcService, p_pcProtocol, pServiceQuery->m_ServiceTypeDomain))) + (os_strlen(p_pcService)) && + (p_pcProtocol) && + (os_strlen(p_pcProtocol)) && + (p_fnCallback) && + ((pServiceQuery = _allocServiceQuery())) && + (_buildDomainForService(p_pcService, p_pcProtocol, pServiceQuery->m_ServiceTypeDomain))) { - pServiceQuery->m_fnCallback = p_fnCallback; pServiceQuery->m_bLegacyQuery = false; @@ -892,11 +860,11 @@ MDNSResponder::hMDNSServiceQuery MDNSResponder::installServiceQuery(const char* _removeServiceQuery(pServiceQuery); } } - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] installServiceQuery: %s for '%s.%s'!\n\n"), (hResult ? "Succeeded" : "FAILED"), (p_pcService ? : "-"), (p_pcProtocol ? : "-"));); + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] installServiceQuery: %s for '%s.%s'!\n\n"), (hResult ? "Succeeded" : "FAILED"), (p_pcService ?: "-"), (p_pcProtocol ?: "-"));); DEBUG_EX_ERR(if (!hResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] installServiceQuery: FAILED for '%s.%s'!\n\n"), (p_pcService ? : "-"), (p_pcProtocol ? : "-")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] installServiceQuery: FAILED for '%s.%s'!\n\n"), (p_pcService ?: "-"), (p_pcProtocol ?: "-")); + }); return hResult; } @@ -908,14 +876,13 @@ MDNSResponder::hMDNSServiceQuery MDNSResponder::installServiceQuery(const char* */ bool MDNSResponder::removeServiceQuery(MDNSResponder::hMDNSServiceQuery p_hServiceQuery) { - - stcMDNSServiceQuery* pServiceQuery = 0; - bool bResult = (((pServiceQuery = _findServiceQuery(p_hServiceQuery))) && - (_removeServiceQuery(pServiceQuery))); + stcMDNSServiceQuery* pServiceQuery = 0; + bool bResult = (((pServiceQuery = _findServiceQuery(p_hServiceQuery))) && + (_removeServiceQuery(pServiceQuery))); DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] removeServiceQuery: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] removeServiceQuery: FAILED!\n")); + }); return bResult; } @@ -924,12 +891,11 @@ bool MDNSResponder::removeServiceQuery(MDNSResponder::hMDNSServiceQuery p_hServi */ uint32_t MDNSResponder::answerCount(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery) { - - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); return (pServiceQuery ? pServiceQuery->answerCount() : 0); } -std::vector MDNSResponder::answerInfo(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery) +std::vector MDNSResponder::answerInfo(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery) { std::vector tempVector; for (uint32_t i = 0; i < answerCount(p_hServiceQuery); i++) @@ -947,17 +913,15 @@ std::vector MDNSResponder::answerInfo(const MDN */ const char* MDNSResponder::answerServiceDomain(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) + const uint32_t p_u32AnswerIndex) { - - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); // Fill m_pcServiceDomain (if not already done) if ((pSQAnswer) && - (pSQAnswer->m_ServiceDomain.m_u16NameLength) && - (!pSQAnswer->m_pcServiceDomain)) + (pSQAnswer->m_ServiceDomain.m_u16NameLength) && + (!pSQAnswer->m_pcServiceDomain)) { - pSQAnswer->m_pcServiceDomain = pSQAnswer->allocServiceDomain(pSQAnswer->m_ServiceDomain.c_strLength()); if (pSQAnswer->m_pcServiceDomain) { @@ -973,8 +937,7 @@ const char* MDNSResponder::answerServiceDomain(const MDNSResponder::hMDNSService bool MDNSResponder::hasAnswerHostDomain(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, const uint32_t p_u32AnswerIndex) { - - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); return ((pSQAnswer) && (pSQAnswer->m_u32ContentFlags & ServiceQueryAnswerType_HostDomainAndPort)); @@ -988,17 +951,15 @@ bool MDNSResponder::hasAnswerHostDomain(const MDNSResponder::hMDNSServiceQuery p */ const char* MDNSResponder::answerHostDomain(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) + const uint32_t p_u32AnswerIndex) { - - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); // Fill m_pcHostDomain (if not already done) if ((pSQAnswer) && - (pSQAnswer->m_HostDomain.m_u16NameLength) && - (!pSQAnswer->m_pcHostDomain)) + (pSQAnswer->m_HostDomain.m_u16NameLength) && + (!pSQAnswer->m_pcHostDomain)) { - pSQAnswer->m_pcHostDomain = pSQAnswer->allocHostDomain(pSQAnswer->m_HostDomain.c_strLength()); if (pSQAnswer->m_pcHostDomain) { @@ -1015,8 +976,7 @@ const char* MDNSResponder::answerHostDomain(const MDNSResponder::hMDNSServiceQue bool MDNSResponder::hasAnswerIP4Address(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, const uint32_t p_u32AnswerIndex) { - - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); return ((pSQAnswer) && (pSQAnswer->m_u32ContentFlags & ServiceQueryAnswerType_IP4Address)); @@ -1026,10 +986,9 @@ bool MDNSResponder::hasAnswerIP4Address(const MDNSResponder::hMDNSServiceQuery p MDNSResponder::answerIP4AddressCount */ uint32_t MDNSResponder::answerIP4AddressCount(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) + const uint32_t p_u32AnswerIndex) { - - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); return (pSQAnswer ? pSQAnswer->IP4AddressCount() : 0); } @@ -1038,13 +997,12 @@ uint32_t MDNSResponder::answerIP4AddressCount(const MDNSResponder::hMDNSServiceQ MDNSResponder::answerIP4Address */ IPAddress MDNSResponder::answerIP4Address(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex, - const uint32_t p_u32AddressIndex) + const uint32_t p_u32AnswerIndex, + const uint32_t p_u32AddressIndex) { - - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); - stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - stcMDNSServiceQuery::stcAnswer::stcIP4Address* pIP4Address = (pSQAnswer ? pSQAnswer->IP4AddressAtIndex(p_u32AddressIndex) : 0); + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); + stcMDNSServiceQuery::stcAnswer::stcIP4Address* pIP4Address = (pSQAnswer ? pSQAnswer->IP4AddressAtIndex(p_u32AddressIndex) : 0); return (pIP4Address ? pIP4Address->m_IPAddress : IPAddress()); } #endif @@ -1056,8 +1014,7 @@ IPAddress MDNSResponder::answerIP4Address(const MDNSResponder::hMDNSServiceQuery bool MDNSResponder::hasAnswerIP6Address(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, const uint32_t p_u32AnswerIndex) { - - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); return ((pSQAnswer) && (pSQAnswer->m_u32ContentFlags & ServiceQueryAnswerType_HostIP6Address)); @@ -1067,10 +1024,9 @@ bool MDNSResponder::hasAnswerIP6Address(const MDNSResponder::hMDNSServiceQuery p MDNSResponder::answerIP6AddressCount */ uint32_t MDNSResponder::answerIP6AddressCount(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) + const uint32_t p_u32AnswerIndex) { - - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); return (pSQAnswer ? pSQAnswer->IP6AddressCount() : 0); } @@ -1079,13 +1035,12 @@ uint32_t MDNSResponder::answerIP6AddressCount(const MDNSResponder::hMDNSServiceQ MDNSResponder::answerIP6Address */ IPAddress MDNSResponder::answerIP6Address(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex, - const uint32_t p_u32AddressIndex) + const uint32_t p_u32AnswerIndex, + const uint32_t p_u32AddressIndex) { - - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); - stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - stcMDNSServiceQuery::stcAnswer::stcIP6Address* pIP6Address = (pSQAnswer ? pSQAnswer->IP6AddressAtIndex(p_u32AddressIndex) : 0); + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); + stcMDNSServiceQuery::stcAnswer::stcIP6Address* pIP6Address = (pSQAnswer ? pSQAnswer->IP6AddressAtIndex(p_u32AddressIndex) : 0); return (pIP6Address ? pIP6Address->m_IPAddress : IPAddress()); } #endif @@ -1096,8 +1051,7 @@ IPAddress MDNSResponder::answerIP6Address(const MDNSResponder::hMDNSServiceQuery bool MDNSResponder::hasAnswerPort(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, const uint32_t p_u32AnswerIndex) { - - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); return ((pSQAnswer) && (pSQAnswer->m_u32ContentFlags & ServiceQueryAnswerType_HostDomainAndPort)); @@ -1109,8 +1063,7 @@ bool MDNSResponder::hasAnswerPort(const MDNSResponder::hMDNSServiceQuery p_hServ uint16_t MDNSResponder::answerPort(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, const uint32_t p_u32AnswerIndex) { - - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); return (pSQAnswer ? pSQAnswer->m_u16Port : 0); } @@ -1121,8 +1074,7 @@ uint16_t MDNSResponder::answerPort(const MDNSResponder::hMDNSServiceQuery p_hSer bool MDNSResponder::hasAnswerTxts(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, const uint32_t p_u32AnswerIndex) { - - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); return ((pSQAnswer) && (pSQAnswer->m_u32ContentFlags & ServiceQueryAnswerType_Txts)); @@ -1138,15 +1090,13 @@ bool MDNSResponder::hasAnswerTxts(const MDNSResponder::hMDNSServiceQuery p_hServ const char* MDNSResponder::answerTxts(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, const uint32_t p_u32AnswerIndex) { - - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); // Fill m_pcTxts (if not already done) if ((pSQAnswer) && - (pSQAnswer->m_Txts.m_pTxts) && - (!pSQAnswer->m_pcTxts)) + (pSQAnswer->m_Txts.m_pTxts) && + (!pSQAnswer->m_pcTxts)) { - pSQAnswer->m_pcTxts = pSQAnswer->allocTxts(pSQAnswer->m_Txts.c_strLength()); if (pSQAnswer->m_pcTxts) { @@ -1172,7 +1122,6 @@ const char* MDNSResponder::answerTxts(const MDNSResponder::hMDNSServiceQuery p_h */ bool MDNSResponder::setHostProbeResultCallback(MDNSResponder::MDNSHostProbeFn p_fnCallback) { - m_HostProbeInformation.m_fnHostProbeResultCallback = p_fnCallback; return true; @@ -1182,9 +1131,7 @@ bool MDNSResponder::setHostProbeResultCallback(MDNSHostProbeFn1 pfn) { using namespace std::placeholders; return setHostProbeResultCallback([this, pfn](const char* p_pcDomainName, bool p_bProbeResult) - { - pfn(*this, p_pcDomainName, p_bProbeResult); - }); + { pfn(*this, p_pcDomainName, p_bProbeResult); }); } /* @@ -1197,10 +1144,9 @@ bool MDNSResponder::setHostProbeResultCallback(MDNSHostProbeFn1 pfn) */ bool MDNSResponder::setServiceProbeResultCallback(const MDNSResponder::hMDNSService p_hService, - MDNSResponder::MDNSServiceProbeFn p_fnCallback) + MDNSResponder::MDNSServiceProbeFn p_fnCallback) { - - bool bResult = false; + bool bResult = false; stcMDNSService* pService = _findService(p_hService); if (pService) @@ -1213,16 +1159,13 @@ bool MDNSResponder::setServiceProbeResultCallback(const MDNSResponder::hMDNSServ } bool MDNSResponder::setServiceProbeResultCallback(const MDNSResponder::hMDNSService p_hService, - MDNSResponder::MDNSServiceProbeFn1 p_fnCallback) + MDNSResponder::MDNSServiceProbeFn1 p_fnCallback) { using namespace std::placeholders; return setServiceProbeResultCallback(p_hService, [this, p_fnCallback](const char* p_pcServiceName, const hMDNSService p_hMDNSService, bool p_bProbeResult) - { - p_fnCallback(*this, p_pcServiceName, p_hMDNSService, p_bProbeResult); - }); + { p_fnCallback(*this, p_pcServiceName, p_hMDNSService, p_bProbeResult); }); } - /* MISC */ @@ -1236,7 +1179,6 @@ bool MDNSResponder::setServiceProbeResultCallback(const MDNSResponder::hMDNSServ */ bool MDNSResponder::notifyAPChange(void) { - return _restart(); } @@ -1258,7 +1200,6 @@ bool MDNSResponder::update(void) */ bool MDNSResponder::announce(void) { - return (_announce(true, true)); } @@ -1269,18 +1210,16 @@ bool MDNSResponder::announce(void) */ MDNSResponder::hMDNSService MDNSResponder::enableArduino(uint16_t p_u16Port, - bool p_bAuthUpload /*= false*/) + bool p_bAuthUpload /*= false*/) { - - hMDNSService hService = addService(0, "arduino", "tcp", p_u16Port); + hMDNSService hService = addService(0, "arduino", "tcp", p_u16Port); if (hService) { if ((!addServiceTxt(hService, "tcp_check", "no")) || - (!addServiceTxt(hService, "ssh_upload", "no")) || - (!addServiceTxt(hService, "board", STRINGIZE_VALUE_OF(ARDUINO_BOARD))) || - (!addServiceTxt(hService, "auth_upload", (p_bAuthUpload) ? "yes" : "no"))) + (!addServiceTxt(hService, "ssh_upload", "no")) || + (!addServiceTxt(hService, "board", STRINGIZE_VALUE_OF(ARDUINO_BOARD))) || + (!addServiceTxt(hService, "auth_upload", (p_bAuthUpload) ? "yes" : "no"))) { - removeService(hService); hService = 0; } @@ -1299,7 +1238,7 @@ MDNSResponder::hMDNSService MDNSResponder::enableArduino(uint16_t p_u16Port, */ bool MDNSResponder::_joinMulticastGroups(void) { - bool bResult = false; + bool bResult = false; // Join multicast group(s) for (netif* pNetIf = netif_list; pNetIf; pNetIf = pNetIf->next) @@ -1307,7 +1246,7 @@ bool MDNSResponder::_joinMulticastGroups(void) if (netif_is_up(pNetIf)) { #ifdef MDNS_IP4_SUPPORT - ip_addr_t multicast_addr_V4 = DNS_MQUERY_IPV4_GROUP_INIT; + ip_addr_t multicast_addr_V4 = DNS_MQUERY_IPV4_GROUP_INIT; if (!(pNetIf->flags & NETIF_FLAG_IGMP)) { DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _createHost: Setting flag: flags & NETIF_FLAG_IGMP\n"));); @@ -1331,11 +1270,11 @@ bool MDNSResponder::_joinMulticastGroups(void) #endif #ifdef MDNS_IPV6_SUPPORT - ip_addr_t multicast_addr_V6 = DNS_MQUERY_IPV6_GROUP_INIT; + ip_addr_t multicast_addr_V6 = DNS_MQUERY_IPV6_GROUP_INIT; bResult = ((bResult) && (ERR_OK == mld6_joingroup_netif(pNetIf, ip_2_ip6(&multicast_addr_V6)))); DEBUG_EX_ERR_IF(!bResult, DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _createHost: mld6_joingroup_netif (" NETIFID_STR ") FAILED!\n"), - NETIFID_VAL(pNetIf))); + NETIFID_VAL(pNetIf))); #endif } } @@ -1347,7 +1286,7 @@ bool MDNSResponder::_joinMulticastGroups(void) */ bool MDNSResponder::_leaveMulticastGroups() { - bool bResult = false; + bool bResult = false; for (netif* pNetIf = netif_list; pNetIf; pNetIf = pNetIf->next) { @@ -1357,15 +1296,15 @@ bool MDNSResponder::_leaveMulticastGroups() // Leave multicast group(s) #ifdef MDNS_IP4_SUPPORT - ip_addr_t multicast_addr_V4 = DNS_MQUERY_IPV4_GROUP_INIT; + ip_addr_t multicast_addr_V4 = DNS_MQUERY_IPV4_GROUP_INIT; if (ERR_OK != igmp_leavegroup_netif(pNetIf, ip_2_ip4(&multicast_addr_V4))) { DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("\n"));); } #endif #ifdef MDNS_IPV6_SUPPORT - ip_addr_t multicast_addr_V6 = DNS_MQUERY_IPV6_GROUP_INIT; - if (ERR_OK != mld6_leavegroup_netif(pNetIf, ip_2_ip6(&multicast_addr_V6)/*&(multicast_addr_V6.u_addr.ip6)*/)) + ip_addr_t multicast_addr_V6 = DNS_MQUERY_IPV6_GROUP_INIT; + if (ERR_OK != mld6_leavegroup_netif(pNetIf, ip_2_ip6(&multicast_addr_V6) /*&(multicast_addr_V6.u_addr.ip6)*/)) { DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("\n"));); } @@ -1375,10 +1314,6 @@ bool MDNSResponder::_leaveMulticastGroups() return bResult; } +} //namespace MDNSImplementation - -} //namespace MDNSImplementation - -} //namespace esp8266 - - +} //namespace esp8266 diff --git a/libraries/ESP8266mDNS/src/LEAmDNS.h b/libraries/ESP8266mDNS/src/LEAmDNS.h index 670de02ed0..7d7b8b7287 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS.h +++ b/libraries/ESP8266mDNS/src/LEAmDNS.h @@ -102,28 +102,24 @@ #ifndef MDNS_H #define MDNS_H -#include // for UdpContext.h +#include +#include // for UdpContext.h +#include +#include #include "WiFiUdp.h" -#include "lwip/udp.h" #include "debug.h" #include "include/UdpContext.h" -#include -#include -#include - +#include "lwip/udp.h" #include "ESP8266WiFi.h" - namespace esp8266 { - /** LEAmDNS */ namespace MDNSImplementation { - //this should be defined at build time #ifndef ARDUINO_BOARD #define ARDUINO_BOARD "generic" @@ -135,47 +131,47 @@ namespace MDNSImplementation #endif #ifdef MDNS_IP4_SUPPORT -#define MDNS_IP4_SIZE 4 +#define MDNS_IP4_SIZE 4 #endif #ifdef MDNS_IP6_SUPPORT -#define MDNS_IP6_SIZE 16 +#define MDNS_IP6_SIZE 16 #endif /* Maximum length for all service txts for one service */ -#define MDNS_SERVICE_TXT_MAXLENGTH 1300 +#define MDNS_SERVICE_TXT_MAXLENGTH 1300 /* Maximum length for a full domain name eg. MyESP._http._tcp.local */ -#define MDNS_DOMAIN_MAXLENGTH 256 +#define MDNS_DOMAIN_MAXLENGTH 256 /* Maximum length of on label in a domain name (length info fits into 6 bits) */ -#define MDNS_DOMAIN_LABEL_MAXLENGTH 63 +#define MDNS_DOMAIN_LABEL_MAXLENGTH 63 /* Maximum length of a service name eg. http */ -#define MDNS_SERVICE_NAME_LENGTH 15 +#define MDNS_SERVICE_NAME_LENGTH 15 /* Maximum length of a service protocol name eg. tcp */ -#define MDNS_SERVICE_PROTOCOL_LENGTH 3 +#define MDNS_SERVICE_PROTOCOL_LENGTH 3 /* Default timeout for static service queries */ -#define MDNS_QUERYSERVICES_WAIT_TIME 1000 +#define MDNS_QUERYSERVICES_WAIT_TIME 1000 /* Timeout for udpContext->sendtimeout() */ -#define MDNS_UDPCONTEXT_TIMEOUT 50 +#define MDNS_UDPCONTEXT_TIMEOUT 50 /** MDNSResponder */ class MDNSResponder { -public: + public: /* INTERFACE */ MDNSResponder(void); @@ -210,7 +206,7 @@ class MDNSResponder /** hMDNSService (opaque handle to access the service) */ - typedef const void* hMDNSService; + typedef const void* hMDNSService; // Add a new service to the MDNS responder. If no name (instance name) is given (p_pcName = 0) // the current hostname is used. If the hostname is changed later, the instance names for @@ -230,7 +226,6 @@ class MDNSResponder const String& p_strProtocol, uint16_t p_u16Port); - // Change the services instance name (and restart probing). bool setServiceName(const hMDNSService p_hService, const char* p_pcInstanceName); @@ -250,7 +245,7 @@ class MDNSResponder /** hMDNSTxt (opaque handle to access the TXT items) */ - typedef void* hMDNSTxt; + typedef void* hMDNSTxt; // Add a (static) MDNS TXT item ('key' = 'value') to the service hMDNSTxt addServiceTxt(const hMDNSService p_hService, @@ -358,35 +353,35 @@ class MDNSResponder /** hMDNSServiceQuery (opaque handle to access dynamic service queries) */ - typedef const void* hMDNSServiceQuery; + typedef const void* hMDNSServiceQuery; /** enuServiceQueryAnswerType */ typedef enum _enuServiceQueryAnswerType { - ServiceQueryAnswerType_ServiceDomain = (1 << 0), // Service instance name - ServiceQueryAnswerType_HostDomainAndPort = (1 << 1), // Host domain and service port - ServiceQueryAnswerType_Txts = (1 << 2), // TXT items + ServiceQueryAnswerType_ServiceDomain = (1 << 0), // Service instance name + ServiceQueryAnswerType_HostDomainAndPort = (1 << 1), // Host domain and service port + ServiceQueryAnswerType_Txts = (1 << 2), // TXT items #ifdef MDNS_IP4_SUPPORT - ServiceQueryAnswerType_IP4Address = (1 << 3), // IP4 address + ServiceQueryAnswerType_IP4Address = (1 << 3), // IP4 address #endif #ifdef MDNS_IP6_SUPPORT - ServiceQueryAnswerType_IP6Address = (1 << 4), // IP6 address + ServiceQueryAnswerType_IP6Address = (1 << 4), // IP6 address #endif } enuServiceQueryAnswerType; enum class AnswerType : uint32_t { - Unknown = 0, - ServiceDomain = ServiceQueryAnswerType_ServiceDomain, - HostDomainAndPort = ServiceQueryAnswerType_HostDomainAndPort, - Txt = ServiceQueryAnswerType_Txts, + Unknown = 0, + ServiceDomain = ServiceQueryAnswerType_ServiceDomain, + HostDomainAndPort = ServiceQueryAnswerType_HostDomainAndPort, + Txt = ServiceQueryAnswerType_Txts, #ifdef MDNS_IP4_SUPPORT - IP4Address = ServiceQueryAnswerType_IP4Address, + IP4Address = ServiceQueryAnswerType_IP4Address, #endif #ifdef MDNS_IP6_SUPPORT - IP6Address = ServiceQueryAnswerType_IP6Address, + IP6Address = ServiceQueryAnswerType_IP6Address, #endif }; @@ -394,11 +389,12 @@ class MDNSResponder MDNSServiceQueryCallbackFn Callback function for received answers for dynamic service queries */ - struct MDNSServiceInfo; // forward declaration + struct MDNSServiceInfo; // forward declaration typedef std::function MDNSServiceQueryCallbackFunc; + AnswerType answerType, // flag for the updated answer item + bool p_bSetContent // true: Answer component set, false: component deleted + )> + MDNSServiceQueryCallbackFunc; // Install a dynamic service query. For every received answer (part) the given callback // function is called. The query will be updated every time, the TTL for an answer @@ -459,20 +455,24 @@ class MDNSResponder Callback function for (host and service domain) probe results */ typedef std::function MDNSHostProbeFn; + bool p_bProbeResult)> + MDNSHostProbeFn; typedef std::function MDNSHostProbeFn1; + bool p_bProbeResult)> + MDNSHostProbeFn1; typedef std::function MDNSServiceProbeFn; + bool p_bProbeResult)> + MDNSServiceProbeFn; typedef std::function MDNSServiceProbeFn1; + bool p_bProbeResult)> + MDNSServiceProbeFn1; // Set a global callback function for host and service probe results // The callback function is called, when the probing for the host domain @@ -509,7 +509,7 @@ class MDNSResponder /** STRUCTS **/ -public: + public: /** MDNSServiceInfo, used in application callbacks */ @@ -518,22 +518,23 @@ class MDNSResponder MDNSServiceInfo(MDNSResponder& p_pM, MDNSResponder::hMDNSServiceQuery p_hS, uint32_t p_u32A) : p_pMDNSResponder(p_pM), p_hServiceQuery(p_hS), - p_u32AnswerIndex(p_u32A) - {}; + p_u32AnswerIndex(p_u32A){}; struct CompareKey { - bool operator()(char const *a, char const *b) const + bool operator()(char const* a, char const* b) const { return strcmp(a, b) < 0; } }; using KeyValueMap = std::map; - protected: + + protected: MDNSResponder& p_pMDNSResponder; MDNSResponder::hMDNSServiceQuery p_hServiceQuery; uint32_t p_u32AnswerIndex; KeyValueMap keyValueMap; - public: + + public: const char* serviceDomain() { return p_pMDNSResponder.answerServiceDomain(p_hServiceQuery, p_u32AnswerIndex); @@ -544,8 +545,7 @@ class MDNSResponder } const char* hostDomain() { - return (hostDomainAvailable()) ? - p_pMDNSResponder.answerHostDomain(p_hServiceQuery, p_u32AnswerIndex) : nullptr; + return (hostDomainAvailable()) ? p_pMDNSResponder.answerHostDomain(p_hServiceQuery, p_u32AnswerIndex) : nullptr; }; bool hostPortAvailable() { @@ -553,8 +553,7 @@ class MDNSResponder } uint16_t hostPort() { - return (hostPortAvailable()) ? - p_pMDNSResponder.answerPort(p_hServiceQuery, p_u32AnswerIndex) : 0; + return (hostPortAvailable()) ? p_pMDNSResponder.answerPort(p_hServiceQuery, p_u32AnswerIndex) : 0; }; bool IP4AddressAvailable() { @@ -579,8 +578,7 @@ class MDNSResponder } const char* strKeyValue() { - return (txtAvailable()) ? - p_pMDNSResponder.answerTxts(p_hServiceQuery, p_u32AnswerIndex) : nullptr; + return (txtAvailable()) ? p_pMDNSResponder.answerTxts(p_hServiceQuery, p_u32AnswerIndex) : nullptr; }; const KeyValueMap& keyValues() { @@ -600,7 +598,7 @@ class MDNSResponder for (stcMDNSServiceTxt* pTxt = p_pMDNSResponder._answerKeyValue(p_hServiceQuery, p_u32AnswerIndex); pTxt; pTxt = pTxt->m_pNext) { if ((key) && - (0 == strcmp(pTxt->m_pcKey, key))) + (0 == strcmp(pTxt->m_pcKey, key))) { result = pTxt->m_pcValue; break; @@ -609,17 +607,17 @@ class MDNSResponder return result; } }; -protected: + protected: /** stcMDNSServiceTxt */ struct stcMDNSServiceTxt { stcMDNSServiceTxt* m_pNext; - char* m_pcKey; - char* m_pcValue; - bool m_bTemp; + char* m_pcKey; + char* m_pcValue; + bool m_bTemp; stcMDNSServiceTxt(const char* p_pcKey = 0, const char* p_pcValue = 0, @@ -656,7 +654,7 @@ class MDNSResponder */ struct stcMDNSServiceTxts { - stcMDNSServiceTxt* m_pTxts; + stcMDNSServiceTxt* m_pTxts; stcMDNSServiceTxts(void); stcMDNSServiceTxts(const stcMDNSServiceTxts& p_Other); @@ -694,15 +692,15 @@ class MDNSResponder typedef enum _enuContentFlags { // Host - ContentFlag_A = 0x01, - ContentFlag_PTR_IP4 = 0x02, - ContentFlag_PTR_IP6 = 0x04, - ContentFlag_AAAA = 0x08, + ContentFlag_A = 0x01, + ContentFlag_PTR_IP4 = 0x02, + ContentFlag_PTR_IP6 = 0x04, + ContentFlag_AAAA = 0x08, // Service - ContentFlag_PTR_TYPE = 0x10, - ContentFlag_PTR_NAME = 0x20, - ContentFlag_TXT = 0x40, - ContentFlag_SRV = 0x80, + ContentFlag_PTR_TYPE = 0x10, + ContentFlag_PTR_NAME = 0x20, + ContentFlag_TXT = 0x40, + ContentFlag_SRV = 0x80, } enuContentFlags; /** @@ -710,19 +708,19 @@ class MDNSResponder */ struct stcMDNS_MsgHeader { - uint16_t m_u16ID; // Identifier - bool m_1bQR : 1; // Query/Response flag - unsigned char m_4bOpcode : 4; // Operation code - bool m_1bAA : 1; // Authoritative Answer flag - bool m_1bTC : 1; // Truncation flag - bool m_1bRD : 1; // Recursion desired - bool m_1bRA : 1; // Recursion available - unsigned char m_3bZ : 3; // Zero - unsigned char m_4bRCode : 4; // Response code - uint16_t m_u16QDCount; // Question count - uint16_t m_u16ANCount; // Answer count - uint16_t m_u16NSCount; // Authority Record count - uint16_t m_u16ARCount; // Additional Record count + uint16_t m_u16ID; // Identifier + bool m_1bQR : 1; // Query/Response flag + unsigned char m_4bOpcode : 4; // Operation code + bool m_1bAA : 1; // Authoritative Answer flag + bool m_1bTC : 1; // Truncation flag + bool m_1bRD : 1; // Recursion desired + bool m_1bRA : 1; // Recursion available + unsigned char m_3bZ : 3; // Zero + unsigned char m_4bRCode : 4; // Response code + uint16_t m_u16QDCount; // Question count + uint16_t m_u16ANCount; // Answer count + uint16_t m_u16NSCount; // Authority Record count + uint16_t m_u16ARCount; // Additional Record count stcMDNS_MsgHeader(uint16_t p_u16ID = 0, bool p_bQR = false, @@ -743,8 +741,8 @@ class MDNSResponder */ struct stcMDNS_RRDomain { - char m_acName[MDNS_DOMAIN_MAXLENGTH]; // Encoded domain name - uint16_t m_u16NameLength; // Length (incl. '\0') + char m_acName[MDNS_DOMAIN_MAXLENGTH]; // Encoded domain name + uint16_t m_u16NameLength; // Length (incl. '\0') stcMDNS_RRDomain(void); stcMDNS_RRDomain(const stcMDNS_RRDomain& p_Other); @@ -770,8 +768,8 @@ class MDNSResponder */ struct stcMDNS_RRAttributes { - uint16_t m_u16Type; // Type - uint16_t m_u16Class; // Class, nearly always 'IN' + uint16_t m_u16Type; // Type + uint16_t m_u16Class; // Class, nearly always 'IN' stcMDNS_RRAttributes(uint16_t p_u16Type = 0, uint16_t p_u16Class = 1 /*DNS_RRCLASS_IN Internet*/); @@ -785,8 +783,8 @@ class MDNSResponder */ struct stcMDNS_RRHeader { - stcMDNS_RRDomain m_Domain; - stcMDNS_RRAttributes m_Attributes; + stcMDNS_RRDomain m_Domain; + stcMDNS_RRAttributes m_Attributes; stcMDNS_RRHeader(void); stcMDNS_RRHeader(const stcMDNS_RRHeader& p_Other); @@ -801,9 +799,9 @@ class MDNSResponder */ struct stcMDNS_RRQuestion { - stcMDNS_RRQuestion* m_pNext; - stcMDNS_RRHeader m_Header; - bool m_bUnicast; // Unicast reply requested + stcMDNS_RRQuestion* m_pNext; + stcMDNS_RRHeader m_Header; + bool m_bUnicast; // Unicast reply requested stcMDNS_RRQuestion(void); }; @@ -826,11 +824,11 @@ class MDNSResponder */ struct stcMDNS_RRAnswer { - stcMDNS_RRAnswer* m_pNext; + stcMDNS_RRAnswer* m_pNext; const enuAnswerType m_AnswerType; - stcMDNS_RRHeader m_Header; - bool m_bCacheFlush; // Cache flush command bit - uint32_t m_u32TTL; // Validity time in seconds + stcMDNS_RRHeader m_Header; + bool m_bCacheFlush; // Cache flush command bit + uint32_t m_u32TTL; // Validity time in seconds virtual ~stcMDNS_RRAnswer(void); @@ -838,7 +836,7 @@ class MDNSResponder bool clear(void); - protected: + protected: stcMDNS_RRAnswer(enuAnswerType p_AnswerType, const stcMDNS_RRHeader& p_Header, uint32_t p_u32TTL); @@ -850,7 +848,7 @@ class MDNSResponder */ struct stcMDNS_RRAnswerA : public stcMDNS_RRAnswer { - IPAddress m_IPAddress; + IPAddress m_IPAddress; stcMDNS_RRAnswerA(const stcMDNS_RRHeader& p_Header, uint32_t p_u32TTL); @@ -865,7 +863,7 @@ class MDNSResponder */ struct stcMDNS_RRAnswerPTR : public stcMDNS_RRAnswer { - stcMDNS_RRDomain m_PTRDomain; + stcMDNS_RRDomain m_PTRDomain; stcMDNS_RRAnswerPTR(const stcMDNS_RRHeader& p_Header, uint32_t p_u32TTL); @@ -879,7 +877,7 @@ class MDNSResponder */ struct stcMDNS_RRAnswerTXT : public stcMDNS_RRAnswer { - stcMDNSServiceTxts m_Txts; + stcMDNSServiceTxts m_Txts; stcMDNS_RRAnswerTXT(const stcMDNS_RRHeader& p_Header, uint32_t p_u32TTL); @@ -909,10 +907,10 @@ class MDNSResponder */ struct stcMDNS_RRAnswerSRV : public stcMDNS_RRAnswer { - uint16_t m_u16Priority; - uint16_t m_u16Weight; - uint16_t m_u16Port; - stcMDNS_RRDomain m_SRVDomain; + uint16_t m_u16Priority; + uint16_t m_u16Weight; + uint16_t m_u16Port; + stcMDNS_RRDomain m_SRVDomain; stcMDNS_RRAnswerSRV(const stcMDNS_RRHeader& p_Header, uint32_t p_u32TTL); @@ -926,8 +924,8 @@ class MDNSResponder */ struct stcMDNS_RRAnswerGeneric : public stcMDNS_RRAnswer { - uint16_t m_u16RDLength; // Length of variable answer - uint8_t* m_pu8RDData; // Offset of start of variable answer in packet + uint16_t m_u16RDLength; // Length of variable answer + uint8_t* m_pu8RDData; // Offset of start of variable answer in packet stcMDNS_RRAnswerGeneric(const stcMDNS_RRHeader& p_Header, uint32_t p_u32TTL); @@ -936,7 +934,6 @@ class MDNSResponder bool clear(void); }; - /** enuProbingStatus */ @@ -953,36 +950,35 @@ class MDNSResponder */ struct stcProbeInformation { - enuProbingStatus m_ProbingStatus; - uint8_t m_u8SentCount; // Used for probes and announcements - esp8266::polledTimeout::oneShotMs m_Timeout; // Used for probes and announcements + enuProbingStatus m_ProbingStatus; + uint8_t m_u8SentCount; // Used for probes and announcements + esp8266::polledTimeout::oneShotMs m_Timeout; // Used for probes and announcements //clsMDNSTimeFlag m_TimeFlag; // Used for probes and announcements - bool m_bConflict; - bool m_bTiebreakNeeded; - MDNSHostProbeFn m_fnHostProbeResultCallback; - MDNSServiceProbeFn m_fnServiceProbeResultCallback; + bool m_bConflict; + bool m_bTiebreakNeeded; + MDNSHostProbeFn m_fnHostProbeResultCallback; + MDNSServiceProbeFn m_fnServiceProbeResultCallback; stcProbeInformation(void); bool clear(bool p_bClearUserdata = false); }; - /** stcMDNSService */ struct stcMDNSService { - stcMDNSService* m_pNext; - char* m_pcName; - bool m_bAutoName; // Name was set automatically to hostname (if no name was supplied) - char* m_pcService; - char* m_pcProtocol; - uint16_t m_u16Port; - uint8_t m_u8ReplyMask; - stcMDNSServiceTxts m_Txts; + stcMDNSService* m_pNext; + char* m_pcName; + bool m_bAutoName; // Name was set automatically to hostname (if no name was supplied) + char* m_pcService; + char* m_pcProtocol; + uint16_t m_u16Port; + uint8_t m_u8ReplyMask; + stcMDNSServiceTxts m_Txts; MDNSDynamicServiceTxtCallbackFunc m_fnTxtCallback; - stcProbeInformation m_ProbeInformation; + stcProbeInformation m_ProbeInformation; stcMDNSService(const char* p_pcName = 0, const char* p_pcService = 0, @@ -1021,14 +1017,14 @@ class MDNSResponder /** TIMEOUTLEVELs */ - const timeoutLevel_t TIMEOUTLEVEL_UNSET = 0; - const timeoutLevel_t TIMEOUTLEVEL_BASE = 80; - const timeoutLevel_t TIMEOUTLEVEL_INTERVAL = 5; - const timeoutLevel_t TIMEOUTLEVEL_FINAL = 100; + const timeoutLevel_t TIMEOUTLEVEL_UNSET = 0; + const timeoutLevel_t TIMEOUTLEVEL_BASE = 80; + const timeoutLevel_t TIMEOUTLEVEL_INTERVAL = 5; + const timeoutLevel_t TIMEOUTLEVEL_FINAL = 100; - uint32_t m_u32TTL; + uint32_t m_u32TTL; esp8266::polledTimeout::oneShotMs m_TTLTimeout; - timeoutLevel_t m_timeoutLevel; + timeoutLevel_t m_timeoutLevel; using timeoutBase = decltype(m_TTLTimeout); @@ -1049,9 +1045,9 @@ class MDNSResponder */ struct stcIP4Address { - stcIP4Address* m_pNext; - IPAddress m_IPAddress; - stcTTL m_TTL; + stcIP4Address* m_pNext; + IPAddress m_IPAddress; + stcTTL m_TTL; stcIP4Address(IPAddress p_IPAddress, uint32_t p_u32TTL = 0); @@ -1063,35 +1059,35 @@ class MDNSResponder */ struct stcIP6Address { - stcIP6Address* m_pNext; - IP6Address m_IPAddress; - stcTTL m_TTL; + stcIP6Address* m_pNext; + IP6Address m_IPAddress; + stcTTL m_TTL; stcIP6Address(IPAddress p_IPAddress, uint32_t p_u32TTL = 0); }; #endif - stcAnswer* m_pNext; + stcAnswer* m_pNext; // The service domain is the first 'answer' (from PTR answer, using service and protocol) to be set // Defines the key for additional answer, like host domain, etc. - stcMDNS_RRDomain m_ServiceDomain; // 1. level answer (PTR), eg. MyESP._http._tcp.local - char* m_pcServiceDomain; - stcTTL m_TTLServiceDomain; - stcMDNS_RRDomain m_HostDomain; // 2. level answer (SRV, using service domain), eg. esp8266.local - char* m_pcHostDomain; - uint16_t m_u16Port; // 2. level answer (SRV, using service domain), eg. 5000 - stcTTL m_TTLHostDomainAndPort; - stcMDNSServiceTxts m_Txts; // 2. level answer (TXT, using service domain), eg. c#=1 - char* m_pcTxts; - stcTTL m_TTLTxts; + stcMDNS_RRDomain m_ServiceDomain; // 1. level answer (PTR), eg. MyESP._http._tcp.local + char* m_pcServiceDomain; + stcTTL m_TTLServiceDomain; + stcMDNS_RRDomain m_HostDomain; // 2. level answer (SRV, using service domain), eg. esp8266.local + char* m_pcHostDomain; + uint16_t m_u16Port; // 2. level answer (SRV, using service domain), eg. 5000 + stcTTL m_TTLHostDomainAndPort; + stcMDNSServiceTxts m_Txts; // 2. level answer (TXT, using service domain), eg. c#=1 + char* m_pcTxts; + stcTTL m_TTLTxts; #ifdef MDNS_IP4_SUPPORT - stcIP4Address* m_pIP4Addresses; // 3. level answer (A, using host domain), eg. 123.456.789.012 + stcIP4Address* m_pIP4Addresses; // 3. level answer (A, using host domain), eg. 123.456.789.012 #endif #ifdef MDNS_IP6_SUPPORT - stcIP6Address* m_pIP6Addresses; // 3. level answer (AAAA, using host domain), eg. 1234::09 + stcIP6Address* m_pIP6Addresses; // 3. level answer (AAAA, using host domain), eg. 1234::09 #endif - uint32_t m_u32ContentFlags; + uint32_t m_u32ContentFlags; stcAnswer(void); ~stcAnswer(void); @@ -1129,14 +1125,14 @@ class MDNSResponder #endif }; - stcMDNSServiceQuery* m_pNext; - stcMDNS_RRDomain m_ServiceTypeDomain; // eg. _http._tcp.local - MDNSServiceQueryCallbackFunc m_fnCallback; - bool m_bLegacyQuery; - uint8_t m_u8SentCount; + stcMDNSServiceQuery* m_pNext; + stcMDNS_RRDomain m_ServiceTypeDomain; // eg. _http._tcp.local + MDNSServiceQueryCallbackFunc m_fnCallback; + bool m_bLegacyQuery; + uint8_t m_u8SentCount; esp8266::polledTimeout::oneShotMs m_ResendTimeout; - bool m_bAwaitingAnswers; - stcAnswer* m_pAnswers; + bool m_bAwaitingAnswers; + stcAnswer* m_pAnswers; stcMDNSServiceQuery(void); ~stcMDNSServiceQuery(void); @@ -1160,34 +1156,34 @@ class MDNSResponder */ struct stcMDNSSendParameter { - protected: + protected: /** stcDomainCacheItem */ struct stcDomainCacheItem { - stcDomainCacheItem* m_pNext; - const void* m_pHostnameOrService; // Opaque id for host or service domain (pointer) - bool m_bAdditionalData; // Opaque flag for special info (service domain included) - uint16_t m_u16Offset; // Offset in UDP output buffer + stcDomainCacheItem* m_pNext; + const void* m_pHostnameOrService; // Opaque id for host or service domain (pointer) + bool m_bAdditionalData; // Opaque flag for special info (service domain included) + uint16_t m_u16Offset; // Offset in UDP output buffer stcDomainCacheItem(const void* p_pHostnameOrService, bool p_bAdditionalData, uint32_t p_u16Offset); }; - public: - uint16_t m_u16ID; // Query ID (used only in lagacy queries) - stcMDNS_RRQuestion* m_pQuestions; // A list of queries - uint8_t m_u8HostReplyMask; // Flags for reply components/answers - bool m_bLegacyQuery; // Flag: Legacy query - bool m_bResponse; // Flag: Response to a query - bool m_bAuthorative; // Flag: Authoritative (owner) response - bool m_bCacheFlush; // Flag: Clients should flush their caches - bool m_bUnicast; // Flag: Unicast response - bool m_bUnannounce; // Flag: Unannounce service - uint16_t m_u16Offset; // Current offset in UDP write buffer (mainly for domain cache) - stcDomainCacheItem* m_pDomainCacheItems; // Cached host and service domains + public: + uint16_t m_u16ID; // Query ID (used only in lagacy queries) + stcMDNS_RRQuestion* m_pQuestions; // A list of queries + uint8_t m_u8HostReplyMask; // Flags for reply components/answers + bool m_bLegacyQuery; // Flag: Legacy query + bool m_bResponse; // Flag: Response to a query + bool m_bAuthorative; // Flag: Authoritative (owner) response + bool m_bCacheFlush; // Flag: Clients should flush their caches + bool m_bUnicast; // Flag: Unicast response + bool m_bUnannounce; // Flag: Unannounce service + uint16_t m_u16Offset; // Current offset in UDP write buffer (mainly for domain cache) + stcDomainCacheItem* m_pDomainCacheItems; // Cached host and service domains stcMDNSSendParameter(void); ~stcMDNSSendParameter(void); @@ -1205,12 +1201,12 @@ class MDNSResponder }; // Instance variables - stcMDNSService* m_pServices; - UdpContext* m_pUDPContext; - char* m_pcHostname; - stcMDNSServiceQuery* m_pServiceQueries; + stcMDNSService* m_pServices; + UdpContext* m_pUDPContext; + char* m_pcHostname; + stcMDNSServiceQuery* m_pServiceQueries; MDNSDynamicServiceTxtCallbackFunc m_fnServiceTxtCallback; - stcProbeInformation m_HostProbeInformation; + stcProbeInformation m_HostProbeInformation; /** CONTROL **/ /* MAINTENANCE */ @@ -1397,7 +1393,7 @@ class MDNSResponder stcMDNSServiceQuery* _findLegacyServiceQuery(void); bool _releaseServiceQueries(void); stcMDNSServiceQuery* _findNextServiceQueryByServiceType(const stcMDNS_RRDomain& p_ServiceDomain, - const stcMDNSServiceQuery* p_pPrevServiceQuery); + const stcMDNSServiceQuery* p_pPrevServiceQuery); /* HOSTNAME */ bool _setHostname(const char* p_pcHostname); @@ -1456,8 +1452,8 @@ class MDNSResponder #endif }; -}// namespace MDNSImplementation +} // namespace MDNSImplementation -}// namespace esp8266 +} // namespace esp8266 -#endif // MDNS_H +#endif // MDNS_H diff --git a/libraries/ESP8266mDNS/src/LEAmDNS_Control.cpp b/libraries/ESP8266mDNS/src/LEAmDNS_Control.cpp index bf1b1cde26..54f31c998b 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS_Control.cpp +++ b/libraries/ESP8266mDNS/src/LEAmDNS_Control.cpp @@ -22,24 +22,25 @@ */ -#include -#include #include -#include +#include #include +#include +#include #include /* ESP8266mDNS Control.cpp */ -extern "C" { +extern "C" +{ #include "user_interface.h" } #include "ESP8266mDNS.h" -#include "LEAmDNS_lwIPdefs.h" #include "LEAmDNS_Priv.h" +#include "LEAmDNS_lwIPdefs.h" namespace esp8266 { @@ -48,12 +49,10 @@ namespace esp8266 */ namespace MDNSImplementation { - /** CONTROL */ - /** MAINTENANCE */ @@ -68,16 +67,13 @@ namespace MDNSImplementation */ bool MDNSResponder::_process(bool p_bUserContext) { - - bool bResult = true; + bool bResult = true; if (!p_bUserContext) { - - if ((m_pUDPContext) && // UDPContext available AND - (m_pUDPContext->next())) // has content + if ((m_pUDPContext) && // UDPContext available AND + (m_pUDPContext->next())) // has content { - //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _update: Calling _parseMessage\n"));); bResult = _parseMessage(); //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parsePacket %s\n"), (bResult ? "succeeded" : "FAILED"));); @@ -85,8 +81,8 @@ bool MDNSResponder::_process(bool p_bUserContext) } else { - bResult = _updateProbeStatus() && // Probing - _checkServiceQueryCache(); // Service query cache check + bResult = _updateProbeStatus() && // Probing + _checkServiceQueryCache(); // Service query cache check } return bResult; } @@ -96,9 +92,8 @@ bool MDNSResponder::_process(bool p_bUserContext) */ bool MDNSResponder::_restart(void) { - - return ((_resetProbeStatus(true/*restart*/)) && // Stop and restart probing - (_allocUDPContext())); // Restart UDP + return ((_resetProbeStatus(true /*restart*/)) && // Stop and restart probing + (_allocUDPContext())); // Restart UDP } /** @@ -111,27 +106,26 @@ bool MDNSResponder::_restart(void) bool MDNSResponder::_parseMessage(void) { DEBUG_EX_INFO( - unsigned long ulStartTime = millis(); - unsigned uStartMemory = ESP.getFreeHeap(); + unsigned long ulStartTime = millis(); + unsigned uStartMemory = ESP.getFreeHeap(); DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseMessage (Time: %lu ms, heap: %u bytes, from %s(%u), to %s(%u))\n"), ulStartTime, uStartMemory, IPAddress(m_pUDPContext->getRemoteAddress()).toString().c_str(), m_pUDPContext->getRemotePort(), - IPAddress(m_pUDPContext->getDestAddress()).toString().c_str(), m_pUDPContext->getLocalPort()); - ); + IPAddress(m_pUDPContext->getDestAddress()).toString().c_str(), m_pUDPContext->getLocalPort());); //DEBUG_EX_INFO(_udpDump();); - bool bResult = false; + bool bResult = false; - stcMDNS_MsgHeader header; + stcMDNS_MsgHeader header; if (_readMDNSMsgHeader(header)) { - if (0 == header.m_4bOpcode) // A standard query + if (0 == header.m_4bOpcode) // A standard query { - if (header.m_1bQR) // Received a response -> answers to a query + if (header.m_1bQR) // Received a response -> answers to a query { //DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseMessage: Reading answers: ID:%u, Q:%u, A:%u, NS:%u, AR:%u\n"), header.m_u16ID, header.m_u16QDCount, header.m_u16ANCount, header.m_u16NSCount, header.m_u16ARCount);); bResult = _parseResponse(header); } - else // Received a query (Questions) + else // Received a query (Questions) { //DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseMessage: Reading query: ID:%u, Q:%u, A:%u, NS:%u, AR:%u\n"), header.m_u16ID, header.m_u16QDCount, header.m_u16ANCount, header.m_u16NSCount, header.m_u16ARCount);); bResult = _parseQuery(header); @@ -149,9 +143,8 @@ bool MDNSResponder::_parseMessage(void) m_pUDPContext->flush(); } DEBUG_EX_INFO( - unsigned uFreeHeap = ESP.getFreeHeap(); - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseMessage: Done (%s after %lu ms, ate %i bytes, remaining %u)\n\n"), (bResult ? "Succeeded" : "FAILED"), (millis() - ulStartTime), (uStartMemory - uFreeHeap), uFreeHeap); - ); + unsigned uFreeHeap = ESP.getFreeHeap(); + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseMessage: Done (%s after %lu ms, ate %i bytes, remaining %u)\n\n"), (bResult ? "Succeeded" : "FAILED"), (millis() - ulStartTime), (uStartMemory - uFreeHeap), uFreeHeap);); return bResult; } @@ -174,33 +167,31 @@ bool MDNSResponder::_parseMessage(void) */ bool MDNSResponder::_parseQuery(const MDNSResponder::stcMDNS_MsgHeader& p_MsgHeader) { + bool bResult = true; - bool bResult = true; - - stcMDNSSendParameter sendParameter; - uint8_t u8HostOrServiceReplies = 0; + stcMDNSSendParameter sendParameter; + uint8_t u8HostOrServiceReplies = 0; for (uint16_t qd = 0; ((bResult) && (qd < p_MsgHeader.m_u16QDCount)); ++qd) { - - stcMDNS_RRQuestion questionRR; + stcMDNS_RRQuestion questionRR; if ((bResult = _readRRQuestion(questionRR))) { // Define host replies, BUT only answer queries after probing is done u8HostOrServiceReplies = sendParameter.m_u8HostReplyMask |= (((ProbingStatus_Done == m_HostProbeInformation.m_ProbingStatus)) - ? _replyMaskForHost(questionRR.m_Header, 0) - : 0); + ? _replyMaskForHost(questionRR.m_Header, 0) + : 0); DEBUG_EX_INFO(if (u8HostOrServiceReplies) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Host reply needed 0x%X\n"), u8HostOrServiceReplies); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Host reply needed 0x%X\n"), u8HostOrServiceReplies); + }); // Check tiebreak need for host domain if (ProbingStatus_InProgress == m_HostProbeInformation.m_ProbingStatus) { - bool bFullNameMatch = false; + bool bFullNameMatch = false; if ((_replyMaskForHost(questionRR.m_Header, &bFullNameMatch)) && - (bFullNameMatch)) + (bFullNameMatch)) { // We're in 'probing' state and someone is asking for our host domain: this might be // a race-condition: Two host with the same domain names try simutanously to probe their domains @@ -217,26 +208,26 @@ bool MDNSResponder::_parseQuery(const MDNSResponder::stcMDNS_MsgHeader& p_MsgHea { // Define service replies, BUT only answer queries after probing is done uint8_t u8ReplyMaskForQuestion = (((ProbingStatus_Done == pService->m_ProbeInformation.m_ProbingStatus)) - ? _replyMaskForService(questionRR.m_Header, *pService, 0) - : 0); + ? _replyMaskForService(questionRR.m_Header, *pService, 0) + : 0); u8HostOrServiceReplies |= (pService->m_u8ReplyMask |= u8ReplyMaskForQuestion); DEBUG_EX_INFO(if (u8ReplyMaskForQuestion) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Service reply needed for (%s.%s.%s): 0x%X (%s)\n"), (pService->m_pcName ? : m_pcHostname), pService->m_pcService, pService->m_pcProtocol, u8ReplyMaskForQuestion, IPAddress(m_pUDPContext->getRemoteAddress()).toString().c_str()); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Service reply needed for (%s.%s.%s): 0x%X (%s)\n"), (pService->m_pcName ?: m_pcHostname), pService->m_pcService, pService->m_pcProtocol, u8ReplyMaskForQuestion, IPAddress(m_pUDPContext->getRemoteAddress()).toString().c_str()); + }); // Check tiebreak need for service domain if (ProbingStatus_InProgress == pService->m_ProbeInformation.m_ProbingStatus) { - bool bFullNameMatch = false; + bool bFullNameMatch = false; if ((_replyMaskForService(questionRR.m_Header, *pService, &bFullNameMatch)) && - (bFullNameMatch)) + (bFullNameMatch)) { // We're in 'probing' state and someone is asking for this service domain: this might be // a race-condition: Two services with the same domain names try simutanously to probe their domains // See: RFC 6762, 8.2 (Tiebraking) // However, we're using a max. reduced approach for tiebreaking here: The 'higher' SRV host wins! - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Possible race-condition for service domain %s.%s.%s detected while probing.\n"), (pService->m_pcName ? : m_pcHostname), pService->m_pcService, pService->m_pcProtocol);); + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Possible race-condition for service domain %s.%s.%s detected while probing.\n"), (pService->m_pcName ?: m_pcHostname), pService->m_pcService, pService->m_pcProtocol);); pService->m_ProbeInformation.m_bTiebreakNeeded = true; } @@ -245,31 +236,29 @@ bool MDNSResponder::_parseQuery(const MDNSResponder::stcMDNS_MsgHeader& p_MsgHea // Handle unicast and legacy specialities // If only one question asks for unicast reply, the whole reply packet is send unicast - if (((DNS_MQUERY_PORT != m_pUDPContext->getRemotePort()) || // Unicast (maybe legacy) query OR - (questionRR.m_bUnicast)) && // Expressivly unicast query - (!sendParameter.m_bUnicast)) + if (((DNS_MQUERY_PORT != m_pUDPContext->getRemotePort()) || // Unicast (maybe legacy) query OR + (questionRR.m_bUnicast)) && // Expressivly unicast query + (!sendParameter.m_bUnicast)) { - sendParameter.m_bUnicast = true; sendParameter.m_bCacheFlush = false; DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Unicast response for %s!\n"), IPAddress(m_pUDPContext->getRemoteAddress()).toString().c_str());); if ((DNS_MQUERY_PORT != m_pUDPContext->getRemotePort()) && // Unicast (maybe legacy) query AND - (1 == p_MsgHeader.m_u16QDCount) && // Only one question AND - ((sendParameter.m_u8HostReplyMask) || // Host replies OR - (u8HostOrServiceReplies))) // Host or service replies available + (1 == p_MsgHeader.m_u16QDCount) && // Only one question AND + ((sendParameter.m_u8HostReplyMask) || // Host replies OR + (u8HostOrServiceReplies))) // Host or service replies available { // We're a match for this legacy query, BUT // make sure, that the query comes from a local host ip_info IPInfo_Local; ip_info IPInfo_Remote; if (((IPInfo_Remote.ip.addr = m_pUDPContext->getRemoteAddress())) && - (((wifi_get_ip_info(SOFTAP_IF, &IPInfo_Local)) && - (ip4_addr_netcmp(&IPInfo_Remote.ip, &IPInfo_Local.ip, &IPInfo_Local.netmask))) || // Remote IP in SOFTAP's subnet OR - ((wifi_get_ip_info(STATION_IF, &IPInfo_Local)) && - (ip4_addr_netcmp(&IPInfo_Remote.ip, &IPInfo_Local.ip, &IPInfo_Local.netmask))))) // Remote IP in STATION's subnet + (((wifi_get_ip_info(SOFTAP_IF, &IPInfo_Local)) && + (ip4_addr_netcmp(&IPInfo_Remote.ip, &IPInfo_Local.ip, &IPInfo_Local.netmask))) || // Remote IP in SOFTAP's subnet OR + ((wifi_get_ip_info(STATION_IF, &IPInfo_Local)) && + (ip4_addr_netcmp(&IPInfo_Remote.ip, &IPInfo_Local.ip, &IPInfo_Local.netmask))))) // Remote IP in STATION's subnet { - DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Legacy query from local host %s, id %u!\n"), IPAddress(m_pUDPContext->getRemoteAddress()).toString().c_str(), p_MsgHeader.m_u16ID);); sendParameter.m_u16ID = p_MsgHeader.m_u16ID; @@ -298,40 +287,37 @@ bool MDNSResponder::_parseQuery(const MDNSResponder::stcMDNS_MsgHeader& p_MsgHea { DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: FAILED to read question!\n"));); } - } // for questions + } // for questions //DEBUG_EX_INFO(if (u8HostOrServiceReplies) { DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Reply needed: %u (%s: %s->%s)\n"), u8HostOrServiceReplies, clsTimeSyncer::timestr(), IPAddress(m_pUDPContext->getRemoteAddress()).toString().c_str(), IPAddress(m_pUDPContext->getDestAddress()).toString().c_str()); } ); // Handle known answers - uint32_t u32Answers = (p_MsgHeader.m_u16ANCount + p_MsgHeader.m_u16NSCount + p_MsgHeader.m_u16ARCount); + uint32_t u32Answers = (p_MsgHeader.m_u16ANCount + p_MsgHeader.m_u16NSCount + p_MsgHeader.m_u16ARCount); DEBUG_EX_INFO(if ((u8HostOrServiceReplies) && (u32Answers)) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Known answers(%u):\n"), u32Answers); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Known answers(%u):\n"), u32Answers); + }); for (uint32_t an = 0; ((bResult) && (an < u32Answers)); ++an) { - stcMDNS_RRAnswer* pKnownRRAnswer = 0; + stcMDNS_RRAnswer* pKnownRRAnswer = 0; if (((bResult = _readRRAnswer(pKnownRRAnswer))) && - (pKnownRRAnswer)) + (pKnownRRAnswer)) { - - if ((DNS_RRTYPE_ANY != pKnownRRAnswer->m_Header.m_Attributes.m_u16Type) && // No ANY type answer - (DNS_RRCLASS_ANY != pKnownRRAnswer->m_Header.m_Attributes.m_u16Class)) // No ANY class answer + if ((DNS_RRTYPE_ANY != pKnownRRAnswer->m_Header.m_Attributes.m_u16Type) && // No ANY type answer + (DNS_RRCLASS_ANY != pKnownRRAnswer->m_Header.m_Attributes.m_u16Class)) // No ANY class answer { - // Find match between planned answer (sendParameter.m_u8HostReplyMask) and this 'known answer' uint8_t u8HostMatchMask = (sendParameter.m_u8HostReplyMask & _replyMaskForHost(pKnownRRAnswer->m_Header)); - if ((u8HostMatchMask) && // The RR in the known answer matches an RR we are planning to send, AND - ((MDNS_HOST_TTL / 2) <= pKnownRRAnswer->m_u32TTL)) // The TTL of the known answer is longer than half of the new host TTL (120s) + if ((u8HostMatchMask) && // The RR in the known answer matches an RR we are planning to send, AND + ((MDNS_HOST_TTL / 2) <= pKnownRRAnswer->m_u32TTL)) // The TTL of the known answer is longer than half of the new host TTL (120s) { - // Compare contents if (AnswerType_PTR == pKnownRRAnswer->answerType()) { - stcMDNS_RRDomain hostDomain; + stcMDNS_RRDomain hostDomain; if ((_buildDomainForHost(m_pcHostname, hostDomain)) && - (((stcMDNS_RRAnswerPTR*)pKnownRRAnswer)->m_PTRDomain == hostDomain)) + (((stcMDNS_RRAnswerPTR*)pKnownRRAnswer)->m_PTRDomain == hostDomain)) { // Host domain match #ifdef MDNS_IP4_SUPPORT @@ -357,11 +343,11 @@ bool MDNSResponder::_parseQuery(const MDNSResponder::stcMDNS_MsgHeader& p_MsgHea // IP4 address was asked for #ifdef MDNS_IP4_SUPPORT if ((AnswerType_A == pKnownRRAnswer->answerType()) && - (((stcMDNS_RRAnswerA*)pKnownRRAnswer)->m_IPAddress == m_pUDPContext->getInputNetif()->ip_addr)) + (((stcMDNS_RRAnswerA*)pKnownRRAnswer)->m_IPAddress == m_pUDPContext->getInputNetif()->ip_addr)) { DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: IP4 address already known... skipping!\n"));); sendParameter.m_u8HostReplyMask &= ~ContentFlag_A; - } // else: RData NOT IP4 length !! + } // else: RData NOT IP4 length !! #endif } else if (u8HostMatchMask & ContentFlag_AAAA) @@ -369,29 +355,27 @@ bool MDNSResponder::_parseQuery(const MDNSResponder::stcMDNS_MsgHeader& p_MsgHea // IP6 address was asked for #ifdef MDNS_IP6_SUPPORT if ((AnswerType_AAAA == pAnswerRR->answerType()) && - (((stcMDNS_RRAnswerAAAA*)pAnswerRR)->m_IPAddress == _getResponseMulticastInterface())) + (((stcMDNS_RRAnswerAAAA*)pAnswerRR)->m_IPAddress == _getResponseMulticastInterface())) { - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: IP6 address already known... skipping!\n"));); sendParameter.m_u8HostReplyMask &= ~ContentFlag_AAAA; - } // else: RData NOT IP6 length !! + } // else: RData NOT IP6 length !! #endif } - } // Host match /*and TTL*/ + } // Host match /*and TTL*/ // // Check host tiebreak possibility if (m_HostProbeInformation.m_bTiebreakNeeded) { - stcMDNS_RRDomain hostDomain; + stcMDNS_RRDomain hostDomain; if ((_buildDomainForHost(m_pcHostname, hostDomain)) && - (pKnownRRAnswer->m_Header.m_Domain == hostDomain)) + (pKnownRRAnswer->m_Header.m_Domain == hostDomain)) { // Host domain match #ifdef MDNS_IP4_SUPPORT if (AnswerType_A == pKnownRRAnswer->answerType()) { - IPAddress localIPAddress(m_pUDPContext->getInputNetif()->ip_addr); if (((stcMDNS_RRAnswerA*)pKnownRRAnswer)->m_IPAddress == localIPAddress) { @@ -401,14 +385,14 @@ bool MDNSResponder::_parseQuery(const MDNSResponder::stcMDNS_MsgHeader& p_MsgHea } else { - if ((uint32_t)(((stcMDNS_RRAnswerA*)pKnownRRAnswer)->m_IPAddress) > (uint32_t)localIPAddress) // The OTHER IP is 'higher' -> LOST + if ((uint32_t)(((stcMDNS_RRAnswerA*)pKnownRRAnswer)->m_IPAddress) > (uint32_t)localIPAddress) // The OTHER IP is 'higher' -> LOST { // LOST tiebreak DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Tiebreak (IP4) LOST (lower)!\n"));); _cancelProbingForHost(); m_HostProbeInformation.m_bTiebreakNeeded = false; } - else // WON tiebreak + else // WON tiebreak { //TiebreakState = TiebreakState_Won; // We received an 'old' message from ourselves -> Just ignore DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Tiebreak (IP4) WON (higher IP)!\n"));); @@ -424,31 +408,29 @@ bool MDNSResponder::_parseQuery(const MDNSResponder::stcMDNS_MsgHeader& p_MsgHea } #endif } - } // Host tiebreak possibility + } // Host tiebreak possibility // Check service answers for (stcMDNSService* pService = m_pServices; pService; pService = pService->m_pNext) { - uint8_t u8ServiceMatchMask = (pService->m_u8ReplyMask & _replyMaskForService(pKnownRRAnswer->m_Header, *pService)); - if ((u8ServiceMatchMask) && // The RR in the known answer matches an RR we are planning to send, AND - ((MDNS_SERVICE_TTL / 2) <= pKnownRRAnswer->m_u32TTL)) // The TTL of the known answer is longer than half of the new service TTL (4500s) + if ((u8ServiceMatchMask) && // The RR in the known answer matches an RR we are planning to send, AND + ((MDNS_SERVICE_TTL / 2) <= pKnownRRAnswer->m_u32TTL)) // The TTL of the known answer is longer than half of the new service TTL (4500s) { - if (AnswerType_PTR == pKnownRRAnswer->answerType()) { - stcMDNS_RRDomain serviceDomain; + stcMDNS_RRDomain serviceDomain; if ((u8ServiceMatchMask & ContentFlag_PTR_TYPE) && - (_buildDomainForService(*pService, false, serviceDomain)) && - (serviceDomain == ((stcMDNS_RRAnswerPTR*)pKnownRRAnswer)->m_PTRDomain)) + (_buildDomainForService(*pService, false, serviceDomain)) && + (serviceDomain == ((stcMDNS_RRAnswerPTR*)pKnownRRAnswer)->m_PTRDomain)) { DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Service type PTR already known... skipping!\n"));); pService->m_u8ReplyMask &= ~ContentFlag_PTR_TYPE; } if ((u8ServiceMatchMask & ContentFlag_PTR_NAME) && - (_buildDomainForService(*pService, true, serviceDomain)) && - (serviceDomain == ((stcMDNS_RRAnswerPTR*)pKnownRRAnswer)->m_PTRDomain)) + (_buildDomainForService(*pService, true, serviceDomain)) && + (serviceDomain == ((stcMDNS_RRAnswerPTR*)pKnownRRAnswer)->m_PTRDomain)) { DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Service name PTR already known... skipping!\n"));); pService->m_u8ReplyMask &= ~ContentFlag_PTR_NAME; @@ -457,19 +439,17 @@ bool MDNSResponder::_parseQuery(const MDNSResponder::stcMDNS_MsgHeader& p_MsgHea else if (u8ServiceMatchMask & ContentFlag_SRV) { DEBUG_EX_ERR(if (AnswerType_SRV != pKnownRRAnswer->answerType()) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: ERROR! INVALID answer type (SRV)!\n"));); - stcMDNS_RRDomain hostDomain; + stcMDNS_RRDomain hostDomain; if ((_buildDomainForHost(m_pcHostname, hostDomain)) && - (hostDomain == ((stcMDNS_RRAnswerSRV*)pKnownRRAnswer)->m_SRVDomain)) // Host domain match + (hostDomain == ((stcMDNS_RRAnswerSRV*)pKnownRRAnswer)->m_SRVDomain)) // Host domain match { - if ((MDNS_SRV_PRIORITY == ((stcMDNS_RRAnswerSRV*)pKnownRRAnswer)->m_u16Priority) && - (MDNS_SRV_WEIGHT == ((stcMDNS_RRAnswerSRV*)pKnownRRAnswer)->m_u16Weight) && - (pService->m_u16Port == ((stcMDNS_RRAnswerSRV*)pKnownRRAnswer)->m_u16Port)) + (MDNS_SRV_WEIGHT == ((stcMDNS_RRAnswerSRV*)pKnownRRAnswer)->m_u16Weight) && + (pService->m_u16Port == ((stcMDNS_RRAnswerSRV*)pKnownRRAnswer)->m_u16Port)) { - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Service SRV answer already known... skipping!\n"));); pService->m_u8ReplyMask &= ~ContentFlag_SRV; - } // else: Small differences -> send update message + } // else: Small differences -> send update message } } else if (u8ServiceMatchMask & ContentFlag_TXT) @@ -483,38 +463,37 @@ bool MDNSResponder::_parseQuery(const MDNSResponder::stcMDNS_MsgHeader& p_MsgHea } _releaseTempServiceTxts(*pService); } - } // Service match and enough TTL + } // Service match and enough TTL // // Check service tiebreak possibility if (pService->m_ProbeInformation.m_bTiebreakNeeded) { - stcMDNS_RRDomain serviceDomain; + stcMDNS_RRDomain serviceDomain; if ((_buildDomainForService(*pService, true, serviceDomain)) && - (pKnownRRAnswer->m_Header.m_Domain == serviceDomain)) + (pKnownRRAnswer->m_Header.m_Domain == serviceDomain)) { // Service domain match if (AnswerType_SRV == pKnownRRAnswer->answerType()) { - stcMDNS_RRDomain hostDomain; + stcMDNS_RRDomain hostDomain; if ((_buildDomainForHost(m_pcHostname, hostDomain)) && - (hostDomain == ((stcMDNS_RRAnswerSRV*)pKnownRRAnswer)->m_SRVDomain)) // Host domain match + (hostDomain == ((stcMDNS_RRAnswerSRV*)pKnownRRAnswer)->m_SRVDomain)) // Host domain match { - // We've received an old message from ourselves (same SRV) DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Tiebreak (SRV) won (was an old message)!\n"));); pService->m_ProbeInformation.m_bTiebreakNeeded = false; } else { - if (((stcMDNS_RRAnswerSRV*)pKnownRRAnswer)->m_SRVDomain > hostDomain) // The OTHER domain is 'higher' -> LOST + if (((stcMDNS_RRAnswerSRV*)pKnownRRAnswer)->m_SRVDomain > hostDomain) // The OTHER domain is 'higher' -> LOST { // LOST tiebreak DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Tiebreak (SRV) LOST (lower)!\n"));); _cancelProbingForService(*pService); pService->m_ProbeInformation.m_bTiebreakNeeded = false; } - else // WON tiebreak + else // WON tiebreak { //TiebreakState = TiebreakState_Won; // We received an 'old' message from ourselves -> Just ignore DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Tiebreak (SRV) won (higher)!\n"));); @@ -523,9 +502,9 @@ bool MDNSResponder::_parseQuery(const MDNSResponder::stcMDNS_MsgHeader& p_MsgHea } } } - } // service tiebreak possibility - } // for services - } // ANY answers + } // service tiebreak possibility + } // for services + } // ANY answers } else { @@ -537,7 +516,7 @@ bool MDNSResponder::_parseQuery(const MDNSResponder::stcMDNS_MsgHeader& p_MsgHea delete pKnownRRAnswer; pKnownRRAnswer = 0; } - } // for answers + } // for answers if (bResult) { @@ -559,10 +538,9 @@ bool MDNSResponder::_parseQuery(const MDNSResponder::stcMDNS_MsgHeader& p_MsgHea } DEBUG_EX_INFO( else - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: No reply needed\n")); - } - ); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: No reply needed\n")); + }); } else { @@ -581,14 +559,14 @@ bool MDNSResponder::_parseQuery(const MDNSResponder::stcMDNS_MsgHeader& p_MsgHea { if (pService->m_ProbeInformation.m_bTiebreakNeeded) { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: UNSOLVED tiebreak-need for service domain (%s.%s.%s)\n"), (pService->m_pcName ? : m_pcHostname), pService->m_pcService, pService->m_pcProtocol);); + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: UNSOLVED tiebreak-need for service domain (%s.%s.%s)\n"), (pService->m_pcName ?: m_pcHostname), pService->m_pcService, pService->m_pcProtocol);); pService->m_ProbeInformation.m_bTiebreakNeeded = false; } } DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: FAILED!\n")); + }); return bResult; } @@ -624,13 +602,12 @@ bool MDNSResponder::_parseResponse(const MDNSResponder::stcMDNS_MsgHeader& p_Msg //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse\n"));); //DEBUG_EX_INFO(_udpDump();); - bool bResult = false; + bool bResult = false; // A response should be the result of a query or a probe - if ((_hasServiceQueriesWaitingForAnswers()) || // Waiting for query answers OR - (_hasProbesWaitingForAnswers())) // Probe responses + if ((_hasServiceQueriesWaitingForAnswers()) || // Waiting for query answers OR + (_hasProbesWaitingForAnswers())) // Probe responses { - DEBUG_EX_INFO( DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse: Received a response\n")); //_udpDump(); @@ -639,22 +616,22 @@ bool MDNSResponder::_parseResponse(const MDNSResponder::stcMDNS_MsgHeader& p_Msg bResult = true; // // Ignore questions here - stcMDNS_RRQuestion dummyRRQ; + stcMDNS_RRQuestion dummyRRQ; for (uint16_t qd = 0; ((bResult) && (qd < p_MsgHeader.m_u16QDCount)); ++qd) { DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse: Received a response containing a question... ignoring!\n"));); bResult = _readRRQuestion(dummyRRQ); - } // for queries + } // for queries // // Read and collect answers - stcMDNS_RRAnswer* pCollectedRRAnswers = 0; - uint32_t u32NumberOfAnswerRRs = (p_MsgHeader.m_u16ANCount + p_MsgHeader.m_u16NSCount + p_MsgHeader.m_u16ARCount); + stcMDNS_RRAnswer* pCollectedRRAnswers = 0; + uint32_t u32NumberOfAnswerRRs = (p_MsgHeader.m_u16ANCount + p_MsgHeader.m_u16NSCount + p_MsgHeader.m_u16ARCount); for (uint32_t an = 0; ((bResult) && (an < u32NumberOfAnswerRRs)); ++an) { - stcMDNS_RRAnswer* pRRAnswer = 0; + stcMDNS_RRAnswer* pRRAnswer = 0; if (((bResult = _readRRAnswer(pRRAnswer))) && - (pRRAnswer)) + (pRRAnswer)) { //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse: ADDING answer!\n"));); pRRAnswer->m_pNext = pCollectedRRAnswers; @@ -670,7 +647,7 @@ bool MDNSResponder::_parseResponse(const MDNSResponder::stcMDNS_MsgHeader& p_Msg } bResult = false; } - } // for answers + } // for answers // // Process answers @@ -679,7 +656,7 @@ bool MDNSResponder::_parseResponse(const MDNSResponder::stcMDNS_MsgHeader& p_Msg bResult = ((!pCollectedRRAnswers) || (_processAnswers(pCollectedRRAnswers))); } - else // Some failure while reading answers + else // Some failure while reading answers { DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse: FAILED to read answers!\n"));); m_pUDPContext->flush(); @@ -689,12 +666,12 @@ bool MDNSResponder::_parseResponse(const MDNSResponder::stcMDNS_MsgHeader& p_Msg while (pCollectedRRAnswers) { //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse: DELETING answer!\n"));); - stcMDNS_RRAnswer* pNextAnswer = pCollectedRRAnswers->m_pNext; + stcMDNS_RRAnswer* pNextAnswer = pCollectedRRAnswers->m_pNext; delete pCollectedRRAnswers; pCollectedRRAnswers = pNextAnswer; } } - else // Received an unexpected response -> ignore + else // Received an unexpected response -> ignore { /* DEBUG_EX_INFO( DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse: Received an unexpected response... ignoring!\nDUMP:\n")); @@ -720,9 +697,9 @@ bool MDNSResponder::_parseResponse(const MDNSResponder::stcMDNS_MsgHeader& p_Msg bResult = true; } DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse: FAILED!\n")); + }); return bResult; } @@ -742,8 +719,7 @@ bool MDNSResponder::_parseResponse(const MDNSResponder::stcMDNS_MsgHeader& p_Msg */ bool MDNSResponder::_processAnswers(const MDNSResponder::stcMDNS_RRAnswer* p_pAnswers) { - - bool bResult = false; + bool bResult = false; if (p_pAnswers) { @@ -752,27 +728,27 @@ bool MDNSResponder::_processAnswers(const MDNSResponder::stcMDNS_RRAnswer* p_pAn // Answers may arrive in an unexpected order. So we loop our answers as long, as we // can connect new information to service queries - bool bFoundNewKeyAnswer; + bool bFoundNewKeyAnswer; do { bFoundNewKeyAnswer = false; const stcMDNS_RRAnswer* pRRAnswer = p_pAnswers; while ((pRRAnswer) && - (bResult)) + (bResult)) { // 1. level answer (PTR) if (AnswerType_PTR == pRRAnswer->answerType()) { // eg. _http._tcp.local PTR xxxx xx MyESP._http._tcp.local - bResult = _processPTRAnswer((stcMDNS_RRAnswerPTR*)pRRAnswer, bFoundNewKeyAnswer); // May 'enable' new SRV or TXT answers to be linked to queries + bResult = _processPTRAnswer((stcMDNS_RRAnswerPTR*)pRRAnswer, bFoundNewKeyAnswer); // May 'enable' new SRV or TXT answers to be linked to queries } // 2. level answers // SRV -> host domain and port else if (AnswerType_SRV == pRRAnswer->answerType()) { // eg. MyESP_http._tcp.local SRV xxxx xx yy zz 5000 esp8266.local - bResult = _processSRVAnswer((stcMDNS_RRAnswerSRV*)pRRAnswer, bFoundNewKeyAnswer); // May 'enable' new A/AAAA answers to be linked to queries + bResult = _processSRVAnswer((stcMDNS_RRAnswerSRV*)pRRAnswer, bFoundNewKeyAnswer); // May 'enable' new A/AAAA answers to be linked to queries } // TXT -> Txts else if (AnswerType_TXT == pRRAnswer->answerType()) @@ -801,15 +777,13 @@ bool MDNSResponder::_processAnswers(const MDNSResponder::stcMDNS_RRAnswer* p_pAn // Finally check for probing conflicts // Host domain if ((ProbingStatus_InProgress == m_HostProbeInformation.m_ProbingStatus) && - ((AnswerType_A == pRRAnswer->answerType()) || - (AnswerType_AAAA == pRRAnswer->answerType()))) + ((AnswerType_A == pRRAnswer->answerType()) || + (AnswerType_AAAA == pRRAnswer->answerType()))) { - - stcMDNS_RRDomain hostDomain; + stcMDNS_RRDomain hostDomain; if ((_buildDomainForHost(m_pcHostname, hostDomain)) && - (pRRAnswer->m_Header.m_Domain == hostDomain)) + (pRRAnswer->m_Header.m_Domain == hostDomain)) { - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAnswers: Probing CONFLICT found with: %s.local\n"), m_pcHostname);); _cancelProbingForHost(); } @@ -818,30 +792,28 @@ bool MDNSResponder::_processAnswers(const MDNSResponder::stcMDNS_RRAnswer* p_pAn for (stcMDNSService* pService = m_pServices; pService; pService = pService->m_pNext) { if ((ProbingStatus_InProgress == pService->m_ProbeInformation.m_ProbingStatus) && - ((AnswerType_TXT == pRRAnswer->answerType()) || - (AnswerType_SRV == pRRAnswer->answerType()))) + ((AnswerType_TXT == pRRAnswer->answerType()) || + (AnswerType_SRV == pRRAnswer->answerType()))) { - - stcMDNS_RRDomain serviceDomain; + stcMDNS_RRDomain serviceDomain; if ((_buildDomainForService(*pService, true, serviceDomain)) && - (pRRAnswer->m_Header.m_Domain == serviceDomain)) + (pRRAnswer->m_Header.m_Domain == serviceDomain)) { - - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAnswers: Probing CONFLICT found with: %s.%s.%s\n"), (pService->m_pcName ? : m_pcHostname), pService->m_pcService, pService->m_pcProtocol);); + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAnswers: Probing CONFLICT found with: %s.%s.%s\n"), (pService->m_pcName ?: m_pcHostname), pService->m_pcService, pService->m_pcProtocol);); _cancelProbingForService(*pService); } } } - pRRAnswer = pRRAnswer->m_pNext; // Next collected answer - } // while (answers) + pRRAnswer = pRRAnswer->m_pNext; // Next collected answer + } // while (answers) } while ((bFoundNewKeyAnswer) && (bResult)); - } // else: No answers provided + } // else: No answers provided DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAnswers: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAnswers: FAILED!\n")); + }); return bResult; } @@ -851,8 +823,7 @@ bool MDNSResponder::_processAnswers(const MDNSResponder::stcMDNS_RRAnswer* p_pAn bool MDNSResponder::_processPTRAnswer(const MDNSResponder::stcMDNS_RRAnswerPTR* p_pPTRAnswer, bool& p_rbFoundNewKeyAnswer) { - - bool bResult = false; + bool bResult = false; if ((bResult = (0 != p_pPTRAnswer))) { @@ -860,36 +831,34 @@ bool MDNSResponder::_processPTRAnswer(const MDNSResponder::stcMDNS_RRAnswerPTR* // eg. _http._tcp.local PTR xxxx xx MyESP._http._tcp.local // Check pending service queries for eg. '_http._tcp' - stcMDNSServiceQuery* pServiceQuery = _findNextServiceQueryByServiceType(p_pPTRAnswer->m_Header.m_Domain, 0); + stcMDNSServiceQuery* pServiceQuery = _findNextServiceQueryByServiceType(p_pPTRAnswer->m_Header.m_Domain, 0); while (pServiceQuery) { if (pServiceQuery->m_bAwaitingAnswers) { // Find answer for service domain (eg. MyESP._http._tcp.local) stcMDNSServiceQuery::stcAnswer* pSQAnswer = pServiceQuery->findAnswerForServiceDomain(p_pPTRAnswer->m_PTRDomain); - if (pSQAnswer) // existing answer + if (pSQAnswer) // existing answer { - if (p_pPTRAnswer->m_u32TTL) // Received update message + if (p_pPTRAnswer->m_u32TTL) // Received update message { - pSQAnswer->m_TTLServiceDomain.set(p_pPTRAnswer->m_u32TTL); // Update TTL tag + pSQAnswer->m_TTLServiceDomain.set(p_pPTRAnswer->m_u32TTL); // Update TTL tag DEBUG_EX_INFO( DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processPTRAnswer: Updated TTL(%d) for "), (int)p_pPTRAnswer->m_u32TTL); _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR("\n")); - ); + DEBUG_OUTPUT.printf_P(PSTR("\n"));); } - else // received goodbye-message + else // received goodbye-message { - pSQAnswer->m_TTLServiceDomain.prepareDeletion(); // Prepare answer deletion according to RFC 6762, 10.1 + pSQAnswer->m_TTLServiceDomain.prepareDeletion(); // Prepare answer deletion according to RFC 6762, 10.1 DEBUG_EX_INFO( DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processPTRAnswer: 'Goodbye' received for ")); _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR("\n")); - ); + DEBUG_OUTPUT.printf_P(PSTR("\n"));); } } - else if ((p_pPTRAnswer->m_u32TTL) && // Not just a goodbye-message - ((pSQAnswer = new stcMDNSServiceQuery::stcAnswer))) // Not yet included -> add answer + else if ((p_pPTRAnswer->m_u32TTL) && // Not just a goodbye-message + ((pSQAnswer = new stcMDNSServiceQuery::stcAnswer))) // Not yet included -> add answer { pSQAnswer->m_ServiceDomain = p_pPTRAnswer->m_PTRDomain; pSQAnswer->m_u32ContentFlags |= ServiceQueryAnswerType_ServiceDomain; @@ -907,11 +876,11 @@ bool MDNSResponder::_processPTRAnswer(const MDNSResponder::stcMDNS_RRAnswerPTR* } pServiceQuery = _findNextServiceQueryByServiceType(p_pPTRAnswer->m_Header.m_Domain, pServiceQuery); } - } // else: No p_pPTRAnswer + } // else: No p_pPTRAnswer DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processPTRAnswer: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processPTRAnswer: FAILED!\n")); + }); return bResult; } @@ -921,32 +890,29 @@ bool MDNSResponder::_processPTRAnswer(const MDNSResponder::stcMDNS_RRAnswerPTR* bool MDNSResponder::_processSRVAnswer(const MDNSResponder::stcMDNS_RRAnswerSRV* p_pSRVAnswer, bool& p_rbFoundNewKeyAnswer) { - - bool bResult = false; + bool bResult = false; if ((bResult = (0 != p_pSRVAnswer))) { // eg. MyESP._http._tcp.local SRV xxxx xx yy zz 5000 esp8266.local - stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; + stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; while (pServiceQuery) { stcMDNSServiceQuery::stcAnswer* pSQAnswer = pServiceQuery->findAnswerForServiceDomain(p_pSRVAnswer->m_Header.m_Domain); - if (pSQAnswer) // Answer for this service domain (eg. MyESP._http._tcp.local) available + if (pSQAnswer) // Answer for this service domain (eg. MyESP._http._tcp.local) available { - if (p_pSRVAnswer->m_u32TTL) // First or update message (TTL != 0) + if (p_pSRVAnswer->m_u32TTL) // First or update message (TTL != 0) { - pSQAnswer->m_TTLHostDomainAndPort.set(p_pSRVAnswer->m_u32TTL); // Update TTL tag + pSQAnswer->m_TTLHostDomainAndPort.set(p_pSRVAnswer->m_u32TTL); // Update TTL tag DEBUG_EX_INFO( DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processSRVAnswer: Updated TTL(%d) for "), (int)p_pSRVAnswer->m_u32TTL); _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR(" host domain and port\n")); - ); + DEBUG_OUTPUT.printf_P(PSTR(" host domain and port\n"));); // Host domain & Port if ((pSQAnswer->m_HostDomain != p_pSRVAnswer->m_SRVDomain) || - (pSQAnswer->m_u16Port != p_pSRVAnswer->m_u16Port)) + (pSQAnswer->m_u16Port != p_pSRVAnswer->m_u16Port)) { - pSQAnswer->m_HostDomain = p_pSRVAnswer->m_SRVDomain; pSQAnswer->releaseHostDomain(); pSQAnswer->m_u16Port = p_pSRVAnswer->m_u16Port; @@ -960,23 +926,22 @@ bool MDNSResponder::_processSRVAnswer(const MDNSResponder::stcMDNS_RRAnswerSRV* } } } - else // Goodby message + else // Goodby message { - pSQAnswer->m_TTLHostDomainAndPort.prepareDeletion(); // Prepare answer deletion according to RFC 6762, 10.1 + pSQAnswer->m_TTLHostDomainAndPort.prepareDeletion(); // Prepare answer deletion according to RFC 6762, 10.1 DEBUG_EX_INFO( DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processSRVAnswer: 'Goodbye' received for ")); _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR(" host domain and port\n")); - ); + DEBUG_OUTPUT.printf_P(PSTR(" host domain and port\n"));); } } pServiceQuery = pServiceQuery->m_pNext; - } // while(service query) - } // else: No p_pSRVAnswer + } // while(service query) + } // else: No p_pSRVAnswer DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processSRVAnswer: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processSRVAnswer: FAILED!\n")); + }); return bResult; } @@ -985,27 +950,25 @@ bool MDNSResponder::_processSRVAnswer(const MDNSResponder::stcMDNS_RRAnswerSRV* */ bool MDNSResponder::_processTXTAnswer(const MDNSResponder::stcMDNS_RRAnswerTXT* p_pTXTAnswer) { - - bool bResult = false; + bool bResult = false; if ((bResult = (0 != p_pTXTAnswer))) { // eg. MyESP._http._tcp.local TXT xxxx xx c#=1 - stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; + stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; while (pServiceQuery) { stcMDNSServiceQuery::stcAnswer* pSQAnswer = pServiceQuery->findAnswerForServiceDomain(p_pTXTAnswer->m_Header.m_Domain); - if (pSQAnswer) // Answer for this service domain (eg. MyESP._http._tcp.local) available + if (pSQAnswer) // Answer for this service domain (eg. MyESP._http._tcp.local) available { - if (p_pTXTAnswer->m_u32TTL) // First or update message + if (p_pTXTAnswer->m_u32TTL) // First or update message { - pSQAnswer->m_TTLTxts.set(p_pTXTAnswer->m_u32TTL); // Update TTL tag + pSQAnswer->m_TTLTxts.set(p_pTXTAnswer->m_u32TTL); // Update TTL tag DEBUG_EX_INFO( DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processTXTAnswer: Updated TTL(%d) for "), (int)p_pTXTAnswer->m_u32TTL); _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR(" TXTs\n")); - ); + DEBUG_OUTPUT.printf_P(PSTR(" TXTs\n"));); if (!pSQAnswer->m_Txts.compare(p_pTXTAnswer->m_Txts)) { pSQAnswer->m_Txts = p_pTXTAnswer->m_Txts; @@ -1019,23 +982,22 @@ bool MDNSResponder::_processTXTAnswer(const MDNSResponder::stcMDNS_RRAnswerTXT* } } } - else // Goodby message + else // Goodby message { - pSQAnswer->m_TTLTxts.prepareDeletion(); // Prepare answer deletion according to RFC 6762, 10.1 + pSQAnswer->m_TTLTxts.prepareDeletion(); // Prepare answer deletion according to RFC 6762, 10.1 DEBUG_EX_INFO( DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processTXTAnswer: 'Goodbye' received for ")); _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR(" TXTs\n")); - ); + DEBUG_OUTPUT.printf_P(PSTR(" TXTs\n"));); } } pServiceQuery = pServiceQuery->m_pNext; - } // while(service query) - } // else: No p_pTXTAnswer + } // while(service query) + } // else: No p_pTXTAnswer DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processTXTAnswer: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processTXTAnswer: FAILED!\n")); + }); return bResult; } @@ -1045,52 +1007,48 @@ bool MDNSResponder::_processTXTAnswer(const MDNSResponder::stcMDNS_RRAnswerTXT* */ bool MDNSResponder::_processAAnswer(const MDNSResponder::stcMDNS_RRAnswerA* p_pAAnswer) { - - bool bResult = false; + bool bResult = false; if ((bResult = (0 != p_pAAnswer))) { // eg. esp8266.local A xxxx xx 192.168.2.120 - stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; + stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; while (pServiceQuery) { stcMDNSServiceQuery::stcAnswer* pSQAnswer = pServiceQuery->findAnswerForHostDomain(p_pAAnswer->m_Header.m_Domain); - if (pSQAnswer) // Answer for this host domain (eg. esp8266.local) available + if (pSQAnswer) // Answer for this host domain (eg. esp8266.local) available { - stcMDNSServiceQuery::stcAnswer::stcIP4Address* pIP4Address = pSQAnswer->findIP4Address(p_pAAnswer->m_IPAddress); + stcMDNSServiceQuery::stcAnswer::stcIP4Address* pIP4Address = pSQAnswer->findIP4Address(p_pAAnswer->m_IPAddress); if (pIP4Address) { // Already known IP4 address - if (p_pAAnswer->m_u32TTL) // Valid TTL -> Update answers TTL + if (p_pAAnswer->m_u32TTL) // Valid TTL -> Update answers TTL { pIP4Address->m_TTL.set(p_pAAnswer->m_u32TTL); DEBUG_EX_INFO( DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAAnswer: Updated TTL(%d) for "), (int)p_pAAnswer->m_u32TTL); _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR(" IP4Address (%s)\n"), pIP4Address->m_IPAddress.toString().c_str()); - ); + DEBUG_OUTPUT.printf_P(PSTR(" IP4Address (%s)\n"), pIP4Address->m_IPAddress.toString().c_str());); } - else // 'Goodbye' message for known IP4 address + else // 'Goodbye' message for known IP4 address { - pIP4Address->m_TTL.prepareDeletion(); // Prepare answer deletion according to RFC 6762, 10.1 + pIP4Address->m_TTL.prepareDeletion(); // Prepare answer deletion according to RFC 6762, 10.1 DEBUG_EX_INFO( DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAAnswer: 'Goodbye' received for ")); _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR(" IP4 address (%s)\n"), pIP4Address->m_IPAddress.toString().c_str()); - ); + DEBUG_OUTPUT.printf_P(PSTR(" IP4 address (%s)\n"), pIP4Address->m_IPAddress.toString().c_str());); } } else { // Until now unknown IP4 address -> Add (if the message isn't just a 'Goodbye' note) - if (p_pAAnswer->m_u32TTL) // NOT just a 'Goodbye' message + if (p_pAAnswer->m_u32TTL) // NOT just a 'Goodbye' message { pIP4Address = new stcMDNSServiceQuery::stcAnswer::stcIP4Address(p_pAAnswer->m_IPAddress, p_pAAnswer->m_u32TTL); if ((pIP4Address) && - (pSQAnswer->addIP4Address(pIP4Address))) + (pSQAnswer->addIP4Address(pIP4Address))) { - pSQAnswer->m_u32ContentFlags |= ServiceQueryAnswerType_IP4Address; if (pServiceQuery->m_fnCallback) { @@ -1106,12 +1064,12 @@ bool MDNSResponder::_processAAnswer(const MDNSResponder::stcMDNS_RRAnswerA* p_pA } } pServiceQuery = pServiceQuery->m_pNext; - } // while(service query) - } // else: No p_pAAnswer + } // while(service query) + } // else: No p_pAAnswer DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAAnswer: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAAnswer: FAILED!\n")); + }); return bResult; } #endif @@ -1122,52 +1080,48 @@ bool MDNSResponder::_processAAnswer(const MDNSResponder::stcMDNS_RRAnswerA* p_pA */ bool MDNSResponder::_processAAAAAnswer(const MDNSResponder::stcMDNS_RRAnswerAAAA* p_pAAAAAnswer) { - - bool bResult = false; + bool bResult = false; if ((bResult = (0 != p_pAAAAAnswer))) { // eg. esp8266.local AAAA xxxx xx 0bf3::0c - stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; + stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; while (pServiceQuery) { stcMDNSServiceQuery::stcAnswer* pSQAnswer = pServiceQuery->findAnswerForHostDomain(p_pAAAAAnswer->m_Header.m_Domain); - if (pSQAnswer) // Answer for this host domain (eg. esp8266.local) available + if (pSQAnswer) // Answer for this host domain (eg. esp8266.local) available { - stcIP6Address* pIP6Address = pSQAnswer->findIP6Address(p_pAAAAAnswer->m_IPAddress); + stcIP6Address* pIP6Address = pSQAnswer->findIP6Address(p_pAAAAAnswer->m_IPAddress); if (pIP6Address) { // Already known IP6 address - if (p_pAAAAAnswer->m_u32TTL) // Valid TTL -> Update answers TTL + if (p_pAAAAAnswer->m_u32TTL) // Valid TTL -> Update answers TTL { pIP6Address->m_TTL.set(p_pAAAAAnswer->m_u32TTL); DEBUG_EX_INFO( DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAAnswer: Updated TTL(%lu) for "), p_pAAAAAnswer->m_u32TTL); _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR(" IP6 address (%s)\n"), pIP6Address->m_IPAddress.toString().c_str()); - ); + DEBUG_OUTPUT.printf_P(PSTR(" IP6 address (%s)\n"), pIP6Address->m_IPAddress.toString().c_str());); } - else // 'Goodbye' message for known IP6 address + else // 'Goodbye' message for known IP6 address { - pIP6Address->m_TTL.prepareDeletion(); // Prepare answer deletion according to RFC 6762, 10.1 + pIP6Address->m_TTL.prepareDeletion(); // Prepare answer deletion according to RFC 6762, 10.1 DEBUG_EX_INFO( DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAAnswer: 'Goodbye' received for ")); _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR(" IP6 address (%s)\n"), pIP6Address->m_IPAddress.toString().c_str()); - ); + DEBUG_OUTPUT.printf_P(PSTR(" IP6 address (%s)\n"), pIP6Address->m_IPAddress.toString().c_str());); } } else { // Until now unknown IP6 address -> Add (if the message isn't just a 'Goodbye' note) - if (p_pAAAAAnswer->m_u32TTL) // NOT just a 'Goodbye' message + if (p_pAAAAAnswer->m_u32TTL) // NOT just a 'Goodbye' message { pIP6Address = new stcIP6Address(p_pAAAAAnswer->m_IPAddress, p_pAAAAAnswer->m_u32TTL); if ((pIP6Address) && - (pSQAnswer->addIP6Address(pIP6Address))) + (pSQAnswer->addIP6Address(pIP6Address))) { - pSQAnswer->m_u32ContentFlags |= ServiceQueryAnswerType_IP6Address; if (pServiceQuery->m_fnCallback) @@ -1183,14 +1137,13 @@ bool MDNSResponder::_processAAAAAnswer(const MDNSResponder::stcMDNS_RRAnswerAAAA } } pServiceQuery = pServiceQuery->m_pNext; - } // while(service query) - } // else: No p_pAAAAAnswer + } // while(service query) + } // else: No p_pAAAAAnswer return bResult; } #endif - /* PROBING */ @@ -1209,8 +1162,7 @@ bool MDNSResponder::_processAAAAAnswer(const MDNSResponder::stcMDNS_RRAnswerAAAA */ bool MDNSResponder::_updateProbeStatus(void) { - - bool bResult = true; + bool bResult = true; // // Probe host domain @@ -1222,11 +1174,10 @@ bool MDNSResponder::_updateProbeStatus(void) m_HostProbeInformation.m_Timeout.reset(rand() % MDNS_PROBE_DELAY); m_HostProbeInformation.m_ProbingStatus = ProbingStatus_InProgress; } - else if ((ProbingStatus_InProgress == m_HostProbeInformation.m_ProbingStatus) && // Probing AND - (m_HostProbeInformation.m_Timeout.expired())) // Time for next probe + else if ((ProbingStatus_InProgress == m_HostProbeInformation.m_ProbingStatus) && // Probing AND + (m_HostProbeInformation.m_Timeout.expired())) // Time for next probe { - - if (MDNS_PROBE_COUNT > m_HostProbeInformation.m_u8SentCount) // Send next probe + if (MDNS_PROBE_COUNT > m_HostProbeInformation.m_u8SentCount) // Send next probe { if ((bResult = _sendHostProbe())) { @@ -1235,7 +1186,7 @@ bool MDNSResponder::_updateProbeStatus(void) ++m_HostProbeInformation.m_u8SentCount; } } - else // Probing finished + else // Probing finished { DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Done host probing.\n"));); m_HostProbeInformation.m_ProbingStatus = ProbingStatus_Done; @@ -1250,12 +1201,11 @@ bool MDNSResponder::_updateProbeStatus(void) m_HostProbeInformation.m_Timeout.reset(MDNS_ANNOUNCE_DELAY); DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Prepared host announcing.\n\n"));); } - } // else: Probing already finished OR waiting for next time slot + } // else: Probing already finished OR waiting for next time slot else if ((ProbingStatus_Done == m_HostProbeInformation.m_ProbingStatus) && (m_HostProbeInformation.m_Timeout.expired())) { - - if ((bResult = _announce(true, false))) // Don't announce services here + if ((bResult = _announce(true, false))) // Don't announce services here { ++m_HostProbeInformation.m_u8SentCount; @@ -1276,17 +1226,15 @@ bool MDNSResponder::_updateProbeStatus(void) // Probe services for (stcMDNSService* pService = m_pServices; ((bResult) && (pService)); pService = pService->m_pNext) { - if (ProbingStatus_ReadyToStart == pService->m_ProbeInformation.m_ProbingStatus) // Ready to get started + if (ProbingStatus_ReadyToStart == pService->m_ProbeInformation.m_ProbingStatus) // Ready to get started { - - pService->m_ProbeInformation.m_Timeout.reset(MDNS_PROBE_DELAY); // More or equal than first probe for host domain + pService->m_ProbeInformation.m_Timeout.reset(MDNS_PROBE_DELAY); // More or equal than first probe for host domain pService->m_ProbeInformation.m_ProbingStatus = ProbingStatus_InProgress; } else if ((ProbingStatus_InProgress == pService->m_ProbeInformation.m_ProbingStatus) && // Probing AND - (pService->m_ProbeInformation.m_Timeout.expired())) // Time for next probe + (pService->m_ProbeInformation.m_Timeout.expired())) // Time for next probe { - - if (MDNS_PROBE_COUNT > pService->m_ProbeInformation.m_u8SentCount) // Send next probe + if (MDNS_PROBE_COUNT > pService->m_ProbeInformation.m_u8SentCount) // Send next probe { if ((bResult = _sendServiceProbe(*pService))) { @@ -1295,9 +1243,9 @@ bool MDNSResponder::_updateProbeStatus(void) ++pService->m_ProbeInformation.m_u8SentCount; } } - else // Probing finished + else // Probing finished { - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Done service probing %s.%s.%s\n\n"), (pService->m_pcName ? : m_pcHostname), pService->m_pcService, pService->m_pcProtocol);); + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Done service probing %s.%s.%s\n\n"), (pService->m_pcName ?: m_pcHostname), pService->m_pcService, pService->m_pcProtocol);); pService->m_ProbeInformation.m_ProbingStatus = ProbingStatus_Done; pService->m_ProbeInformation.m_Timeout.resetToNeverExpires(); if (pService->m_ProbeInformation.m_fnServiceProbeResultCallback) @@ -1309,32 +1257,31 @@ bool MDNSResponder::_updateProbeStatus(void) pService->m_ProbeInformation.m_Timeout.reset(MDNS_ANNOUNCE_DELAY); DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Prepared service announcing.\n\n"));); } - } // else: Probing already finished OR waiting for next time slot + } // else: Probing already finished OR waiting for next time slot else if ((ProbingStatus_Done == pService->m_ProbeInformation.m_ProbingStatus) && (pService->m_ProbeInformation.m_Timeout.expired())) { - - if ((bResult = _announceService(*pService))) // Announce service + if ((bResult = _announceService(*pService))) // Announce service { ++pService->m_ProbeInformation.m_u8SentCount; if (MDNS_ANNOUNCE_COUNT > pService->m_ProbeInformation.m_u8SentCount) { pService->m_ProbeInformation.m_Timeout.reset(MDNS_ANNOUNCE_DELAY); - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Announcing service %s.%s.%s (%d)\n\n"), (pService->m_pcName ? : m_pcHostname), pService->m_pcService, pService->m_pcProtocol, pService->m_ProbeInformation.m_u8SentCount);); + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Announcing service %s.%s.%s (%d)\n\n"), (pService->m_pcName ?: m_pcHostname), pService->m_pcService, pService->m_pcProtocol, pService->m_ProbeInformation.m_u8SentCount);); } else { pService->m_ProbeInformation.m_Timeout.resetToNeverExpires(); - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Done service announcing for %s.%s.%s\n\n"), (pService->m_pcName ? : m_pcHostname), pService->m_pcService, pService->m_pcProtocol);); + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Done service announcing for %s.%s.%s\n\n"), (pService->m_pcName ?: m_pcHostname), pService->m_pcService, pService->m_pcProtocol);); } } } } DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: FAILED!\n\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: FAILED!\n\n")); + }); return bResult; } @@ -1348,7 +1295,6 @@ bool MDNSResponder::_updateProbeStatus(void) */ bool MDNSResponder::_resetProbeStatus(bool p_bRestart /*= true*/) { - m_HostProbeInformation.clear(false); m_HostProbeInformation.m_ProbingStatus = (p_bRestart ? ProbingStatus_ReadyToStart : ProbingStatus_Done); @@ -1365,14 +1311,13 @@ bool MDNSResponder::_resetProbeStatus(bool p_bRestart /*= true*/) */ bool MDNSResponder::_hasProbesWaitingForAnswers(void) const { - - bool bResult = ((ProbingStatus_InProgress == m_HostProbeInformation.m_ProbingStatus) && // Probing - (0 < m_HostProbeInformation.m_u8SentCount)); // And really probing + bool bResult = ((ProbingStatus_InProgress == m_HostProbeInformation.m_ProbingStatus) && // Probing + (0 < m_HostProbeInformation.m_u8SentCount)); // And really probing for (stcMDNSService* pService = m_pServices; ((!bResult) && (pService)); pService = pService->m_pNext) { - bResult = ((ProbingStatus_InProgress == pService->m_ProbeInformation.m_ProbingStatus) && // Probing - (0 < pService->m_ProbeInformation.m_u8SentCount)); // And really probing + bResult = ((ProbingStatus_InProgress == pService->m_ProbeInformation.m_ProbingStatus) && // Probing + (0 < pService->m_ProbeInformation.m_u8SentCount)); // And really probing } return bResult; } @@ -1392,27 +1337,26 @@ bool MDNSResponder::_sendHostProbe(void) { DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendHostProbe (%s, %lu)\n"), m_pcHostname, millis());); - bool bResult = true; + bool bResult = true; // Requests for host domain - stcMDNSSendParameter sendParameter; - sendParameter.m_bCacheFlush = false; // RFC 6762 10.2 + stcMDNSSendParameter sendParameter; + sendParameter.m_bCacheFlush = false; // RFC 6762 10.2 sendParameter.m_pQuestions = new stcMDNS_RRQuestion; if (((bResult = (0 != sendParameter.m_pQuestions))) && - ((bResult = _buildDomainForHost(m_pcHostname, sendParameter.m_pQuestions->m_Header.m_Domain)))) + ((bResult = _buildDomainForHost(m_pcHostname, sendParameter.m_pQuestions->m_Header.m_Domain)))) { - //sendParameter.m_pQuestions->m_bUnicast = true; sendParameter.m_pQuestions->m_Header.m_Attributes.m_u16Type = DNS_RRTYPE_ANY; - sendParameter.m_pQuestions->m_Header.m_Attributes.m_u16Class = (0x8000 | DNS_RRCLASS_IN); // Unicast & INternet + sendParameter.m_pQuestions->m_Header.m_Attributes.m_u16Class = (0x8000 | DNS_RRCLASS_IN); // Unicast & INternet // Add known answers #ifdef MDNS_IP4_SUPPORT - sendParameter.m_u8HostReplyMask |= ContentFlag_A; // Add A answer + sendParameter.m_u8HostReplyMask |= ContentFlag_A; // Add A answer #endif #ifdef MDNS_IP6_SUPPORT - sendParameter.m_u8HostReplyMask |= ContentFlag_AAAA; // Add AAAA answer + sendParameter.m_u8HostReplyMask |= ContentFlag_AAAA; // Add AAAA answer #endif } else @@ -1425,9 +1369,9 @@ bool MDNSResponder::_sendHostProbe(void) } } DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendHostProbe: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendHostProbe: FAILED!\n")); + }); return ((bResult) && (_sendMDNSMessage(sendParameter))); } @@ -1446,25 +1390,24 @@ bool MDNSResponder::_sendHostProbe(void) */ bool MDNSResponder::_sendServiceProbe(stcMDNSService& p_rService) { - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendServiceProbe (%s.%s.%s, %lu)\n"), (p_rService.m_pcName ? : m_pcHostname), p_rService.m_pcService, p_rService.m_pcProtocol, millis());); + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendServiceProbe (%s.%s.%s, %lu)\n"), (p_rService.m_pcName ?: m_pcHostname), p_rService.m_pcService, p_rService.m_pcProtocol, millis());); - bool bResult = true; + bool bResult = true; // Requests for service instance domain - stcMDNSSendParameter sendParameter; - sendParameter.m_bCacheFlush = false; // RFC 6762 10.2 + stcMDNSSendParameter sendParameter; + sendParameter.m_bCacheFlush = false; // RFC 6762 10.2 sendParameter.m_pQuestions = new stcMDNS_RRQuestion; if (((bResult = (0 != sendParameter.m_pQuestions))) && - ((bResult = _buildDomainForService(p_rService, true, sendParameter.m_pQuestions->m_Header.m_Domain)))) + ((bResult = _buildDomainForService(p_rService, true, sendParameter.m_pQuestions->m_Header.m_Domain)))) { - sendParameter.m_pQuestions->m_bUnicast = true; sendParameter.m_pQuestions->m_Header.m_Attributes.m_u16Type = DNS_RRTYPE_ANY; - sendParameter.m_pQuestions->m_Header.m_Attributes.m_u16Class = (0x8000 | DNS_RRCLASS_IN); // Unicast & INternet + sendParameter.m_pQuestions->m_Header.m_Attributes.m_u16Class = (0x8000 | DNS_RRCLASS_IN); // Unicast & INternet // Add known answers - p_rService.m_u8ReplyMask = (ContentFlag_SRV | ContentFlag_PTR_NAME); // Add SRV and PTR NAME answers + p_rService.m_u8ReplyMask = (ContentFlag_SRV | ContentFlag_PTR_NAME); // Add SRV and PTR NAME answers } else { @@ -1476,9 +1419,9 @@ bool MDNSResponder::_sendServiceProbe(stcMDNSService& p_rService) } } DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendServiceProbe: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendServiceProbe: FAILED!\n")); + }); return ((bResult) && (_sendMDNSMessage(sendParameter))); } @@ -1488,8 +1431,7 @@ bool MDNSResponder::_sendServiceProbe(stcMDNSService& p_rService) */ bool MDNSResponder::_cancelProbingForHost(void) { - - bool bResult = false; + bool bResult = false; m_HostProbeInformation.clear(false); // Send host notification @@ -1512,8 +1454,7 @@ bool MDNSResponder::_cancelProbingForHost(void) */ bool MDNSResponder::_cancelProbingForService(stcMDNSService& p_rService) { - - bool bResult = false; + bool bResult = false; p_rService.m_ProbeInformation.clear(false); // Send notification @@ -1525,8 +1466,6 @@ bool MDNSResponder::_cancelProbingForService(stcMDNSService& p_rService) return bResult; } - - /** ANNOUNCING */ @@ -1551,28 +1490,26 @@ bool MDNSResponder::_cancelProbingForService(stcMDNSService& p_rService) bool MDNSResponder::_announce(bool p_bAnnounce, bool p_bIncludeServices) { + bool bResult = false; - bool bResult = false; - - stcMDNSSendParameter sendParameter; + stcMDNSSendParameter sendParameter; if (ProbingStatus_Done == m_HostProbeInformation.m_ProbingStatus) { - bResult = true; - sendParameter.m_bResponse = true; // Announces are 'Unsolicited authoritative responses' + sendParameter.m_bResponse = true; // Announces are 'Unsolicited authoritative responses' sendParameter.m_bAuthorative = true; - sendParameter.m_bUnannounce = !p_bAnnounce; // When unannouncing, the TTL is set to '0' while creating the answers + sendParameter.m_bUnannounce = !p_bAnnounce; // When unannouncing, the TTL is set to '0' while creating the answers // Announce host sendParameter.m_u8HostReplyMask = 0; #ifdef MDNS_IP4_SUPPORT - sendParameter.m_u8HostReplyMask |= ContentFlag_A; // A answer - sendParameter.m_u8HostReplyMask |= ContentFlag_PTR_IP4; // PTR_IP4 answer + sendParameter.m_u8HostReplyMask |= ContentFlag_A; // A answer + sendParameter.m_u8HostReplyMask |= ContentFlag_PTR_IP4; // PTR_IP4 answer #endif #ifdef MDNS_IP6_SUPPORT - sendParameter.m_u8HostReplyMask |= ContentFlag_AAAA; // AAAA answer - sendParameter.m_u8HostReplyMask |= ContentFlag_PTR_IP6; // PTR_IP6 answer + sendParameter.m_u8HostReplyMask |= ContentFlag_AAAA; // AAAA answer + sendParameter.m_u8HostReplyMask |= ContentFlag_PTR_IP6; // PTR_IP6 answer #endif DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _announce: Announcing host %s (content 0x%X)\n"), m_pcHostname, sendParameter.m_u8HostReplyMask);); @@ -1586,15 +1523,15 @@ bool MDNSResponder::_announce(bool p_bAnnounce, { pService->m_u8ReplyMask = (ContentFlag_PTR_TYPE | ContentFlag_PTR_NAME | ContentFlag_SRV | ContentFlag_TXT); - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _announce: Announcing service %s.%s.%s (content %u)\n"), (pService->m_pcName ? : m_pcHostname), pService->m_pcService, pService->m_pcProtocol, pService->m_u8ReplyMask);); + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _announce: Announcing service %s.%s.%s (content %u)\n"), (pService->m_pcName ?: m_pcHostname), pService->m_pcService, pService->m_pcProtocol, pService->m_u8ReplyMask);); } } } } DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _announce: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _announce: FAILED!\n")); + }); return ((bResult) && (_sendMDNSMessage(sendParameter))); } @@ -1605,35 +1542,32 @@ bool MDNSResponder::_announce(bool p_bAnnounce, bool MDNSResponder::_announceService(stcMDNSService& p_rService, bool p_bAnnounce /*= true*/) { + bool bResult = false; - bool bResult = false; - - stcMDNSSendParameter sendParameter; + stcMDNSSendParameter sendParameter; if (ProbingStatus_Done == p_rService.m_ProbeInformation.m_ProbingStatus) { - - sendParameter.m_bResponse = true; // Announces are 'Unsolicited authoritative responses' + sendParameter.m_bResponse = true; // Announces are 'Unsolicited authoritative responses' sendParameter.m_bAuthorative = true; - sendParameter.m_bUnannounce = !p_bAnnounce; // When unannouncing, the TTL is set to '0' while creating the answers + sendParameter.m_bUnannounce = !p_bAnnounce; // When unannouncing, the TTL is set to '0' while creating the answers // DON'T announce host sendParameter.m_u8HostReplyMask = 0; // Announce services (service type, name, SRV (location) and TXTs) p_rService.m_u8ReplyMask = (ContentFlag_PTR_TYPE | ContentFlag_PTR_NAME | ContentFlag_SRV | ContentFlag_TXT); - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _announceService: Announcing service %s.%s.%s (content 0x%X)\n"), (p_rService.m_pcName ? : m_pcHostname), p_rService.m_pcService, p_rService.m_pcProtocol, p_rService.m_u8ReplyMask);); + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _announceService: Announcing service %s.%s.%s (content 0x%X)\n"), (p_rService.m_pcName ?: m_pcHostname), p_rService.m_pcService, p_rService.m_pcProtocol, p_rService.m_u8ReplyMask);); bResult = true; } DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _announceService: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _announceService: FAILED!\n")); + }); return ((bResult) && (_sendMDNSMessage(sendParameter))); } - /** SERVICE QUERY CACHE */ @@ -1643,8 +1577,7 @@ bool MDNSResponder::_announceService(stcMDNSService& p_rService, */ bool MDNSResponder::_hasServiceQueriesWaitingForAnswers(void) const { - - bool bOpenQueries = false; + bool bOpenQueries = false; for (stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; pServiceQuery; pServiceQuery = pServiceQuery->m_pNext) { @@ -1668,33 +1601,28 @@ bool MDNSResponder::_hasServiceQueriesWaitingForAnswers(void) const */ bool MDNSResponder::_checkServiceQueryCache(void) { - - bool bResult = true; + bool bResult = true; DEBUG_EX_INFO( - bool printedInfo = false; - ); + bool printedInfo = false;); for (stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; ((bResult) && (pServiceQuery)); pServiceQuery = pServiceQuery->m_pNext) { - // // Resend dynamic service queries, if not already done often enough if ((!pServiceQuery->m_bLegacyQuery) && - (MDNS_DYNAMIC_QUERY_RESEND_COUNT > pServiceQuery->m_u8SentCount) && - (pServiceQuery->m_ResendTimeout.expired())) + (MDNS_DYNAMIC_QUERY_RESEND_COUNT > pServiceQuery->m_u8SentCount) && + (pServiceQuery->m_ResendTimeout.expired())) { - if ((bResult = _sendMDNSServiceQuery(*pServiceQuery))) { ++pServiceQuery->m_u8SentCount; pServiceQuery->m_ResendTimeout.reset((MDNS_DYNAMIC_QUERY_RESEND_COUNT > pServiceQuery->m_u8SentCount) - ? (MDNS_DYNAMIC_QUERY_RESEND_DELAY * (pServiceQuery->m_u8SentCount - 1)) - : esp8266::polledTimeout::oneShotMs::neverExpires); + ? (MDNS_DYNAMIC_QUERY_RESEND_DELAY * (pServiceQuery->m_u8SentCount - 1)) + : esp8266::polledTimeout::oneShotMs::neverExpires); } DEBUG_EX_INFO( DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: %s to resend service query!"), (bResult ? "Succeeded" : "FAILED")); - printedInfo = true; - ); + printedInfo = true;); } // @@ -1703,26 +1631,23 @@ bool MDNSResponder::_checkServiceQueryCache(void) { stcMDNSServiceQuery::stcAnswer* pSQAnswer = pServiceQuery->m_pAnswers; while ((bResult) && - (pSQAnswer)) + (pSQAnswer)) { stcMDNSServiceQuery::stcAnswer* pNextSQAnswer = pSQAnswer->m_pNext; // 1. level answer if ((bResult) && - (pSQAnswer->m_TTLServiceDomain.flagged())) + (pSQAnswer->m_TTLServiceDomain.flagged())) { - if (!pSQAnswer->m_TTLServiceDomain.finalTimeoutLevel()) { - bResult = ((_sendMDNSServiceQuery(*pServiceQuery)) && (pSQAnswer->m_TTLServiceDomain.restart())); DEBUG_EX_INFO( DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: PTR update scheduled for ")); _printRRDomain(pSQAnswer->m_ServiceDomain); DEBUG_OUTPUT.printf_P(PSTR(" %s\n"), (bResult ? "OK" : "FAILURE")); - printedInfo = true; - ); + printedInfo = true;); } else { @@ -1736,32 +1661,28 @@ bool MDNSResponder::_checkServiceQueryCache(void) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: Will remove PTR answer for ")); _printRRDomain(pSQAnswer->m_ServiceDomain); DEBUG_OUTPUT.printf_P(PSTR("\n")); - printedInfo = true; - ); + printedInfo = true;); bResult = pServiceQuery->removeAnswer(pSQAnswer); pSQAnswer = 0; - continue; // Don't use this answer anymore + continue; // Don't use this answer anymore } - } // ServiceDomain flagged + } // ServiceDomain flagged // 2. level answers // HostDomain & Port (from SRV) if ((bResult) && - (pSQAnswer->m_TTLHostDomainAndPort.flagged())) + (pSQAnswer->m_TTLHostDomainAndPort.flagged())) { - if (!pSQAnswer->m_TTLHostDomainAndPort.finalTimeoutLevel()) { - bResult = ((_sendMDNSQuery(pSQAnswer->m_ServiceDomain, DNS_RRTYPE_SRV)) && (pSQAnswer->m_TTLHostDomainAndPort.restart())); DEBUG_EX_INFO( DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: SRV update scheduled for ")); _printRRDomain(pSQAnswer->m_ServiceDomain); DEBUG_OUTPUT.printf_P(PSTR(" host domain and port %s\n"), (bResult ? "OK" : "FAILURE")); - printedInfo = true; - ); + printedInfo = true;); } else { @@ -1770,14 +1691,13 @@ bool MDNSResponder::_checkServiceQueryCache(void) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: Will remove SRV answer for ")); _printRRDomain(pSQAnswer->m_ServiceDomain); DEBUG_OUTPUT.printf_P(PSTR(" host domain and port\n")); - printedInfo = true; - ); + printedInfo = true;); // Delete pSQAnswer->m_HostDomain.clear(); pSQAnswer->releaseHostDomain(); pSQAnswer->m_u16Port = 0; pSQAnswer->m_TTLHostDomainAndPort.set(0); - uint32_t u32ContentFlags = ServiceQueryAnswerType_HostDomainAndPort; + uint32_t u32ContentFlags = ServiceQueryAnswerType_HostDomainAndPort; // As the host domain is the base for the IP4- and IP6Address, remove these too #ifdef MDNS_IP4_SUPPORT pSQAnswer->releaseIP4Addresses(); @@ -1796,24 +1716,21 @@ bool MDNSResponder::_checkServiceQueryCache(void) pServiceQuery->m_fnCallback(serviceInfo, static_cast(u32ContentFlags), false); } } - } // HostDomainAndPort flagged + } // HostDomainAndPort flagged // Txts (from TXT) if ((bResult) && - (pSQAnswer->m_TTLTxts.flagged())) + (pSQAnswer->m_TTLTxts.flagged())) { - if (!pSQAnswer->m_TTLTxts.finalTimeoutLevel()) { - bResult = ((_sendMDNSQuery(pSQAnswer->m_ServiceDomain, DNS_RRTYPE_TXT)) && (pSQAnswer->m_TTLTxts.restart())); DEBUG_EX_INFO( DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: TXT update scheduled for ")); _printRRDomain(pSQAnswer->m_ServiceDomain); DEBUG_OUTPUT.printf_P(PSTR(" TXTs %s\n"), (bResult ? "OK" : "FAILURE")); - printedInfo = true; - ); + printedInfo = true;); } else { @@ -1822,8 +1739,7 @@ bool MDNSResponder::_checkServiceQueryCache(void) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: Will remove TXT answer for ")); _printRRDomain(pSQAnswer->m_ServiceDomain); DEBUG_OUTPUT.printf_P(PSTR(" TXTs\n")); - printedInfo = true; - ); + printedInfo = true;); // Delete pSQAnswer->m_Txts.clear(); pSQAnswer->m_TTLTxts.set(0); @@ -1837,29 +1753,25 @@ bool MDNSResponder::_checkServiceQueryCache(void) pServiceQuery->m_fnCallback(serviceInfo, static_cast(ServiceQueryAnswerType_Txts), false); } } - } // TXTs flagged + } // TXTs flagged // 3. level answers #ifdef MDNS_IP4_SUPPORT // IP4Address (from A) - stcMDNSServiceQuery::stcAnswer::stcIP4Address* pIP4Address = pSQAnswer->m_pIP4Addresses; - bool bAUpdateQuerySent = false; + stcMDNSServiceQuery::stcAnswer::stcIP4Address* pIP4Address = pSQAnswer->m_pIP4Addresses; + bool bAUpdateQuerySent = false; while ((pIP4Address) && - (bResult)) + (bResult)) { - - stcMDNSServiceQuery::stcAnswer::stcIP4Address* pNextIP4Address = pIP4Address->m_pNext; // Get 'next' early, as 'current' may be deleted at the end... + stcMDNSServiceQuery::stcAnswer::stcIP4Address* pNextIP4Address = pIP4Address->m_pNext; // Get 'next' early, as 'current' may be deleted at the end... if (pIP4Address->m_TTL.flagged()) { - - if (!pIP4Address->m_TTL.finalTimeoutLevel()) // Needs update + if (!pIP4Address->m_TTL.finalTimeoutLevel()) // Needs update { - if ((bAUpdateQuerySent) || - ((bResult = _sendMDNSQuery(pSQAnswer->m_HostDomain, DNS_RRTYPE_A)))) + ((bResult = _sendMDNSQuery(pSQAnswer->m_HostDomain, DNS_RRTYPE_A)))) { - pIP4Address->m_TTL.restart(); bAUpdateQuerySent = true; @@ -1867,8 +1779,7 @@ bool MDNSResponder::_checkServiceQueryCache(void) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: IP4 update scheduled for ")); _printRRDomain(pSQAnswer->m_ServiceDomain); DEBUG_OUTPUT.printf_P(PSTR(" IP4 address (%s)\n"), (pIP4Address->m_IPAddress.toString().c_str())); - printedInfo = true; - ); + printedInfo = true;); } } else @@ -1878,10 +1789,9 @@ bool MDNSResponder::_checkServiceQueryCache(void) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: Will remove IP4 answer for ")); _printRRDomain(pSQAnswer->m_ServiceDomain); DEBUG_OUTPUT.printf_P(PSTR(" IP4 address\n")); - printedInfo = true; - ); + printedInfo = true;); pSQAnswer->removeIP4Address(pIP4Address); - if (!pSQAnswer->m_pIP4Addresses) // NO IP4 address left -> remove content flag + if (!pSQAnswer->m_pIP4Addresses) // NO IP4 address left -> remove content flag { pSQAnswer->m_u32ContentFlags &= ~ServiceQueryAnswerType_IP4Address; } @@ -1892,31 +1802,27 @@ bool MDNSResponder::_checkServiceQueryCache(void) pServiceQuery->m_fnCallback(serviceInfo, static_cast(ServiceQueryAnswerType_IP4Address), false); } } - } // IP4 flagged + } // IP4 flagged pIP4Address = pNextIP4Address; // Next - } // while + } // while #endif #ifdef MDNS_IP6_SUPPORT // IP6Address (from AAAA) - stcMDNSServiceQuery::stcAnswer::stcIP6Address* pIP6Address = pSQAnswer->m_pIP6Addresses; - bool bAAAAUpdateQuerySent = false; + stcMDNSServiceQuery::stcAnswer::stcIP6Address* pIP6Address = pSQAnswer->m_pIP6Addresses; + bool bAAAAUpdateQuerySent = false; while ((pIP6Address) && - (bResult)) + (bResult)) { - - stcMDNSServiceQuery::stcAnswer::stcIP6Address* pNextIP6Address = pIP6Address->m_pNext; // Get 'next' early, as 'current' may be deleted at the end... + stcMDNSServiceQuery::stcAnswer::stcIP6Address* pNextIP6Address = pIP6Address->m_pNext; // Get 'next' early, as 'current' may be deleted at the end... if (pIP6Address->m_TTL.flagged()) { - - if (!pIP6Address->m_TTL.finalTimeoutLevel()) // Needs update + if (!pIP6Address->m_TTL.finalTimeoutLevel()) // Needs update { - if ((bAAAAUpdateQuerySent) || - ((bResult = _sendMDNSQuery(pSQAnswer->m_HostDomain, DNS_RRTYPE_AAAA)))) + ((bResult = _sendMDNSQuery(pSQAnswer->m_HostDomain, DNS_RRTYPE_AAAA)))) { - pIP6Address->m_TTL.restart(); bAAAAUpdateQuerySent = true; @@ -1924,8 +1830,7 @@ bool MDNSResponder::_checkServiceQueryCache(void) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: IP6 update scheduled for ")); _printRRDomain(pSQAnswer->m_ServiceDomain); DEBUG_OUTPUT.printf_P(PSTR(" IP6 address (%s)\n"), (pIP6Address->m_IPAddress.toString().c_str())); - printedInfo = true; - ); + printedInfo = true;); } } else @@ -1935,10 +1840,9 @@ bool MDNSResponder::_checkServiceQueryCache(void) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: Will remove answer for ")); _printRRDomain(pSQAnswer->m_ServiceDomain); DEBUG_OUTPUT.printf_P(PSTR(" IP6Address\n")); - printedInfo = true; - ); + printedInfo = true;); pSQAnswer->removeIP6Address(pIP6Address); - if (!pSQAnswer->m_pIP6Addresses) // NO IP6 address left -> remove content flag + if (!pSQAnswer->m_pIP6Addresses) // NO IP6 address left -> remove content flag { pSQAnswer->m_u32ContentFlags &= ~ServiceQueryAnswerType_IP6Address; } @@ -1948,10 +1852,10 @@ bool MDNSResponder::_checkServiceQueryCache(void) pServiceQuery->m_fnCallback(this, (hMDNSServiceQuery)pServiceQuery, pServiceQuery->indexOfAnswer(pSQAnswer), ServiceQueryAnswerType_IP6Address, false, pServiceQuery->m_pUserdata); } } - } // IP6 flagged + } // IP6 flagged pIP6Address = pNextIP6Address; // Next - } // while + } // while #endif pSQAnswer = pNextSQAnswer; } @@ -1959,18 +1863,16 @@ bool MDNSResponder::_checkServiceQueryCache(void) } DEBUG_EX_INFO( if (printedInfo) -{ - DEBUG_OUTPUT.printf_P(PSTR("\n")); - } - ); + { + DEBUG_OUTPUT.printf_P(PSTR("\n")); + }); DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: FAILED!\n")); + }); return bResult; } - /* MDNSResponder::_replyMaskForHost @@ -1981,29 +1883,28 @@ bool MDNSResponder::_checkServiceQueryCache(void) In addition, a full name match (question domain == host domain) is marked. */ uint8_t MDNSResponder::_replyMaskForHost(const MDNSResponder::stcMDNS_RRHeader& p_RRHeader, - bool* p_pbFullNameMatch /*= 0*/) const + bool* p_pbFullNameMatch /*= 0*/) const { //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _replyMaskForHost\n"));); uint8_t u8ReplyMask = 0; - (p_pbFullNameMatch ? *p_pbFullNameMatch = false : 0); + (p_pbFullNameMatch ? * p_pbFullNameMatch = false : 0); if ((DNS_RRCLASS_IN == p_RRHeader.m_Attributes.m_u16Class) || - (DNS_RRCLASS_ANY == p_RRHeader.m_Attributes.m_u16Class)) + (DNS_RRCLASS_ANY == p_RRHeader.m_Attributes.m_u16Class)) { - if ((DNS_RRTYPE_PTR == p_RRHeader.m_Attributes.m_u16Type) || - (DNS_RRTYPE_ANY == p_RRHeader.m_Attributes.m_u16Type)) + (DNS_RRTYPE_ANY == p_RRHeader.m_Attributes.m_u16Type)) { // PTR request #ifdef MDNS_IP4_SUPPORT - stcMDNS_RRDomain reverseIP4Domain; + stcMDNS_RRDomain reverseIP4Domain; for (netif* pNetIf = netif_list; pNetIf; pNetIf = pNetIf->next) { if (netif_is_up(pNetIf)) { if ((_buildDomainForReverseIP4(pNetIf->ip_addr, reverseIP4Domain)) && - (p_RRHeader.m_Domain == reverseIP4Domain)) + (p_RRHeader.m_Domain == reverseIP4Domain)) { // Reverse domain match u8ReplyMask |= ContentFlag_PTR_IP4; @@ -2014,18 +1915,17 @@ uint8_t MDNSResponder::_replyMaskForHost(const MDNSResponder::stcMDNS_RRHeader& #ifdef MDNS_IP6_SUPPORT // TODO #endif - } // Address qeuest + } // Address qeuest - stcMDNS_RRDomain hostDomain; + stcMDNS_RRDomain hostDomain; if ((_buildDomainForHost(m_pcHostname, hostDomain)) && - (p_RRHeader.m_Domain == hostDomain)) // Host domain match + (p_RRHeader.m_Domain == hostDomain)) // Host domain match { - (p_pbFullNameMatch ? (*p_pbFullNameMatch = true) : (0)); #ifdef MDNS_IP4_SUPPORT if ((DNS_RRTYPE_A == p_RRHeader.m_Attributes.m_u16Type) || - (DNS_RRTYPE_ANY == p_RRHeader.m_Attributes.m_u16Type)) + (DNS_RRTYPE_ANY == p_RRHeader.m_Attributes.m_u16Type)) { // IP4 address request u8ReplyMask |= ContentFlag_A; @@ -2033,7 +1933,7 @@ uint8_t MDNSResponder::_replyMaskForHost(const MDNSResponder::stcMDNS_RRHeader& #endif #ifdef MDNS_IP6_SUPPORT if ((DNS_RRTYPE_AAAA == p_RRHeader.m_Attributes.m_u16Type) || - (DNS_RRTYPE_ANY == p_RRHeader.m_Attributes.m_u16Type)) + (DNS_RRTYPE_ANY == p_RRHeader.m_Attributes.m_u16Type)) { // IP6 address request u8ReplyMask |= ContentFlag_AAAA; @@ -2046,9 +1946,9 @@ uint8_t MDNSResponder::_replyMaskForHost(const MDNSResponder::stcMDNS_RRHeader& //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _replyMaskForHost: INVALID RR-class (0x%04X)!\n"), p_RRHeader.m_Attributes.m_u16Class);); } DEBUG_EX_INFO(if (u8ReplyMask) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _replyMaskForHost: 0x%X\n"), u8ReplyMask); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _replyMaskForHost: 0x%X\n"), u8ReplyMask); + }); return u8ReplyMask; } @@ -2065,51 +1965,48 @@ uint8_t MDNSResponder::_replyMaskForHost(const MDNSResponder::stcMDNS_RRHeader& In addition, a full name match (question domain == service instance domain) is marked. */ uint8_t MDNSResponder::_replyMaskForService(const MDNSResponder::stcMDNS_RRHeader& p_RRHeader, - const MDNSResponder::stcMDNSService& p_Service, - bool* p_pbFullNameMatch /*= 0*/) const + const MDNSResponder::stcMDNSService& p_Service, + bool* p_pbFullNameMatch /*= 0*/) const { - uint8_t u8ReplyMask = 0; - (p_pbFullNameMatch ? *p_pbFullNameMatch = false : 0); + (p_pbFullNameMatch ? * p_pbFullNameMatch = false : 0); if ((DNS_RRCLASS_IN == p_RRHeader.m_Attributes.m_u16Class) || - (DNS_RRCLASS_ANY == p_RRHeader.m_Attributes.m_u16Class)) + (DNS_RRCLASS_ANY == p_RRHeader.m_Attributes.m_u16Class)) { - - stcMDNS_RRDomain DNSSDDomain; - if ((_buildDomainForDNSSD(DNSSDDomain)) && // _services._dns-sd._udp.local - (p_RRHeader.m_Domain == DNSSDDomain) && - ((DNS_RRTYPE_PTR == p_RRHeader.m_Attributes.m_u16Type) || - (DNS_RRTYPE_ANY == p_RRHeader.m_Attributes.m_u16Type))) + stcMDNS_RRDomain DNSSDDomain; + if ((_buildDomainForDNSSD(DNSSDDomain)) && // _services._dns-sd._udp.local + (p_RRHeader.m_Domain == DNSSDDomain) && + ((DNS_RRTYPE_PTR == p_RRHeader.m_Attributes.m_u16Type) || + (DNS_RRTYPE_ANY == p_RRHeader.m_Attributes.m_u16Type))) { // Common service info requested u8ReplyMask |= ContentFlag_PTR_TYPE; } - stcMDNS_RRDomain serviceDomain; - if ((_buildDomainForService(p_Service, false, serviceDomain)) && // eg. _http._tcp.local - (p_RRHeader.m_Domain == serviceDomain) && - ((DNS_RRTYPE_PTR == p_RRHeader.m_Attributes.m_u16Type) || - (DNS_RRTYPE_ANY == p_RRHeader.m_Attributes.m_u16Type))) + stcMDNS_RRDomain serviceDomain; + if ((_buildDomainForService(p_Service, false, serviceDomain)) && // eg. _http._tcp.local + (p_RRHeader.m_Domain == serviceDomain) && + ((DNS_RRTYPE_PTR == p_RRHeader.m_Attributes.m_u16Type) || + (DNS_RRTYPE_ANY == p_RRHeader.m_Attributes.m_u16Type))) { // Special service info requested u8ReplyMask |= ContentFlag_PTR_NAME; } - if ((_buildDomainForService(p_Service, true, serviceDomain)) && // eg. MyESP._http._tcp.local - (p_RRHeader.m_Domain == serviceDomain)) + if ((_buildDomainForService(p_Service, true, serviceDomain)) && // eg. MyESP._http._tcp.local + (p_RRHeader.m_Domain == serviceDomain)) { - (p_pbFullNameMatch ? (*p_pbFullNameMatch = true) : (0)); if ((DNS_RRTYPE_SRV == p_RRHeader.m_Attributes.m_u16Type) || - (DNS_RRTYPE_ANY == p_RRHeader.m_Attributes.m_u16Type)) + (DNS_RRTYPE_ANY == p_RRHeader.m_Attributes.m_u16Type)) { // Instance info SRV requested u8ReplyMask |= ContentFlag_SRV; } if ((DNS_RRTYPE_TXT == p_RRHeader.m_Attributes.m_u16Type) || - (DNS_RRTYPE_ANY == p_RRHeader.m_Attributes.m_u16Type)) + (DNS_RRTYPE_ANY == p_RRHeader.m_Attributes.m_u16Type)) { // Instance info TXT requested u8ReplyMask |= ContentFlag_TXT; @@ -2121,12 +2018,12 @@ uint8_t MDNSResponder::_replyMaskForService(const MDNSResponder::stcMDNS_RRHeade //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _replyMaskForService: INVALID RR-class (0x%04X)!\n"), p_RRHeader.m_Attributes.m_u16Class);); } DEBUG_EX_INFO(if (u8ReplyMask) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _replyMaskForService(%s.%s.%s): 0x%X\n"), p_Service.m_pcName, p_Service.m_pcService, p_Service.m_pcProtocol, u8ReplyMask); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _replyMaskForService(%s.%s.%s): 0x%X\n"), p_Service.m_pcName, p_Service.m_pcService, p_Service.m_pcProtocol, u8ReplyMask); + }); return u8ReplyMask; } -} // namespace MDNSImplementation +} // namespace MDNSImplementation -} // namespace esp8266 +} // namespace esp8266 diff --git a/libraries/ESP8266mDNS/src/LEAmDNS_Helpers.cpp b/libraries/ESP8266mDNS/src/LEAmDNS_Helpers.cpp index d4014db993..7a7f3e5104 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS_Helpers.cpp +++ b/libraries/ESP8266mDNS/src/LEAmDNS_Helpers.cpp @@ -23,21 +23,19 @@ */ #include -#include // strrstr() +#include // strrstr() #include "ESP8266mDNS.h" -#include "LEAmDNS_lwIPdefs.h" #include "LEAmDNS_Priv.h" +#include "LEAmDNS_lwIPdefs.h" namespace esp8266 { - /* LEAmDNS */ namespace MDNSImplementation { - /** HELPERS */ @@ -55,31 +53,29 @@ namespace MDNSImplementation */ /*static*/ bool MDNSResponder::indexDomain(char*& p_rpcDomain, - const char* p_pcDivider /*= "-"*/, - const char* p_pcDefaultDomain /*= 0*/) + const char* p_pcDivider /*= "-"*/, + const char* p_pcDefaultDomain /*= 0*/) { - - bool bResult = false; + bool bResult = false; // Ensure a divider exists; use '-' as default - const char* pcDivider = (p_pcDivider ? : "-"); + const char* pcDivider = (p_pcDivider ?: "-"); if (p_rpcDomain) { const char* pFoundDivider = strrstr(p_rpcDomain, pcDivider); - if (pFoundDivider) // maybe already extended + if (pFoundDivider) // maybe already extended { - char* pEnd = 0; + char* pEnd = 0; unsigned long ulIndex = strtoul((pFoundDivider + strlen(pcDivider)), &pEnd, 10); if ((ulIndex) && - ((pEnd - p_rpcDomain) == (ptrdiff_t)strlen(p_rpcDomain)) && - (!*pEnd)) // Valid (old) index found + ((pEnd - p_rpcDomain) == (ptrdiff_t)strlen(p_rpcDomain)) && + (!*pEnd)) // Valid (old) index found { - - char acIndexBuffer[16]; + char acIndexBuffer[16]; sprintf(acIndexBuffer, "%lu", (++ulIndex)); - size_t stLength = ((pFoundDivider - p_rpcDomain + strlen(pcDivider)) + strlen(acIndexBuffer) + 1); - char* pNewHostname = new char[stLength]; + size_t stLength = ((pFoundDivider - p_rpcDomain + strlen(pcDivider)) + strlen(acIndexBuffer) + 1); + char* pNewHostname = new char[stLength]; if (pNewHostname) { memcpy(pNewHostname, p_rpcDomain, (pFoundDivider - p_rpcDomain + strlen(pcDivider))); @@ -102,10 +98,10 @@ namespace MDNSImplementation } } - if (!pFoundDivider) // not yet extended (or failed to increment extension) -> start indexing + if (!pFoundDivider) // not yet extended (or failed to increment extension) -> start indexing { - size_t stLength = strlen(p_rpcDomain) + (strlen(pcDivider) + 1 + 1); // Name + Divider + '2' + '\0' - char* pNewHostname = new char[stLength]; + size_t stLength = strlen(p_rpcDomain) + (strlen(pcDivider) + 1 + 1); // Name + Divider + '2' + '\0' + char* pNewHostname = new char[stLength]; if (pNewHostname) { sprintf(pNewHostname, "%s%s2", p_rpcDomain, pcDivider); @@ -124,9 +120,9 @@ namespace MDNSImplementation else { // No given host domain, use base or default - const char* cpcDefaultName = (p_pcDefaultDomain ? : "esp8266"); + const char* cpcDefaultName = (p_pcDefaultDomain ?: "esp8266"); - size_t stLength = strlen(cpcDefaultName) + 1; // '\0' + size_t stLength = strlen(cpcDefaultName) + 1; // '\0' p_rpcDomain = new char[stLength]; if (p_rpcDomain) { @@ -142,7 +138,6 @@ namespace MDNSImplementation return bResult; } - /* UDP CONTEXT */ @@ -192,7 +187,6 @@ bool MDNSResponder::_allocUDPContext(void) */ bool MDNSResponder::_releaseUDPContext(void) { - if (m_pUDPContext) { m_pUDPContext->unref(); @@ -202,7 +196,6 @@ bool MDNSResponder::_releaseUDPContext(void) return true; } - /* SERVICE QUERY */ @@ -212,8 +205,7 @@ bool MDNSResponder::_releaseUDPContext(void) */ MDNSResponder::stcMDNSServiceQuery* MDNSResponder::_allocServiceQuery(void) { - - stcMDNSServiceQuery* pServiceQuery = new stcMDNSServiceQuery; + stcMDNSServiceQuery* pServiceQuery = new stcMDNSServiceQuery; if (pServiceQuery) { // Link to query list @@ -228,14 +220,13 @@ MDNSResponder::stcMDNSServiceQuery* MDNSResponder::_allocServiceQuery(void) */ bool MDNSResponder::_removeServiceQuery(MDNSResponder::stcMDNSServiceQuery* p_pServiceQuery) { - - bool bResult = false; + bool bResult = false; if (p_pServiceQuery) { - stcMDNSServiceQuery* pPred = m_pServiceQueries; + stcMDNSServiceQuery* pPred = m_pServiceQueries; while ((pPred) && - (pPred->m_pNext != p_pServiceQuery)) + (pPred->m_pNext != p_pServiceQuery)) { pPred = pPred->m_pNext; } @@ -245,7 +236,7 @@ bool MDNSResponder::_removeServiceQuery(MDNSResponder::stcMDNSServiceQuery* p_pS delete p_pServiceQuery; bResult = true; } - else // No predecessor + else // No predecessor { if (m_pServiceQueries == p_pServiceQuery) { @@ -267,8 +258,7 @@ bool MDNSResponder::_removeServiceQuery(MDNSResponder::stcMDNSServiceQuery* p_pS */ bool MDNSResponder::_removeLegacyServiceQuery(void) { - - stcMDNSServiceQuery* pLegacyServiceQuery = _findLegacyServiceQuery(); + stcMDNSServiceQuery* pLegacyServiceQuery = _findLegacyServiceQuery(); return (pLegacyServiceQuery ? _removeServiceQuery(pLegacyServiceQuery) : true); } @@ -280,8 +270,7 @@ bool MDNSResponder::_removeLegacyServiceQuery(void) */ MDNSResponder::stcMDNSServiceQuery* MDNSResponder::_findServiceQuery(MDNSResponder::hMDNSServiceQuery p_hServiceQuery) { - - stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; + stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; while (pServiceQuery) { if ((hMDNSServiceQuery)pServiceQuery == p_hServiceQuery) @@ -298,8 +287,7 @@ MDNSResponder::stcMDNSServiceQuery* MDNSResponder::_findServiceQuery(MDNSRespond */ MDNSResponder::stcMDNSServiceQuery* MDNSResponder::_findLegacyServiceQuery(void) { - - stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; + stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; while (pServiceQuery) { if (pServiceQuery->m_bLegacyQuery) @@ -318,7 +306,7 @@ bool MDNSResponder::_releaseServiceQueries(void) { while (m_pServiceQueries) { - stcMDNSServiceQuery* pNext = m_pServiceQueries->m_pNext; + stcMDNSServiceQuery* pNext = m_pServiceQueries->m_pNext; delete m_pServiceQueries; m_pServiceQueries = pNext; } @@ -329,11 +317,11 @@ bool MDNSResponder::_releaseServiceQueries(void) MDNSResponder::_findNextServiceQueryByServiceType */ MDNSResponder::stcMDNSServiceQuery* MDNSResponder::_findNextServiceQueryByServiceType(const stcMDNS_RRDomain& p_ServiceTypeDomain, - const stcMDNSServiceQuery* p_pPrevServiceQuery) + const stcMDNSServiceQuery* p_pPrevServiceQuery) { - stcMDNSServiceQuery* pMatchingServiceQuery = 0; + stcMDNSServiceQuery* pMatchingServiceQuery = 0; - stcMDNSServiceQuery* pServiceQuery = (p_pPrevServiceQuery ? p_pPrevServiceQuery->m_pNext : m_pServiceQueries); + stcMDNSServiceQuery* pServiceQuery = (p_pPrevServiceQuery ? p_pPrevServiceQuery->m_pNext : m_pServiceQueries); while (pServiceQuery) { if (p_ServiceTypeDomain == pServiceQuery->m_ServiceTypeDomain) @@ -346,7 +334,6 @@ MDNSResponder::stcMDNSServiceQuery* MDNSResponder::_findNextServiceQueryByServic return pMatchingServiceQuery; } - /* HOSTNAME */ @@ -358,13 +345,13 @@ bool MDNSResponder::_setHostname(const char* p_pcHostname) { //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _allocHostname (%s)\n"), p_pcHostname);); - bool bResult = false; + bool bResult = false; _releaseHostname(); - size_t stLength = 0; + size_t stLength = 0; if ((p_pcHostname) && - (MDNS_DOMAIN_LABEL_MAXLENGTH >= (stLength = strlen(p_pcHostname)))) // char max size for a single label + (MDNS_DOMAIN_LABEL_MAXLENGTH >= (stLength = strlen(p_pcHostname)))) // char max size for a single label { // Copy in hostname characters as lowercase if ((bResult = (0 != (m_pcHostname = new char[stLength + 1])))) @@ -389,7 +376,6 @@ bool MDNSResponder::_setHostname(const char* p_pcHostname) */ bool MDNSResponder::_releaseHostname(void) { - if (m_pcHostname) { delete[] m_pcHostname; @@ -398,7 +384,6 @@ bool MDNSResponder::_releaseHostname(void) return true; } - /* SERVICE */ @@ -407,25 +392,23 @@ bool MDNSResponder::_releaseHostname(void) MDNSResponder::_allocService */ MDNSResponder::stcMDNSService* MDNSResponder::_allocService(const char* p_pcName, - const char* p_pcService, - const char* p_pcProtocol, - uint16_t p_u16Port) + const char* p_pcService, + const char* p_pcProtocol, + uint16_t p_u16Port) { - stcMDNSService* pService = 0; if (((!p_pcName) || - (MDNS_DOMAIN_LABEL_MAXLENGTH >= strlen(p_pcName))) && - (p_pcService) && - (MDNS_SERVICE_NAME_LENGTH >= strlen(p_pcService)) && - (p_pcProtocol) && - (MDNS_SERVICE_PROTOCOL_LENGTH >= strlen(p_pcProtocol)) && - (p_u16Port) && - (0 != (pService = new stcMDNSService)) && - (pService->setName(p_pcName ? : m_pcHostname)) && - (pService->setService(p_pcService)) && - (pService->setProtocol(p_pcProtocol))) + (MDNS_DOMAIN_LABEL_MAXLENGTH >= strlen(p_pcName))) && + (p_pcService) && + (MDNS_SERVICE_NAME_LENGTH >= strlen(p_pcService)) && + (p_pcProtocol) && + (MDNS_SERVICE_PROTOCOL_LENGTH >= strlen(p_pcProtocol)) && + (p_u16Port) && + (0 != (pService = new stcMDNSService)) && + (pService->setName(p_pcName ?: m_pcHostname)) && + (pService->setService(p_pcService)) && + (pService->setProtocol(p_pcProtocol))) { - pService->m_bAutoName = (0 == p_pcName); pService->m_u16Port = p_u16Port; @@ -441,14 +424,13 @@ MDNSResponder::stcMDNSService* MDNSResponder::_allocService(const char* p_pcName */ bool MDNSResponder::_releaseService(MDNSResponder::stcMDNSService* p_pService) { - - bool bResult = false; + bool bResult = false; if (p_pService) { stcMDNSService* pPred = m_pServices; while ((pPred) && - (pPred->m_pNext != p_pService)) + (pPred->m_pNext != p_pService)) { pPred = pPred->m_pNext; } @@ -458,7 +440,7 @@ bool MDNSResponder::_releaseService(MDNSResponder::stcMDNSService* p_pService) delete p_pService; bResult = true; } - else // No predecessor + else // No predecessor { if (m_pServices == p_pService) { @@ -480,7 +462,6 @@ bool MDNSResponder::_releaseService(MDNSResponder::stcMDNSService* p_pService) */ bool MDNSResponder::_releaseServices(void) { - stcMDNSService* pService = m_pServices; while (pService) { @@ -494,18 +475,16 @@ bool MDNSResponder::_releaseServices(void) MDNSResponder::_findService */ MDNSResponder::stcMDNSService* MDNSResponder::_findService(const char* p_pcName, - const char* p_pcService, - const char* p_pcProtocol) + const char* p_pcService, + const char* p_pcProtocol) { - stcMDNSService* pService = m_pServices; while (pService) { if ((0 == strcmp(pService->m_pcName, p_pcName)) && - (0 == strcmp(pService->m_pcService, p_pcService)) && - (0 == strcmp(pService->m_pcProtocol, p_pcProtocol))) + (0 == strcmp(pService->m_pcService, p_pcService)) && + (0 == strcmp(pService->m_pcProtocol, p_pcProtocol))) { - break; } pService = pService->m_pNext; @@ -518,7 +497,6 @@ MDNSResponder::stcMDNSService* MDNSResponder::_findService(const char* p_pcName, */ MDNSResponder::stcMDNSService* MDNSResponder::_findService(const MDNSResponder::hMDNSService p_hService) { - stcMDNSService* pService = m_pServices; while (pService) { @@ -531,7 +509,6 @@ MDNSResponder::stcMDNSService* MDNSResponder::_findService(const MDNSResponder:: return pService; } - /* SERVICE TXT */ @@ -540,30 +517,29 @@ MDNSResponder::stcMDNSService* MDNSResponder::_findService(const MDNSResponder:: MDNSResponder::_allocServiceTxt */ MDNSResponder::stcMDNSServiceTxt* MDNSResponder::_allocServiceTxt(MDNSResponder::stcMDNSService* p_pService, - const char* p_pcKey, - const char* p_pcValue, - bool p_bTemp) + const char* p_pcKey, + const char* p_pcValue, + bool p_bTemp) { - - stcMDNSServiceTxt* pTxt = 0; + stcMDNSServiceTxt* pTxt = 0; if ((p_pService) && - (p_pcKey) && - (MDNS_SERVICE_TXT_MAXLENGTH > (p_pService->m_Txts.length() + - 1 + // Length byte - (p_pcKey ? strlen(p_pcKey) : 0) + - 1 + // '=' - (p_pcValue ? strlen(p_pcValue) : 0)))) + (p_pcKey) && + (MDNS_SERVICE_TXT_MAXLENGTH > (p_pService->m_Txts.length() + + 1 + // Length byte + (p_pcKey ? strlen(p_pcKey) : 0) + + 1 + // '=' + (p_pcValue ? strlen(p_pcValue) : 0)))) { - pTxt = new stcMDNSServiceTxt; if (pTxt) { - size_t stLength = (p_pcKey ? strlen(p_pcKey) : 0); + size_t stLength = (p_pcKey ? strlen(p_pcKey) : 0); pTxt->m_pcKey = new char[stLength + 1]; if (pTxt->m_pcKey) { - strncpy(pTxt->m_pcKey, p_pcKey, stLength); pTxt->m_pcKey[stLength] = 0; + strncpy(pTxt->m_pcKey, p_pcKey, stLength); + pTxt->m_pcKey[stLength] = 0; } if (p_pcValue) @@ -572,7 +548,8 @@ MDNSResponder::stcMDNSServiceTxt* MDNSResponder::_allocServiceTxt(MDNSResponder: pTxt->m_pcValue = new char[stLength + 1]; if (pTxt->m_pcValue) { - strncpy(pTxt->m_pcValue, p_pcValue, stLength); pTxt->m_pcValue[stLength] = 0; + strncpy(pTxt->m_pcValue, p_pcValue, stLength); + pTxt->m_pcValue[stLength] = 0; } } pTxt->m_bTemp = p_bTemp; @@ -590,7 +567,6 @@ MDNSResponder::stcMDNSServiceTxt* MDNSResponder::_allocServiceTxt(MDNSResponder: bool MDNSResponder::_releaseServiceTxt(MDNSResponder::stcMDNSService* p_pService, MDNSResponder::stcMDNSServiceTxt* p_pTxt) { - return ((p_pService) && (p_pTxt) && (p_pService->m_Txts.remove(p_pTxt))); @@ -600,16 +576,15 @@ bool MDNSResponder::_releaseServiceTxt(MDNSResponder::stcMDNSService* p_pService MDNSResponder::_updateServiceTxt */ MDNSResponder::stcMDNSServiceTxt* MDNSResponder::_updateServiceTxt(MDNSResponder::stcMDNSService* p_pService, - MDNSResponder::stcMDNSServiceTxt* p_pTxt, - const char* p_pcValue, - bool p_bTemp) + MDNSResponder::stcMDNSServiceTxt* p_pTxt, + const char* p_pcValue, + bool p_bTemp) { - if ((p_pService) && - (p_pTxt) && - (MDNS_SERVICE_TXT_MAXLENGTH > (p_pService->m_Txts.length() - - (p_pTxt->m_pcValue ? strlen(p_pTxt->m_pcValue) : 0) + - (p_pcValue ? strlen(p_pcValue) : 0)))) + (p_pTxt) && + (MDNS_SERVICE_TXT_MAXLENGTH > (p_pService->m_Txts.length() - + (p_pTxt->m_pcValue ? strlen(p_pTxt->m_pcValue) : 0) + + (p_pcValue ? strlen(p_pcValue) : 0)))) { p_pTxt->update(p_pcValue); p_pTxt->m_bTemp = p_bTemp; @@ -621,9 +596,8 @@ MDNSResponder::stcMDNSServiceTxt* MDNSResponder::_updateServiceTxt(MDNSResponder MDNSResponder::_findServiceTxt */ MDNSResponder::stcMDNSServiceTxt* MDNSResponder::_findServiceTxt(MDNSResponder::stcMDNSService* p_pService, - const char* p_pcKey) + const char* p_pcKey) { - return (p_pService ? p_pService->m_Txts.find(p_pcKey) : 0); } @@ -631,9 +605,8 @@ MDNSResponder::stcMDNSServiceTxt* MDNSResponder::_findServiceTxt(MDNSResponder:: MDNSResponder::_findServiceTxt */ MDNSResponder::stcMDNSServiceTxt* MDNSResponder::_findServiceTxt(MDNSResponder::stcMDNSService* p_pService, - const hMDNSTxt p_hTxt) + const hMDNSTxt p_hTxt) { - return (((p_pService) && (p_hTxt)) ? p_pService->m_Txts.find((stcMDNSServiceTxt*)p_hTxt) : 0); } @@ -641,18 +614,17 @@ MDNSResponder::stcMDNSServiceTxt* MDNSResponder::_findServiceTxt(MDNSResponder:: MDNSResponder::_addServiceTxt */ MDNSResponder::stcMDNSServiceTxt* MDNSResponder::_addServiceTxt(MDNSResponder::stcMDNSService* p_pService, - const char* p_pcKey, - const char* p_pcValue, - bool p_bTemp) + const char* p_pcKey, + const char* p_pcValue, + bool p_bTemp) { - stcMDNSServiceTxt* pResult = 0; + stcMDNSServiceTxt* pResult = 0; if ((p_pService) && - (p_pcKey) && - (strlen(p_pcKey))) + (p_pcKey) && + (strlen(p_pcKey))) { - - stcMDNSServiceTxt* pTxt = p_pService->m_Txts.find(p_pcKey); + stcMDNSServiceTxt* pTxt = p_pService->m_Txts.find(p_pcKey); if (pTxt) { pResult = _updateServiceTxt(p_pService, pTxt, p_pcValue, p_bTemp); @@ -666,12 +638,12 @@ MDNSResponder::stcMDNSServiceTxt* MDNSResponder::_addServiceTxt(MDNSResponder::s } MDNSResponder::stcMDNSServiceTxt* MDNSResponder::_answerKeyValue(const hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) + const uint32_t p_u32AnswerIndex) { - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); // Fill m_pcTxts (if not already done) - return (pSQAnswer) ? pSQAnswer->m_Txts.m_pTxts : 0; + return (pSQAnswer) ? pSQAnswer->m_Txts.m_pTxts : 0; } /* @@ -679,7 +651,6 @@ MDNSResponder::stcMDNSServiceTxt* MDNSResponder::_answerKeyValue(const hMDNSServ */ bool MDNSResponder::_collectServiceTxts(MDNSResponder::stcMDNSService& p_rService) { - // Call Dynamic service callbacks if (m_fnServiceTxtCallback) { @@ -697,11 +668,9 @@ bool MDNSResponder::_collectServiceTxts(MDNSResponder::stcMDNSService& p_rServic */ bool MDNSResponder::_releaseTempServiceTxts(MDNSResponder::stcMDNSService& p_rService) { - return (p_rService.m_Txts.removeTempTxts()); } - /* MISC */ @@ -712,11 +681,10 @@ bool MDNSResponder::_releaseTempServiceTxts(MDNSResponder::stcMDNSService& p_rSe */ bool MDNSResponder::_printRRDomain(const MDNSResponder::stcMDNS_RRDomain& p_RRDomain) const { - //DEBUG_OUTPUT.printf_P(PSTR("Domain: ")); const char* pCursor = p_RRDomain.m_acName; - uint8_t u8Length = *pCursor++; + uint8_t u8Length = *pCursor++; if (u8Length) { while (u8Length) @@ -732,7 +700,7 @@ bool MDNSResponder::_printRRDomain(const MDNSResponder::stcMDNS_RRDomain& p_RRDo } } } - else // empty domain + else // empty domain { DEBUG_OUTPUT.printf_P(PSTR("-empty-")); } @@ -746,45 +714,44 @@ bool MDNSResponder::_printRRDomain(const MDNSResponder::stcMDNS_RRDomain& p_RRDo */ bool MDNSResponder::_printRRAnswer(const MDNSResponder::stcMDNS_RRAnswer& p_RRAnswer) const { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] RRAnswer: ")); _printRRDomain(p_RRAnswer.m_Header.m_Domain); DEBUG_OUTPUT.printf_P(PSTR(" Type:0x%04X Class:0x%04X TTL:%u, "), p_RRAnswer.m_Header.m_Attributes.m_u16Type, p_RRAnswer.m_Header.m_Attributes.m_u16Class, p_RRAnswer.m_u32TTL); - switch (p_RRAnswer.m_Header.m_Attributes.m_u16Type & (~0x8000)) // Topmost bit might carry 'cache flush' flag + switch (p_RRAnswer.m_Header.m_Attributes.m_u16Type & (~0x8000)) // Topmost bit might carry 'cache flush' flag { #ifdef MDNS_IP4_SUPPORT - case DNS_RRTYPE_A: - DEBUG_OUTPUT.printf_P(PSTR("A IP:%s"), ((const stcMDNS_RRAnswerA*)&p_RRAnswer)->m_IPAddress.toString().c_str()); - break; + case DNS_RRTYPE_A: + DEBUG_OUTPUT.printf_P(PSTR("A IP:%s"), ((const stcMDNS_RRAnswerA*)&p_RRAnswer)->m_IPAddress.toString().c_str()); + break; #endif - case DNS_RRTYPE_PTR: - DEBUG_OUTPUT.printf_P(PSTR("PTR ")); - _printRRDomain(((const stcMDNS_RRAnswerPTR*)&p_RRAnswer)->m_PTRDomain); - break; - case DNS_RRTYPE_TXT: - { - size_t stTxtLength = ((const stcMDNS_RRAnswerTXT*)&p_RRAnswer)->m_Txts.c_strLength(); - char* pTxts = new char[stTxtLength]; - if (pTxts) + case DNS_RRTYPE_PTR: + DEBUG_OUTPUT.printf_P(PSTR("PTR ")); + _printRRDomain(((const stcMDNS_RRAnswerPTR*)&p_RRAnswer)->m_PTRDomain); + break; + case DNS_RRTYPE_TXT: { - ((/*const c_str()!!*/stcMDNS_RRAnswerTXT*)&p_RRAnswer)->m_Txts.c_str(pTxts); - DEBUG_OUTPUT.printf_P(PSTR("TXT(%zu) %s"), stTxtLength, pTxts); - delete[] pTxts; + size_t stTxtLength = ((const stcMDNS_RRAnswerTXT*)&p_RRAnswer)->m_Txts.c_strLength(); + char* pTxts = new char[stTxtLength]; + if (pTxts) + { + ((/*const c_str()!!*/ stcMDNS_RRAnswerTXT*)&p_RRAnswer)->m_Txts.c_str(pTxts); + DEBUG_OUTPUT.printf_P(PSTR("TXT(%zu) %s"), stTxtLength, pTxts); + delete[] pTxts; + } + break; } - break; - } #ifdef MDNS_IP6_SUPPORT - case DNS_RRTYPE_AAAA: - DEBUG_OUTPUT.printf_P(PSTR("AAAA IP:%s"), ((stcMDNS_RRAnswerA*&)p_rpRRAnswer)->m_IPAddress.toString().c_str()); - break; + case DNS_RRTYPE_AAAA: + DEBUG_OUTPUT.printf_P(PSTR("AAAA IP:%s"), ((stcMDNS_RRAnswerA*&)p_rpRRAnswer)->m_IPAddress.toString().c_str()); + break; #endif - case DNS_RRTYPE_SRV: - DEBUG_OUTPUT.printf_P(PSTR("SRV Port:%u "), ((const stcMDNS_RRAnswerSRV*)&p_RRAnswer)->m_u16Port); - _printRRDomain(((const stcMDNS_RRAnswerSRV*)&p_RRAnswer)->m_SRVDomain); - break; - default: - DEBUG_OUTPUT.printf_P(PSTR("generic ")); - break; + case DNS_RRTYPE_SRV: + DEBUG_OUTPUT.printf_P(PSTR("SRV Port:%u "), ((const stcMDNS_RRAnswerSRV*)&p_RRAnswer)->m_u16Port); + _printRRDomain(((const stcMDNS_RRAnswerSRV*)&p_RRAnswer)->m_SRVDomain); + break; + default: + DEBUG_OUTPUT.printf_P(PSTR("generic ")); + break; } DEBUG_OUTPUT.printf_P(PSTR("\n")); @@ -792,10 +759,6 @@ bool MDNSResponder::_printRRAnswer(const MDNSResponder::stcMDNS_RRAnswer& p_RRAn } #endif -} // namespace MDNSImplementation - -} // namespace esp8266 - - - +} // namespace MDNSImplementation +} // namespace esp8266 diff --git a/libraries/ESP8266mDNS/src/LEAmDNS_Priv.h b/libraries/ESP8266mDNS/src/LEAmDNS_Priv.h index 49fc5bb608..70e81de5e6 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS_Priv.h +++ b/libraries/ESP8266mDNS/src/LEAmDNS_Priv.h @@ -27,14 +27,12 @@ namespace esp8266 { - /* LEAmDNS */ namespace MDNSImplementation { - // Enable class debug functions #define ESP_8266_MDNS_INCLUDE //#define DEBUG_ESP_MDNS_RESPONDER @@ -62,7 +60,7 @@ namespace MDNSImplementation #ifdef DEBUG_ESP_MDNS_RESPONDER #ifdef DEBUG_ESP_MDNS_INFO -#define DEBUG_EX_INFO(A) A +#define DEBUG_EX_INFO(A) A #else #define DEBUG_EX_INFO(A) #endif @@ -72,12 +70,12 @@ namespace MDNSImplementation #define DEBUG_EX_ERR(A) #endif #ifdef DEBUG_ESP_MDNS_TX -#define DEBUG_EX_TX(A) A +#define DEBUG_EX_TX(A) A #else #define DEBUG_EX_TX(A) #endif #ifdef DEBUG_ESP_MDNS_RX -#define DEBUG_EX_RX(A) A +#define DEBUG_EX_RX(A) A #else #define DEBUG_EX_RX(A) #endif @@ -88,10 +86,26 @@ namespace MDNSImplementation #define DEBUG_OUTPUT Serial #endif #else -#define DEBUG_EX_INFO(A) do { (void)0; } while (0) -#define DEBUG_EX_ERR(A) do { (void)0; } while (0) -#define DEBUG_EX_TX(A) do { (void)0; } while (0) -#define DEBUG_EX_RX(A) do { (void)0; } while (0) +#define DEBUG_EX_INFO(A) \ + do \ + { \ + (void)0; \ + } while (0) +#define DEBUG_EX_ERR(A) \ + do \ + { \ + (void)0; \ + } while (0) +#define DEBUG_EX_TX(A) \ + do \ + { \ + (void)0; \ + } while (0) +#define DEBUG_EX_RX(A) \ + do \ + { \ + (void)0; \ + } while (0) #endif /* already defined in lwIP ('lwip/prot/dns.h') @@ -111,44 +125,43 @@ namespace MDNSImplementation However, RFC 3171 seems to force 255 instead */ -#define MDNS_MULTICAST_TTL 255/*1*/ +#define MDNS_MULTICAST_TTL 255 /*1*/ /* This is the MDNS record TTL Host level records are set to 2min (120s) service level records are set to 75min (4500s) */ -#define MDNS_HOST_TTL 120 -#define MDNS_SERVICE_TTL 4500 +#define MDNS_HOST_TTL 120 +#define MDNS_SERVICE_TTL 4500 /* Compressed labels are flagged by the two topmost bits of the length byte being set */ -#define MDNS_DOMAIN_COMPRESS_MARK 0xC0 +#define MDNS_DOMAIN_COMPRESS_MARK 0xC0 /* Avoid endless recursion because of malformed compressed labels */ -#define MDNS_DOMAIN_MAX_REDIRCTION 6 +#define MDNS_DOMAIN_MAX_REDIRCTION 6 /* Default service priority and weight in SRV answers */ -#define MDNS_SRV_PRIORITY 0 -#define MDNS_SRV_WEIGHT 0 +#define MDNS_SRV_PRIORITY 0 +#define MDNS_SRV_WEIGHT 0 /* Delay between and number of probes for host and service domains Delay between and number of announces for host and service domains Delay between and number of service queries; the delay is multiplied by the resent number in '_checkServiceQueryCache' */ -#define MDNS_PROBE_DELAY 250 -#define MDNS_PROBE_COUNT 3 -#define MDNS_ANNOUNCE_DELAY 1000 -#define MDNS_ANNOUNCE_COUNT 8 +#define MDNS_PROBE_DELAY 250 +#define MDNS_PROBE_COUNT 3 +#define MDNS_ANNOUNCE_DELAY 1000 +#define MDNS_ANNOUNCE_COUNT 8 #define MDNS_DYNAMIC_QUERY_RESEND_COUNT 5 #define MDNS_DYNAMIC_QUERY_RESEND_DELAY 5000 - /* Force host domain to use only lowercase letters */ @@ -167,15 +180,14 @@ namespace MDNSImplementation #ifdef F #undef F #endif -#define F(A) A +#define F(A) A #endif -} // namespace MDNSImplementation +} // namespace MDNSImplementation -} // namespace esp8266 +} // namespace esp8266 // Include the main header, so the submodlues only need to include this header #include "LEAmDNS.h" - #endif // MDNS_PRIV_H diff --git a/libraries/ESP8266mDNS/src/LEAmDNS_Structs.cpp b/libraries/ESP8266mDNS/src/LEAmDNS_Structs.cpp index 786287457d..f6bf0bf543 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS_Structs.cpp +++ b/libraries/ESP8266mDNS/src/LEAmDNS_Structs.cpp @@ -28,13 +28,11 @@ namespace esp8266 { - /* LEAmDNS */ namespace MDNSImplementation { - /** STRUCTS */ @@ -53,14 +51,13 @@ namespace MDNSImplementation MDNSResponder::stcMDNSServiceTxt::stcMDNSServiceTxt constructor */ MDNSResponder::stcMDNSServiceTxt::stcMDNSServiceTxt(const char* p_pcKey /*= 0*/, - const char* p_pcValue /*= 0*/, - bool p_bTemp /*= false*/) - : m_pNext(0), - m_pcKey(0), - m_pcValue(0), - m_bTemp(p_bTemp) + const char* p_pcValue /*= 0*/, + bool p_bTemp /*= false*/) + : m_pNext(0), + m_pcKey(0), + m_pcValue(0), + m_bTemp(p_bTemp) { - setKey(p_pcKey); setValue(p_pcValue); } @@ -69,12 +66,11 @@ MDNSResponder::stcMDNSServiceTxt::stcMDNSServiceTxt(const char* p_pcKey /*= 0*/, MDNSResponder::stcMDNSServiceTxt::stcMDNSServiceTxt copy-constructor */ MDNSResponder::stcMDNSServiceTxt::stcMDNSServiceTxt(const MDNSResponder::stcMDNSServiceTxt& p_Other) - : m_pNext(0), - m_pcKey(0), - m_pcValue(0), - m_bTemp(false) + : m_pNext(0), + m_pcKey(0), + m_pcValue(0), + m_bTemp(false) { - operator=(p_Other); } @@ -83,7 +79,6 @@ MDNSResponder::stcMDNSServiceTxt::stcMDNSServiceTxt(const MDNSResponder::stcMDNS */ MDNSResponder::stcMDNSServiceTxt::~stcMDNSServiceTxt(void) { - clear(); } @@ -92,7 +87,6 @@ MDNSResponder::stcMDNSServiceTxt::~stcMDNSServiceTxt(void) */ MDNSResponder::stcMDNSServiceTxt& MDNSResponder::stcMDNSServiceTxt::operator=(const MDNSResponder::stcMDNSServiceTxt& p_Other) { - if (&p_Other != this) { clear(); @@ -106,7 +100,6 @@ MDNSResponder::stcMDNSServiceTxt& MDNSResponder::stcMDNSServiceTxt::operator=(co */ bool MDNSResponder::stcMDNSServiceTxt::clear(void) { - releaseKey(); releaseValue(); return true; @@ -117,7 +110,6 @@ bool MDNSResponder::stcMDNSServiceTxt::clear(void) */ char* MDNSResponder::stcMDNSServiceTxt::allocKey(size_t p_stLength) { - releaseKey(); if (p_stLength) { @@ -130,9 +122,8 @@ char* MDNSResponder::stcMDNSServiceTxt::allocKey(size_t p_stLength) MDNSResponder::stcMDNSServiceTxt::setKey */ bool MDNSResponder::stcMDNSServiceTxt::setKey(const char* p_pcKey, - size_t p_stLength) + size_t p_stLength) { - bool bResult = false; releaseKey(); @@ -153,7 +144,6 @@ bool MDNSResponder::stcMDNSServiceTxt::setKey(const char* p_pcKey, */ bool MDNSResponder::stcMDNSServiceTxt::setKey(const char* p_pcKey) { - return setKey(p_pcKey, (p_pcKey ? strlen(p_pcKey) : 0)); } @@ -162,7 +152,6 @@ bool MDNSResponder::stcMDNSServiceTxt::setKey(const char* p_pcKey) */ bool MDNSResponder::stcMDNSServiceTxt::releaseKey(void) { - if (m_pcKey) { delete[] m_pcKey; @@ -176,7 +165,6 @@ bool MDNSResponder::stcMDNSServiceTxt::releaseKey(void) */ char* MDNSResponder::stcMDNSServiceTxt::allocValue(size_t p_stLength) { - releaseValue(); if (p_stLength) { @@ -189,9 +177,8 @@ char* MDNSResponder::stcMDNSServiceTxt::allocValue(size_t p_stLength) MDNSResponder::stcMDNSServiceTxt::setValue */ bool MDNSResponder::stcMDNSServiceTxt::setValue(const char* p_pcValue, - size_t p_stLength) + size_t p_stLength) { - bool bResult = false; releaseValue(); @@ -204,7 +191,7 @@ bool MDNSResponder::stcMDNSServiceTxt::setValue(const char* p_pcValue, bResult = true; } } - else // No value -> also OK + else // No value -> also OK { bResult = true; } @@ -216,7 +203,6 @@ bool MDNSResponder::stcMDNSServiceTxt::setValue(const char* p_pcValue, */ bool MDNSResponder::stcMDNSServiceTxt::setValue(const char* p_pcValue) { - return setValue(p_pcValue, (p_pcValue ? strlen(p_pcValue) : 0)); } @@ -225,7 +211,6 @@ bool MDNSResponder::stcMDNSServiceTxt::setValue(const char* p_pcValue) */ bool MDNSResponder::stcMDNSServiceTxt::releaseValue(void) { - if (m_pcValue) { delete[] m_pcValue; @@ -238,10 +223,9 @@ bool MDNSResponder::stcMDNSServiceTxt::releaseValue(void) MDNSResponder::stcMDNSServiceTxt::set */ bool MDNSResponder::stcMDNSServiceTxt::set(const char* p_pcKey, - const char* p_pcValue, - bool p_bTemp /*= false*/) + const char* p_pcValue, + bool p_bTemp /*= false*/) { - m_bTemp = p_bTemp; return ((setKey(p_pcKey)) && (setValue(p_pcValue))); @@ -252,7 +236,6 @@ bool MDNSResponder::stcMDNSServiceTxt::set(const char* p_pcKey, */ bool MDNSResponder::stcMDNSServiceTxt::update(const char* p_pcValue) { - return setValue(p_pcValue); } @@ -263,18 +246,16 @@ bool MDNSResponder::stcMDNSServiceTxt::update(const char* p_pcValue) */ size_t MDNSResponder::stcMDNSServiceTxt::length(void) const { - - size_t stLength = 0; + size_t stLength = 0; if (m_pcKey) { - stLength += strlen(m_pcKey); // Key - stLength += 1; // '=' - stLength += (m_pcValue ? strlen(m_pcValue) : 0); // Value + stLength += strlen(m_pcKey); // Key + stLength += 1; // '=' + stLength += (m_pcValue ? strlen(m_pcValue) : 0); // Value } return stLength; } - /** MDNSResponder::stcMDNSServiceTxts @@ -291,18 +272,16 @@ size_t MDNSResponder::stcMDNSServiceTxt::length(void) const MDNSResponder::stcMDNSServiceTxts::stcMDNSServiceTxts constructor */ MDNSResponder::stcMDNSServiceTxts::stcMDNSServiceTxts(void) - : m_pTxts(0) + : m_pTxts(0) { - } /* MDNSResponder::stcMDNSServiceTxts::stcMDNSServiceTxts copy-constructor */ MDNSResponder::stcMDNSServiceTxts::stcMDNSServiceTxts(const stcMDNSServiceTxts& p_Other) - : m_pTxts(0) + : m_pTxts(0) { - operator=(p_Other); } @@ -311,7 +290,6 @@ MDNSResponder::stcMDNSServiceTxts::stcMDNSServiceTxts(const stcMDNSServiceTxts& */ MDNSResponder::stcMDNSServiceTxts::~stcMDNSServiceTxts(void) { - clear(); } @@ -320,7 +298,6 @@ MDNSResponder::stcMDNSServiceTxts::~stcMDNSServiceTxts(void) */ MDNSResponder::stcMDNSServiceTxts& MDNSResponder::stcMDNSServiceTxts::operator=(const stcMDNSServiceTxts& p_Other) { - if (this != &p_Other) { clear(); @@ -338,7 +315,6 @@ MDNSResponder::stcMDNSServiceTxts& MDNSResponder::stcMDNSServiceTxts::operator=( */ bool MDNSResponder::stcMDNSServiceTxts::clear(void) { - while (m_pTxts) { stcMDNSServiceTxt* pNext = m_pTxts->m_pNext; @@ -353,7 +329,6 @@ bool MDNSResponder::stcMDNSServiceTxts::clear(void) */ bool MDNSResponder::stcMDNSServiceTxts::add(MDNSResponder::stcMDNSServiceTxt* p_pTxt) { - bool bResult = false; if (p_pTxt) @@ -370,14 +345,13 @@ bool MDNSResponder::stcMDNSServiceTxts::add(MDNSResponder::stcMDNSServiceTxt* p_ */ bool MDNSResponder::stcMDNSServiceTxts::remove(stcMDNSServiceTxt* p_pTxt) { - - bool bResult = false; + bool bResult = false; if (p_pTxt) { - stcMDNSServiceTxt* pPred = m_pTxts; + stcMDNSServiceTxt* pPred = m_pTxts; while ((pPred) && - (pPred->m_pNext != p_pTxt)) + (pPred->m_pNext != p_pTxt)) { pPred = pPred->m_pNext; } @@ -387,7 +361,7 @@ bool MDNSResponder::stcMDNSServiceTxts::remove(stcMDNSServiceTxt* p_pTxt) delete p_pTxt; bResult = true; } - else if (m_pTxts == p_pTxt) // No predecessor, but first item + else if (m_pTxts == p_pTxt) // No predecessor, but first item { m_pTxts = p_pTxt->m_pNext; delete p_pTxt; @@ -402,14 +376,13 @@ bool MDNSResponder::stcMDNSServiceTxts::remove(stcMDNSServiceTxt* p_pTxt) */ bool MDNSResponder::stcMDNSServiceTxts::removeTempTxts(void) { + bool bResult = true; - bool bResult = true; - - stcMDNSServiceTxt* pTxt = m_pTxts; + stcMDNSServiceTxt* pTxt = m_pTxts; while ((bResult) && - (pTxt)) + (pTxt)) { - stcMDNSServiceTxt* pNext = pTxt->m_pNext; + stcMDNSServiceTxt* pNext = pTxt->m_pNext; if (pTxt->m_bTemp) { bResult = remove(pTxt); @@ -424,13 +397,12 @@ bool MDNSResponder::stcMDNSServiceTxts::removeTempTxts(void) */ MDNSResponder::stcMDNSServiceTxt* MDNSResponder::stcMDNSServiceTxts::find(const char* p_pcKey) { - stcMDNSServiceTxt* pResult = 0; for (stcMDNSServiceTxt* pTxt = m_pTxts; pTxt; pTxt = pTxt->m_pNext) { if ((p_pcKey) && - (0 == strcmp(pTxt->m_pcKey, p_pcKey))) + (0 == strcmp(pTxt->m_pcKey, p_pcKey))) { pResult = pTxt; break; @@ -444,15 +416,13 @@ MDNSResponder::stcMDNSServiceTxt* MDNSResponder::stcMDNSServiceTxts::find(const */ const MDNSResponder::stcMDNSServiceTxt* MDNSResponder::stcMDNSServiceTxts::find(const char* p_pcKey) const { - - const stcMDNSServiceTxt* pResult = 0; + const stcMDNSServiceTxt* pResult = 0; for (const stcMDNSServiceTxt* pTxt = m_pTxts; pTxt; pTxt = pTxt->m_pNext) { if ((p_pcKey) && - (0 == strcmp(pTxt->m_pcKey, p_pcKey))) + (0 == strcmp(pTxt->m_pcKey, p_pcKey))) { - pResult = pTxt; break; } @@ -465,7 +435,6 @@ const MDNSResponder::stcMDNSServiceTxt* MDNSResponder::stcMDNSServiceTxts::find( */ MDNSResponder::stcMDNSServiceTxt* MDNSResponder::stcMDNSServiceTxts::find(const stcMDNSServiceTxt* p_pTxt) { - stcMDNSServiceTxt* pResult = 0; for (stcMDNSServiceTxt* pTxt = m_pTxts; pTxt; pTxt = pTxt->m_pNext) @@ -484,14 +453,13 @@ MDNSResponder::stcMDNSServiceTxt* MDNSResponder::stcMDNSServiceTxts::find(const */ uint16_t MDNSResponder::stcMDNSServiceTxts::length(void) const { + uint16_t u16Length = 0; - uint16_t u16Length = 0; - - stcMDNSServiceTxt* pTxt = m_pTxts; + stcMDNSServiceTxt* pTxt = m_pTxts; while (pTxt) { - u16Length += 1; // Length byte - u16Length += pTxt->length(); // Text + u16Length += 1; // Length byte + u16Length += pTxt->length(); // Text pTxt = pTxt->m_pNext; } return u16Length; @@ -504,7 +472,6 @@ uint16_t MDNSResponder::stcMDNSServiceTxts::length(void) const */ size_t MDNSResponder::stcMDNSServiceTxts::c_strLength(void) const { - return length(); } @@ -513,7 +480,6 @@ size_t MDNSResponder::stcMDNSServiceTxts::c_strLength(void) const */ bool MDNSResponder::stcMDNSServiceTxts::c_str(char* p_pcBuffer) { - bool bResult = false; if (p_pcBuffer) @@ -523,19 +489,21 @@ bool MDNSResponder::stcMDNSServiceTxts::c_str(char* p_pcBuffer) *p_pcBuffer = 0; for (stcMDNSServiceTxt* pTxt = m_pTxts; ((bResult) && (pTxt)); pTxt = pTxt->m_pNext) { - size_t stLength; + size_t stLength; if ((bResult = (0 != (stLength = (pTxt->m_pcKey ? strlen(pTxt->m_pcKey) : 0))))) { if (pTxt != m_pTxts) { *p_pcBuffer++ = ';'; } - strncpy(p_pcBuffer, pTxt->m_pcKey, stLength); p_pcBuffer[stLength] = 0; + strncpy(p_pcBuffer, pTxt->m_pcKey, stLength); + p_pcBuffer[stLength] = 0; p_pcBuffer += stLength; *p_pcBuffer++ = '='; if ((stLength = (pTxt->m_pcValue ? strlen(pTxt->m_pcValue) : 0))) { - strncpy(p_pcBuffer, pTxt->m_pcValue, stLength); p_pcBuffer[stLength] = 0; + strncpy(p_pcBuffer, pTxt->m_pcValue, stLength); + p_pcBuffer[stLength] = 0; p_pcBuffer += stLength; } } @@ -552,7 +520,6 @@ bool MDNSResponder::stcMDNSServiceTxts::c_str(char* p_pcBuffer) */ size_t MDNSResponder::stcMDNSServiceTxts::bufferLength(void) const { - return (length() + 1); } @@ -561,7 +528,6 @@ size_t MDNSResponder::stcMDNSServiceTxts::bufferLength(void) const */ bool MDNSResponder::stcMDNSServiceTxts::buffer(char* p_pcBuffer) { - bool bResult = false; if (p_pcBuffer) @@ -572,7 +538,7 @@ bool MDNSResponder::stcMDNSServiceTxts::buffer(char* p_pcBuffer) for (stcMDNSServiceTxt* pTxt = m_pTxts; ((bResult) && (pTxt)); pTxt = pTxt->m_pNext) { *(unsigned char*)p_pcBuffer++ = pTxt->length(); - size_t stLength; + size_t stLength; if ((bResult = (0 != (stLength = (pTxt->m_pcKey ? strlen(pTxt->m_pcKey) : 0))))) { memcpy(p_pcBuffer, pTxt->m_pcKey, stLength); @@ -595,15 +561,14 @@ bool MDNSResponder::stcMDNSServiceTxts::buffer(char* p_pcBuffer) */ bool MDNSResponder::stcMDNSServiceTxts::compare(const MDNSResponder::stcMDNSServiceTxts& p_Other) const { - - bool bResult = false; + bool bResult = false; if ((bResult = (length() == p_Other.length()))) { // Compare A->B for (const stcMDNSServiceTxt* pTxt = m_pTxts; ((bResult) && (pTxt)); pTxt = pTxt->m_pNext) { - const stcMDNSServiceTxt* pOtherTxt = p_Other.find(pTxt->m_pcKey); + const stcMDNSServiceTxt* pOtherTxt = p_Other.find(pTxt->m_pcKey); bResult = ((pOtherTxt) && (pTxt->m_pcValue) && (pOtherTxt->m_pcValue) && @@ -613,7 +578,7 @@ bool MDNSResponder::stcMDNSServiceTxts::compare(const MDNSResponder::stcMDNSServ // Compare B->A for (const stcMDNSServiceTxt* pOtherTxt = p_Other.m_pTxts; ((bResult) && (pOtherTxt)); pOtherTxt = pOtherTxt->m_pNext) { - const stcMDNSServiceTxt* pTxt = find(pOtherTxt->m_pcKey); + const stcMDNSServiceTxt* pTxt = find(pOtherTxt->m_pcKey); bResult = ((pTxt) && (pOtherTxt->m_pcValue) && (pTxt->m_pcValue) && @@ -629,7 +594,6 @@ bool MDNSResponder::stcMDNSServiceTxts::compare(const MDNSResponder::stcMDNSServ */ bool MDNSResponder::stcMDNSServiceTxts::operator==(const stcMDNSServiceTxts& p_Other) const { - return compare(p_Other); } @@ -638,11 +602,9 @@ bool MDNSResponder::stcMDNSServiceTxts::operator==(const stcMDNSServiceTxts& p_O */ bool MDNSResponder::stcMDNSServiceTxts::operator!=(const stcMDNSServiceTxts& p_Other) const { - return !compare(p_Other); } - /** MDNSResponder::stcMDNS_MsgHeader @@ -654,29 +616,33 @@ bool MDNSResponder::stcMDNSServiceTxts::operator!=(const stcMDNSServiceTxts& p_O MDNSResponder::stcMDNS_MsgHeader::stcMDNS_MsgHeader */ MDNSResponder::stcMDNS_MsgHeader::stcMDNS_MsgHeader(uint16_t p_u16ID /*= 0*/, - bool p_bQR /*= false*/, - unsigned char p_ucOpcode /*= 0*/, - bool p_bAA /*= false*/, - bool p_bTC /*= false*/, - bool p_bRD /*= false*/, - bool p_bRA /*= false*/, - unsigned char p_ucRCode /*= 0*/, - uint16_t p_u16QDCount /*= 0*/, - uint16_t p_u16ANCount /*= 0*/, - uint16_t p_u16NSCount /*= 0*/, - uint16_t p_u16ARCount /*= 0*/) - : m_u16ID(p_u16ID), - m_1bQR(p_bQR), m_4bOpcode(p_ucOpcode), m_1bAA(p_bAA), m_1bTC(p_bTC), m_1bRD(p_bRD), - m_1bRA(p_bRA), m_3bZ(0), m_4bRCode(p_ucRCode), - m_u16QDCount(p_u16QDCount), - m_u16ANCount(p_u16ANCount), - m_u16NSCount(p_u16NSCount), - m_u16ARCount(p_u16ARCount) + bool p_bQR /*= false*/, + unsigned char p_ucOpcode /*= 0*/, + bool p_bAA /*= false*/, + bool p_bTC /*= false*/, + bool p_bRD /*= false*/, + bool p_bRA /*= false*/, + unsigned char p_ucRCode /*= 0*/, + uint16_t p_u16QDCount /*= 0*/, + uint16_t p_u16ANCount /*= 0*/, + uint16_t p_u16NSCount /*= 0*/, + uint16_t p_u16ARCount /*= 0*/) + : m_u16ID(p_u16ID), + m_1bQR(p_bQR), + m_4bOpcode(p_ucOpcode), + m_1bAA(p_bAA), + m_1bTC(p_bTC), + m_1bRD(p_bRD), + m_1bRA(p_bRA), + m_3bZ(0), + m_4bRCode(p_ucRCode), + m_u16QDCount(p_u16QDCount), + m_u16ANCount(p_u16ANCount), + m_u16NSCount(p_u16NSCount), + m_u16ARCount(p_u16ARCount) { - } - /** MDNSResponder::stcMDNS_RRDomain @@ -694,9 +660,8 @@ MDNSResponder::stcMDNS_MsgHeader::stcMDNS_MsgHeader(uint16_t p_u16ID /*= 0*/, MDNSResponder::stcMDNS_RRDomain::stcMDNS_RRDomain constructor */ MDNSResponder::stcMDNS_RRDomain::stcMDNS_RRDomain(void) - : m_u16NameLength(0) + : m_u16NameLength(0) { - clear(); } @@ -704,9 +669,8 @@ MDNSResponder::stcMDNS_RRDomain::stcMDNS_RRDomain(void) MDNSResponder::stcMDNS_RRDomain::stcMDNS_RRDomain copy-constructor */ MDNSResponder::stcMDNS_RRDomain::stcMDNS_RRDomain(const stcMDNS_RRDomain& p_Other) - : m_u16NameLength(0) + : m_u16NameLength(0) { - operator=(p_Other); } @@ -715,7 +679,6 @@ MDNSResponder::stcMDNS_RRDomain::stcMDNS_RRDomain(const stcMDNS_RRDomain& p_Othe */ MDNSResponder::stcMDNS_RRDomain& MDNSResponder::stcMDNS_RRDomain::operator=(const stcMDNS_RRDomain& p_Other) { - if (&p_Other != this) { memcpy(m_acName, p_Other.m_acName, sizeof(m_acName)); @@ -729,7 +692,6 @@ MDNSResponder::stcMDNS_RRDomain& MDNSResponder::stcMDNS_RRDomain::operator=(cons */ bool MDNSResponder::stcMDNS_RRDomain::clear(void) { - memset(m_acName, 0, sizeof(m_acName)); m_u16NameLength = 0; return true; @@ -739,19 +701,18 @@ bool MDNSResponder::stcMDNS_RRDomain::clear(void) MDNSResponder::stcMDNS_RRDomain::addLabel */ bool MDNSResponder::stcMDNS_RRDomain::addLabel(const char* p_pcLabel, - bool p_bPrependUnderline /*= false*/) + bool p_bPrependUnderline /*= false*/) { + bool bResult = false; - bool bResult = false; - - size_t stLength = (p_pcLabel - ? (strlen(p_pcLabel) + (p_bPrependUnderline ? 1 : 0)) - : 0); + size_t stLength = (p_pcLabel + ? (strlen(p_pcLabel) + (p_bPrependUnderline ? 1 : 0)) + : 0); if ((MDNS_DOMAIN_LABEL_MAXLENGTH >= stLength) && - (MDNS_DOMAIN_MAXLENGTH >= (m_u16NameLength + (1 + stLength)))) + (MDNS_DOMAIN_MAXLENGTH >= (m_u16NameLength + (1 + stLength)))) { // Length byte - m_acName[m_u16NameLength] = (unsigned char)stLength; // Might be 0! + m_acName[m_u16NameLength] = (unsigned char)stLength; // Might be 0! ++m_u16NameLength; // Label if (stLength) @@ -761,7 +722,8 @@ bool MDNSResponder::stcMDNS_RRDomain::addLabel(const char* p_pcLabel, m_acName[m_u16NameLength++] = '_'; --stLength; } - strncpy(&(m_acName[m_u16NameLength]), p_pcLabel, stLength); m_acName[m_u16NameLength + stLength] = 0; + strncpy(&(m_acName[m_u16NameLength]), p_pcLabel, stLength); + m_acName[m_u16NameLength + stLength] = 0; m_u16NameLength += stLength; } bResult = true; @@ -774,24 +736,23 @@ bool MDNSResponder::stcMDNS_RRDomain::addLabel(const char* p_pcLabel, */ bool MDNSResponder::stcMDNS_RRDomain::compare(const stcMDNS_RRDomain& p_Other) const { - - bool bResult = false; + bool bResult = false; if (m_u16NameLength == p_Other.m_u16NameLength) { const char* pT = m_acName; const char* pO = p_Other.m_acName; while ((pT) && - (pO) && - (*((unsigned char*)pT) == *((unsigned char*)pO)) && // Same length AND - (0 == strncasecmp((pT + 1), (pO + 1), *((unsigned char*)pT)))) // Same content + (pO) && + (*((unsigned char*)pT) == *((unsigned char*)pO)) && // Same length AND + (0 == strncasecmp((pT + 1), (pO + 1), *((unsigned char*)pT)))) // Same content { - if (*((unsigned char*)pT)) // Not 0 + if (*((unsigned char*)pT)) // Not 0 { - pT += (1 + * ((unsigned char*)pT)); // Shift by length byte and length - pO += (1 + * ((unsigned char*)pO)); + pT += (1 + *((unsigned char*)pT)); // Shift by length byte and length + pO += (1 + *((unsigned char*)pO)); } - else // Is 0 -> Successfully reached the end + else // Is 0 -> Successfully reached the end { bResult = true; break; @@ -806,7 +767,6 @@ bool MDNSResponder::stcMDNS_RRDomain::compare(const stcMDNS_RRDomain& p_Other) c */ bool MDNSResponder::stcMDNS_RRDomain::operator==(const stcMDNS_RRDomain& p_Other) const { - return compare(p_Other); } @@ -815,7 +775,6 @@ bool MDNSResponder::stcMDNS_RRDomain::operator==(const stcMDNS_RRDomain& p_Other */ bool MDNSResponder::stcMDNS_RRDomain::operator!=(const stcMDNS_RRDomain& p_Other) const { - return !compare(p_Other); } @@ -824,7 +783,6 @@ bool MDNSResponder::stcMDNS_RRDomain::operator!=(const stcMDNS_RRDomain& p_Other */ bool MDNSResponder::stcMDNS_RRDomain::operator>(const stcMDNS_RRDomain& p_Other) const { - // TODO: Check, if this is a good idea... return !compare(p_Other); } @@ -834,10 +792,9 @@ bool MDNSResponder::stcMDNS_RRDomain::operator>(const stcMDNS_RRDomain& p_Other) */ size_t MDNSResponder::stcMDNS_RRDomain::c_strLength(void) const { + size_t stLength = 0; - size_t stLength = 0; - - unsigned char* pucLabelLength = (unsigned char*)m_acName; + unsigned char* pucLabelLength = (unsigned char*)m_acName; while (*pucLabelLength) { stLength += (*pucLabelLength + 1 /* +1 for '.' or '\0'*/); @@ -851,7 +808,6 @@ size_t MDNSResponder::stcMDNS_RRDomain::c_strLength(void) const */ bool MDNSResponder::stcMDNS_RRDomain::c_str(char* p_pcBuffer) { - bool bResult = false; if (p_pcBuffer) @@ -870,7 +826,6 @@ bool MDNSResponder::stcMDNS_RRDomain::c_str(char* p_pcBuffer) return bResult; } - /** MDNSResponder::stcMDNS_RRAttributes @@ -882,11 +837,10 @@ bool MDNSResponder::stcMDNS_RRDomain::c_str(char* p_pcBuffer) MDNSResponder::stcMDNS_RRAttributes::stcMDNS_RRAttributes constructor */ MDNSResponder::stcMDNS_RRAttributes::stcMDNS_RRAttributes(uint16_t p_u16Type /*= 0*/, - uint16_t p_u16Class /*= 1 DNS_RRCLASS_IN Internet*/) - : m_u16Type(p_u16Type), - m_u16Class(p_u16Class) + uint16_t p_u16Class /*= 1 DNS_RRCLASS_IN Internet*/) + : m_u16Type(p_u16Type), + m_u16Class(p_u16Class) { - } /* @@ -894,7 +848,6 @@ MDNSResponder::stcMDNS_RRAttributes::stcMDNS_RRAttributes(uint16_t p_u16Type /*= */ MDNSResponder::stcMDNS_RRAttributes::stcMDNS_RRAttributes(const MDNSResponder::stcMDNS_RRAttributes& p_Other) { - operator=(p_Other); } @@ -903,7 +856,6 @@ MDNSResponder::stcMDNS_RRAttributes::stcMDNS_RRAttributes(const MDNSResponder::s */ MDNSResponder::stcMDNS_RRAttributes& MDNSResponder::stcMDNS_RRAttributes::operator=(const MDNSResponder::stcMDNS_RRAttributes& p_Other) { - if (&p_Other != this) { m_u16Type = p_Other.m_u16Type; @@ -912,7 +864,6 @@ MDNSResponder::stcMDNS_RRAttributes& MDNSResponder::stcMDNS_RRAttributes::operat return *this; } - /** MDNSResponder::stcMDNS_RRHeader @@ -925,7 +876,6 @@ MDNSResponder::stcMDNS_RRAttributes& MDNSResponder::stcMDNS_RRAttributes::operat */ MDNSResponder::stcMDNS_RRHeader::stcMDNS_RRHeader(void) { - } /* @@ -933,7 +883,6 @@ MDNSResponder::stcMDNS_RRHeader::stcMDNS_RRHeader(void) */ MDNSResponder::stcMDNS_RRHeader::stcMDNS_RRHeader(const stcMDNS_RRHeader& p_Other) { - operator=(p_Other); } @@ -942,7 +891,6 @@ MDNSResponder::stcMDNS_RRHeader::stcMDNS_RRHeader(const stcMDNS_RRHeader& p_Othe */ MDNSResponder::stcMDNS_RRHeader& MDNSResponder::stcMDNS_RRHeader::operator=(const MDNSResponder::stcMDNS_RRHeader& p_Other) { - if (&p_Other != this) { m_Domain = p_Other.m_Domain; @@ -956,12 +904,10 @@ MDNSResponder::stcMDNS_RRHeader& MDNSResponder::stcMDNS_RRHeader::operator=(cons */ bool MDNSResponder::stcMDNS_RRHeader::clear(void) { - m_Domain.clear(); return true; } - /** MDNSResponder::stcMDNS_RRQuestion @@ -973,13 +919,11 @@ bool MDNSResponder::stcMDNS_RRHeader::clear(void) MDNSResponder::stcMDNS_RRQuestion::stcMDNS_RRQuestion constructor */ MDNSResponder::stcMDNS_RRQuestion::stcMDNS_RRQuestion(void) - : m_pNext(0), - m_bUnicast(false) + : m_pNext(0), + m_bUnicast(false) { - } - /** MDNSResponder::stcMDNS_RRAnswer @@ -992,14 +936,13 @@ MDNSResponder::stcMDNS_RRQuestion::stcMDNS_RRQuestion(void) MDNSResponder::stcMDNS_RRAnswer::stcMDNS_RRAnswer constructor */ MDNSResponder::stcMDNS_RRAnswer::stcMDNS_RRAnswer(enuAnswerType p_AnswerType, - const MDNSResponder::stcMDNS_RRHeader& p_Header, - uint32_t p_u32TTL) - : m_pNext(0), - m_AnswerType(p_AnswerType), - m_Header(p_Header), - m_u32TTL(p_u32TTL) + const MDNSResponder::stcMDNS_RRHeader& p_Header, + uint32_t p_u32TTL) + : m_pNext(0), + m_AnswerType(p_AnswerType), + m_Header(p_Header), + m_u32TTL(p_u32TTL) { - // Extract 'cache flush'-bit m_bCacheFlush = (m_Header.m_Attributes.m_u16Class & 0x8000); m_Header.m_Attributes.m_u16Class &= (~0x8000); @@ -1010,7 +953,6 @@ MDNSResponder::stcMDNS_RRAnswer::stcMDNS_RRAnswer(enuAnswerType p_AnswerType, */ MDNSResponder::stcMDNS_RRAnswer::~stcMDNS_RRAnswer(void) { - } /* @@ -1018,7 +960,6 @@ MDNSResponder::stcMDNS_RRAnswer::~stcMDNS_RRAnswer(void) */ MDNSResponder::enuAnswerType MDNSResponder::stcMDNS_RRAnswer::answerType(void) const { - return m_AnswerType; } @@ -1027,13 +968,11 @@ MDNSResponder::enuAnswerType MDNSResponder::stcMDNS_RRAnswer::answerType(void) c */ bool MDNSResponder::stcMDNS_RRAnswer::clear(void) { - m_pNext = 0; m_Header.clear(); return true; } - /** MDNSResponder::stcMDNS_RRAnswerA @@ -1047,11 +986,10 @@ bool MDNSResponder::stcMDNS_RRAnswer::clear(void) MDNSResponder::stcMDNS_RRAnswerA::stcMDNS_RRAnswerA constructor */ MDNSResponder::stcMDNS_RRAnswerA::stcMDNS_RRAnswerA(const MDNSResponder::stcMDNS_RRHeader& p_Header, - uint32_t p_u32TTL) - : stcMDNS_RRAnswer(AnswerType_A, p_Header, p_u32TTL), - m_IPAddress(0, 0, 0, 0) + uint32_t p_u32TTL) + : stcMDNS_RRAnswer(AnswerType_A, p_Header, p_u32TTL), + m_IPAddress(0, 0, 0, 0) { - } /* @@ -1059,7 +997,6 @@ MDNSResponder::stcMDNS_RRAnswerA::stcMDNS_RRAnswerA(const MDNSResponder::stcMDNS */ MDNSResponder::stcMDNS_RRAnswerA::~stcMDNS_RRAnswerA(void) { - clear(); } @@ -1068,13 +1005,11 @@ MDNSResponder::stcMDNS_RRAnswerA::~stcMDNS_RRAnswerA(void) */ bool MDNSResponder::stcMDNS_RRAnswerA::clear(void) { - m_IPAddress = IPAddress(0, 0, 0, 0); return true; } #endif - /** MDNSResponder::stcMDNS_RRAnswerPTR @@ -1087,10 +1022,9 @@ bool MDNSResponder::stcMDNS_RRAnswerA::clear(void) MDNSResponder::stcMDNS_RRAnswerPTR::stcMDNS_RRAnswerPTR constructor */ MDNSResponder::stcMDNS_RRAnswerPTR::stcMDNS_RRAnswerPTR(const MDNSResponder::stcMDNS_RRHeader& p_Header, - uint32_t p_u32TTL) - : stcMDNS_RRAnswer(AnswerType_PTR, p_Header, p_u32TTL) + uint32_t p_u32TTL) + : stcMDNS_RRAnswer(AnswerType_PTR, p_Header, p_u32TTL) { - } /* @@ -1098,7 +1032,6 @@ MDNSResponder::stcMDNS_RRAnswerPTR::stcMDNS_RRAnswerPTR(const MDNSResponder::stc */ MDNSResponder::stcMDNS_RRAnswerPTR::~stcMDNS_RRAnswerPTR(void) { - clear(); } @@ -1107,12 +1040,10 @@ MDNSResponder::stcMDNS_RRAnswerPTR::~stcMDNS_RRAnswerPTR(void) */ bool MDNSResponder::stcMDNS_RRAnswerPTR::clear(void) { - m_PTRDomain.clear(); return true; } - /** MDNSResponder::stcMDNS_RRAnswerTXT @@ -1125,10 +1056,9 @@ bool MDNSResponder::stcMDNS_RRAnswerPTR::clear(void) MDNSResponder::stcMDNS_RRAnswerTXT::stcMDNS_RRAnswerTXT constructor */ MDNSResponder::stcMDNS_RRAnswerTXT::stcMDNS_RRAnswerTXT(const MDNSResponder::stcMDNS_RRHeader& p_Header, - uint32_t p_u32TTL) - : stcMDNS_RRAnswer(AnswerType_TXT, p_Header, p_u32TTL) + uint32_t p_u32TTL) + : stcMDNS_RRAnswer(AnswerType_TXT, p_Header, p_u32TTL) { - } /* @@ -1136,7 +1066,6 @@ MDNSResponder::stcMDNS_RRAnswerTXT::stcMDNS_RRAnswerTXT(const MDNSResponder::stc */ MDNSResponder::stcMDNS_RRAnswerTXT::~stcMDNS_RRAnswerTXT(void) { - clear(); } @@ -1145,12 +1074,10 @@ MDNSResponder::stcMDNS_RRAnswerTXT::~stcMDNS_RRAnswerTXT(void) */ bool MDNSResponder::stcMDNS_RRAnswerTXT::clear(void) { - m_Txts.clear(); return true; } - /** MDNSResponder::stcMDNS_RRAnswerAAAA @@ -1164,10 +1091,9 @@ bool MDNSResponder::stcMDNS_RRAnswerTXT::clear(void) MDNSResponder::stcMDNS_RRAnswerAAAA::stcMDNS_RRAnswerAAAA constructor */ MDNSResponder::stcMDNS_RRAnswerAAAA::stcMDNS_RRAnswerAAAA(const MDNSResponder::stcMDNS_RRHeader& p_Header, - uint32_t p_u32TTL) - : stcMDNS_RRAnswer(AnswerType_AAAA, p_Header, p_u32TTL) + uint32_t p_u32TTL) + : stcMDNS_RRAnswer(AnswerType_AAAA, p_Header, p_u32TTL) { - } /* @@ -1175,7 +1101,6 @@ MDNSResponder::stcMDNS_RRAnswerAAAA::stcMDNS_RRAnswerAAAA(const MDNSResponder::s */ MDNSResponder::stcMDNS_RRAnswerAAAA::~stcMDNS_RRAnswerAAAA(void) { - clear(); } @@ -1184,12 +1109,10 @@ MDNSResponder::stcMDNS_RRAnswerAAAA::~stcMDNS_RRAnswerAAAA(void) */ bool MDNSResponder::stcMDNS_RRAnswerAAAA::clear(void) { - return true; } #endif - /** MDNSResponder::stcMDNS_RRAnswerSRV @@ -1202,13 +1125,12 @@ bool MDNSResponder::stcMDNS_RRAnswerAAAA::clear(void) MDNSResponder::stcMDNS_RRAnswerSRV::stcMDNS_RRAnswerSRV constructor */ MDNSResponder::stcMDNS_RRAnswerSRV::stcMDNS_RRAnswerSRV(const MDNSResponder::stcMDNS_RRHeader& p_Header, - uint32_t p_u32TTL) - : stcMDNS_RRAnswer(AnswerType_SRV, p_Header, p_u32TTL), - m_u16Priority(0), - m_u16Weight(0), - m_u16Port(0) + uint32_t p_u32TTL) + : stcMDNS_RRAnswer(AnswerType_SRV, p_Header, p_u32TTL), + m_u16Priority(0), + m_u16Weight(0), + m_u16Port(0) { - } /* @@ -1216,7 +1138,6 @@ MDNSResponder::stcMDNS_RRAnswerSRV::stcMDNS_RRAnswerSRV(const MDNSResponder::stc */ MDNSResponder::stcMDNS_RRAnswerSRV::~stcMDNS_RRAnswerSRV(void) { - clear(); } @@ -1225,7 +1146,6 @@ MDNSResponder::stcMDNS_RRAnswerSRV::~stcMDNS_RRAnswerSRV(void) */ bool MDNSResponder::stcMDNS_RRAnswerSRV::clear(void) { - m_u16Priority = 0; m_u16Weight = 0; m_u16Port = 0; @@ -1233,7 +1153,6 @@ bool MDNSResponder::stcMDNS_RRAnswerSRV::clear(void) return true; } - /** MDNSResponder::stcMDNS_RRAnswerGeneric @@ -1246,12 +1165,11 @@ bool MDNSResponder::stcMDNS_RRAnswerSRV::clear(void) MDNSResponder::stcMDNS_RRAnswerGeneric::stcMDNS_RRAnswerGeneric constructor */ MDNSResponder::stcMDNS_RRAnswerGeneric::stcMDNS_RRAnswerGeneric(const stcMDNS_RRHeader& p_Header, - uint32_t p_u32TTL) - : stcMDNS_RRAnswer(AnswerType_Generic, p_Header, p_u32TTL), - m_u16RDLength(0), - m_pu8RDData(0) + uint32_t p_u32TTL) + : stcMDNS_RRAnswer(AnswerType_Generic, p_Header, p_u32TTL), + m_u16RDLength(0), + m_pu8RDData(0) { - } /* @@ -1259,7 +1177,6 @@ MDNSResponder::stcMDNS_RRAnswerGeneric::stcMDNS_RRAnswerGeneric(const stcMDNS_RR */ MDNSResponder::stcMDNS_RRAnswerGeneric::~stcMDNS_RRAnswerGeneric(void) { - clear(); } @@ -1268,7 +1185,6 @@ MDNSResponder::stcMDNS_RRAnswerGeneric::~stcMDNS_RRAnswerGeneric(void) */ bool MDNSResponder::stcMDNS_RRAnswerGeneric::clear(void) { - if (m_pu8RDData) { delete[] m_pu8RDData; @@ -1279,7 +1195,6 @@ bool MDNSResponder::stcMDNS_RRAnswerGeneric::clear(void) return true; } - /** MDNSResponder::stcProbeInformation @@ -1291,13 +1206,13 @@ bool MDNSResponder::stcMDNS_RRAnswerGeneric::clear(void) MDNSResponder::stcProbeInformation::stcProbeInformation constructor */ MDNSResponder::stcProbeInformation::stcProbeInformation(void) - : m_ProbingStatus(ProbingStatus_WaitingForData), - m_u8SentCount(0), - m_Timeout(esp8266::polledTimeout::oneShotMs::neverExpires), - m_bConflict(false), - m_bTiebreakNeeded(false), - m_fnHostProbeResultCallback(0), - m_fnServiceProbeResultCallback(0) + : m_ProbingStatus(ProbingStatus_WaitingForData), + m_u8SentCount(0), + m_Timeout(esp8266::polledTimeout::oneShotMs::neverExpires), + m_bConflict(false), + m_bTiebreakNeeded(false), + m_fnHostProbeResultCallback(0), + m_fnServiceProbeResultCallback(0) { } @@ -1306,7 +1221,6 @@ MDNSResponder::stcProbeInformation::stcProbeInformation(void) */ bool MDNSResponder::stcProbeInformation::clear(bool p_bClearUserdata /*= false*/) { - m_ProbingStatus = ProbingStatus_WaitingForData; m_u8SentCount = 0; m_Timeout.resetToNeverExpires(); @@ -1335,18 +1249,17 @@ bool MDNSResponder::stcProbeInformation::clear(bool p_bClearUserdata /*= false*/ MDNSResponder::stcMDNSService::stcMDNSService constructor */ MDNSResponder::stcMDNSService::stcMDNSService(const char* p_pcName /*= 0*/, - const char* p_pcService /*= 0*/, - const char* p_pcProtocol /*= 0*/) - : m_pNext(0), - m_pcName(0), - m_bAutoName(false), - m_pcService(0), - m_pcProtocol(0), - m_u16Port(0), - m_u8ReplyMask(0), - m_fnTxtCallback(0) + const char* p_pcService /*= 0*/, + const char* p_pcProtocol /*= 0*/) + : m_pNext(0), + m_pcName(0), + m_bAutoName(false), + m_pcService(0), + m_pcProtocol(0), + m_u16Port(0), + m_u8ReplyMask(0), + m_fnTxtCallback(0) { - setName(p_pcName); setService(p_pcService); setProtocol(p_pcProtocol); @@ -1357,7 +1270,6 @@ MDNSResponder::stcMDNSService::stcMDNSService(const char* p_pcName /*= 0*/, */ MDNSResponder::stcMDNSService::~stcMDNSService(void) { - releaseName(); releaseService(); releaseProtocol(); @@ -1368,7 +1280,6 @@ MDNSResponder::stcMDNSService::~stcMDNSService(void) */ bool MDNSResponder::stcMDNSService::setName(const char* p_pcName) { - bool bResult = false; releaseName(); @@ -1393,7 +1304,6 @@ bool MDNSResponder::stcMDNSService::setName(const char* p_pcName) */ bool MDNSResponder::stcMDNSService::releaseName(void) { - if (m_pcName) { delete[] m_pcName; @@ -1407,7 +1317,6 @@ bool MDNSResponder::stcMDNSService::releaseName(void) */ bool MDNSResponder::stcMDNSService::setService(const char* p_pcService) { - bool bResult = false; releaseService(); @@ -1432,7 +1341,6 @@ bool MDNSResponder::stcMDNSService::setService(const char* p_pcService) */ bool MDNSResponder::stcMDNSService::releaseService(void) { - if (m_pcService) { delete[] m_pcService; @@ -1446,7 +1354,6 @@ bool MDNSResponder::stcMDNSService::releaseService(void) */ bool MDNSResponder::stcMDNSService::setProtocol(const char* p_pcProtocol) { - bool bResult = false; releaseProtocol(); @@ -1471,7 +1378,6 @@ bool MDNSResponder::stcMDNSService::setProtocol(const char* p_pcProtocol) */ bool MDNSResponder::stcMDNSService::releaseProtocol(void) { - if (m_pcProtocol) { delete[] m_pcProtocol; @@ -1480,7 +1386,6 @@ bool MDNSResponder::stcMDNSService::releaseProtocol(void) return true; } - /** MDNSResponder::stcMDNSServiceQuery @@ -1562,7 +1467,6 @@ bool MDNSResponder::stcMDNSService::releaseProtocol(void) (m_TTLTimeFlag.flagged())); }*/ - /** MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL @@ -1577,11 +1481,10 @@ bool MDNSResponder::stcMDNSService::releaseProtocol(void) MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::stcTTL constructor */ MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::stcTTL(void) - : m_u32TTL(0), - m_TTLTimeout(esp8266::polledTimeout::oneShotMs::neverExpires), - m_timeoutLevel(TIMEOUTLEVEL_UNSET) + : m_u32TTL(0), + m_TTLTimeout(esp8266::polledTimeout::oneShotMs::neverExpires), + m_timeoutLevel(TIMEOUTLEVEL_UNSET) { - } /* @@ -1589,16 +1492,15 @@ MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::stcTTL(void) */ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::set(uint32_t p_u32TTL) { - m_u32TTL = p_u32TTL; if (m_u32TTL) { - m_timeoutLevel = TIMEOUTLEVEL_BASE; // Set to 80% + m_timeoutLevel = TIMEOUTLEVEL_BASE; // Set to 80% m_TTLTimeout.reset(timeout()); } else { - m_timeoutLevel = TIMEOUTLEVEL_UNSET; // undef + m_timeoutLevel = TIMEOUTLEVEL_UNSET; // undef m_TTLTimeout.resetToNeverExpires(); } return true; @@ -1609,7 +1511,6 @@ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::set(uint32_t p_u32TT */ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::flagged(void) { - return ((m_u32TTL) && (TIMEOUTLEVEL_UNSET != m_timeoutLevel) && (m_TTLTimeout.expired())); @@ -1620,14 +1521,12 @@ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::flagged(void) */ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::restart(void) { + bool bResult = true; - bool bResult = true; - - if ((TIMEOUTLEVEL_BASE <= m_timeoutLevel) && // >= 80% AND - (TIMEOUTLEVEL_FINAL > m_timeoutLevel)) // < 100% + if ((TIMEOUTLEVEL_BASE <= m_timeoutLevel) && // >= 80% AND + (TIMEOUTLEVEL_FINAL > m_timeoutLevel)) // < 100% { - - m_timeoutLevel += TIMEOUTLEVEL_INTERVAL; // increment by 5% + m_timeoutLevel += TIMEOUTLEVEL_INTERVAL; // increment by 5% m_TTLTimeout.reset(timeout()); } else @@ -1644,9 +1543,8 @@ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::restart(void) */ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::prepareDeletion(void) { - m_timeoutLevel = TIMEOUTLEVEL_FINAL; - m_TTLTimeout.reset(1 * 1000); // See RFC 6762, 10.1 + m_TTLTimeout.reset(1 * 1000); // See RFC 6762, 10.1 return true; } @@ -1656,7 +1554,6 @@ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::prepareDeletion(void */ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::finalTimeoutLevel(void) const { - return (TIMEOUTLEVEL_FINAL == m_timeoutLevel); } @@ -1665,20 +1562,18 @@ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::finalTimeoutLevel(vo */ MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::timeoutBase::timeType MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::timeout(void) const { - if (TIMEOUTLEVEL_BASE == m_timeoutLevel) // 80% + if (TIMEOUTLEVEL_BASE == m_timeoutLevel) // 80% { - return (m_u32TTL * 800L); // to milliseconds + return (m_u32TTL * 800L); // to milliseconds } - else if ((TIMEOUTLEVEL_BASE < m_timeoutLevel) && // >80% AND - (TIMEOUTLEVEL_FINAL >= m_timeoutLevel)) // <= 100% + else if ((TIMEOUTLEVEL_BASE < m_timeoutLevel) && // >80% AND + (TIMEOUTLEVEL_FINAL >= m_timeoutLevel)) // <= 100% { - return (m_u32TTL * 50L); - } // else: invalid + } // else: invalid return MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::timeoutBase::neverExpires; } - #ifdef MDNS_IP4_SUPPORT /** MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address @@ -1689,16 +1584,14 @@ MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::timeoutBase::timeType MDN MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address::stcIP4Address constructor */ MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address::stcIP4Address(IPAddress p_IPAddress, - uint32_t p_u32TTL /*= 0*/) - : m_pNext(0), - m_IPAddress(p_IPAddress) + uint32_t p_u32TTL /*= 0*/) + : m_pNext(0), + m_IPAddress(p_IPAddress) { - m_TTL.set(p_u32TTL); } #endif - /** MDNSResponder::stcMDNSServiceQuery::stcAnswer */ @@ -1707,18 +1600,18 @@ MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address::stcIP4Address(IPAd MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcAnswer constructor */ MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcAnswer(void) - : m_pNext(0), - m_pcServiceDomain(0), - m_pcHostDomain(0), - m_u16Port(0), - m_pcTxts(0), + : m_pNext(0), + m_pcServiceDomain(0), + m_pcHostDomain(0), + m_u16Port(0), + m_pcTxts(0), #ifdef MDNS_IP4_SUPPORT - m_pIP4Addresses(0), + m_pIP4Addresses(0), #endif #ifdef MDNS_IP6_SUPPORT - m_pIP6Addresses(0), + m_pIP6Addresses(0), #endif - m_u32ContentFlags(0) + m_u32ContentFlags(0) { } @@ -1727,7 +1620,6 @@ MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcAnswer(void) */ MDNSResponder::stcMDNSServiceQuery::stcAnswer::~stcAnswer(void) { - clear(); } @@ -1736,7 +1628,6 @@ MDNSResponder::stcMDNSServiceQuery::stcAnswer::~stcAnswer(void) */ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::clear(void) { - return ((releaseTxts()) && #ifdef MDNS_IP4_SUPPORT (releaseIP4Addresses()) && @@ -1744,7 +1635,7 @@ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::clear(void) #ifdef MDNS_IP6_SUPPORT (releaseIP6Addresses()) #endif - (releaseHostDomain()) && + (releaseHostDomain()) && (releaseServiceDomain())); } @@ -1756,7 +1647,6 @@ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::clear(void) */ char* MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocServiceDomain(size_t p_stLength) { - releaseServiceDomain(); if (p_stLength) { @@ -1770,7 +1660,6 @@ char* MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocServiceDomain(size_t p */ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseServiceDomain(void) { - if (m_pcServiceDomain) { delete[] m_pcServiceDomain; @@ -1787,7 +1676,6 @@ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseServiceDomain(void) */ char* MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocHostDomain(size_t p_stLength) { - releaseHostDomain(); if (p_stLength) { @@ -1801,7 +1689,6 @@ char* MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocHostDomain(size_t p_st */ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseHostDomain(void) { - if (m_pcHostDomain) { delete[] m_pcHostDomain; @@ -1818,7 +1705,6 @@ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseHostDomain(void) */ char* MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocTxts(size_t p_stLength) { - releaseTxts(); if (p_stLength) { @@ -1832,7 +1718,6 @@ char* MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocTxts(size_t p_stLength */ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseTxts(void) { - if (m_pcTxts) { delete[] m_pcTxts; @@ -1847,10 +1732,9 @@ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseTxts(void) */ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseIP4Addresses(void) { - while (m_pIP4Addresses) { - stcIP4Address* pNext = m_pIP4Addresses->m_pNext; + stcIP4Address* pNext = m_pIP4Addresses->m_pNext; delete m_pIP4Addresses; m_pIP4Addresses = pNext; } @@ -1862,7 +1746,6 @@ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseIP4Addresses(void) */ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::addIP4Address(MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* p_pIP4Address) { - bool bResult = false; if (p_pIP4Address) @@ -1879,14 +1762,13 @@ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::addIP4Address(MDNSResponder: */ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::removeIP4Address(MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* p_pIP4Address) { - - bool bResult = false; + bool bResult = false; if (p_pIP4Address) { - stcIP4Address* pPred = m_pIP4Addresses; + stcIP4Address* pPred = m_pIP4Addresses; while ((pPred) && - (pPred->m_pNext != p_pIP4Address)) + (pPred->m_pNext != p_pIP4Address)) { pPred = pPred->m_pNext; } @@ -1896,7 +1778,7 @@ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::removeIP4Address(MDNSRespond delete p_pIP4Address; bResult = true; } - else if (m_pIP4Addresses == p_pIP4Address) // No predecessor, but first item + else if (m_pIP4Addresses == p_pIP4Address) // No predecessor, but first item { m_pIP4Addresses = p_pIP4Address->m_pNext; delete p_pIP4Address; @@ -1911,7 +1793,6 @@ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::removeIP4Address(MDNSRespond */ const MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::findIP4Address(const IPAddress& p_IPAddress) const { - return (stcIP4Address*)(((const stcAnswer*)this)->findIP4Address(p_IPAddress)); } @@ -1920,8 +1801,7 @@ const MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* MDNSResponde */ MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::findIP4Address(const IPAddress& p_IPAddress) { - - stcIP4Address* pIP4Address = m_pIP4Addresses; + stcIP4Address* pIP4Address = m_pIP4Addresses; while (pIP4Address) { if (pIP4Address->m_IPAddress == p_IPAddress) @@ -1938,10 +1818,9 @@ MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* MDNSResponder::stc */ uint32_t MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP4AddressCount(void) const { + uint32_t u32Count = 0; - uint32_t u32Count = 0; - - stcIP4Address* pIP4Address = m_pIP4Addresses; + stcIP4Address* pIP4Address = m_pIP4Addresses; while (pIP4Address) { ++u32Count; @@ -1955,7 +1834,6 @@ uint32_t MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP4AddressCount(void) co */ MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP4AddressAtIndex(uint32_t p_u32Index) { - return (stcIP4Address*)(((const stcAnswer*)this)->IP4AddressAtIndex(p_u32Index)); } @@ -1964,15 +1842,14 @@ MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* MDNSResponder::stc */ const MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP4AddressAtIndex(uint32_t p_u32Index) const { - - const stcIP4Address* pIP4Address = 0; + const stcIP4Address* pIP4Address = 0; if (((uint32_t)(-1) != p_u32Index) && - (m_pIP4Addresses)) + (m_pIP4Addresses)) { - - uint32_t u32Index; - for (pIP4Address = m_pIP4Addresses, u32Index = 0; ((pIP4Address) && (u32Index < p_u32Index)); pIP4Address = pIP4Address->m_pNext, ++u32Index); + uint32_t u32Index; + for (pIP4Address = m_pIP4Addresses, u32Index = 0; ((pIP4Address) && (u32Index < p_u32Index)); pIP4Address = pIP4Address->m_pNext, ++u32Index) + ; } return pIP4Address; } @@ -1984,10 +1861,9 @@ const MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* MDNSResponde */ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseIP6Addresses(void) { - while (m_pIP6Addresses) { - stcIP6Address* pNext = m_pIP6Addresses->m_pNext; + stcIP6Address* pNext = m_pIP6Addresses->m_pNext; delete m_pIP6Addresses; m_pIP6Addresses = pNext; } @@ -1999,7 +1875,6 @@ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseIP6Addresses(void) */ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::addIP6Address(MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* p_pIP6Address) { - bool bResult = false; if (p_pIP6Address) @@ -2016,14 +1891,13 @@ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::addIP6Address(MDNSResponder: */ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::removeIP6Address(MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* p_pIP6Address) { - - bool bResult = false; + bool bResult = false; if (p_pIP6Address) { - stcIP6Address* pPred = m_pIP6Addresses; + stcIP6Address* pPred = m_pIP6Addresses; while ((pPred) && - (pPred->m_pNext != p_pIP6Address)) + (pPred->m_pNext != p_pIP6Address)) { pPred = pPred->m_pNext; } @@ -2033,7 +1907,7 @@ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::removeIP6Address(MDNSRespond delete p_pIP6Address; bResult = true; } - else if (m_pIP6Addresses == p_pIP6Address) // No predecessor, but first item + else if (m_pIP6Addresses == p_pIP6Address) // No predecessor, but first item { m_pIP6Addresses = p_pIP6Address->m_pNext; delete p_pIP6Address; @@ -2048,7 +1922,6 @@ bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::removeIP6Address(MDNSRespond */ MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::findIP6Address(const IP6Address& p_IPAddress) { - return (stcIP6Address*)(((const stcAnswer*)this)->findIP6Address(p_IPAddress)); } @@ -2057,8 +1930,7 @@ MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* MDNSResponder::stc */ const MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::findIP6Address(const IPAddress& p_IPAddress) const { - - const stcIP6Address* pIP6Address = m_pIP6Addresses; + const stcIP6Address* pIP6Address = m_pIP6Addresses; while (pIP6Address) { if (p_IP6Address->m_IPAddress == p_IPAddress) @@ -2075,10 +1947,9 @@ const MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* MDNSResponde */ uint32_t MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP6AddressCount(void) const { + uint32_t u32Count = 0; - uint32_t u32Count = 0; - - stcIP6Address* pIP6Address = m_pIP6Addresses; + stcIP6Address* pIP6Address = m_pIP6Addresses; while (pIP6Address) { ++u32Count; @@ -2092,7 +1963,6 @@ uint32_t MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP6AddressCount(void) co */ const MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP6AddressAtIndex(uint32_t p_u32Index) const { - return (stcIP6Address*)(((const stcAnswer*)this)->IP6AddressAtIndex(p_u32Index)); } @@ -2101,21 +1971,19 @@ const MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* MDNSResponde */ MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP6AddressAtIndex(uint32_t p_u32Index) { - - stcIP6Address* pIP6Address = 0; + stcIP6Address* pIP6Address = 0; if (((uint32_t)(-1) != p_u32Index) && - (m_pIP6Addresses)) + (m_pIP6Addresses)) { - - uint32_t u32Index; - for (pIP6Address = m_pIP6Addresses, u32Index = 0; ((pIP6Address) && (u32Index < p_u32Index)); pIP6Address = pIP6Address->m_pNext, ++u32Index); + uint32_t u32Index; + for (pIP6Address = m_pIP6Addresses, u32Index = 0; ((pIP6Address) && (u32Index < p_u32Index)); pIP6Address = pIP6Address->m_pNext, ++u32Index) + ; } return pIP6Address; } #endif - /** MDNSResponder::stcMDNSServiceQuery @@ -2137,15 +2005,14 @@ MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* MDNSResponder::stc MDNSResponder::stcMDNSServiceQuery::stcMDNSServiceQuery constructor */ MDNSResponder::stcMDNSServiceQuery::stcMDNSServiceQuery(void) - : m_pNext(0), - m_fnCallback(0), - m_bLegacyQuery(false), - m_u8SentCount(0), - m_ResendTimeout(esp8266::polledTimeout::oneShotMs::neverExpires), - m_bAwaitingAnswers(true), - m_pAnswers(0) + : m_pNext(0), + m_fnCallback(0), + m_bLegacyQuery(false), + m_u8SentCount(0), + m_ResendTimeout(esp8266::polledTimeout::oneShotMs::neverExpires), + m_bAwaitingAnswers(true), + m_pAnswers(0) { - clear(); } @@ -2154,7 +2021,6 @@ MDNSResponder::stcMDNSServiceQuery::stcMDNSServiceQuery(void) */ MDNSResponder::stcMDNSServiceQuery::~stcMDNSServiceQuery(void) { - clear(); } @@ -2163,7 +2029,6 @@ MDNSResponder::stcMDNSServiceQuery::~stcMDNSServiceQuery(void) */ bool MDNSResponder::stcMDNSServiceQuery::clear(void) { - m_fnCallback = 0; m_bLegacyQuery = false; m_u8SentCount = 0; @@ -2171,7 +2036,7 @@ bool MDNSResponder::stcMDNSServiceQuery::clear(void) m_bAwaitingAnswers = true; while (m_pAnswers) { - stcAnswer* pNext = m_pAnswers->m_pNext; + stcAnswer* pNext = m_pAnswers->m_pNext; delete m_pAnswers; m_pAnswers = pNext; } @@ -2183,10 +2048,9 @@ bool MDNSResponder::stcMDNSServiceQuery::clear(void) */ uint32_t MDNSResponder::stcMDNSServiceQuery::answerCount(void) const { + uint32_t u32Count = 0; - uint32_t u32Count = 0; - - stcAnswer* pAnswer = m_pAnswers; + stcAnswer* pAnswer = m_pAnswers; while (pAnswer) { ++u32Count; @@ -2200,15 +2064,14 @@ uint32_t MDNSResponder::stcMDNSServiceQuery::answerCount(void) const */ const MDNSResponder::stcMDNSServiceQuery::stcAnswer* MDNSResponder::stcMDNSServiceQuery::answerAtIndex(uint32_t p_u32Index) const { - - const stcAnswer* pAnswer = 0; + const stcAnswer* pAnswer = 0; if (((uint32_t)(-1) != p_u32Index) && - (m_pAnswers)) + (m_pAnswers)) { - - uint32_t u32Index; - for (pAnswer = m_pAnswers, u32Index = 0; ((pAnswer) && (u32Index < p_u32Index)); pAnswer = pAnswer->m_pNext, ++u32Index); + uint32_t u32Index; + for (pAnswer = m_pAnswers, u32Index = 0; ((pAnswer) && (u32Index < p_u32Index)); pAnswer = pAnswer->m_pNext, ++u32Index) + ; } return pAnswer; } @@ -2218,7 +2081,6 @@ const MDNSResponder::stcMDNSServiceQuery::stcAnswer* MDNSResponder::stcMDNSServi */ MDNSResponder::stcMDNSServiceQuery::stcAnswer* MDNSResponder::stcMDNSServiceQuery::answerAtIndex(uint32_t p_u32Index) { - return (stcAnswer*)(((const stcMDNSServiceQuery*)this)->answerAtIndex(p_u32Index)); } @@ -2227,8 +2089,7 @@ MDNSResponder::stcMDNSServiceQuery::stcAnswer* MDNSResponder::stcMDNSServiceQuer */ uint32_t MDNSResponder::stcMDNSServiceQuery::indexOfAnswer(const MDNSResponder::stcMDNSServiceQuery::stcAnswer* p_pAnswer) const { - - uint32_t u32Index = 0; + uint32_t u32Index = 0; for (const stcAnswer* pAnswer = m_pAnswers; pAnswer; pAnswer = pAnswer->m_pNext, ++u32Index) { @@ -2245,8 +2106,7 @@ uint32_t MDNSResponder::stcMDNSServiceQuery::indexOfAnswer(const MDNSResponder:: */ bool MDNSResponder::stcMDNSServiceQuery::addAnswer(MDNSResponder::stcMDNSServiceQuery::stcAnswer* p_pAnswer) { - - bool bResult = false; + bool bResult = false; if (p_pAnswer) { @@ -2262,14 +2122,13 @@ bool MDNSResponder::stcMDNSServiceQuery::addAnswer(MDNSResponder::stcMDNSService */ bool MDNSResponder::stcMDNSServiceQuery::removeAnswer(MDNSResponder::stcMDNSServiceQuery::stcAnswer* p_pAnswer) { - - bool bResult = false; + bool bResult = false; if (p_pAnswer) { - stcAnswer* pPred = m_pAnswers; + stcAnswer* pPred = m_pAnswers; while ((pPred) && - (pPred->m_pNext != p_pAnswer)) + (pPred->m_pNext != p_pAnswer)) { pPred = pPred->m_pNext; } @@ -2279,7 +2138,7 @@ bool MDNSResponder::stcMDNSServiceQuery::removeAnswer(MDNSResponder::stcMDNSServ delete p_pAnswer; bResult = true; } - else if (m_pAnswers == p_pAnswer) // No predecessor, but first item + else if (m_pAnswers == p_pAnswer) // No predecessor, but first item { m_pAnswers = p_pAnswer->m_pNext; delete p_pAnswer; @@ -2294,8 +2153,7 @@ bool MDNSResponder::stcMDNSServiceQuery::removeAnswer(MDNSResponder::stcMDNSServ */ MDNSResponder::stcMDNSServiceQuery::stcAnswer* MDNSResponder::stcMDNSServiceQuery::findAnswerForServiceDomain(const MDNSResponder::stcMDNS_RRDomain& p_ServiceDomain) { - - stcAnswer* pAnswer = m_pAnswers; + stcAnswer* pAnswer = m_pAnswers; while (pAnswer) { if (pAnswer->m_ServiceDomain == p_ServiceDomain) @@ -2312,8 +2170,7 @@ MDNSResponder::stcMDNSServiceQuery::stcAnswer* MDNSResponder::stcMDNSServiceQuer */ MDNSResponder::stcMDNSServiceQuery::stcAnswer* MDNSResponder::stcMDNSServiceQuery::findAnswerForHostDomain(const MDNSResponder::stcMDNS_RRDomain& p_HostDomain) { - - stcAnswer* pAnswer = m_pAnswers; + stcAnswer* pAnswer = m_pAnswers; while (pAnswer) { if (pAnswer->m_HostDomain == p_HostDomain) @@ -2325,7 +2182,6 @@ MDNSResponder::stcMDNSServiceQuery::stcAnswer* MDNSResponder::stcMDNSServiceQuer return pAnswer; } - /** MDNSResponder::stcMDNSSendParameter @@ -2347,14 +2203,13 @@ MDNSResponder::stcMDNSServiceQuery::stcAnswer* MDNSResponder::stcMDNSServiceQuer MDNSResponder::stcMDNSSendParameter::stcDomainCacheItem::stcDomainCacheItem constructor */ MDNSResponder::stcMDNSSendParameter::stcDomainCacheItem::stcDomainCacheItem(const void* p_pHostnameOrService, - bool p_bAdditionalData, - uint32_t p_u16Offset) - : m_pNext(0), - m_pHostnameOrService(p_pHostnameOrService), - m_bAdditionalData(p_bAdditionalData), - m_u16Offset(p_u16Offset) + bool p_bAdditionalData, + uint32_t p_u16Offset) + : m_pNext(0), + m_pHostnameOrService(p_pHostnameOrService), + m_bAdditionalData(p_bAdditionalData), + m_u16Offset(p_u16Offset) { - } /** @@ -2365,10 +2220,9 @@ MDNSResponder::stcMDNSSendParameter::stcDomainCacheItem::stcDomainCacheItem(cons MDNSResponder::stcMDNSSendParameter::stcMDNSSendParameter constructor */ MDNSResponder::stcMDNSSendParameter::stcMDNSSendParameter(void) - : m_pQuestions(0), - m_pDomainCacheItems(0) + : m_pQuestions(0), + m_pDomainCacheItems(0) { - clear(); } @@ -2377,7 +2231,6 @@ MDNSResponder::stcMDNSSendParameter::stcMDNSSendParameter(void) */ MDNSResponder::stcMDNSSendParameter::~stcMDNSSendParameter(void) { - clear(); } @@ -2386,7 +2239,6 @@ MDNSResponder::stcMDNSSendParameter::~stcMDNSSendParameter(void) */ bool MDNSResponder::stcMDNSSendParameter::clear(void) { - m_u16ID = 0; m_u8HostReplyMask = 0; m_u16Offset = 0; @@ -2406,14 +2258,14 @@ bool MDNSResponder::stcMDNSSendParameter::clear(void) m_pQuestions = pNext; } - return clearCachedNames();; + return clearCachedNames(); + ; } /* MDNSResponder::stcMDNSSendParameter::clear cached names */ bool MDNSResponder::stcMDNSSendParameter::clearCachedNames(void) { - m_u16Offset = 0; while (m_pDomainCacheItems) @@ -2432,7 +2284,6 @@ bool MDNSResponder::stcMDNSSendParameter::clearCachedNames(void) */ bool MDNSResponder::stcMDNSSendParameter::shiftOffset(uint16_t p_u16Shift) { - m_u16Offset += p_u16Shift; return true; } @@ -2441,18 +2292,16 @@ bool MDNSResponder::stcMDNSSendParameter::shiftOffset(uint16_t p_u16Shift) MDNSResponder::stcMDNSSendParameter::addDomainCacheItem */ bool MDNSResponder::stcMDNSSendParameter::addDomainCacheItem(const void* p_pHostnameOrService, - bool p_bAdditionalData, - uint16_t p_u16Offset) + bool p_bAdditionalData, + uint16_t p_u16Offset) { - - bool bResult = false; + bool bResult = false; stcDomainCacheItem* pNewItem = 0; if ((p_pHostnameOrService) && - (p_u16Offset) && - ((pNewItem = new stcDomainCacheItem(p_pHostnameOrService, p_bAdditionalData, p_u16Offset)))) + (p_u16Offset) && + ((pNewItem = new stcDomainCacheItem(p_pHostnameOrService, p_bAdditionalData, p_u16Offset)))) { - pNewItem->m_pNext = m_pDomainCacheItems; bResult = ((m_pDomainCacheItems = pNewItem)); } @@ -2463,15 +2312,14 @@ bool MDNSResponder::stcMDNSSendParameter::addDomainCacheItem(const void* p_pHost MDNSResponder::stcMDNSSendParameter::findCachedDomainOffset */ uint16_t MDNSResponder::stcMDNSSendParameter::findCachedDomainOffset(const void* p_pHostnameOrService, - bool p_bAdditionalData) const + bool p_bAdditionalData) const { - - const stcDomainCacheItem* pCacheItem = m_pDomainCacheItems; + const stcDomainCacheItem* pCacheItem = m_pDomainCacheItems; for (; pCacheItem; pCacheItem = pCacheItem->m_pNext) { if ((pCacheItem->m_pHostnameOrService == p_pHostnameOrService) && - (pCacheItem->m_bAdditionalData == p_bAdditionalData)) // Found cache item + (pCacheItem->m_bAdditionalData == p_bAdditionalData)) // Found cache item { break; } @@ -2479,9 +2327,6 @@ uint16_t MDNSResponder::stcMDNSSendParameter::findCachedDomainOffset(const void* return (pCacheItem ? pCacheItem->m_u16Offset : 0); } -} // namespace MDNSImplementation - -} // namespace esp8266 - - +} // namespace MDNSImplementation +} // namespace esp8266 diff --git a/libraries/ESP8266mDNS/src/LEAmDNS_Transfer.cpp b/libraries/ESP8266mDNS/src/LEAmDNS_Transfer.cpp index ebe66dff1c..4248b582a8 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS_Transfer.cpp +++ b/libraries/ESP8266mDNS/src/LEAmDNS_Transfer.cpp @@ -22,46 +22,43 @@ */ -extern "C" { +extern "C" +{ #include "user_interface.h" } #include "ESP8266mDNS.h" -#include "LEAmDNS_lwIPdefs.h" #include "LEAmDNS_Priv.h" - +#include "LEAmDNS_lwIPdefs.h" namespace esp8266 { - /* LEAmDNS */ namespace MDNSImplementation { - /** CONST STRINGS */ -static const char* scpcLocal = "local"; -static const char* scpcServices = "services"; -static const char* scpcDNSSD = "dns-sd"; -static const char* scpcUDP = "udp"; +static const char* scpcLocal = "local"; +static const char* scpcServices = "services"; +static const char* scpcDNSSD = "dns-sd"; +static const char* scpcUDP = "udp"; //static const char* scpcTCP = "tcp"; #ifdef MDNS_IP4_SUPPORT -static const char* scpcReverseIP4Domain = "in-addr"; +static const char* scpcReverseIP4Domain = "in-addr"; #endif #ifdef MDNS_IP6_SUPPORT -static const char* scpcReverseIP6Domain = "ip6"; +static const char* scpcReverseIP6Domain = "ip6"; #endif -static const char* scpcReverseTopDomain = "arpa"; +static const char* scpcReverseTopDomain = "arpa"; /** TRANSFER */ - /** SENDING */ @@ -77,22 +74,21 @@ static const char* scpcReverseTopDomain = "arpa"; */ bool MDNSResponder::_sendMDNSMessage(MDNSResponder::stcMDNSSendParameter& p_rSendParameter) { - - bool bResult = true; + bool bResult = true; if (p_rSendParameter.m_bResponse && - p_rSendParameter.m_bUnicast) // Unicast response -> Send to querier + p_rSendParameter.m_bUnicast) // Unicast response -> Send to querier { DEBUG_EX_ERR(if (!m_pUDPContext->getRemoteAddress()) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendMDNSMessage: MISSING remote address for response!\n")); - }); - IPAddress ipRemote; + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendMDNSMessage: MISSING remote address for response!\n")); + }); + IPAddress ipRemote; ipRemote = m_pUDPContext->getRemoteAddress(); bResult = ((_prepareMDNSMessage(p_rSendParameter, m_pUDPContext->getInputNetif()->ip_addr)) && (m_pUDPContext->sendTimeout(ipRemote, m_pUDPContext->getRemotePort(), MDNS_UDPCONTEXT_TIMEOUT))); } - else // Multicast response + else // Multicast response { bResult = _sendMDNSMessage_Multicast(p_rSendParameter); } @@ -104,9 +100,9 @@ bool MDNSResponder::_sendMDNSMessage(MDNSResponder::stcMDNSSendParameter& p_rSen } DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendMDNSMessage: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendMDNSMessage: FAILED!\n")); + }); return bResult; } @@ -118,33 +114,32 @@ bool MDNSResponder::_sendMDNSMessage(MDNSResponder::stcMDNSSendParameter& p_rSen */ bool MDNSResponder::_sendMDNSMessage_Multicast(MDNSResponder::stcMDNSSendParameter& p_rSendParameter) { - - bool bResult = false; + bool bResult = false; for (netif* pNetIf = netif_list; pNetIf; pNetIf = pNetIf->next) { if (netif_is_up(pNetIf)) { - IPAddress fromIPAddress; + IPAddress fromIPAddress; //fromIPAddress = _getResponseMulticastInterface(); fromIPAddress = pNetIf->ip_addr; m_pUDPContext->setMulticastInterface(fromIPAddress); #ifdef MDNS_IP4_SUPPORT - IPAddress toMulticastAddress(DNS_MQUERY_IPV4_GROUP_INIT); + IPAddress toMulticastAddress(DNS_MQUERY_IPV4_GROUP_INIT); #endif #ifdef MDNS_IP6_SUPPORT //TODO: set multicast address - IPAddress toMulticastAddress(DNS_MQUERY_IPV6_GROUP_INIT); + IPAddress toMulticastAddress(DNS_MQUERY_IPV6_GROUP_INIT); #endif DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendMDNSMessage_Multicast: Will send to '%s'.\n"), toMulticastAddress.toString().c_str());); bResult = ((_prepareMDNSMessage(p_rSendParameter, fromIPAddress)) && (m_pUDPContext->sendTimeout(toMulticastAddress, DNS_MQUERY_PORT, MDNS_UDPCONTEXT_TIMEOUT))); DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendMDNSMessage_Multicast: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendMDNSMessage_Multicast: FAILED!\n")); + }); } } return bResult; @@ -163,24 +158,24 @@ bool MDNSResponder::_prepareMDNSMessage(MDNSResponder::stcMDNSSendParameter& p_r IPAddress p_IPAddress) { DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage\n"));); - bool bResult = true; - p_rSendParameter.clearCachedNames(); // Need to remove cached names, p_SendParameter might have been used before on other interface + bool bResult = true; + p_rSendParameter.clearCachedNames(); // Need to remove cached names, p_SendParameter might have been used before on other interface // Prepare header; count answers - stcMDNS_MsgHeader msgHeader(p_rSendParameter.m_u16ID, p_rSendParameter.m_bResponse, 0, p_rSendParameter.m_bAuthorative); + stcMDNS_MsgHeader msgHeader(p_rSendParameter.m_u16ID, p_rSendParameter.m_bResponse, 0, p_rSendParameter.m_bAuthorative); // If this is a response, the answers are anwers, // else this is a query or probe and the answers go into auth section - uint16_t& ru16Answers = (p_rSendParameter.m_bResponse - ? msgHeader.m_u16ANCount - : msgHeader.m_u16NSCount); + uint16_t& ru16Answers = (p_rSendParameter.m_bResponse + ? msgHeader.m_u16ANCount + : msgHeader.m_u16NSCount); /** enuSequence */ enum enuSequence { - Sequence_Count = 0, - Sequence_Send = 1 + Sequence_Count = 0, + Sequence_Send = 1 }; // Two step sequence: 'Count' and 'Send' @@ -188,66 +183,65 @@ bool MDNSResponder::_prepareMDNSMessage(MDNSResponder::stcMDNSSendParameter& p_r { DEBUG_EX_INFO( if (Sequence_Send == sequence) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: ID:%u QR:%u OP:%u AA:%u TC:%u RD:%u RA:%u R:%u QD:%u AN:%u NS:%u AR:%u\n"), - (unsigned)msgHeader.m_u16ID, - (unsigned)msgHeader.m_1bQR, (unsigned)msgHeader.m_4bOpcode, (unsigned)msgHeader.m_1bAA, (unsigned)msgHeader.m_1bTC, (unsigned)msgHeader.m_1bRD, - (unsigned)msgHeader.m_1bRA, (unsigned)msgHeader.m_4bRCode, - (unsigned)msgHeader.m_u16QDCount, - (unsigned)msgHeader.m_u16ANCount, - (unsigned)msgHeader.m_u16NSCount, - (unsigned)msgHeader.m_u16ARCount); - } - ); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: ID:%u QR:%u OP:%u AA:%u TC:%u RD:%u RA:%u R:%u QD:%u AN:%u NS:%u AR:%u\n"), + (unsigned)msgHeader.m_u16ID, + (unsigned)msgHeader.m_1bQR, (unsigned)msgHeader.m_4bOpcode, (unsigned)msgHeader.m_1bAA, (unsigned)msgHeader.m_1bTC, (unsigned)msgHeader.m_1bRD, + (unsigned)msgHeader.m_1bRA, (unsigned)msgHeader.m_4bRCode, + (unsigned)msgHeader.m_u16QDCount, + (unsigned)msgHeader.m_u16ANCount, + (unsigned)msgHeader.m_u16NSCount, + (unsigned)msgHeader.m_u16ARCount); + }); // Count/send // Header bResult = ((Sequence_Count == sequence) - ? true - : _writeMDNSMsgHeader(msgHeader, p_rSendParameter)); + ? true + : _writeMDNSMsgHeader(msgHeader, p_rSendParameter)); DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSMsgHeader FAILED!\n"));); // Questions for (stcMDNS_RRQuestion* pQuestion = p_rSendParameter.m_pQuestions; ((bResult) && (pQuestion)); pQuestion = pQuestion->m_pNext) { ((Sequence_Count == sequence) - ? ++msgHeader.m_u16QDCount - : (bResult = _writeMDNSQuestion(*pQuestion, p_rSendParameter))); + ? ++msgHeader.m_u16QDCount + : (bResult = _writeMDNSQuestion(*pQuestion, p_rSendParameter))); DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSQuestion FAILED!\n"));); } // Answers and authoritative answers #ifdef MDNS_IP4_SUPPORT if ((bResult) && - (p_rSendParameter.m_u8HostReplyMask & ContentFlag_A)) + (p_rSendParameter.m_u8HostReplyMask & ContentFlag_A)) { ((Sequence_Count == sequence) - ? ++ru16Answers - : (bResult = _writeMDNSAnswer_A(p_IPAddress, p_rSendParameter))); + ? ++ru16Answers + : (bResult = _writeMDNSAnswer_A(p_IPAddress, p_rSendParameter))); DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_A(A) FAILED!\n"));); } if ((bResult) && - (p_rSendParameter.m_u8HostReplyMask & ContentFlag_PTR_IP4)) + (p_rSendParameter.m_u8HostReplyMask & ContentFlag_PTR_IP4)) { ((Sequence_Count == sequence) - ? ++ru16Answers - : (bResult = _writeMDNSAnswer_PTR_IP4(p_IPAddress, p_rSendParameter))); + ? ++ru16Answers + : (bResult = _writeMDNSAnswer_PTR_IP4(p_IPAddress, p_rSendParameter))); DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_PTR_IP4 FAILED!\n"));); } #endif #ifdef MDNS_IP6_SUPPORT if ((bResult) && - (p_rSendParameter.m_u8HostReplyMask & ContentFlag_AAAA)) + (p_rSendParameter.m_u8HostReplyMask & ContentFlag_AAAA)) { ((Sequence_Count == sequence) - ? ++ru16Answers - : (bResult = _writeMDNSAnswer_AAAA(p_IPAddress, p_rSendParameter))); + ? ++ru16Answers + : (bResult = _writeMDNSAnswer_AAAA(p_IPAddress, p_rSendParameter))); DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_AAAA(A) FAILED!\n"));); } if ((bResult) && - (p_rSendParameter.m_u8HostReplyMask & ContentFlag_PTR_IP6)) + (p_rSendParameter.m_u8HostReplyMask & ContentFlag_PTR_IP6)) { ((Sequence_Count == sequence) - ? ++ru16Answers - : (bResult = _writeMDNSAnswer_PTR_IP6(p_IPAddress, p_rSendParameter))); + ? ++ru16Answers + : (bResult = _writeMDNSAnswer_PTR_IP6(p_IPAddress, p_rSendParameter))); DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_PTR_IP6 FAILED!\n"));); } #endif @@ -255,110 +249,110 @@ bool MDNSResponder::_prepareMDNSMessage(MDNSResponder::stcMDNSSendParameter& p_r for (stcMDNSService* pService = m_pServices; ((bResult) && (pService)); pService = pService->m_pNext) { if ((bResult) && - (pService->m_u8ReplyMask & ContentFlag_PTR_TYPE)) + (pService->m_u8ReplyMask & ContentFlag_PTR_TYPE)) { ((Sequence_Count == sequence) - ? ++ru16Answers - : (bResult = _writeMDNSAnswer_PTR_TYPE(*pService, p_rSendParameter))); + ? ++ru16Answers + : (bResult = _writeMDNSAnswer_PTR_TYPE(*pService, p_rSendParameter))); DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_PTR_TYPE FAILED!\n"));); } if ((bResult) && - (pService->m_u8ReplyMask & ContentFlag_PTR_NAME)) + (pService->m_u8ReplyMask & ContentFlag_PTR_NAME)) { ((Sequence_Count == sequence) - ? ++ru16Answers - : (bResult = _writeMDNSAnswer_PTR_NAME(*pService, p_rSendParameter))); + ? ++ru16Answers + : (bResult = _writeMDNSAnswer_PTR_NAME(*pService, p_rSendParameter))); DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_PTR_NAME FAILED!\n"));); } if ((bResult) && - (pService->m_u8ReplyMask & ContentFlag_SRV)) + (pService->m_u8ReplyMask & ContentFlag_SRV)) { ((Sequence_Count == sequence) - ? ++ru16Answers - : (bResult = _writeMDNSAnswer_SRV(*pService, p_rSendParameter))); + ? ++ru16Answers + : (bResult = _writeMDNSAnswer_SRV(*pService, p_rSendParameter))); DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_SRV(A) FAILED!\n"));); } if ((bResult) && - (pService->m_u8ReplyMask & ContentFlag_TXT)) + (pService->m_u8ReplyMask & ContentFlag_TXT)) { ((Sequence_Count == sequence) - ? ++ru16Answers - : (bResult = _writeMDNSAnswer_TXT(*pService, p_rSendParameter))); + ? ++ru16Answers + : (bResult = _writeMDNSAnswer_TXT(*pService, p_rSendParameter))); DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_TXT(A) FAILED!\n"));); } - } // for services + } // for services // Additional answers #ifdef MDNS_IP4_SUPPORT - bool bNeedsAdditionalAnswerA = false; + bool bNeedsAdditionalAnswerA = false; #endif #ifdef MDNS_IP6_SUPPORT - bool bNeedsAdditionalAnswerAAAA = false; + bool bNeedsAdditionalAnswerAAAA = false; #endif for (stcMDNSService* pService = m_pServices; ((bResult) && (pService)); pService = pService->m_pNext) { if ((bResult) && - (pService->m_u8ReplyMask & ContentFlag_PTR_NAME) && // If PTR_NAME is requested, AND - (!(pService->m_u8ReplyMask & ContentFlag_SRV))) // NOT SRV -> add SRV as additional answer + (pService->m_u8ReplyMask & ContentFlag_PTR_NAME) && // If PTR_NAME is requested, AND + (!(pService->m_u8ReplyMask & ContentFlag_SRV))) // NOT SRV -> add SRV as additional answer { ((Sequence_Count == sequence) - ? ++msgHeader.m_u16ARCount - : (bResult = _writeMDNSAnswer_SRV(*pService, p_rSendParameter))); + ? ++msgHeader.m_u16ARCount + : (bResult = _writeMDNSAnswer_SRV(*pService, p_rSendParameter))); DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_SRV(B) FAILED!\n"));); } if ((bResult) && - (pService->m_u8ReplyMask & ContentFlag_PTR_NAME) && // If PTR_NAME is requested, AND - (!(pService->m_u8ReplyMask & ContentFlag_TXT))) // NOT TXT -> add TXT as additional answer + (pService->m_u8ReplyMask & ContentFlag_PTR_NAME) && // If PTR_NAME is requested, AND + (!(pService->m_u8ReplyMask & ContentFlag_TXT))) // NOT TXT -> add TXT as additional answer { ((Sequence_Count == sequence) - ? ++msgHeader.m_u16ARCount - : (bResult = _writeMDNSAnswer_TXT(*pService, p_rSendParameter))); + ? ++msgHeader.m_u16ARCount + : (bResult = _writeMDNSAnswer_TXT(*pService, p_rSendParameter))); DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_TXT(B) FAILED!\n"));); } - if ((pService->m_u8ReplyMask & (ContentFlag_PTR_NAME | ContentFlag_SRV)) || // If service instance name or SRV OR - (p_rSendParameter.m_u8HostReplyMask & (ContentFlag_A | ContentFlag_AAAA))) // any host IP address is requested + if ((pService->m_u8ReplyMask & (ContentFlag_PTR_NAME | ContentFlag_SRV)) || // If service instance name or SRV OR + (p_rSendParameter.m_u8HostReplyMask & (ContentFlag_A | ContentFlag_AAAA))) // any host IP address is requested { #ifdef MDNS_IP4_SUPPORT if ((bResult) && - (!(p_rSendParameter.m_u8HostReplyMask & ContentFlag_A))) // Add IP4 address + (!(p_rSendParameter.m_u8HostReplyMask & ContentFlag_A))) // Add IP4 address { bNeedsAdditionalAnswerA = true; } #endif #ifdef MDNS_IP6_SUPPORT if ((bResult) && - (!(p_rSendParameter.m_u8HostReplyMask & ContentFlag_AAAA))) // Add IP6 address + (!(p_rSendParameter.m_u8HostReplyMask & ContentFlag_AAAA))) // Add IP6 address { bNeedsAdditionalAnswerAAAA = true; } #endif } - } // for services + } // for services // Answer A needed? #ifdef MDNS_IP4_SUPPORT if ((bResult) && - (bNeedsAdditionalAnswerA)) + (bNeedsAdditionalAnswerA)) { ((Sequence_Count == sequence) - ? ++msgHeader.m_u16ARCount - : (bResult = _writeMDNSAnswer_A(p_IPAddress, p_rSendParameter))); + ? ++msgHeader.m_u16ARCount + : (bResult = _writeMDNSAnswer_A(p_IPAddress, p_rSendParameter))); DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_A(B) FAILED!\n"));); } #endif #ifdef MDNS_IP6_SUPPORT // Answer AAAA needed? if ((bResult) && - (bNeedsAdditionalAnswerAAAA)) + (bNeedsAdditionalAnswerAAAA)) { ((Sequence_Count == sequence) - ? ++msgHeader.m_u16ARCount - : (bResult = _writeMDNSAnswer_AAAA(p_IPAddress, p_rSendParameter))); + ? ++msgHeader.m_u16ARCount + : (bResult = _writeMDNSAnswer_AAAA(p_IPAddress, p_rSendParameter))); DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_AAAA(B) FAILED!\n"));); } #endif DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: Loop %i FAILED!\n"), sequence);); - } // for sequence + } // for sequence DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: FAILED!\n"));); return bResult; } @@ -371,7 +365,6 @@ bool MDNSResponder::_prepareMDNSMessage(MDNSResponder::stcMDNSSendParameter& p_r */ bool MDNSResponder::_sendMDNSServiceQuery(const MDNSResponder::stcMDNSServiceQuery& p_ServiceQuery) { - return _sendMDNSQuery(p_ServiceQuery.m_ServiceTypeDomain, DNS_RRTYPE_PTR); } @@ -385,23 +378,22 @@ bool MDNSResponder::_sendMDNSQuery(const MDNSResponder::stcMDNS_RRDomain& p_Quer uint16_t p_u16QueryType, stcMDNSServiceQuery::stcAnswer* p_pKnownAnswers /*= 0*/) { + bool bResult = false; - bool bResult = false; - - stcMDNSSendParameter sendParameter; + stcMDNSSendParameter sendParameter; if (0 != ((sendParameter.m_pQuestions = new stcMDNS_RRQuestion))) { sendParameter.m_pQuestions->m_Header.m_Domain = p_QueryDomain; sendParameter.m_pQuestions->m_Header.m_Attributes.m_u16Type = p_u16QueryType; // It seems, that some mDNS implementations don't support 'unicast response' questions... - sendParameter.m_pQuestions->m_Header.m_Attributes.m_u16Class = (/*0x8000 |*/ DNS_RRCLASS_IN); // /*Unicast &*/ INternet + sendParameter.m_pQuestions->m_Header.m_Attributes.m_u16Class = (/*0x8000 |*/ DNS_RRCLASS_IN); // /*Unicast &*/ INternet // TODO: Add known answer to the query (void)p_pKnownAnswers; bResult = _sendMDNSMessage(sendParameter); - } // else: FAILED to alloc question + } // else: FAILED to alloc question DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendMDNSQuery: FAILED to alloc question!\n"));); return bResult; } @@ -424,7 +416,7 @@ bool MDNSResponder::_readRRQuestion(MDNSResponder::stcMDNS_RRQuestion& p_rRRQues { DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRQuestion\n"));); - bool bResult = false; + bool bResult = false; if ((bResult = _readRRHeader(p_rRRQuestion.m_Header))) { @@ -435,13 +427,12 @@ bool MDNSResponder::_readRRQuestion(MDNSResponder::stcMDNS_RRQuestion& p_rRRQues DEBUG_EX_INFO( DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRQuestion ")); _printRRDomain(p_rRRQuestion.m_Header.m_Domain); - DEBUG_OUTPUT.printf_P(PSTR(" Type:0x%04X Class:0x%04X %s\n"), (unsigned)p_rRRQuestion.m_Header.m_Attributes.m_u16Type, (unsigned)p_rRRQuestion.m_Header.m_Attributes.m_u16Class, (p_rRRQuestion.m_bUnicast ? "Unicast" : "Multicast")); - ); + DEBUG_OUTPUT.printf_P(PSTR(" Type:0x%04X Class:0x%04X %s\n"), (unsigned)p_rRRQuestion.m_Header.m_Attributes.m_u16Type, (unsigned)p_rRRQuestion.m_Header.m_Attributes.m_u16Class, (p_rRRQuestion.m_bUnicast ? "Unicast" : "Multicast"));); } DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRQuestion: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRQuestion: FAILED!\n")); + }); return bResult; } @@ -460,103 +451,100 @@ bool MDNSResponder::_readRRAnswer(MDNSResponder::stcMDNS_RRAnswer*& p_rpRRAnswer { //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswer\n"));); - bool bResult = false; + bool bResult = false; - stcMDNS_RRHeader header; - uint32_t u32TTL; - uint16_t u16RDLength; + stcMDNS_RRHeader header; + uint32_t u32TTL; + uint16_t u16RDLength; if ((_readRRHeader(header)) && - (_udpRead32(u32TTL)) && - (_udpRead16(u16RDLength))) + (_udpRead32(u32TTL)) && + (_udpRead16(u16RDLength))) { - /* DEBUG_EX_INFO( DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswer: Reading 0x%04X answer (class:0x%04X, TTL:%u, RDLength:%u) for "), header.m_Attributes.m_u16Type, header.m_Attributes.m_u16Class, u32TTL, u16RDLength); _printRRDomain(header.m_Domain); DEBUG_OUTPUT.printf_P(PSTR("\n")); );*/ - switch (header.m_Attributes.m_u16Type & (~0x8000)) // Topmost bit might carry 'cache flush' flag + switch (header.m_Attributes.m_u16Type & (~0x8000)) // Topmost bit might carry 'cache flush' flag { -#ifdef MDNS_IP4_SUPPORT - case DNS_RRTYPE_A: - p_rpRRAnswer = new stcMDNS_RRAnswerA(header, u32TTL); - bResult = _readRRAnswerA(*(stcMDNS_RRAnswerA*&)p_rpRRAnswer, u16RDLength); - break; -#endif - case DNS_RRTYPE_PTR: - p_rpRRAnswer = new stcMDNS_RRAnswerPTR(header, u32TTL); - bResult = _readRRAnswerPTR(*(stcMDNS_RRAnswerPTR*&)p_rpRRAnswer, u16RDLength); - break; - case DNS_RRTYPE_TXT: - p_rpRRAnswer = new stcMDNS_RRAnswerTXT(header, u32TTL); - bResult = _readRRAnswerTXT(*(stcMDNS_RRAnswerTXT*&)p_rpRRAnswer, u16RDLength); - break; -#ifdef MDNS_IP6_SUPPORT - case DNS_RRTYPE_AAAA: - p_rpRRAnswer = new stcMDNS_RRAnswerAAAA(header, u32TTL); - bResult = _readRRAnswerAAAA(*(stcMDNS_RRAnswerAAAA*&)p_rpRRAnswer, u16RDLength); - break; -#endif - case DNS_RRTYPE_SRV: - p_rpRRAnswer = new stcMDNS_RRAnswerSRV(header, u32TTL); - bResult = _readRRAnswerSRV(*(stcMDNS_RRAnswerSRV*&)p_rpRRAnswer, u16RDLength); - break; - default: - p_rpRRAnswer = new stcMDNS_RRAnswerGeneric(header, u32TTL); - bResult = _readRRAnswerGeneric(*(stcMDNS_RRAnswerGeneric*&)p_rpRRAnswer, u16RDLength); - break; - } - DEBUG_EX_INFO( - if ((bResult) && - (p_rpRRAnswer)) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswer: ")); - _printRRDomain(p_rpRRAnswer->m_Header.m_Domain); - DEBUG_OUTPUT.printf_P(PSTR(" Type:0x%04X Class:0x%04X TTL:%u, RDLength:%u "), p_rpRRAnswer->m_Header.m_Attributes.m_u16Type, p_rpRRAnswer->m_Header.m_Attributes.m_u16Class, p_rpRRAnswer->m_u32TTL, u16RDLength); - switch (header.m_Attributes.m_u16Type & (~0x8000)) // Topmost bit might carry 'cache flush' flag - { #ifdef MDNS_IP4_SUPPORT case DNS_RRTYPE_A: - DEBUG_OUTPUT.printf_P(PSTR("A IP:%s"), ((stcMDNS_RRAnswerA*&)p_rpRRAnswer)->m_IPAddress.toString().c_str()); + p_rpRRAnswer = new stcMDNS_RRAnswerA(header, u32TTL); + bResult = _readRRAnswerA(*(stcMDNS_RRAnswerA*&)p_rpRRAnswer, u16RDLength); break; #endif case DNS_RRTYPE_PTR: - DEBUG_OUTPUT.printf_P(PSTR("PTR ")); - _printRRDomain(((stcMDNS_RRAnswerPTR*&)p_rpRRAnswer)->m_PTRDomain); + p_rpRRAnswer = new stcMDNS_RRAnswerPTR(header, u32TTL); + bResult = _readRRAnswerPTR(*(stcMDNS_RRAnswerPTR*&)p_rpRRAnswer, u16RDLength); break; case DNS_RRTYPE_TXT: - { - size_t stTxtLength = ((stcMDNS_RRAnswerTXT*&)p_rpRRAnswer)->m_Txts.c_strLength(); - char* pTxts = new char[stTxtLength]; - if (pTxts) - { - ((stcMDNS_RRAnswerTXT*&)p_rpRRAnswer)->m_Txts.c_str(pTxts); - DEBUG_OUTPUT.printf_P(PSTR("TXT(%zu) %s"), stTxtLength, pTxts); - delete[] pTxts; - } + p_rpRRAnswer = new stcMDNS_RRAnswerTXT(header, u32TTL); + bResult = _readRRAnswerTXT(*(stcMDNS_RRAnswerTXT*&)p_rpRRAnswer, u16RDLength); break; - } #ifdef MDNS_IP6_SUPPORT case DNS_RRTYPE_AAAA: - DEBUG_OUTPUT.printf_P(PSTR("AAAA IP:%s"), ((stcMDNS_RRAnswerA*&)p_rpRRAnswer)->m_IPAddress.toString().c_str()); + p_rpRRAnswer = new stcMDNS_RRAnswerAAAA(header, u32TTL); + bResult = _readRRAnswerAAAA(*(stcMDNS_RRAnswerAAAA*&)p_rpRRAnswer, u16RDLength); break; #endif case DNS_RRTYPE_SRV: - DEBUG_OUTPUT.printf_P(PSTR("SRV Port:%u "), ((stcMDNS_RRAnswerSRV*&)p_rpRRAnswer)->m_u16Port); - _printRRDomain(((stcMDNS_RRAnswerSRV*&)p_rpRRAnswer)->m_SRVDomain); + p_rpRRAnswer = new stcMDNS_RRAnswerSRV(header, u32TTL); + bResult = _readRRAnswerSRV(*(stcMDNS_RRAnswerSRV*&)p_rpRRAnswer, u16RDLength); break; default: - DEBUG_OUTPUT.printf_P(PSTR("generic ")); + p_rpRRAnswer = new stcMDNS_RRAnswerGeneric(header, u32TTL); + bResult = _readRRAnswerGeneric(*(stcMDNS_RRAnswerGeneric*&)p_rpRRAnswer, u16RDLength); break; - } - DEBUG_OUTPUT.printf_P(PSTR("\n")); - } - else - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswer: FAILED to read specific answer of type 0x%04X!\n"), p_rpRRAnswer->m_Header.m_Attributes.m_u16Type); } - ); // DEBUG_EX_INFO + DEBUG_EX_INFO( + if ((bResult) && + (p_rpRRAnswer)) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswer: ")); + _printRRDomain(p_rpRRAnswer->m_Header.m_Domain); + DEBUG_OUTPUT.printf_P(PSTR(" Type:0x%04X Class:0x%04X TTL:%u, RDLength:%u "), p_rpRRAnswer->m_Header.m_Attributes.m_u16Type, p_rpRRAnswer->m_Header.m_Attributes.m_u16Class, p_rpRRAnswer->m_u32TTL, u16RDLength); + switch (header.m_Attributes.m_u16Type & (~0x8000)) // Topmost bit might carry 'cache flush' flag + { +#ifdef MDNS_IP4_SUPPORT + case DNS_RRTYPE_A: + DEBUG_OUTPUT.printf_P(PSTR("A IP:%s"), ((stcMDNS_RRAnswerA*&)p_rpRRAnswer)->m_IPAddress.toString().c_str()); + break; +#endif + case DNS_RRTYPE_PTR: + DEBUG_OUTPUT.printf_P(PSTR("PTR ")); + _printRRDomain(((stcMDNS_RRAnswerPTR*&)p_rpRRAnswer)->m_PTRDomain); + break; + case DNS_RRTYPE_TXT: + { + size_t stTxtLength = ((stcMDNS_RRAnswerTXT*&)p_rpRRAnswer)->m_Txts.c_strLength(); + char* pTxts = new char[stTxtLength]; + if (pTxts) + { + ((stcMDNS_RRAnswerTXT*&)p_rpRRAnswer)->m_Txts.c_str(pTxts); + DEBUG_OUTPUT.printf_P(PSTR("TXT(%zu) %s"), stTxtLength, pTxts); + delete[] pTxts; + } + break; + } +#ifdef MDNS_IP6_SUPPORT + case DNS_RRTYPE_AAAA: + DEBUG_OUTPUT.printf_P(PSTR("AAAA IP:%s"), ((stcMDNS_RRAnswerA*&)p_rpRRAnswer)->m_IPAddress.toString().c_str()); + break; +#endif + case DNS_RRTYPE_SRV: + DEBUG_OUTPUT.printf_P(PSTR("SRV Port:%u "), ((stcMDNS_RRAnswerSRV*&)p_rpRRAnswer)->m_u16Port); + _printRRDomain(((stcMDNS_RRAnswerSRV*&)p_rpRRAnswer)->m_SRVDomain); + break; + default: + DEBUG_OUTPUT.printf_P(PSTR("generic ")); + break; + } + DEBUG_OUTPUT.printf_P(PSTR("\n")); + } else + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswer: FAILED to read specific answer of type 0x%04X!\n"), p_rpRRAnswer->m_Header.m_Attributes.m_u16Type); + }); // DEBUG_EX_INFO } DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswer: FAILED!\n"));); return bResult; @@ -569,11 +557,10 @@ bool MDNSResponder::_readRRAnswer(MDNSResponder::stcMDNS_RRAnswer*& p_rpRRAnswer bool MDNSResponder::_readRRAnswerA(MDNSResponder::stcMDNS_RRAnswerA& p_rRRAnswerA, uint16_t p_u16RDLength) { - - uint32_t u32IP4Address; - bool bResult = ((MDNS_IP4_SIZE == p_u16RDLength) && - (_udpReadBuffer((unsigned char*)&u32IP4Address, MDNS_IP4_SIZE)) && - ((p_rRRAnswerA.m_IPAddress = IPAddress(u32IP4Address)))); + uint32_t u32IP4Address; + bool bResult = ((MDNS_IP4_SIZE == p_u16RDLength) && + (_udpReadBuffer((unsigned char*)&u32IP4Address, MDNS_IP4_SIZE)) && + ((p_rRRAnswerA.m_IPAddress = IPAddress(u32IP4Address)))); DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerA: FAILED!\n"));); return bResult; } @@ -585,9 +572,8 @@ bool MDNSResponder::_readRRAnswerA(MDNSResponder::stcMDNS_RRAnswerA& p_rRRAnswer bool MDNSResponder::_readRRAnswerPTR(MDNSResponder::stcMDNS_RRAnswerPTR& p_rRRAnswerPTR, uint16_t p_u16RDLength) { - - bool bResult = ((p_u16RDLength) && - (_readRRDomain(p_rRRAnswerPTR.m_PTRDomain))); + bool bResult = ((p_u16RDLength) && + (_readRRDomain(p_rRRAnswerPTR.m_PTRDomain))); DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerPTR: FAILED!\n"));); return bResult; } @@ -601,43 +587,42 @@ bool MDNSResponder::_readRRAnswerTXT(MDNSResponder::stcMDNS_RRAnswerTXT& p_rRRAn uint16_t p_u16RDLength) { DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerTXT: RDLength:%u\n"), p_u16RDLength);); - bool bResult = true; + bool bResult = true; p_rRRAnswerTXT.clear(); if (p_u16RDLength) { bResult = false; - unsigned char* pucBuffer = new unsigned char[p_u16RDLength]; + unsigned char* pucBuffer = new unsigned char[p_u16RDLength]; if (pucBuffer) { if (_udpReadBuffer(pucBuffer, p_u16RDLength)) { bResult = true; - const unsigned char* pucCursor = pucBuffer; + const unsigned char* pucCursor = pucBuffer; while ((pucCursor < (pucBuffer + p_u16RDLength)) && - (bResult)) + (bResult)) { bResult = false; - stcMDNSServiceTxt* pTxt = 0; - unsigned char ucLength = *pucCursor++; // Length of the next txt item + stcMDNSServiceTxt* pTxt = 0; + unsigned char ucLength = *pucCursor++; // Length of the next txt item if (ucLength) { DEBUG_EX_INFO( static char sacBuffer[64]; *sacBuffer = 0; uint8_t u8MaxLength = ((ucLength > (sizeof(sacBuffer) - 1)) ? (sizeof(sacBuffer) - 1) : ucLength); os_strncpy(sacBuffer, (const char*)pucCursor, u8MaxLength); sacBuffer[u8MaxLength] = 0; - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerTXT: Item(%u): %s\n"), ucLength, sacBuffer); - ); + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerTXT: Item(%u): %s\n"), ucLength, sacBuffer);); - unsigned char* pucEqualSign = (unsigned char*)os_strchr((const char*)pucCursor, '='); // Position of the '=' sign - unsigned char ucKeyLength; + unsigned char* pucEqualSign = (unsigned char*)os_strchr((const char*)pucCursor, '='); // Position of the '=' sign + unsigned char ucKeyLength; if ((pucEqualSign) && - ((ucKeyLength = (pucEqualSign - pucCursor)))) + ((ucKeyLength = (pucEqualSign - pucCursor)))) { - unsigned char ucValueLength = (ucLength - (pucEqualSign - pucCursor + 1)); + unsigned char ucValueLength = (ucLength - (pucEqualSign - pucCursor + 1)); bResult = (((pTxt = new stcMDNSServiceTxt)) && (pTxt->setKey((const char*)pucCursor, ucKeyLength)) && (pTxt->setValue((const char*)(pucEqualSign + 1), ucValueLength))); @@ -648,20 +633,20 @@ bool MDNSResponder::_readRRAnswerTXT(MDNSResponder::stcMDNS_RRAnswerTXT& p_rRRAn } pucCursor += ucLength; } - else // no/zero length TXT + else // no/zero length TXT { DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerTXT: TXT answer contains no items.\n"));); bResult = true; } if ((bResult) && - (pTxt)) // Everything is fine so far + (pTxt)) // Everything is fine so far { // Link TXT item to answer TXTs pTxt->m_pNext = p_rRRAnswerTXT.m_Txts.m_pTxts; p_rRRAnswerTXT.m_Txts.m_pTxts = pTxt; } - else // At least no TXT (might be OK, if length was 0) OR an error + else // At least no TXT (might be OK, if length was 0) OR an error { if (!bResult) { @@ -669,8 +654,7 @@ bool MDNSResponder::_readRRAnswerTXT(MDNSResponder::stcMDNS_RRAnswerTXT& p_rRRAn DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerTXT: FAILED to read TXT item!\n")); DEBUG_OUTPUT.printf_P(PSTR("RData dump:\n")); _udpDump((m_pUDPContext->tell() - p_u16RDLength), p_u16RDLength); - DEBUG_OUTPUT.printf_P(PSTR("\n")); - ); + DEBUG_OUTPUT.printf_P(PSTR("\n"));); } if (pTxt) { @@ -679,16 +663,15 @@ bool MDNSResponder::_readRRAnswerTXT(MDNSResponder::stcMDNS_RRAnswerTXT& p_rRRAn } p_rRRAnswerTXT.clear(); } - } // while + } // while DEBUG_EX_ERR( - if (!bResult) // Some failure - { - DEBUG_OUTPUT.printf_P(PSTR("RData dump:\n")); - _udpDump((m_pUDPContext->tell() - p_u16RDLength), p_u16RDLength); - DEBUG_OUTPUT.printf_P(PSTR("\n")); - } - ); + if (!bResult) // Some failure + { + DEBUG_OUTPUT.printf_P(PSTR("RData dump:\n")); + _udpDump((m_pUDPContext->tell() - p_u16RDLength), p_u16RDLength); + DEBUG_OUTPUT.printf_P(PSTR("\n")); + }); } else { @@ -714,7 +697,7 @@ bool MDNSResponder::_readRRAnswerTXT(MDNSResponder::stcMDNS_RRAnswerTXT& p_rRRAn bool MDNSResponder::_readRRAnswerAAAA(MDNSResponder::stcMDNS_RRAnswerAAAA& p_rRRAnswerAAAA, uint16_t p_u16RDLength) { - bool bResult = false; + bool bResult = false; // TODO: Implement return bResult; } @@ -726,12 +709,11 @@ bool MDNSResponder::_readRRAnswerAAAA(MDNSResponder::stcMDNS_RRAnswerAAAA& p_rRR bool MDNSResponder::_readRRAnswerSRV(MDNSResponder::stcMDNS_RRAnswerSRV& p_rRRAnswerSRV, uint16_t p_u16RDLength) { - - bool bResult = (((3 * sizeof(uint16_t)) < p_u16RDLength) && - (_udpRead16(p_rRRAnswerSRV.m_u16Priority)) && - (_udpRead16(p_rRRAnswerSRV.m_u16Weight)) && - (_udpRead16(p_rRRAnswerSRV.m_u16Port)) && - (_readRRDomain(p_rRRAnswerSRV.m_SRVDomain))); + bool bResult = (((3 * sizeof(uint16_t)) < p_u16RDLength) && + (_udpRead16(p_rRRAnswerSRV.m_u16Priority)) && + (_udpRead16(p_rRRAnswerSRV.m_u16Weight)) && + (_udpRead16(p_rRRAnswerSRV.m_u16Port)) && + (_readRRDomain(p_rRRAnswerSRV.m_SRVDomain))); DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerSRV: FAILED!\n"));); return bResult; } @@ -740,15 +722,14 @@ bool MDNSResponder::_readRRAnswerSRV(MDNSResponder::stcMDNS_RRAnswerSRV& p_rRRAn MDNSResponder::_readRRAnswerGeneric */ bool MDNSResponder::_readRRAnswerGeneric(MDNSResponder::stcMDNS_RRAnswerGeneric& p_rRRAnswerGeneric, - uint16_t p_u16RDLength) + uint16_t p_u16RDLength) { - bool bResult = (0 == p_u16RDLength); + bool bResult = (0 == p_u16RDLength); p_rRRAnswerGeneric.clear(); if (((p_rRRAnswerGeneric.m_u16RDLength = p_u16RDLength)) && - ((p_rRRAnswerGeneric.m_pu8RDData = new unsigned char[p_rRRAnswerGeneric.m_u16RDLength]))) + ((p_rRRAnswerGeneric.m_pu8RDData = new unsigned char[p_rRRAnswerGeneric.m_u16RDLength]))) { - bResult = _udpReadBuffer(p_rRRAnswerGeneric.m_pu8RDData, p_rRRAnswerGeneric.m_u16RDLength); } DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerGeneric: FAILED!\n"));); @@ -762,8 +743,8 @@ bool MDNSResponder::_readRRHeader(MDNSResponder::stcMDNS_RRHeader& p_rRRHeader) { //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRHeader\n"));); - bool bResult = ((_readRRDomain(p_rRRHeader.m_Domain)) && - (_readRRAttributes(p_rRRHeader.m_Attributes))); + bool bResult = ((_readRRDomain(p_rRRHeader.m_Domain)) && + (_readRRAttributes(p_rRRHeader.m_Attributes))); DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRHeader: FAILED!\n"));); return bResult; } @@ -778,8 +759,8 @@ bool MDNSResponder::_readRRDomain(MDNSResponder::stcMDNS_RRDomain& p_rRRDomain) { //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain\n"));); - bool bResult = ((p_rRRDomain.clear()) && - (_readRRDomain_Loop(p_rRRDomain, 0))); + bool bResult = ((p_rRRDomain.clear()) && + (_readRRDomain_Loop(p_rRRDomain, 0))); DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain: FAILED!\n"));); return bResult; } @@ -797,7 +778,7 @@ bool MDNSResponder::_readRRDomain_Loop(MDNSResponder::stcMDNS_RRDomain& p_rRRDom { //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain_Loop(%u)\n"), p_u8Depth);); - bool bResult = false; + bool bResult = false; if (MDNS_DOMAIN_MAX_REDIRCTION >= p_u8Depth) { @@ -812,20 +793,20 @@ bool MDNSResponder::_readRRDomain_Loop(MDNSResponder::stcMDNS_RRDomain& p_rRRDom if (u8Len & MDNS_DOMAIN_COMPRESS_MARK) { // Compressed label(s) - uint16_t u16Offset = ((u8Len & ~MDNS_DOMAIN_COMPRESS_MARK) << 8); // Implicit BE to LE conversion! + uint16_t u16Offset = ((u8Len & ~MDNS_DOMAIN_COMPRESS_MARK) << 8); // Implicit BE to LE conversion! _udpRead8(u8Len); u16Offset |= u8Len; if (m_pUDPContext->isValidOffset(u16Offset)) { - size_t stCurrentPosition = m_pUDPContext->tell(); // Prepare return from recursion + size_t stCurrentPosition = m_pUDPContext->tell(); // Prepare return from recursion //DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain_Loop(%u): Redirecting from %u to %u!\n"), p_u8Depth, stCurrentPosition, u16Offset);); m_pUDPContext->seek(u16Offset); - if (_readRRDomain_Loop(p_rRRDomain, p_u8Depth + 1)) // Do recursion + if (_readRRDomain_Loop(p_rRRDomain, p_u8Depth + 1)) // Do recursion { //DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain_Loop(%u): Succeeded to read redirected label! Returning to %u\n"), p_u8Depth, stCurrentPosition);); - m_pUDPContext->seek(stCurrentPosition); // Restore after recursion + m_pUDPContext->seek(stCurrentPosition); // Restore after recursion } else { @@ -848,9 +829,9 @@ bool MDNSResponder::_readRRDomain_Loop(MDNSResponder::stcMDNS_RRDomain& p_rRRDom // Add length byte p_rRRDomain.m_acName[p_rRRDomain.m_u16NameLength] = u8Len; ++(p_rRRDomain.m_u16NameLength); - if (u8Len) // Add name + if (u8Len) // Add name { - if ((bResult = _udpReadBuffer((unsigned char*) & (p_rRRDomain.m_acName[p_rRRDomain.m_u16NameLength]), u8Len))) + if ((bResult = _udpReadBuffer((unsigned char*)&(p_rRRDomain.m_acName[p_rRRDomain.m_u16NameLength]), u8Len))) { /* DEBUG_EX_INFO( p_rRRDomain.m_acName[p_rRRDomain.m_u16NameLength + u8Len] = 0; // Closing '\0' for printing @@ -886,13 +867,12 @@ bool MDNSResponder::_readRRAttributes(MDNSResponder::stcMDNS_RRAttributes& p_rRR { //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAttributes\n"));); - bool bResult = ((_udpRead16(p_rRRAttributes.m_u16Type)) && - (_udpRead16(p_rRRAttributes.m_u16Class))); + bool bResult = ((_udpRead16(p_rRRAttributes.m_u16Type)) && + (_udpRead16(p_rRRAttributes.m_u16Class))); DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAttributes: FAILED!\n"));); return bResult; } - /* DOMAIN NAMES */ @@ -906,13 +886,12 @@ bool MDNSResponder::_readRRAttributes(MDNSResponder::stcMDNS_RRAttributes& p_rRR bool MDNSResponder::_buildDomainForHost(const char* p_pcHostname, MDNSResponder::stcMDNS_RRDomain& p_rHostDomain) const { - p_rHostDomain.clear(); - bool bResult = ((p_pcHostname) && - (*p_pcHostname) && - (p_rHostDomain.addLabel(p_pcHostname)) && - (p_rHostDomain.addLabel(scpcLocal)) && - (p_rHostDomain.addLabel(0))); + bool bResult = ((p_pcHostname) && + (*p_pcHostname) && + (p_rHostDomain.addLabel(p_pcHostname)) && + (p_rHostDomain.addLabel(scpcLocal)) && + (p_rHostDomain.addLabel(0))); DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _buildDomainForHost: FAILED!\n"));); return bResult; } @@ -926,13 +905,12 @@ bool MDNSResponder::_buildDomainForHost(const char* p_pcHostname, */ bool MDNSResponder::_buildDomainForDNSSD(MDNSResponder::stcMDNS_RRDomain& p_rDNSSDDomain) const { - p_rDNSSDDomain.clear(); - bool bResult = ((p_rDNSSDDomain.addLabel(scpcServices, true)) && - (p_rDNSSDDomain.addLabel(scpcDNSSD, true)) && - (p_rDNSSDDomain.addLabel(scpcUDP, true)) && - (p_rDNSSDDomain.addLabel(scpcLocal)) && - (p_rDNSSDDomain.addLabel(0))); + bool bResult = ((p_rDNSSDDomain.addLabel(scpcServices, true)) && + (p_rDNSSDDomain.addLabel(scpcDNSSD, true)) && + (p_rDNSSDDomain.addLabel(scpcUDP, true)) && + (p_rDNSSDDomain.addLabel(scpcLocal)) && + (p_rDNSSDDomain.addLabel(0))); DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _buildDomainForDNSSD: FAILED!\n"));); return bResult; } @@ -945,17 +923,16 @@ bool MDNSResponder::_buildDomainForDNSSD(MDNSResponder::stcMDNS_RRDomain& p_rDNS */ bool MDNSResponder::_buildDomainForService(const MDNSResponder::stcMDNSService& p_Service, - bool p_bIncludeName, - MDNSResponder::stcMDNS_RRDomain& p_rServiceDomain) const + bool p_bIncludeName, + MDNSResponder::stcMDNS_RRDomain& p_rServiceDomain) const { - p_rServiceDomain.clear(); - bool bResult = (((!p_bIncludeName) || - (p_rServiceDomain.addLabel(p_Service.m_pcName))) && - (p_rServiceDomain.addLabel(p_Service.m_pcService, true)) && - (p_rServiceDomain.addLabel(p_Service.m_pcProtocol, true)) && - (p_rServiceDomain.addLabel(scpcLocal)) && - (p_rServiceDomain.addLabel(0))); + bool bResult = (((!p_bIncludeName) || + (p_rServiceDomain.addLabel(p_Service.m_pcName))) && + (p_rServiceDomain.addLabel(p_Service.m_pcService, true)) && + (p_rServiceDomain.addLabel(p_Service.m_pcProtocol, true)) && + (p_rServiceDomain.addLabel(scpcLocal)) && + (p_rServiceDomain.addLabel(0))); DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _buildDomainForService: FAILED!\n"));); return bResult; } @@ -968,18 +945,17 @@ bool MDNSResponder::_buildDomainForService(const MDNSResponder::stcMDNSService& */ bool MDNSResponder::_buildDomainForService(const char* p_pcService, - const char* p_pcProtocol, - MDNSResponder::stcMDNS_RRDomain& p_rServiceDomain) const + const char* p_pcProtocol, + MDNSResponder::stcMDNS_RRDomain& p_rServiceDomain) const { - p_rServiceDomain.clear(); - bool bResult = ((p_pcService) && - (p_pcProtocol) && - (p_rServiceDomain.addLabel(p_pcService, ('_' != *p_pcService))) && - (p_rServiceDomain.addLabel(p_pcProtocol, ('_' != *p_pcProtocol))) && - (p_rServiceDomain.addLabel(scpcLocal)) && - (p_rServiceDomain.addLabel(0))); - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _buildDomainForService: FAILED for (%s.%s)!\n"), (p_pcService ? : "-"), (p_pcProtocol ? : "-"));); + bool bResult = ((p_pcService) && + (p_pcProtocol) && + (p_rServiceDomain.addLabel(p_pcService, ('_' != *p_pcService))) && + (p_rServiceDomain.addLabel(p_pcProtocol, ('_' != *p_pcProtocol))) && + (p_rServiceDomain.addLabel(scpcLocal)) && + (p_rServiceDomain.addLabel(0))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _buildDomainForService: FAILED for (%s.%s)!\n"), (p_pcService ?: "-"), (p_pcProtocol ?: "-"));); return bResult; } @@ -992,14 +968,13 @@ bool MDNSResponder::_buildDomainForService(const char* p_pcService, Used while detecting reverse IP4 questions and answering these */ bool MDNSResponder::_buildDomainForReverseIP4(IPAddress p_IP4Address, - MDNSResponder::stcMDNS_RRDomain& p_rReverseIP4Domain) const + MDNSResponder::stcMDNS_RRDomain& p_rReverseIP4Domain) const { - - bool bResult = true; + bool bResult = true; p_rReverseIP4Domain.clear(); - char acBuffer[32]; + char acBuffer[32]; for (int i = MDNS_IP4_SIZE; ((bResult) && (i >= 1)); --i) { itoa(p_IP4Address[i - 1], acBuffer, 10); @@ -1021,14 +996,13 @@ bool MDNSResponder::_buildDomainForReverseIP4(IPAddress p_IP4Address, Used while detecting reverse IP6 questions and answering these */ bool MDNSResponder::_buildDomainForReverseIP6(IPAddress p_IP4Address, - MDNSResponder::stcMDNS_RRDomain& p_rReverseIP6Domain) const + MDNSResponder::stcMDNS_RRDomain& p_rReverseIP6Domain) const { // TODO: Implement return false; } #endif - /* UDP */ @@ -1039,16 +1013,15 @@ bool MDNSResponder::_buildDomainForReverseIP6(IPAddress p_IP4Address, bool MDNSResponder::_udpReadBuffer(unsigned char* p_pBuffer, size_t p_stLength) { - - bool bResult = ((m_pUDPContext) && - (true/*m_pUDPContext->getSize() > p_stLength*/) && - (p_pBuffer) && - (p_stLength) && - ((p_stLength == m_pUDPContext->read((char*)p_pBuffer, p_stLength)))); + bool bResult = ((m_pUDPContext) && + (true /*m_pUDPContext->getSize() > p_stLength*/) && + (p_pBuffer) && + (p_stLength) && + ((p_stLength == m_pUDPContext->read((char*)p_pBuffer, p_stLength)))); DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _udpReadBuffer: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _udpReadBuffer: FAILED!\n")); + }); return bResult; } @@ -1057,7 +1030,6 @@ bool MDNSResponder::_udpReadBuffer(unsigned char* p_pBuffer, */ bool MDNSResponder::_udpRead8(uint8_t& p_ru8Value) { - return _udpReadBuffer((unsigned char*)&p_ru8Value, sizeof(p_ru8Value)); } @@ -1066,8 +1038,7 @@ bool MDNSResponder::_udpRead8(uint8_t& p_ru8Value) */ bool MDNSResponder::_udpRead16(uint16_t& p_ru16Value) { - - bool bResult = false; + bool bResult = false; if (_udpReadBuffer((unsigned char*)&p_ru16Value, sizeof(p_ru16Value))) { @@ -1082,8 +1053,7 @@ bool MDNSResponder::_udpRead16(uint16_t& p_ru16Value) */ bool MDNSResponder::_udpRead32(uint32_t& p_ru32Value) { - - bool bResult = false; + bool bResult = false; if (_udpReadBuffer((unsigned char*)&p_ru32Value, sizeof(p_ru32Value))) { @@ -1099,15 +1069,14 @@ bool MDNSResponder::_udpRead32(uint32_t& p_ru32Value) bool MDNSResponder::_udpAppendBuffer(const unsigned char* p_pcBuffer, size_t p_stLength) { - bool bResult = ((m_pUDPContext) && (p_pcBuffer) && (p_stLength) && (p_stLength == m_pUDPContext->append((const char*)p_pcBuffer, p_stLength))); DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _udpAppendBuffer: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _udpAppendBuffer: FAILED!\n")); + }); return bResult; } @@ -1116,7 +1085,6 @@ bool MDNSResponder::_udpAppendBuffer(const unsigned char* p_pcBuffer, */ bool MDNSResponder::_udpAppend8(uint8_t p_u8Value) { - return (_udpAppendBuffer((unsigned char*)&p_u8Value, sizeof(p_u8Value))); } @@ -1125,7 +1093,6 @@ bool MDNSResponder::_udpAppend8(uint8_t p_u8Value) */ bool MDNSResponder::_udpAppend16(uint16_t p_u16Value) { - p_u16Value = lwip_htons(p_u16Value); return (_udpAppendBuffer((unsigned char*)&p_u16Value, sizeof(p_u16Value))); } @@ -1135,7 +1102,6 @@ bool MDNSResponder::_udpAppend16(uint16_t p_u16Value) */ bool MDNSResponder::_udpAppend32(uint32_t p_u32Value) { - p_u32Value = lwip_htonl(p_u32Value); return (_udpAppendBuffer((unsigned char*)&p_u32Value, sizeof(p_u32Value))); } @@ -1146,13 +1112,12 @@ bool MDNSResponder::_udpAppend32(uint32_t p_u32Value) */ bool MDNSResponder::_udpDump(bool p_bMovePointer /*= false*/) { + const uint8_t cu8BytesPerLine = 16; - const uint8_t cu8BytesPerLine = 16; - - uint32_t u32StartPosition = m_pUDPContext->tell(); + uint32_t u32StartPosition = m_pUDPContext->tell(); DEBUG_OUTPUT.println("UDP Context Dump:"); - uint32_t u32Counter = 0; - uint8_t u8Byte = 0; + uint32_t u32Counter = 0; + uint8_t u8Byte = 0; while (_udpRead8(u8Byte)) { @@ -1160,7 +1125,7 @@ bool MDNSResponder::_udpDump(bool p_bMovePointer /*= false*/) } DEBUG_OUTPUT.printf_P(PSTR("%sDone: %u bytes\n"), (((u32Counter) && (u32Counter % cu8BytesPerLine)) ? "\n" : ""), u32Counter); - if (!p_bMovePointer) // Restore + if (!p_bMovePointer) // Restore { m_pUDPContext->seek(u32StartPosition); } @@ -1173,11 +1138,10 @@ bool MDNSResponder::_udpDump(bool p_bMovePointer /*= false*/) bool MDNSResponder::_udpDump(unsigned p_uOffset, unsigned p_uLength) { - if ((m_pUDPContext) && - (m_pUDPContext->isValidOffset(p_uOffset))) + (m_pUDPContext->isValidOffset(p_uOffset))) { - unsigned uCurrentPosition = m_pUDPContext->tell(); // Remember start position + unsigned uCurrentPosition = m_pUDPContext->tell(); // Remember start position m_pUDPContext->seek(p_uOffset); uint8_t u8Byte; @@ -1192,7 +1156,6 @@ bool MDNSResponder::_udpDump(unsigned p_uOffset, } #endif - /** READ/WRITE MDNS STRUCTS */ @@ -1212,29 +1175,27 @@ bool MDNSResponder::_udpDump(unsigned p_uOffset, */ bool MDNSResponder::_readMDNSMsgHeader(MDNSResponder::stcMDNS_MsgHeader& p_rMsgHeader) { - - bool bResult = false; + bool bResult = false; uint8_t u8B1; uint8_t u8B2; if ((_udpRead16(p_rMsgHeader.m_u16ID)) && - (_udpRead8(u8B1)) && - (_udpRead8(u8B2)) && - (_udpRead16(p_rMsgHeader.m_u16QDCount)) && - (_udpRead16(p_rMsgHeader.m_u16ANCount)) && - (_udpRead16(p_rMsgHeader.m_u16NSCount)) && - (_udpRead16(p_rMsgHeader.m_u16ARCount))) + (_udpRead8(u8B1)) && + (_udpRead8(u8B2)) && + (_udpRead16(p_rMsgHeader.m_u16QDCount)) && + (_udpRead16(p_rMsgHeader.m_u16ANCount)) && + (_udpRead16(p_rMsgHeader.m_u16NSCount)) && + (_udpRead16(p_rMsgHeader.m_u16ARCount))) { + p_rMsgHeader.m_1bQR = (u8B1 & 0x80); // Query/Respond flag + p_rMsgHeader.m_4bOpcode = (u8B1 & 0x78); // Operation code (0: Standard query, others ignored) + p_rMsgHeader.m_1bAA = (u8B1 & 0x04); // Authoritative answer + p_rMsgHeader.m_1bTC = (u8B1 & 0x02); // Truncation flag + p_rMsgHeader.m_1bRD = (u8B1 & 0x01); // Recursion desired - p_rMsgHeader.m_1bQR = (u8B1 & 0x80); // Query/Respond flag - p_rMsgHeader.m_4bOpcode = (u8B1 & 0x78); // Operation code (0: Standard query, others ignored) - p_rMsgHeader.m_1bAA = (u8B1 & 0x04); // Authoritative answer - p_rMsgHeader.m_1bTC = (u8B1 & 0x02); // Truncation flag - p_rMsgHeader.m_1bRD = (u8B1 & 0x01); // Recursion desired - - p_rMsgHeader.m_1bRA = (u8B2 & 0x80); // Recursion available - p_rMsgHeader.m_3bZ = (u8B2 & 0x70); // Zero - p_rMsgHeader.m_4bRCode = (u8B2 & 0x0F); // Response code + p_rMsgHeader.m_1bRA = (u8B2 & 0x80); // Recursion available + p_rMsgHeader.m_3bZ = (u8B2 & 0x70); // Zero + p_rMsgHeader.m_4bRCode = (u8B2 & 0x0F); // Response code /* DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readMDNSMsgHeader: ID:%u QR:%u OP:%u AA:%u TC:%u RD:%u RA:%u R:%u QD:%u AN:%u NS:%u AR:%u\n"), (unsigned)p_rMsgHeader.m_u16ID, @@ -1247,9 +1208,9 @@ bool MDNSResponder::_readMDNSMsgHeader(MDNSResponder::stcMDNS_MsgHeader& p_rMsgH bResult = true; } DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readMDNSMsgHeader: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readMDNSMsgHeader: FAILED!\n")); + }); return bResult; } @@ -1259,7 +1220,6 @@ bool MDNSResponder::_readMDNSMsgHeader(MDNSResponder::stcMDNS_MsgHeader& p_rMsgH bool MDNSResponder::_write8(uint8_t p_u8Value, MDNSResponder::stcMDNSSendParameter& p_rSendParameter) { - return ((_udpAppend8(p_u8Value)) && (p_rSendParameter.shiftOffset(sizeof(p_u8Value)))); } @@ -1270,7 +1230,6 @@ bool MDNSResponder::_write8(uint8_t p_u8Value, bool MDNSResponder::_write16(uint16_t p_u16Value, MDNSResponder::stcMDNSSendParameter& p_rSendParameter) { - return ((_udpAppend16(p_u16Value)) && (p_rSendParameter.shiftOffset(sizeof(p_u16Value)))); } @@ -1281,7 +1240,6 @@ bool MDNSResponder::_write16(uint16_t p_u16Value, bool MDNSResponder::_write32(uint32_t p_u32Value, MDNSResponder::stcMDNSSendParameter& p_rSendParameter) { - return ((_udpAppend32(p_u32Value)) && (p_rSendParameter.shiftOffset(sizeof(p_u32Value)))); } @@ -1309,18 +1267,18 @@ bool MDNSResponder::_writeMDNSMsgHeader(const MDNSResponder::stcMDNS_MsgHeader& uint8_t u8B1((p_MsgHeader.m_1bQR << 7) | (p_MsgHeader.m_4bOpcode << 3) | (p_MsgHeader.m_1bAA << 2) | (p_MsgHeader.m_1bTC << 1) | (p_MsgHeader.m_1bRD)); uint8_t u8B2((p_MsgHeader.m_1bRA << 7) | (p_MsgHeader.m_3bZ << 4) | (p_MsgHeader.m_4bRCode)); - bool bResult = ((_write16(p_MsgHeader.m_u16ID, p_rSendParameter)) && - (_write8(u8B1, p_rSendParameter)) && - (_write8(u8B2, p_rSendParameter)) && - (_write16(p_MsgHeader.m_u16QDCount, p_rSendParameter)) && - (_write16(p_MsgHeader.m_u16ANCount, p_rSendParameter)) && - (_write16(p_MsgHeader.m_u16NSCount, p_rSendParameter)) && - (_write16(p_MsgHeader.m_u16ARCount, p_rSendParameter))); + bool bResult = ((_write16(p_MsgHeader.m_u16ID, p_rSendParameter)) && + (_write8(u8B1, p_rSendParameter)) && + (_write8(u8B2, p_rSendParameter)) && + (_write16(p_MsgHeader.m_u16QDCount, p_rSendParameter)) && + (_write16(p_MsgHeader.m_u16ANCount, p_rSendParameter)) && + (_write16(p_MsgHeader.m_u16NSCount, p_rSendParameter)) && + (_write16(p_MsgHeader.m_u16ARCount, p_rSendParameter))); DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSMsgHeader: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSMsgHeader: FAILED!\n")); + }); return bResult; } @@ -1328,16 +1286,15 @@ bool MDNSResponder::_writeMDNSMsgHeader(const MDNSResponder::stcMDNS_MsgHeader& MDNSResponder::_writeRRAttributes */ bool MDNSResponder::_writeMDNSRRAttributes(const MDNSResponder::stcMDNS_RRAttributes& p_Attributes, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + MDNSResponder::stcMDNSSendParameter& p_rSendParameter) { - - bool bResult = ((_write16(p_Attributes.m_u16Type, p_rSendParameter)) && - (_write16(p_Attributes.m_u16Class, p_rSendParameter))); + bool bResult = ((_write16(p_Attributes.m_u16Type, p_rSendParameter)) && + (_write16(p_Attributes.m_u16Class, p_rSendParameter))); DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSRRAttributes: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSRRAttributes: FAILED!\n")); + }); return bResult; } @@ -1347,14 +1304,13 @@ bool MDNSResponder::_writeMDNSRRAttributes(const MDNSResponder::stcMDNS_RRAttrib bool MDNSResponder::_writeMDNSRRDomain(const MDNSResponder::stcMDNS_RRDomain& p_Domain, MDNSResponder::stcMDNSSendParameter& p_rSendParameter) { - - bool bResult = ((_udpAppendBuffer((const unsigned char*)p_Domain.m_acName, p_Domain.m_u16NameLength)) && - (p_rSendParameter.shiftOffset(p_Domain.m_u16NameLength))); + bool bResult = ((_udpAppendBuffer((const unsigned char*)p_Domain.m_acName, p_Domain.m_u16NameLength)) && + (p_rSendParameter.shiftOffset(p_Domain.m_u16NameLength))); DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSRRDomain: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSRRDomain: FAILED!\n")); + }); return bResult; } @@ -1374,34 +1330,32 @@ bool MDNSResponder::_writeMDNSRRDomain(const MDNSResponder::stcMDNS_RRDomain& p_ */ bool MDNSResponder::_writeMDNSHostDomain(const char* p_pcHostname, - bool p_bPrependRDLength, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + bool p_bPrependRDLength, + MDNSResponder::stcMDNSSendParameter& p_rSendParameter) { - // The 'skip-compression' version is handled in '_writeMDNSAnswer_SRV' - uint16_t u16CachedDomainOffset = p_rSendParameter.findCachedDomainOffset((const void*)p_pcHostname, false); - - stcMDNS_RRDomain hostDomain; - bool bResult = (u16CachedDomainOffset - // Found cached domain -> mark as compressed domain - ? ((MDNS_DOMAIN_COMPRESS_MARK > ((u16CachedDomainOffset >> 8) & ~MDNS_DOMAIN_COMPRESS_MARK)) && // Valid offset - ((!p_bPrependRDLength) || - (_write16(2, p_rSendParameter))) && // Length of 'Cxxx' - (_write8(((u16CachedDomainOffset >> 8) | MDNS_DOMAIN_COMPRESS_MARK), p_rSendParameter)) && // Compression mark (and offset) - (_write8((uint8_t)(u16CachedDomainOffset & 0xFF), p_rSendParameter))) - // No cached domain -> add this domain to cache and write full domain name - : ((_buildDomainForHost(p_pcHostname, hostDomain)) && // eg. esp8266.local - ((!p_bPrependRDLength) || - (_write16(hostDomain.m_u16NameLength, p_rSendParameter))) && // RDLength (if needed) - (p_rSendParameter.addDomainCacheItem((const void*)p_pcHostname, false, p_rSendParameter.m_u16Offset)) && - (_writeMDNSRRDomain(hostDomain, p_rSendParameter)))); + uint16_t u16CachedDomainOffset = p_rSendParameter.findCachedDomainOffset((const void*)p_pcHostname, false); + + stcMDNS_RRDomain hostDomain; + bool bResult = (u16CachedDomainOffset + // Found cached domain -> mark as compressed domain + ? ((MDNS_DOMAIN_COMPRESS_MARK > ((u16CachedDomainOffset >> 8) & ~MDNS_DOMAIN_COMPRESS_MARK)) && // Valid offset + ((!p_bPrependRDLength) || + (_write16(2, p_rSendParameter))) && // Length of 'Cxxx' + (_write8(((u16CachedDomainOffset >> 8) | MDNS_DOMAIN_COMPRESS_MARK), p_rSendParameter)) && // Compression mark (and offset) + (_write8((uint8_t)(u16CachedDomainOffset & 0xFF), p_rSendParameter))) + // No cached domain -> add this domain to cache and write full domain name + : ((_buildDomainForHost(p_pcHostname, hostDomain)) && // eg. esp8266.local + ((!p_bPrependRDLength) || + (_write16(hostDomain.m_u16NameLength, p_rSendParameter))) && // RDLength (if needed) + (p_rSendParameter.addDomainCacheItem((const void*)p_pcHostname, false, p_rSendParameter.m_u16Offset)) && + (_writeMDNSRRDomain(hostDomain, p_rSendParameter)))); DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSHostDomain: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSHostDomain: FAILED!\n")); + }); return bResult; - } /* @@ -1417,35 +1371,33 @@ bool MDNSResponder::_writeMDNSHostDomain(const char* p_pcHostname, */ bool MDNSResponder::_writeMDNSServiceDomain(const MDNSResponder::stcMDNSService& p_Service, - bool p_bIncludeName, - bool p_bPrependRDLength, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + bool p_bIncludeName, + bool p_bPrependRDLength, + MDNSResponder::stcMDNSSendParameter& p_rSendParameter) { - // The 'skip-compression' version is handled in '_writeMDNSAnswer_SRV' - uint16_t u16CachedDomainOffset = p_rSendParameter.findCachedDomainOffset((const void*)&p_Service, p_bIncludeName); - - stcMDNS_RRDomain serviceDomain; - bool bResult = (u16CachedDomainOffset - // Found cached domain -> mark as compressed domain - ? ((MDNS_DOMAIN_COMPRESS_MARK > ((u16CachedDomainOffset >> 8) & ~MDNS_DOMAIN_COMPRESS_MARK)) && // Valid offset - ((!p_bPrependRDLength) || - (_write16(2, p_rSendParameter))) && // Length of 'Cxxx' - (_write8(((u16CachedDomainOffset >> 8) | MDNS_DOMAIN_COMPRESS_MARK), p_rSendParameter)) && // Compression mark (and offset) - (_write8((uint8_t)(u16CachedDomainOffset & 0xFF), p_rSendParameter))) - // No cached domain -> add this domain to cache and write full domain name - : ((_buildDomainForService(p_Service, p_bIncludeName, serviceDomain)) && // eg. MyESP._http._tcp.local - ((!p_bPrependRDLength) || - (_write16(serviceDomain.m_u16NameLength, p_rSendParameter))) && // RDLength (if needed) - (p_rSendParameter.addDomainCacheItem((const void*)&p_Service, p_bIncludeName, p_rSendParameter.m_u16Offset)) && - (_writeMDNSRRDomain(serviceDomain, p_rSendParameter)))); + uint16_t u16CachedDomainOffset = p_rSendParameter.findCachedDomainOffset((const void*)&p_Service, p_bIncludeName); + + stcMDNS_RRDomain serviceDomain; + bool bResult = (u16CachedDomainOffset + // Found cached domain -> mark as compressed domain + ? ((MDNS_DOMAIN_COMPRESS_MARK > ((u16CachedDomainOffset >> 8) & ~MDNS_DOMAIN_COMPRESS_MARK)) && // Valid offset + ((!p_bPrependRDLength) || + (_write16(2, p_rSendParameter))) && // Length of 'Cxxx' + (_write8(((u16CachedDomainOffset >> 8) | MDNS_DOMAIN_COMPRESS_MARK), p_rSendParameter)) && // Compression mark (and offset) + (_write8((uint8_t)(u16CachedDomainOffset & 0xFF), p_rSendParameter))) + // No cached domain -> add this domain to cache and write full domain name + : ((_buildDomainForService(p_Service, p_bIncludeName, serviceDomain)) && // eg. MyESP._http._tcp.local + ((!p_bPrependRDLength) || + (_write16(serviceDomain.m_u16NameLength, p_rSendParameter))) && // RDLength (if needed) + (p_rSendParameter.addDomainCacheItem((const void*)&p_Service, p_bIncludeName, p_rSendParameter.m_u16Offset)) && + (_writeMDNSRRDomain(serviceDomain, p_rSendParameter)))); DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSServiceDomain: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSServiceDomain: FAILED!\n")); + }); return bResult; - } /* @@ -1463,18 +1415,16 @@ bool MDNSResponder::_writeMDNSQuestion(MDNSResponder::stcMDNS_RRQuestion& p_Ques { DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSQuestion\n"));); - bool bResult = ((_writeMDNSRRDomain(p_Question.m_Header.m_Domain, p_rSendParameter)) && - (_writeMDNSRRAttributes(p_Question.m_Header.m_Attributes, p_rSendParameter))); + bool bResult = ((_writeMDNSRRDomain(p_Question.m_Header.m_Domain, p_rSendParameter)) && + (_writeMDNSRRAttributes(p_Question.m_Header.m_Attributes, p_rSendParameter))); DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSQuestion: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSQuestion: FAILED!\n")); + }); return bResult; - } - #ifdef MDNS_IP4_SUPPORT /* MDNSResponder::_writeMDNSAnswer_A @@ -1496,22 +1446,21 @@ bool MDNSResponder::_writeMDNSAnswer_A(IPAddress p_IPAddress, { DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_A (%s)\n"), p_IPAddress.toString().c_str());); - stcMDNS_RRAttributes attributes(DNS_RRTYPE_A, - ((p_rSendParameter.m_bCacheFlush ? 0x8000 : 0) | DNS_RRCLASS_IN)); // Cache flush? & INternet - const unsigned char aucIPAddress[MDNS_IP4_SIZE] = { p_IPAddress[0], p_IPAddress[1], p_IPAddress[2], p_IPAddress[3] }; - bool bResult = ((_writeMDNSHostDomain(m_pcHostname, false, p_rSendParameter)) && - (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS - (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_HOST_TTL), p_rSendParameter)) && // TTL - (_write16(MDNS_IP4_SIZE, p_rSendParameter)) && // RDLength - (_udpAppendBuffer(aucIPAddress, MDNS_IP4_SIZE)) && // RData - (p_rSendParameter.shiftOffset(MDNS_IP4_SIZE))); + stcMDNS_RRAttributes attributes(DNS_RRTYPE_A, + ((p_rSendParameter.m_bCacheFlush ? 0x8000 : 0) | DNS_RRCLASS_IN)); // Cache flush? & INternet + const unsigned char aucIPAddress[MDNS_IP4_SIZE] = {p_IPAddress[0], p_IPAddress[1], p_IPAddress[2], p_IPAddress[3]}; + bool bResult = ((_writeMDNSHostDomain(m_pcHostname, false, p_rSendParameter)) && + (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS + (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_HOST_TTL), p_rSendParameter)) && // TTL + (_write16(MDNS_IP4_SIZE, p_rSendParameter)) && // RDLength + (_udpAppendBuffer(aucIPAddress, MDNS_IP4_SIZE)) && // RData + (p_rSendParameter.shiftOffset(MDNS_IP4_SIZE))); DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_A: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_A: FAILED!\n")); + }); return bResult; - } /* @@ -1524,24 +1473,24 @@ bool MDNSResponder::_writeMDNSAnswer_A(IPAddress p_IPAddress, Used while answering reverse IP4 questions */ bool MDNSResponder::_writeMDNSAnswer_PTR_IP4(IPAddress p_IPAddress, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + MDNSResponder::stcMDNSSendParameter& p_rSendParameter) { DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_IP4 (%s)\n"), p_IPAddress.toString().c_str());); - stcMDNS_RRDomain reverseIP4Domain; - stcMDNS_RRAttributes attributes(DNS_RRTYPE_PTR, - ((p_rSendParameter.m_bCacheFlush ? 0x8000 : 0) | DNS_RRCLASS_IN)); // Cache flush? & INternet - stcMDNS_RRDomain hostDomain; - bool bResult = ((_buildDomainForReverseIP4(p_IPAddress, reverseIP4Domain)) && // 012.789.456.123.in-addr.arpa - (_writeMDNSRRDomain(reverseIP4Domain, p_rSendParameter)) && - (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS - (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_HOST_TTL), p_rSendParameter)) && // TTL - (_writeMDNSHostDomain(m_pcHostname, true, p_rSendParameter))); // RDLength & RData (host domain, eg. esp8266.local) + stcMDNS_RRDomain reverseIP4Domain; + stcMDNS_RRAttributes attributes(DNS_RRTYPE_PTR, + ((p_rSendParameter.m_bCacheFlush ? 0x8000 : 0) | DNS_RRCLASS_IN)); // Cache flush? & INternet + stcMDNS_RRDomain hostDomain; + bool bResult = ((_buildDomainForReverseIP4(p_IPAddress, reverseIP4Domain)) && // 012.789.456.123.in-addr.arpa + (_writeMDNSRRDomain(reverseIP4Domain, p_rSendParameter)) && + (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS + (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_HOST_TTL), p_rSendParameter)) && // TTL + (_writeMDNSHostDomain(m_pcHostname, true, p_rSendParameter))); // RDLength & RData (host domain, eg. esp8266.local) DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_IP4: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_IP4: FAILED!\n")); + }); return bResult; } #endif @@ -1557,23 +1506,23 @@ bool MDNSResponder::_writeMDNSAnswer_PTR_IP4(IPAddress p_IPAddress, http://www.zytrax.com/books/dns/ch8/ptr.html */ bool MDNSResponder::_writeMDNSAnswer_PTR_TYPE(MDNSResponder::stcMDNSService& p_rService, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + MDNSResponder::stcMDNSSendParameter& p_rSendParameter) { DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_TYPE\n"));); - stcMDNS_RRDomain dnssdDomain; - stcMDNS_RRDomain serviceDomain; - stcMDNS_RRAttributes attributes(DNS_RRTYPE_PTR, DNS_RRCLASS_IN); // No cache flush! only INternet - bool bResult = ((_buildDomainForDNSSD(dnssdDomain)) && // _services._dns-sd._udp.local - (_writeMDNSRRDomain(dnssdDomain, p_rSendParameter)) && - (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS - (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_SERVICE_TTL), p_rSendParameter)) && // TTL - (_writeMDNSServiceDomain(p_rService, false, true, p_rSendParameter))); // RDLength & RData (service domain, eg. _http._tcp.local) + stcMDNS_RRDomain dnssdDomain; + stcMDNS_RRDomain serviceDomain; + stcMDNS_RRAttributes attributes(DNS_RRTYPE_PTR, DNS_RRCLASS_IN); // No cache flush! only INternet + bool bResult = ((_buildDomainForDNSSD(dnssdDomain)) && // _services._dns-sd._udp.local + (_writeMDNSRRDomain(dnssdDomain, p_rSendParameter)) && + (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS + (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_SERVICE_TTL), p_rSendParameter)) && // TTL + (_writeMDNSServiceDomain(p_rService, false, true, p_rSendParameter))); // RDLength & RData (service domain, eg. _http._tcp.local) DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_TYPE: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_TYPE: FAILED!\n")); + }); return bResult; } @@ -1588,24 +1537,23 @@ bool MDNSResponder::_writeMDNSAnswer_PTR_TYPE(MDNSResponder::stcMDNSService& p_r http://www.zytrax.com/books/dns/ch8/ptr.html */ bool MDNSResponder::_writeMDNSAnswer_PTR_NAME(MDNSResponder::stcMDNSService& p_rService, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + MDNSResponder::stcMDNSSendParameter& p_rSendParameter) { DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_NAME\n"));); - stcMDNS_RRAttributes attributes(DNS_RRTYPE_PTR, DNS_RRCLASS_IN); // No cache flush! only INternet - bool bResult = ((_writeMDNSServiceDomain(p_rService, false, false, p_rSendParameter)) && // _http._tcp.local - (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS - (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_SERVICE_TTL), p_rSendParameter)) && // TTL - (_writeMDNSServiceDomain(p_rService, true, true, p_rSendParameter))); // RDLength & RData (service domain, eg. MyESP._http._tcp.local) + stcMDNS_RRAttributes attributes(DNS_RRTYPE_PTR, DNS_RRCLASS_IN); // No cache flush! only INternet + bool bResult = ((_writeMDNSServiceDomain(p_rService, false, false, p_rSendParameter)) && // _http._tcp.local + (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS + (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_SERVICE_TTL), p_rSendParameter)) && // TTL + (_writeMDNSServiceDomain(p_rService, true, true, p_rSendParameter))); // RDLength & RData (service domain, eg. MyESP._http._tcp.local) DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_NAME: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_NAME: FAILED!\n")); + }); return bResult; } - /* MDNSResponder::_writeMDNSAnswer_TXT @@ -1618,49 +1566,48 @@ bool MDNSResponder::_writeMDNSAnswer_PTR_NAME(MDNSResponder::stcMDNSService& p_r http://www.zytrax.com/books/dns/ch8/txt.html */ bool MDNSResponder::_writeMDNSAnswer_TXT(MDNSResponder::stcMDNSService& p_rService, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + MDNSResponder::stcMDNSSendParameter& p_rSendParameter) { DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_TXT\n"));); - bool bResult = false; + bool bResult = false; - stcMDNS_RRAttributes attributes(DNS_RRTYPE_TXT, - ((p_rSendParameter.m_bCacheFlush ? 0x8000 : 0) | DNS_RRCLASS_IN)); // Cache flush? & INternet + stcMDNS_RRAttributes attributes(DNS_RRTYPE_TXT, + ((p_rSendParameter.m_bCacheFlush ? 0x8000 : 0) | DNS_RRCLASS_IN)); // Cache flush? & INternet if ((_collectServiceTxts(p_rService)) && - (_writeMDNSServiceDomain(p_rService, true, false, p_rSendParameter)) && // MyESP._http._tcp.local - (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS - (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_SERVICE_TTL), p_rSendParameter)) && // TTL - (_write16(p_rService.m_Txts.length(), p_rSendParameter))) // RDLength + (_writeMDNSServiceDomain(p_rService, true, false, p_rSendParameter)) && // MyESP._http._tcp.local + (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS + (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_SERVICE_TTL), p_rSendParameter)) && // TTL + (_write16(p_rService.m_Txts.length(), p_rSendParameter))) // RDLength { - bResult = true; // RData Txts for (stcMDNSServiceTxt* pTxt = p_rService.m_Txts.m_pTxts; ((bResult) && (pTxt)); pTxt = pTxt->m_pNext) { - unsigned char ucLengthByte = pTxt->length(); - bResult = ((_udpAppendBuffer((unsigned char*)&ucLengthByte, sizeof(ucLengthByte))) && // Length + unsigned char ucLengthByte = pTxt->length(); + bResult = ((_udpAppendBuffer((unsigned char*)&ucLengthByte, sizeof(ucLengthByte))) && // Length (p_rSendParameter.shiftOffset(sizeof(ucLengthByte))) && - ((size_t)os_strlen(pTxt->m_pcKey) == m_pUDPContext->append(pTxt->m_pcKey, os_strlen(pTxt->m_pcKey))) && // Key + ((size_t)os_strlen(pTxt->m_pcKey) == m_pUDPContext->append(pTxt->m_pcKey, os_strlen(pTxt->m_pcKey))) && // Key (p_rSendParameter.shiftOffset((size_t)os_strlen(pTxt->m_pcKey))) && - (1 == m_pUDPContext->append("=", 1)) && // = + (1 == m_pUDPContext->append("=", 1)) && // = (p_rSendParameter.shiftOffset(1)) && ((!pTxt->m_pcValue) || (((size_t)os_strlen(pTxt->m_pcValue) == m_pUDPContext->append(pTxt->m_pcValue, os_strlen(pTxt->m_pcValue))) && // Value (p_rSendParameter.shiftOffset((size_t)os_strlen(pTxt->m_pcValue)))))); DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_TXT: FAILED to write %sTxt %s=%s!\n"), (pTxt->m_bTemp ? "temp. " : ""), (pTxt->m_pcKey ? : "?"), (pTxt->m_pcValue ? : "?")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_TXT: FAILED to write %sTxt %s=%s!\n"), (pTxt->m_bTemp ? "temp. " : ""), (pTxt->m_pcKey ?: "?"), (pTxt->m_pcValue ?: "?")); + }); } } _releaseTempServiceTxts(p_rService); DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_TXT: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_TXT: FAILED!\n")); + }); return bResult; } @@ -1675,22 +1622,22 @@ bool MDNSResponder::_writeMDNSAnswer_TXT(MDNSResponder::stcMDNSService& p_rServi http://www.zytrax.com/books/dns/ch8/aaaa.html */ bool MDNSResponder::_writeMDNSAnswer_AAAA(IPAddress p_IPAddress, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + MDNSResponder::stcMDNSSendParameter& p_rSendParameter) { DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_AAAA\n"));); - stcMDNS_RRAttributes attributes(DNS_RRTYPE_AAAA, - ((p_rSendParameter.m_bCacheFlush ? 0x8000 : 0) | DNS_RRCLASS_IN)); // Cache flush? & INternet - bool bResult = ((_writeMDNSHostDomain(m_pcHostname, false, p_rSendParameter)) && // esp8266.local - (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS - (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_HOST_TTL), p_rSendParameter)) && // TTL - (_write16(MDNS_IP6_SIZE, p_rSendParameter)) && // RDLength - (false /*TODO: IP6 version of: _udpAppendBuffer((uint32_t)p_IPAddress, MDNS_IP4_SIZE)*/)); // RData + stcMDNS_RRAttributes attributes(DNS_RRTYPE_AAAA, + ((p_rSendParameter.m_bCacheFlush ? 0x8000 : 0) | DNS_RRCLASS_IN)); // Cache flush? & INternet + bool bResult = ((_writeMDNSHostDomain(m_pcHostname, false, p_rSendParameter)) && // esp8266.local + (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS + (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_HOST_TTL), p_rSendParameter)) && // TTL + (_write16(MDNS_IP6_SIZE, p_rSendParameter)) && // RDLength + (false /*TODO: IP6 version of: _udpAppendBuffer((uint32_t)p_IPAddress, MDNS_IP4_SIZE)*/)); // RData DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_AAAA: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_AAAA: FAILED!\n")); + }); return bResult; } @@ -1704,23 +1651,23 @@ bool MDNSResponder::_writeMDNSAnswer_AAAA(IPAddress p_IPAddress, Used while answering reverse IP6 questions */ bool MDNSResponder::_writeMDNSAnswer_PTR_IP6(IPAddress p_IPAddress, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + MDNSResponder::stcMDNSSendParameter& p_rSendParameter) { DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_IP6\n"));); - stcMDNS_RRDomain reverseIP6Domain; - stcMDNS_RRAttributes attributes(DNS_RRTYPE_PTR, - ((p_rSendParameter.m_bCacheFlush ? 0x8000 : 0) | DNS_RRCLASS_IN)); // Cache flush? & INternet - bool bResult = ((_buildDomainForReverseIP6(p_IPAddress, reverseIP6Domain)) && // xxxx::xx.ip6.arpa - (_writeMDNSRRDomain(reverseIP6Domain, p_rSendParameter)) && - (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS - (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_HOST_TTL), p_rSendParameter)) && // TTL - (_writeMDNSHostDomain(m_pcHostname, true, p_rSendParameter))); // RDLength & RData (host domain, eg. esp8266.local) + stcMDNS_RRDomain reverseIP6Domain; + stcMDNS_RRAttributes attributes(DNS_RRTYPE_PTR, + ((p_rSendParameter.m_bCacheFlush ? 0x8000 : 0) | DNS_RRCLASS_IN)); // Cache flush? & INternet + bool bResult = ((_buildDomainForReverseIP6(p_IPAddress, reverseIP6Domain)) && // xxxx::xx.ip6.arpa + (_writeMDNSRRDomain(reverseIP6Domain, p_rSendParameter)) && + (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS + (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_HOST_TTL), p_rSendParameter)) && // TTL + (_writeMDNSHostDomain(m_pcHostname, true, p_rSendParameter))); // RDLength & RData (host domain, eg. esp8266.local) DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_IP6: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_IP6: FAILED!\n")); + }); return bResult; } #endif @@ -1732,57 +1679,53 @@ bool MDNSResponder::_writeMDNSAnswer_PTR_IP6(IPAddress p_IPAddress, http://www.zytrax.com/books/dns/ch8/srv.html ???? Include instance name ???? */ bool MDNSResponder::_writeMDNSAnswer_SRV(MDNSResponder::stcMDNSService& p_rService, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + MDNSResponder::stcMDNSSendParameter& p_rSendParameter) { DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_SRV\n"));); - uint16_t u16CachedDomainOffset = (p_rSendParameter.m_bLegacyQuery - ? 0 - : p_rSendParameter.findCachedDomainOffset((const void*)m_pcHostname, false)); - - stcMDNS_RRAttributes attributes(DNS_RRTYPE_SRV, - ((p_rSendParameter.m_bCacheFlush ? 0x8000 : 0) | DNS_RRCLASS_IN)); // Cache flush? & INternet - stcMDNS_RRDomain hostDomain; - bool bResult = ((_writeMDNSServiceDomain(p_rService, true, false, p_rSendParameter)) && // MyESP._http._tcp.local - (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS - (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_SERVICE_TTL), p_rSendParameter)) && // TTL - (!u16CachedDomainOffset - // No cache for domain name (or no compression allowed) - ? ((_buildDomainForHost(m_pcHostname, hostDomain)) && - (_write16((sizeof(uint16_t /*Prio*/) + // RDLength - sizeof(uint16_t /*Weight*/) + - sizeof(uint16_t /*Port*/) + - hostDomain.m_u16NameLength), p_rSendParameter)) && // Domain length - (_write16(MDNS_SRV_PRIORITY, p_rSendParameter)) && // Priority - (_write16(MDNS_SRV_WEIGHT, p_rSendParameter)) && // Weight - (_write16(p_rService.m_u16Port, p_rSendParameter)) && // Port - (p_rSendParameter.addDomainCacheItem((const void*)m_pcHostname, false, p_rSendParameter.m_u16Offset)) && - (_writeMDNSRRDomain(hostDomain, p_rSendParameter))) // Host, eg. esp8266.local - // Cache available for domain - : ((MDNS_DOMAIN_COMPRESS_MARK > ((u16CachedDomainOffset >> 8) & ~MDNS_DOMAIN_COMPRESS_MARK)) && // Valid offset - (_write16((sizeof(uint16_t /*Prio*/) + // RDLength - sizeof(uint16_t /*Weight*/) + - sizeof(uint16_t /*Port*/) + - 2), p_rSendParameter)) && // Length of 'C0xx' - (_write16(MDNS_SRV_PRIORITY, p_rSendParameter)) && // Priority - (_write16(MDNS_SRV_WEIGHT, p_rSendParameter)) && // Weight - (_write16(p_rService.m_u16Port, p_rSendParameter)) && // Port - (_write8(((u16CachedDomainOffset >> 8) | MDNS_DOMAIN_COMPRESS_MARK), p_rSendParameter)) && // Compression mark (and offset) - (_write8((uint8_t)u16CachedDomainOffset, p_rSendParameter))))); // Offset + uint16_t u16CachedDomainOffset = (p_rSendParameter.m_bLegacyQuery + ? 0 + : p_rSendParameter.findCachedDomainOffset((const void*)m_pcHostname, false)); + + stcMDNS_RRAttributes attributes(DNS_RRTYPE_SRV, + ((p_rSendParameter.m_bCacheFlush ? 0x8000 : 0) | DNS_RRCLASS_IN)); // Cache flush? & INternet + stcMDNS_RRDomain hostDomain; + bool bResult = ((_writeMDNSServiceDomain(p_rService, true, false, p_rSendParameter)) && // MyESP._http._tcp.local + (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS + (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_SERVICE_TTL), p_rSendParameter)) && // TTL + (!u16CachedDomainOffset + // No cache for domain name (or no compression allowed) + ? ((_buildDomainForHost(m_pcHostname, hostDomain)) && + (_write16((sizeof(uint16_t /*Prio*/) + // RDLength + sizeof(uint16_t /*Weight*/) + + sizeof(uint16_t /*Port*/) + + hostDomain.m_u16NameLength), + p_rSendParameter)) && // Domain length + (_write16(MDNS_SRV_PRIORITY, p_rSendParameter)) && // Priority + (_write16(MDNS_SRV_WEIGHT, p_rSendParameter)) && // Weight + (_write16(p_rService.m_u16Port, p_rSendParameter)) && // Port + (p_rSendParameter.addDomainCacheItem((const void*)m_pcHostname, false, p_rSendParameter.m_u16Offset)) && + (_writeMDNSRRDomain(hostDomain, p_rSendParameter))) // Host, eg. esp8266.local + // Cache available for domain + : ((MDNS_DOMAIN_COMPRESS_MARK > ((u16CachedDomainOffset >> 8) & ~MDNS_DOMAIN_COMPRESS_MARK)) && // Valid offset + (_write16((sizeof(uint16_t /*Prio*/) + // RDLength + sizeof(uint16_t /*Weight*/) + + sizeof(uint16_t /*Port*/) + + 2), + p_rSendParameter)) && // Length of 'C0xx' + (_write16(MDNS_SRV_PRIORITY, p_rSendParameter)) && // Priority + (_write16(MDNS_SRV_WEIGHT, p_rSendParameter)) && // Weight + (_write16(p_rService.m_u16Port, p_rSendParameter)) && // Port + (_write8(((u16CachedDomainOffset >> 8) | MDNS_DOMAIN_COMPRESS_MARK), p_rSendParameter)) && // Compression mark (and offset) + (_write8((uint8_t)u16CachedDomainOffset, p_rSendParameter))))); // Offset DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_SRV: FAILED!\n")); - }); + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_SRV: FAILED!\n")); + }); return bResult; } -} // namespace MDNSImplementation - -} // namespace esp8266 - - - - - +} // namespace MDNSImplementation +} // namespace esp8266 diff --git a/libraries/ESP8266mDNS/src/LEAmDNS_lwIPdefs.h b/libraries/ESP8266mDNS/src/LEAmDNS_lwIPdefs.h index 3686440f10..ea2128a9ed 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS_lwIPdefs.h +++ b/libraries/ESP8266mDNS/src/LEAmDNS_lwIPdefs.h @@ -27,4 +27,4 @@ #include // DNS_RRTYPE_xxx, DNS_MQUERY_PORT -#endif // MDNS_LWIPDEFS_H +#endif // MDNS_LWIPDEFS_H diff --git a/libraries/Netdump/examples/Netdump/Netdump.ino b/libraries/Netdump/examples/Netdump/Netdump.ino index dbba63869b..86523705b1 100644 --- a/libraries/Netdump/examples/Netdump/Netdump.ino +++ b/libraries/Netdump/examples/Netdump/Netdump.ino @@ -1,9 +1,9 @@ #include "Arduino.h" -#include "Netdump.h" -#include #include +#include #include +#include "Netdump.h" //#include #include #include @@ -12,7 +12,7 @@ using namespace NetCapture; #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* ssid = STASSID; @@ -24,8 +24,8 @@ Netdump nd; FS* filesystem = &LittleFS; ESP8266WebServer webServer(80); // Used for sending commands -WiFiServer tcpServer(8000); // Used to show netcat option. -File tracefile; +WiFiServer tcpServer(8000); // Used to show netcat option. +File tracefile; std::map packetCount; @@ -37,25 +37,23 @@ enum class SerialOption : uint8_t { void startSerial(SerialOption option) { switch (option) { - case SerialOption::AllFull : //All Packets, show packet summary. + case SerialOption::AllFull: //All Packets, show packet summary. nd.printDump(Serial, Packet::PacketDetail::FULL); break; - case SerialOption::LocalNone : // Only local IP traffic, full details + case SerialOption::LocalNone: // Only local IP traffic, full details nd.printDump(Serial, Packet::PacketDetail::NONE, [](Packet n) { return (n.hasIP(WiFi.localIP())); - } - ); + }); break; - case SerialOption::HTTPChar : // Only HTTP traffic, show packet content as chars + case SerialOption::HTTPChar: // Only HTTP traffic, show packet content as chars nd.printDump(Serial, Packet::PacketDetail::CHAR, [](Packet n) { return (n.isHTTP()); - } - ); + }); break; - default : + default: Serial.printf("No valid SerialOption provided\r\n"); }; } @@ -99,16 +97,14 @@ void setup(void) { d.concat("
  • " + dir.fileName() + "
  • "); } webServer.send(200, "text.html", d); - } - ); + }); webServer.on("/req", []() { static int rq = 0; String a = "

    You are connected, Number of requests = " + String(rq++) + "

    "; webServer.send(200, "text/html", a); - } - ); + }); webServer.on("/reset", []() { @@ -116,13 +112,12 @@ void setup(void) { tracefile.close(); tcpServer.close(); webServer.send(200, "text.html", "

    Netdump session reset

    "); - } - ); + }); webServer.serveStatic("/", *filesystem, "/"); webServer.begin(); - startSerial(SerialOption::AllFull); // Serial output examples, use enum SerialOption for selection + startSerial(SerialOption::AllFull); // Serial output examples, use enum SerialOption for selection // startTcpDump(); // tcpdump option // startTracefile(); // output to SPIFFS or LittleFS @@ -130,21 +125,21 @@ void setup(void) { // use a self provide callback, this count network packets /* nd.setCallback( - [](Packet p) - { - Serial.printf("PKT : %s : ",p.sourceIP().toString().c_str()); - for ( auto pp : p.allPacketTypes()) - { - Serial.printf("%s ",pp.toString().c_str()); - packetCount[pp]++; - } - Serial.printf("\r\n CNT "); - for (auto pc : packetCount) - { - Serial.printf("%s %d ", pc.first.toString().c_str(),pc.second); - } - Serial.printf("\r\n"); - } + [](Packet p) + { + Serial.printf("PKT : %s : ",p.sourceIP().toString().c_str()); + for ( auto pp : p.allPacketTypes()) + { + Serial.printf("%s ",pp.toString().c_str()); + packetCount[pp]++; + } + Serial.printf("\r\n CNT "); + for (auto pc : packetCount) + { + Serial.printf("%s %d ", pc.first.toString().c_str(),pc.second); + } + Serial.printf("\r\n"); + } ); */ } @@ -153,4 +148,3 @@ void loop(void) { webServer.handleClient(); MDNS.update(); } - diff --git a/libraries/Netdump/src/Netdump.cpp b/libraries/Netdump/src/Netdump.cpp index 4d4deb05b2..9e688f3ca7 100644 --- a/libraries/Netdump/src/Netdump.cpp +++ b/libraries/Netdump/src/Netdump.cpp @@ -23,10 +23,8 @@ #include #include "Schedule.h" - namespace NetCapture { - CallBackList Netdump::lwipCallback; Netdump::Netdump() @@ -52,7 +50,7 @@ void Netdump::setCallback(const Callback nc) void Netdump::setCallback(const Callback nc, const Filter nf) { - netDumpFilter = nf; + netDumpFilter = nf; netDumpCallback = nc; } @@ -69,24 +67,20 @@ void Netdump::reset() void Netdump::printDump(Print& out, Packet::PacketDetail ndd, const Filter nf) { out.printf_P(PSTR("netDump starting\r\n")); - setCallback([&out, ndd, this](const Packet & ndp) - { - printDumpProcess(out, ndd, ndp); - }, nf); + setCallback([&out, ndd, this](const Packet& ndp) + { printDumpProcess(out, ndd, ndp); }, + nf); } void Netdump::fileDump(File& outfile, const Filter nf) { - writePcapHeader(outfile); - setCallback([&outfile, this](const Packet & ndp) - { - fileDumpProcess(outfile, ndp); - }, nf); + setCallback([&outfile, this](const Packet& ndp) + { fileDumpProcess(outfile, ndp); }, + nf); } -bool Netdump::tcpDump(WiFiServer &tcpDumpServer, const Filter nf) +bool Netdump::tcpDump(WiFiServer& tcpDumpServer, const Filter nf) { - if (!packetBuffer) { packetBuffer = new (std::nothrow) char[tcpBufferSize]; @@ -99,9 +93,7 @@ bool Netdump::tcpDump(WiFiServer &tcpDumpServer, const Filter nf) bufferIndex = 0; schedule_function([&tcpDumpServer, this, nf]() - { - tcpDumpLoop(tcpDumpServer, nf); - }); + { tcpDumpLoop(tcpDumpServer, nf); }); return true; } @@ -109,7 +101,7 @@ void Netdump::capture(int netif_idx, const char* data, size_t len, int out, int { if (lwipCallback.execute(netif_idx, data, len, out, success) == 0) { - phy_capture = nullptr; // No active callback/netdump instances, will be set again by new object. + phy_capture = nullptr; // No active callback/netdump instances, will be set again by new object. } } @@ -118,7 +110,7 @@ void Netdump::netdumpCapture(int netif_idx, const char* data, size_t len, int ou if (netDumpCallback) { Packet np(millis(), netif_idx, data, len, out, success); - if (netDumpFilter && !netDumpFilter(np)) + if (netDumpFilter && !netDumpFilter(np)) { return; } @@ -131,8 +123,8 @@ void Netdump::writePcapHeader(Stream& s) const uint32_t pcapHeader[6]; pcapHeader[0] = 0xa1b2c3d4; // pcap magic number pcapHeader[1] = 0x00040002; // pcap major/minor version - pcapHeader[2] = 0; // pcap UTC correction in seconds - pcapHeader[3] = 0; // pcap time stamp accuracy + pcapHeader[2] = 0; // pcap UTC correction in seconds + pcapHeader[3] = 0; // pcap time stamp accuracy pcapHeader[4] = maxPcapLength; // pcap max packet length per record pcapHeader[5] = 1; // pacp data linkt type = ethernet s.write(reinterpret_cast(pcapHeader), 24); @@ -154,7 +146,7 @@ void Netdump::fileDumpProcess(File& outfile, const Packet& np) const pcapHeader[1] = tv.tv_usec; pcapHeader[2] = incl_len; pcapHeader[3] = np.getPacketSize(); - outfile.write(reinterpret_cast(pcapHeader), 16); // pcap record header + outfile.write(reinterpret_cast(pcapHeader), 16); // pcap record header outfile.write(np.rawData(), incl_len); } @@ -168,16 +160,16 @@ void Netdump::tcpDumpProcess(const Packet& np) } size_t incl_len = np.getPacketSize() > maxPcapLength ? maxPcapLength : np.getPacketSize(); - if (bufferIndex + 16 + incl_len < tcpBufferSize) // only add if enough space available + if (bufferIndex + 16 + incl_len < tcpBufferSize) // only add if enough space available { struct timeval tv; gettimeofday(&tv, nullptr); uint32_t* pcapHeader = reinterpret_cast(&packetBuffer[bufferIndex]); - pcapHeader[0] = tv.tv_sec; // add pcap record header + pcapHeader[0] = tv.tv_sec; // add pcap record header pcapHeader[1] = tv.tv_usec; pcapHeader[2] = incl_len; pcapHeader[3] = np.getPacketSize(); - bufferIndex += 16; // pcap header size + bufferIndex += 16; // pcap header size memcpy(&packetBuffer[bufferIndex], np.rawData(), incl_len); bufferIndex += incl_len; } @@ -189,7 +181,7 @@ void Netdump::tcpDumpProcess(const Packet& np) } } -void Netdump::tcpDumpLoop(WiFiServer &tcpDumpServer, const Filter nf) +void Netdump::tcpDumpLoop(WiFiServer& tcpDumpServer, const Filter nf) { if (tcpDumpServer.hasClient()) { @@ -199,10 +191,9 @@ void Netdump::tcpDumpLoop(WiFiServer &tcpDumpServer, const Filter nf) bufferIndex = 0; writePcapHeader(tcpDumpClient); - setCallback([this](const Packet & ndp) - { - tcpDumpProcess(ndp); - }, nf); + setCallback([this](const Packet& ndp) + { tcpDumpProcess(ndp); }, + nf); } if (!tcpDumpClient || !tcpDumpClient.connected()) { @@ -217,10 +208,8 @@ void Netdump::tcpDumpLoop(WiFiServer &tcpDumpServer, const Filter nf) if (tcpDumpServer.status() != CLOSED) { schedule_function([&tcpDumpServer, this, nf]() - { - tcpDumpLoop(tcpDumpServer, nf); - }); + { tcpDumpLoop(tcpDumpServer, nf); }); } } -} // namespace NetCapture +} // namespace NetCapture diff --git a/libraries/Netdump/src/Netdump.h b/libraries/Netdump/src/Netdump.h index 0e8b6cbb00..dd5a3d124c 100644 --- a/libraries/Netdump/src/Netdump.h +++ b/libraries/Netdump/src/Netdump.h @@ -22,23 +22,21 @@ #ifndef __NETDUMP_H #define __NETDUMP_H +#include +#include #include -#include #include -#include -#include "NetdumpPacket.h" -#include +#include #include "CallBackList.h" +#include "NetdumpPacket.h" namespace NetCapture { - using namespace experimental::CBListImplentation; class Netdump { -public: - + public: using Filter = std::function; using Callback = std::function; using LwipCallback = std::function; @@ -53,12 +51,11 @@ class Netdump void printDump(Print& out, Packet::PacketDetail ndd, const Filter nf = nullptr); void fileDump(File& outfile, const Filter nf = nullptr); - bool tcpDump(WiFiServer &tcpDumpServer, const Filter nf = nullptr); - + bool tcpDump(WiFiServer& tcpDumpServer, const Filter nf = nullptr); -private: + private: Callback netDumpCallback = nullptr; - Filter netDumpFilter = nullptr; + Filter netDumpFilter = nullptr; static void capture(int netif_idx, const char* data, size_t len, int out, int success); static CallBackList lwipCallback; @@ -69,7 +66,7 @@ class Netdump void printDumpProcess(Print& out, Packet::PacketDetail ndd, const Packet& np) const; void fileDumpProcess(File& outfile, const Packet& np) const; void tcpDumpProcess(const Packet& np); - void tcpDumpLoop(WiFiServer &tcpDumpServer, const Filter nf); + void tcpDumpLoop(WiFiServer& tcpDumpServer, const Filter nf); void writePcapHeader(Stream& s) const; @@ -82,6 +79,6 @@ class Netdump static constexpr uint32_t pcapMagic = 0xa1b2c3d4; }; -} // namespace NetCapture +} // namespace NetCapture #endif /* __NETDUMP_H */ diff --git a/libraries/Netdump/src/NetdumpIP.cpp b/libraries/Netdump/src/NetdumpIP.cpp index 56936c744a..f90113f47b 100644 --- a/libraries/Netdump/src/NetdumpIP.cpp +++ b/libraries/Netdump/src/NetdumpIP.cpp @@ -23,7 +23,6 @@ namespace NetCapture { - NetdumpIP::NetdumpIP() { } @@ -37,7 +36,7 @@ NetdumpIP::NetdumpIP(uint8_t first_octet, uint8_t second_octet, uint8_t third_oc (*this)[3] = fourth_octet; } -NetdumpIP::NetdumpIP(const uint8_t *address, bool v4) +NetdumpIP::NetdumpIP(const uint8_t* address, bool v4) { uint8_t cnt; if (v4) @@ -88,7 +87,7 @@ NetdumpIP::NetdumpIP(const String& ip) } } -bool NetdumpIP::fromString(const char *address) +bool NetdumpIP::fromString(const char* address) { if (!fromString4(address)) { @@ -97,11 +96,11 @@ bool NetdumpIP::fromString(const char *address) return true; } -bool NetdumpIP::fromString4(const char *address) +bool NetdumpIP::fromString4(const char* address) { // TODO: (IPv4) add support for "a", "a.b", "a.b.c" formats - uint16_t acc = 0; // Accumulator + uint16_t acc = 0; // Accumulator uint8_t dots = 0; while (*address) @@ -144,11 +143,11 @@ bool NetdumpIP::fromString4(const char *address) return true; } -bool NetdumpIP::fromString6(const char *address) +bool NetdumpIP::fromString6(const char* address) { // TODO: test test test - uint32_t acc = 0; // Accumulator + uint32_t acc = 0; // Accumulator int dots = 0, doubledots = -1; while (*address) @@ -162,7 +161,7 @@ bool NetdumpIP::fromString6(const char *address) } acc = acc * 16 + (c - '0'); if (acc > 0xffff) - // Value out of range + // Value out of range { return false; } @@ -172,7 +171,7 @@ bool NetdumpIP::fromString6(const char *address) if (*address == ':') { if (doubledots >= 0) - // :: allowed once + // :: allowed once { return false; } @@ -181,7 +180,7 @@ bool NetdumpIP::fromString6(const char *address) address++; } if (dots == 7) - // too many separators + // too many separators { return false; } @@ -189,14 +188,14 @@ bool NetdumpIP::fromString6(const char *address) acc = 0; } else - // Invalid char + // Invalid char { return false; } } if (doubledots == -1 && dots != 7) - // Too few separators + // Too few separators { return false; } @@ -223,12 +222,11 @@ String NetdumpIP::toString() StreamString sstr; if (isV6()) { - sstr.reserve(40); // 8 shorts x 4 chars each + 7 colons + nullterm - + sstr.reserve(40); // 8 shorts x 4 chars each + 7 colons + nullterm } else { - sstr.reserve(16); // 4 bytes with 3 chars max + 3 dots + nullterm, or '(IP unset)' + sstr.reserve(16); // 4 bytes with 3 chars max + 3 dots + nullterm, or '(IP unset)' } printTo(sstr); return sstr; @@ -253,7 +251,7 @@ size_t NetdumpIP::printTo(Print& p) { n += p.printf_P(PSTR("%x"), bit); if (count0 > 0) - // no more hiding 0 + // no more hiding 0 { count0 = -8; } @@ -280,7 +278,7 @@ size_t NetdumpIP::printTo(Print& p) return n; } -bool NetdumpIP::compareRaw(IPversion v, const uint8_t* a, const uint8_t* b) const +bool NetdumpIP::compareRaw(IPversion v, const uint8_t* a, const uint8_t* b) const { for (int i = 0; i < (v == IPversion::IPV4 ? 4 : 16); i++) { @@ -296,39 +294,39 @@ bool NetdumpIP::compareIP(const IPAddress& ip) const { switch (ipv) { - case IPversion::UNSET : - if (ip.isSet()) - { - return false; - } - else - { - return true; - } - break; - case IPversion::IPV4 : - if (ip.isV6() || !ip.isSet()) - { - return false; - } - else - { - return compareRaw(IPversion::IPV4, rawip, reinterpret_cast(&ip.v4())); - } - break; - case IPversion::IPV6 : - if (ip.isV4() || !ip.isSet()) - { + case IPversion::UNSET: + if (ip.isSet()) + { + return false; + } + else + { + return true; + } + break; + case IPversion::IPV4: + if (ip.isV6() || !ip.isSet()) + { + return false; + } + else + { + return compareRaw(IPversion::IPV4, rawip, reinterpret_cast(&ip.v4())); + } + break; + case IPversion::IPV6: + if (ip.isV4() || !ip.isSet()) + { + return false; + } + else + { + return compareRaw(IPversion::IPV6, rawip, reinterpret_cast(ip.raw6())); + } + break; + default: return false; - } - else - { - return compareRaw(IPversion::IPV6, rawip, reinterpret_cast(ip.raw6())); - } - break; - default : - return false; - break; + break; } } @@ -336,40 +334,40 @@ bool NetdumpIP::compareIP(const NetdumpIP& nip) const { switch (ipv) { - case IPversion::UNSET : - if (nip.isSet()) - { - return false; - } - else - { - return true; - } - break; - case IPversion::IPV4 : - if (nip.isV6() || !nip.isSet()) - { - return false; - } - else - { - return compareRaw(IPversion::IPV4, rawip, nip.rawip); - } - break; - case IPversion::IPV6 : - if (nip.isV4() || !nip.isSet()) - { + case IPversion::UNSET: + if (nip.isSet()) + { + return false; + } + else + { + return true; + } + break; + case IPversion::IPV4: + if (nip.isV6() || !nip.isSet()) + { + return false; + } + else + { + return compareRaw(IPversion::IPV4, rawip, nip.rawip); + } + break; + case IPversion::IPV6: + if (nip.isV4() || !nip.isSet()) + { + return false; + } + else + { + return compareRaw(IPversion::IPV6, rawip, nip.rawip); + } + break; + default: return false; - } - else - { - return compareRaw(IPversion::IPV6, rawip, nip.rawip); - } - break; - default : - return false; - break; + break; } } -} // namespace NetCapture +} // namespace NetCapture diff --git a/libraries/Netdump/src/NetdumpIP.h b/libraries/Netdump/src/NetdumpIP.h index 8a450c374a..ae8efc7e94 100644 --- a/libraries/Netdump/src/NetdumpIP.h +++ b/libraries/Netdump/src/NetdumpIP.h @@ -8,21 +8,20 @@ #ifndef LIBRARIES_ESPGOODIES_HR_SRC_NETDUMP_NETDUMPIP_H_ #define LIBRARIES_ESPGOODIES_HR_SRC_NETDUMP_NETDUMPIP_H_ -#include -#include -#include #include +#include +#include +#include namespace NetCapture { - class NetdumpIP { -public: + public: NetdumpIP(); NetdumpIP(uint8_t first_octet, uint8_t second_octet, uint8_t third_octet, uint8_t fourth_octet); - NetdumpIP(const uint8_t *address, bool V4 = true); + NetdumpIP(const uint8_t* address, bool V4 = true); NetdumpIP(const IPAddress& ip); NetdumpIP(const String& ip); @@ -31,12 +30,17 @@ class NetdumpIP return rawip[index]; } - bool fromString(const char *address); + bool fromString(const char* address); String toString(); -private: - enum class IPversion {UNSET, IPV4, IPV6}; + private: + enum class IPversion + { + UNSET, + IPV4, + IPV6 + }; IPversion ipv = IPversion::UNSET; uint8_t rawip[16] = {0}; @@ -70,15 +74,16 @@ class NetdumpIP return (ipv != IPversion::UNSET); }; - bool compareRaw(IPversion v, const uint8_t* a, const uint8_t* b) const; + bool compareRaw(IPversion v, const uint8_t* a, const uint8_t* b) const; bool compareIP(const IPAddress& ip) const; bool compareIP(const NetdumpIP& nip) const; - bool fromString4(const char *address); - bool fromString6(const char *address); + bool fromString4(const char* address); + bool fromString6(const char* address); size_t printTo(Print& p); -public: + + public: bool operator==(const IPAddress& addr) const { return compareIP(addr); @@ -95,9 +100,8 @@ class NetdumpIP { return !compareIP(addr); }; - }; -} // namespace NetCapture +} // namespace NetCapture #endif /* LIBRARIES_ESPGOODIES_HR_SRC_NETDUMP_NETDUMPIP_H_ */ diff --git a/libraries/Netdump/src/NetdumpPacket.cpp b/libraries/Netdump/src/NetdumpPacket.cpp index bb4e09920c..9efad50490 100644 --- a/libraries/Netdump/src/NetdumpPacket.cpp +++ b/libraries/Netdump/src/NetdumpPacket.cpp @@ -19,12 +19,11 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -#include "Netdump.h" #include +#include "Netdump.h" namespace NetCapture { - void Packet::printDetail(Print& out, const String& indent, const char* data, size_t size, PacketDetail pd) const { if (pd == PacketDetail::NONE) @@ -159,18 +158,19 @@ void Packet::MACtoString(int dataIdx, StreamString& sstr) const sstr.print(':'); } } - } void Packet::ARPtoString(PacketDetail netdumpDetail, StreamString& sstr) const { switch (getARPType()) { - case 1 : sstr.printf_P(PSTR("who has %s tell %s"), getIP(ETH_HDR_LEN + 24).toString().c_str(), getIP(ETH_HDR_LEN + 14).toString().c_str()); - break; - case 2 : sstr.printf_P(PSTR("%s is at "), getIP(ETH_HDR_LEN + 14).toString().c_str()); - MACtoString(ETH_HDR_LEN + 8, sstr); - break; + case 1: + sstr.printf_P(PSTR("who has %s tell %s"), getIP(ETH_HDR_LEN + 24).toString().c_str(), getIP(ETH_HDR_LEN + 14).toString().c_str()); + break; + case 2: + sstr.printf_P(PSTR("%s is at "), getIP(ETH_HDR_LEN + 14).toString().c_str()); + MACtoString(ETH_HDR_LEN + 8, sstr); + break; } sstr.printf("\r\n"); printDetail(sstr, PSTR(" D "), &data[ETH_HDR_LEN], packetLength - ETH_HDR_LEN, netdumpDetail); @@ -217,7 +217,7 @@ void Packet::TCPtoString(PacketDetail netdumpDetail, StreamString& sstr) const sstr.printf_P(PSTR("%d:%d "), getSrcPort(), getDstPort()); uint16_t flags = getTcpFlags(); sstr.print('['); - const char chars [] = "FSRPAUECN"; + const char chars[] = "FSRPAUECN"; for (uint8_t i = 0; i < sizeof chars; i++) if (flags & (1 << i)) { @@ -237,20 +237,36 @@ void Packet::ICMPtoString(PacketDetail, StreamString& sstr) const { switch (getIcmpType()) { - case 0 : sstr.printf_P(PSTR("ping reply")); break; - case 8 : sstr.printf_P(PSTR("ping request")); break; - default: sstr.printf_P(PSTR("type(0x%02x)"), getIcmpType()); break; + case 0: + sstr.printf_P(PSTR("ping reply")); + break; + case 8: + sstr.printf_P(PSTR("ping request")); + break; + default: + sstr.printf_P(PSTR("type(0x%02x)"), getIcmpType()); + break; } } if (isIPv6()) { switch (getIcmpType()) { - case 129 : sstr.printf_P(PSTR("ping reply")); break; - case 128 : sstr.printf_P(PSTR("ping request")); break; - case 135 : sstr.printf_P(PSTR("Neighbour solicitation")); break; - case 136 : sstr.printf_P(PSTR("Neighbour advertisement")); break; - default: sstr.printf_P(PSTR("type(0x%02x)"), getIcmpType()); break; + case 129: + sstr.printf_P(PSTR("ping reply")); + break; + case 128: + sstr.printf_P(PSTR("ping request")); + break; + case 135: + sstr.printf_P(PSTR("Neighbour solicitation")); + break; + case 136: + sstr.printf_P(PSTR("Neighbour advertisement")); + break; + default: + sstr.printf_P(PSTR("type(0x%02x)"), getIcmpType()); + break; } } sstr.printf_P(PSTR("\r\n")); @@ -260,18 +276,42 @@ void Packet::IGMPtoString(PacketDetail, StreamString& sstr) const { switch (getIgmpType()) { - case 1 : sstr.printf_P(PSTR("Create Group Request")); break; - case 2 : sstr.printf_P(PSTR("Create Group Reply")); break; - case 3 : sstr.printf_P(PSTR("Join Group Request")); break; - case 4 : sstr.printf_P(PSTR("Join Group Reply")); break; - case 5 : sstr.printf_P(PSTR("Leave Group Request")); break; - case 6 : sstr.printf_P(PSTR("Leave Group Reply")); break; - case 7 : sstr.printf_P(PSTR("Confirm Group Request")); break; - case 8 : sstr.printf_P(PSTR("Confirm Group Reply")); break; - case 0x11 : sstr.printf_P(PSTR("Group Membership Query")); break; - case 0x12 : sstr.printf_P(PSTR("IGMPv1 Membership Report")); break; - case 0x22 : sstr.printf_P(PSTR("IGMPv3 Membership Report")); break; - default: sstr.printf_P(PSTR("type(0x%02x)"), getIgmpType()); break; + case 1: + sstr.printf_P(PSTR("Create Group Request")); + break; + case 2: + sstr.printf_P(PSTR("Create Group Reply")); + break; + case 3: + sstr.printf_P(PSTR("Join Group Request")); + break; + case 4: + sstr.printf_P(PSTR("Join Group Reply")); + break; + case 5: + sstr.printf_P(PSTR("Leave Group Request")); + break; + case 6: + sstr.printf_P(PSTR("Leave Group Reply")); + break; + case 7: + sstr.printf_P(PSTR("Confirm Group Request")); + break; + case 8: + sstr.printf_P(PSTR("Confirm Group Reply")); + break; + case 0x11: + sstr.printf_P(PSTR("Group Membership Query")); + break; + case 0x12: + sstr.printf_P(PSTR("IGMPv1 Membership Report")); + break; + case 0x22: + sstr.printf_P(PSTR("IGMPv3 Membership Report")); + break; + default: + sstr.printf_P(PSTR("type(0x%02x)"), getIgmpType()); + break; } sstr.printf_P(PSTR("\r\n")); } @@ -298,7 +338,6 @@ const String Packet::toString() const return toString(PacketDetail::NONE); } - const String Packet::toString(PacketDetail netdumpDetail) const { StreamString sstr; @@ -320,62 +359,62 @@ const String Packet::toString(PacketDetail netdumpDetail) const switch (thisPacketType) { - case PacketType::ARP : - { - ARPtoString(netdumpDetail, sstr); - break; - } - case PacketType::MDNS : - case PacketType::DNS : - { - DNStoString(netdumpDetail, sstr); - break; - } - case PacketType::SSDP : - case PacketType::DHCP : - case PacketType::WSDD : - case PacketType::NETBIOS : - case PacketType::SMB : - case PacketType::OTA : - case PacketType::UDP : - { - UDPtoString(netdumpDetail, sstr); - break; - } - case PacketType::TCP : - case PacketType::HTTP : - { - TCPtoString(netdumpDetail, sstr); - break; - } - case PacketType::ICMP : - { - ICMPtoString(netdumpDetail, sstr); - break; - } - case PacketType::IGMP : - { - IGMPtoString(netdumpDetail, sstr); - break; - } - case PacketType::IPv4 : - case PacketType::IPv6 : - { - IPtoString(netdumpDetail, sstr); - break; - } - case PacketType::UKNW : - { - UKNWtoString(netdumpDetail, sstr); - break; - } - default : - { - sstr.printf_P(PSTR("Non identified packet\r\n")); - break; - } + case PacketType::ARP: + { + ARPtoString(netdumpDetail, sstr); + break; + } + case PacketType::MDNS: + case PacketType::DNS: + { + DNStoString(netdumpDetail, sstr); + break; + } + case PacketType::SSDP: + case PacketType::DHCP: + case PacketType::WSDD: + case PacketType::NETBIOS: + case PacketType::SMB: + case PacketType::OTA: + case PacketType::UDP: + { + UDPtoString(netdumpDetail, sstr); + break; + } + case PacketType::TCP: + case PacketType::HTTP: + { + TCPtoString(netdumpDetail, sstr); + break; + } + case PacketType::ICMP: + { + ICMPtoString(netdumpDetail, sstr); + break; + } + case PacketType::IGMP: + { + IGMPtoString(netdumpDetail, sstr); + break; + } + case PacketType::IPv4: + case PacketType::IPv6: + { + IPtoString(netdumpDetail, sstr); + break; + } + case PacketType::UKNW: + { + UKNWtoString(netdumpDetail, sstr); + break; + } + default: + { + sstr.printf_P(PSTR("Non identified packet\r\n")); + break; + } } return sstr; } -} // namespace NetCapture +} // namespace NetCapture diff --git a/libraries/Netdump/src/NetdumpPacket.h b/libraries/Netdump/src/NetdumpPacket.h index a898ef230f..8cf13169e0 100644 --- a/libraries/Netdump/src/NetdumpPacket.h +++ b/libraries/Netdump/src/NetdumpPacket.h @@ -22,21 +22,20 @@ #ifndef __NETDUMP_PACKET_H #define __NETDUMP_PACKET_H -#include #include #include +#include +#include #include "NetdumpIP.h" #include "PacketType.h" -#include namespace NetCapture { - int constexpr ETH_HDR_LEN = 14; class Packet { -public: + public: Packet(unsigned long msec, int n, const char* d, size_t l, int o, int s) : packetTime(msec), netif_idx(n), data(d), packetLength(l), out(o), success(s) { @@ -75,7 +74,7 @@ class Packet { return ntoh16(idx + 2) | (((uint32_t)ntoh16(idx)) << 16); }; - uint8_t byteData(uint16_t idx) const + uint8_t byteData(uint16_t idx) const { return data[idx]; } @@ -87,17 +86,17 @@ class Packet { return ntoh16(12); }; - uint8_t ipType() const + uint8_t ipType() const { return isIP() ? isIPv4() ? data[ETH_HDR_LEN + 9] : data[ETH_HDR_LEN + 6] : 0; }; uint16_t getIpHdrLen() const { - return isIPv4() ? (((unsigned char)data[ETH_HDR_LEN]) & 0x0f) << 2 : 40 ; // IPv6 is fixed length + return isIPv4() ? (((unsigned char)data[ETH_HDR_LEN]) & 0x0f) << 2 : 40; // IPv6 is fixed length } uint16_t getIpTotalLen() const { - return isIP() ? isIPv4() ? ntoh16(ETH_HDR_LEN + 2) : (packetLength - ETH_HDR_LEN) : 0; + return isIP() ? isIPv4() ? ntoh16(ETH_HDR_LEN + 2) : (packetLength - ETH_HDR_LEN) : 0; } uint32_t getTcpSeq() const { @@ -115,20 +114,20 @@ class Packet { return isTCP() ? ntoh16(ETH_HDR_LEN + getIpHdrLen() + 14) : 0; } - uint8_t getTcpHdrLen() const + uint8_t getTcpHdrLen() const { return isTCP() ? (data[ETH_HDR_LEN + getIpHdrLen() + 12] >> 4) * 4 : 0; - };//Header len is in multiple of 4 bytes + }; //Header len is in multiple of 4 bytes uint16_t getTcpLen() const { - return isTCP() ? getIpTotalLen() - getIpHdrLen() - getTcpHdrLen() : 0 ; + return isTCP() ? getIpTotalLen() - getIpHdrLen() - getTcpHdrLen() : 0; }; - uint8_t getIcmpType() const + uint8_t getIcmpType() const { return isICMP() ? data[ETH_HDR_LEN + getIpHdrLen() + 0] : 0; } - uint8_t getIgmpType() const + uint8_t getIgmpType() const { return isIGMP() ? data[ETH_HDR_LEN + getIpHdrLen() + 0] : 0; } @@ -136,11 +135,11 @@ class Packet { return isARP() ? data[ETH_HDR_LEN + 7] : 0; } - bool is_ARP_who() const + bool is_ARP_who() const { return (getARPType() == 1); } - bool is_ARP_is() const + bool is_ARP_is() const { return (getARPType() == 2); } @@ -244,7 +243,7 @@ class Packet return ip; }; - bool hasIP(NetdumpIP ip) const + bool hasIP(NetdumpIP ip) const { return (isIP() && ((ip == sourceIP()) || (ip == destIP()))); } @@ -270,7 +269,7 @@ class Packet { return isIP() ? ntoh16(ETH_HDR_LEN + getIpHdrLen() + 2) : 0; } - bool hasPort(uint16_t p) const + bool hasPort(uint16_t p) const { return (isIP() && ((getSrcPort() == p) || (getDstPort() == p))); } @@ -282,9 +281,7 @@ class Packet const PacketType packetType() const; const std::vector& allPacketTypes() const; - -private: - + private: void setPacketType(PacketType); void setPacketTypes(); @@ -298,7 +295,6 @@ class Packet void IPtoString(PacketDetail netdumpDetail, StreamString& sstr) const; void UKNWtoString(PacketDetail netdumpDetail, StreamString& sstr) const; - time_t packetTime; int netif_idx; const char* data; @@ -309,6 +305,6 @@ class Packet std::vector thisAllPacketTypes; }; -} // namespace NetCapture +} // namespace NetCapture #endif /* __NETDUMP_PACKET_H */ diff --git a/libraries/Netdump/src/PacketType.cpp b/libraries/Netdump/src/PacketType.cpp index 565aa55f0a..05bf35a9f6 100644 --- a/libraries/Netdump/src/PacketType.cpp +++ b/libraries/Netdump/src/PacketType.cpp @@ -9,7 +9,6 @@ namespace NetCapture { - PacketType::PacketType() { } @@ -18,25 +17,44 @@ String PacketType::toString() const { switch (ptype) { - case PType::ARP : return PSTR("ARP"); - case PType::IP : return PSTR("IP"); - case PType::UDP : return PSTR("UDP"); - case PType::MDNS : return PSTR("MDNS"); - case PType::DNS : return PSTR("DNS"); - case PType::SSDP : return PSTR("SSDP"); - case PType::DHCP : return PSTR("DHCP"); - case PType::WSDD : return PSTR("WSDD"); - case PType::NETBIOS: return PSTR("NBIO"); - case PType::SMB : return PSTR("SMB"); - case PType::OTA : return PSTR("OTA"); - case PType::TCP : return PSTR("TCP"); - case PType::HTTP : return PSTR("HTTP"); - case PType::ICMP : return PSTR("ICMP"); - case PType::IGMP : return PSTR("IGMP"); - case PType::IPv4: return PSTR("IPv4"); - case PType::IPv6: return PSTR("IPv6"); - case PType::UKNW : return PSTR("UKNW"); - default : return PSTR("ERR"); + case PType::ARP: + return PSTR("ARP"); + case PType::IP: + return PSTR("IP"); + case PType::UDP: + return PSTR("UDP"); + case PType::MDNS: + return PSTR("MDNS"); + case PType::DNS: + return PSTR("DNS"); + case PType::SSDP: + return PSTR("SSDP"); + case PType::DHCP: + return PSTR("DHCP"); + case PType::WSDD: + return PSTR("WSDD"); + case PType::NETBIOS: + return PSTR("NBIO"); + case PType::SMB: + return PSTR("SMB"); + case PType::OTA: + return PSTR("OTA"); + case PType::TCP: + return PSTR("TCP"); + case PType::HTTP: + return PSTR("HTTP"); + case PType::ICMP: + return PSTR("ICMP"); + case PType::IGMP: + return PSTR("IGMP"); + case PType::IPv4: + return PSTR("IPv4"); + case PType::IPv6: + return PSTR("IPv6"); + case PType::UKNW: + return PSTR("UKNW"); + default: + return PSTR("ERR"); }; } diff --git a/libraries/Netdump/src/PacketType.h b/libraries/Netdump/src/PacketType.h index 8f4aa5ce79..c819f15511 100644 --- a/libraries/Netdump/src/PacketType.h +++ b/libraries/Netdump/src/PacketType.h @@ -11,11 +11,9 @@ namespace NetCapture { - class PacketType { -public: - + public: enum PType : int { ARP, @@ -39,7 +37,8 @@ class PacketType }; PacketType(); - PacketType(PType pt) : ptype(pt) {}; + PacketType(PType pt) + : ptype(pt){}; operator PType() const { @@ -52,7 +51,7 @@ class PacketType String toString() const; -private: + private: PType ptype; }; diff --git a/libraries/SoftwareSerial b/libraries/SoftwareSerial index eb4b29074b..bd2f6ce6a7 160000 --- a/libraries/SoftwareSerial +++ b/libraries/SoftwareSerial @@ -1 +1 @@ -Subproject commit eb4b29074b75eacac3585bf84b5495b8f80a92cf +Subproject commit bd2f6ce6a78d0c31b6978bcffb3c8379a5e4e2e4 diff --git a/libraries/Wire/Wire.cpp b/libraries/Wire/Wire.cpp index e9fc796bbf..f389a7b24e 100644 --- a/libraries/Wire/Wire.cpp +++ b/libraries/Wire/Wire.cpp @@ -22,15 +22,15 @@ Modified January 2017 by Bjorn Hammarberg (bjoham@esp8266.com) - i2c slave support */ -extern "C" { +extern "C" +{ +#include #include #include -#include } -#include "twi.h" #include "Wire.h" - +#include "twi.h" //Some boards don't have these pins available, and hence don't support Wire. //Check here for compile-time error. @@ -199,7 +199,7 @@ size_t TwoWire::write(uint8_t data) return 1; } -size_t TwoWire::write(const uint8_t *data, size_t quantity) +size_t TwoWire::write(const uint8_t* data, size_t quantity) { if (transmitting) { @@ -312,7 +312,7 @@ void TwoWire::onReceive(void (*function)(int)) // arduino api compatibility fixer: // really hope size parameter will not exceed 2^31 :) static_assert(sizeof(int) == sizeof(size_t), "something is wrong in Arduino kingdom"); - user_onReceive = reinterpret_cast(function); + user_onReceive = reinterpret_cast(function); } void TwoWire::onReceive(void (*function)(size_t)) diff --git a/libraries/Wire/Wire.h b/libraries/Wire/Wire.h index be73f10fe6..626087a4b2 100644 --- a/libraries/Wire/Wire.h +++ b/libraries/Wire/Wire.h @@ -27,7 +27,6 @@ #include #include "Stream.h" - #ifndef I2C_BUFFER_LENGTH // DEPRECATED: Do not use BUFFER_LENGTH, prefer I2C_BUFFER_LENGTH #define BUFFER_LENGTH 128 @@ -36,7 +35,7 @@ class TwoWire : public Stream { -private: + private: static uint8_t rxBuffer[]; static size_t rxBufferIndex; static size_t rxBufferLength; @@ -51,11 +50,12 @@ class TwoWire : public Stream static void (*user_onReceive)(size_t); static void onRequestService(void); static void onReceiveService(uint8_t*, size_t); -public: + + public: TwoWire(); void begin(int sda, int scl); void begin(int sda, int scl, uint8_t address); - void pins(int sda, int scl) __attribute__((deprecated)); // use begin(sda, scl) in new code + void pins(int sda, int scl) __attribute__((deprecated)); // use begin(sda, scl) in new code void begin(); void begin(uint8_t); void begin(int); @@ -74,13 +74,13 @@ class TwoWire : public Stream uint8_t requestFrom(int, int, int); virtual size_t write(uint8_t); - virtual size_t write(const uint8_t *, size_t); + virtual size_t write(const uint8_t*, size_t); virtual int available(void); virtual int read(void); virtual int peek(void); virtual void flush(void); - void onReceive(void (*)(int)); // arduino api - void onReceive(void (*)(size_t)); // legacy esp8266 backward compatibility + void onReceive(void (*)(int)); // arduino api + void onReceive(void (*)(size_t)); // legacy esp8266 backward compatibility void onRequest(void (*)(void)); using Print::write; @@ -91,4 +91,3 @@ extern TwoWire Wire; #endif #endif - diff --git a/libraries/lwIP_PPP/src/PPPServer.cpp b/libraries/lwIP_PPP/src/PPPServer.cpp index 98fddd7777..ef0e571ec5 100644 --- a/libraries/lwIP_PPP/src/PPPServer.cpp +++ b/libraries/lwIP_PPP/src/PPPServer.cpp @@ -10,13 +10,14 @@ // using NAT instead (see in example) #include -#include #include +#include #include #include "PPPServer.h" -PPPServer::PPPServer(Stream* sio): _sio(sio), _cb(netif_status_cb_s), _enabled(false) +PPPServer::PPPServer(Stream* sio) + : _sio(sio), _cb(netif_status_cb_s), _enabled(false) { } @@ -43,85 +44,85 @@ void PPPServer::link_status_cb_s(ppp_pcb* pcb, int err_code, void* ctx) switch (err_code) { - case PPPERR_NONE: /* No error. */ - { + case PPPERR_NONE: /* No error. */ + { #if LWIP_DNS - const ip_addr_t *ns; + const ip_addr_t* ns; #endif /* LWIP_DNS */ - ets_printf("ppp_link_status_cb: PPPERR_NONE\n\r"); + ets_printf("ppp_link_status_cb: PPPERR_NONE\n\r"); #if LWIP_IPV4 - ets_printf(" our_ip4addr = %s\n\r", ip4addr_ntoa(netif_ip4_addr(nif))); - ets_printf(" his_ipaddr = %s\n\r", ip4addr_ntoa(netif_ip4_gw(nif))); - ets_printf(" netmask = %s\n\r", ip4addr_ntoa(netif_ip4_netmask(nif))); + ets_printf(" our_ip4addr = %s\n\r", ip4addr_ntoa(netif_ip4_addr(nif))); + ets_printf(" his_ipaddr = %s\n\r", ip4addr_ntoa(netif_ip4_gw(nif))); + ets_printf(" netmask = %s\n\r", ip4addr_ntoa(netif_ip4_netmask(nif))); #endif /* LWIP_IPV4 */ #if LWIP_IPV6 - ets_printf(" our_ip6addr = %s\n\r", ip6addr_ntoa(netif_ip6_addr(nif, 0))); + ets_printf(" our_ip6addr = %s\n\r", ip6addr_ntoa(netif_ip6_addr(nif, 0))); #endif /* LWIP_IPV6 */ #if LWIP_DNS - ns = dns_getserver(0); - ets_printf(" dns1 = %s\n\r", ipaddr_ntoa(ns)); - ns = dns_getserver(1); - ets_printf(" dns2 = %s\n\r", ipaddr_ntoa(ns)); + ns = dns_getserver(0); + ets_printf(" dns1 = %s\n\r", ipaddr_ntoa(ns)); + ns = dns_getserver(1); + ets_printf(" dns2 = %s\n\r", ipaddr_ntoa(ns)); #endif /* LWIP_DNS */ #if PPP_IPV6_SUPPORT - ets_printf(" our6_ipaddr = %s\n\r", ip6addr_ntoa(netif_ip6_addr(nif, 0))); + ets_printf(" our6_ipaddr = %s\n\r", ip6addr_ntoa(netif_ip6_addr(nif, 0))); #endif /* PPP_IPV6_SUPPORT */ - } - stop = false; - break; + } + stop = false; + break; - case PPPERR_PARAM: /* Invalid parameter. */ - ets_printf("ppp_link_status_cb: PPPERR_PARAM\n"); - break; + case PPPERR_PARAM: /* Invalid parameter. */ + ets_printf("ppp_link_status_cb: PPPERR_PARAM\n"); + break; - case PPPERR_OPEN: /* Unable to open PPP session. */ - ets_printf("ppp_link_status_cb: PPPERR_OPEN\n"); - break; + case PPPERR_OPEN: /* Unable to open PPP session. */ + ets_printf("ppp_link_status_cb: PPPERR_OPEN\n"); + break; - case PPPERR_DEVICE: /* Invalid I/O device for PPP. */ - ets_printf("ppp_link_status_cb: PPPERR_DEVICE\n"); - break; + case PPPERR_DEVICE: /* Invalid I/O device for PPP. */ + ets_printf("ppp_link_status_cb: PPPERR_DEVICE\n"); + break; - case PPPERR_ALLOC: /* Unable to allocate resources. */ - ets_printf("ppp_link_status_cb: PPPERR_ALLOC\n"); - break; + case PPPERR_ALLOC: /* Unable to allocate resources. */ + ets_printf("ppp_link_status_cb: PPPERR_ALLOC\n"); + break; - case PPPERR_USER: /* User interrupt. */ - ets_printf("ppp_link_status_cb: PPPERR_USER\n"); - break; + case PPPERR_USER: /* User interrupt. */ + ets_printf("ppp_link_status_cb: PPPERR_USER\n"); + break; - case PPPERR_CONNECT: /* Connection lost. */ - ets_printf("ppp_link_status_cb: PPPERR_CONNECT\n"); - break; + case PPPERR_CONNECT: /* Connection lost. */ + ets_printf("ppp_link_status_cb: PPPERR_CONNECT\n"); + break; - case PPPERR_AUTHFAIL: /* Failed authentication challenge. */ - ets_printf("ppp_link_status_cb: PPPERR_AUTHFAIL\n"); - break; + case PPPERR_AUTHFAIL: /* Failed authentication challenge. */ + ets_printf("ppp_link_status_cb: PPPERR_AUTHFAIL\n"); + break; - case PPPERR_PROTOCOL: /* Failed to meet protocol. */ - ets_printf("ppp_link_status_cb: PPPERR_PROTOCOL\n"); - break; + case PPPERR_PROTOCOL: /* Failed to meet protocol. */ + ets_printf("ppp_link_status_cb: PPPERR_PROTOCOL\n"); + break; - case PPPERR_PEERDEAD: /* Connection timeout. */ - ets_printf("ppp_link_status_cb: PPPERR_PEERDEAD\n"); - break; + case PPPERR_PEERDEAD: /* Connection timeout. */ + ets_printf("ppp_link_status_cb: PPPERR_PEERDEAD\n"); + break; - case PPPERR_IDLETIMEOUT: /* Idle Timeout. */ - ets_printf("ppp_link_status_cb: PPPERR_IDLETIMEOUT\n"); - break; + case PPPERR_IDLETIMEOUT: /* Idle Timeout. */ + ets_printf("ppp_link_status_cb: PPPERR_IDLETIMEOUT\n"); + break; - case PPPERR_CONNECTTIME: /* PPPERR_CONNECTTIME. */ - ets_printf("ppp_link_status_cb: PPPERR_CONNECTTIME\n"); - break; + case PPPERR_CONNECTTIME: /* PPPERR_CONNECTTIME. */ + ets_printf("ppp_link_status_cb: PPPERR_CONNECTTIME\n"); + break; - case PPPERR_LOOPBACK: /* Connection timeout. */ - ets_printf("ppp_link_status_cb: PPPERR_LOOPBACK\n"); - break; + case PPPERR_LOOPBACK: /* Connection timeout. */ + ets_printf("ppp_link_status_cb: PPPERR_LOOPBACK\n"); + break; - default: - ets_printf("ppp_link_status_cb: unknown errCode %d\n", err_code); - break; + default: + ets_printf("ppp_link_status_cb: unknown errCode %d\n", err_code); + break; } if (stop) @@ -178,9 +179,8 @@ bool PPPServer::begin(const IPAddress& ourAddress, const IPAddress& peer) _enabled = true; if (!schedule_recurrent_function_us([&]() -{ - return this->handlePackets(); - }, 1000)) + { return this->handlePackets(); }, + 1000)) { netif_remove(&_netif); return false; diff --git a/libraries/lwIP_PPP/src/PPPServer.h b/libraries/lwIP_PPP/src/PPPServer.h index e2c95658a6..5bae0ebe6b 100644 --- a/libraries/lwIP_PPP/src/PPPServer.h +++ b/libraries/lwIP_PPP/src/PPPServer.h @@ -27,7 +27,6 @@ */ - #ifndef __PPPSERVER_H #define __PPPSERVER_H @@ -39,8 +38,7 @@ class PPPServer { -public: - + public: PPPServer(Stream* sio); bool begin(const IPAddress& ourAddress, const IPAddress& peer = IPAddress(172, 31, 255, 254)); @@ -55,8 +53,7 @@ class PPPServer return &_netif.gw; } -protected: - + protected: static constexpr size_t _bufsize = 128; Stream* _sio; ppp_pcb* _ppp; @@ -71,7 +68,6 @@ class PPPServer static u32_t output_cb_s(ppp_pcb* pcb, u8_t* data, u32_t len, void* ctx); static void link_status_cb_s(ppp_pcb* pcb, int err_code, void* ctx); static void netif_status_cb_s(netif* nif); - }; -#endif // __PPPSERVER_H +#endif // __PPPSERVER_H diff --git a/libraries/lwIP_enc28j60/src/ENC28J60lwIP.h b/libraries/lwIP_enc28j60/src/ENC28J60lwIP.h index e525e94069..cef7d61f8e 100644 --- a/libraries/lwIP_enc28j60/src/ENC28J60lwIP.h +++ b/libraries/lwIP_enc28j60/src/ENC28J60lwIP.h @@ -7,4 +7,4 @@ using ENC28J60lwIP = LwipIntfDev; -#endif // _ENC28J60LWIP_H +#endif // _ENC28J60LWIP_H diff --git a/libraries/lwIP_enc28j60/src/utility/enc28j60.cpp b/libraries/lwIP_enc28j60/src/utility/enc28j60.cpp index 42d1af7fc2..a1ac345a3c 100644 --- a/libraries/lwIP_enc28j60/src/utility/enc28j60.cpp +++ b/libraries/lwIP_enc28j60/src/utility/enc28j60.cpp @@ -35,15 +35,14 @@ #include #include +#include #include #include -#include #include #include "enc28j60.h" - -void serial_printf(const char *fmt, ...) +void serial_printf(const char* fmt, ...) { char buf[128]; va_list args; @@ -57,11 +56,15 @@ void serial_printf(const char *fmt, ...) #if DEBUG #define PRINTF(...) printf(__VA_ARGS__) #else -#define PRINTF(...) do { (void)0; } while (0) +#define PRINTF(...) \ + do \ + { \ + (void)0; \ + } while (0) #endif -#define EIE 0x1b -#define EIR 0x1c +#define EIE 0x1b +#define EIR 0x1c #define ESTAT 0x1d #define ECON2 0x1e #define ECON1 0x1f @@ -69,13 +72,13 @@ void serial_printf(const char *fmt, ...) #define ESTAT_CLKRDY 0x01 #define ESTAT_TXABRT 0x02 -#define ECON1_RXEN 0x04 -#define ECON1_TXRTS 0x08 +#define ECON1_RXEN 0x04 +#define ECON1_TXRTS 0x08 #define ECON2_AUTOINC 0x80 -#define ECON2_PKTDEC 0x40 +#define ECON2_PKTDEC 0x40 -#define EIR_TXIF 0x08 +#define EIR_TXIF 0x08 #define ERXTX_BANK 0x00 @@ -95,19 +98,19 @@ void serial_printf(const char *fmt, ...) #define ERXRDPTH 0x0d #define RX_BUF_START 0x0000 -#define RX_BUF_END 0x0fff +#define RX_BUF_END 0x0fff #define TX_BUF_START 0x1200 /* MACONx registers are in bank 2 */ #define MACONX_BANK 0x02 -#define MACON1 0x00 -#define MACON3 0x02 -#define MACON4 0x03 +#define MACON1 0x00 +#define MACON3 0x02 +#define MACON4 0x03 #define MABBIPG 0x04 -#define MAIPGL 0x06 -#define MAIPGH 0x07 +#define MAIPGL 0x06 +#define MAIPGH 0x07 #define MAMXFLL 0x0a #define MAMXFLH 0x0b @@ -116,9 +119,9 @@ void serial_printf(const char *fmt, ...) #define MACON1_MARXEN 0x01 #define MACON3_PADCFG_FULL 0xe0 -#define MACON3_TXCRCEN 0x10 -#define MACON3_FRMLNEN 0x02 -#define MACON3_FULDPX 0x01 +#define MACON3_TXCRCEN 0x10 +#define MACON3_FRMLNEN 0x02 +#define MACON3_FULDPX 0x01 #define MAX_MAC_LENGTH 1518 @@ -136,36 +139,33 @@ void serial_printf(const char *fmt, ...) #define ERXFCON 0x18 #define EPKTCNT 0x19 -#define ERXFCON_UCEN 0x80 +#define ERXFCON_UCEN 0x80 #define ERXFCON_ANDOR 0x40 #define ERXFCON_CRCEN 0x20 -#define ERXFCON_MCEN 0x02 -#define ERXFCON_BCEN 0x01 +#define ERXFCON_MCEN 0x02 +#define ERXFCON_BCEN 0x01 // The ENC28J60 SPI Interface supports clock speeds up to 20 MHz static const SPISettings spiSettings(20000000, MSBFIRST, SPI_MODE0); -ENC28J60::ENC28J60(int8_t cs, SPIClass& spi, int8_t intr): - _bank(ERXTX_BANK), _cs(cs), _spi(spi) +ENC28J60::ENC28J60(int8_t cs, SPIClass& spi, int8_t intr) + : _bank(ERXTX_BANK), _cs(cs), _spi(spi) { (void)intr; } -void -ENC28J60::enc28j60_arch_spi_select(void) +void ENC28J60::enc28j60_arch_spi_select(void) { SPI.beginTransaction(spiSettings); digitalWrite(_cs, LOW); } -void -ENC28J60::enc28j60_arch_spi_deselect(void) +void ENC28J60::enc28j60_arch_spi_deselect(void) { digitalWrite(_cs, HIGH); SPI.endTransaction(); } - /*---------------------------------------------------------------------------*/ uint8_t ENC28J60::is_mac_mii_reg(uint8_t reg) @@ -173,14 +173,14 @@ ENC28J60::is_mac_mii_reg(uint8_t reg) /* MAC or MII register (otherwise, ETH register)? */ switch (_bank) { - case MACONX_BANK: - return reg < EIE; - case MAADRX_BANK: - return reg <= MAADR2 || reg == MISTAT; - case ERXTX_BANK: - case EPKTCNT_BANK: - default: - return 0; + case MACONX_BANK: + return reg < EIE; + case MAADRX_BANK: + return reg <= MAADR2 || reg == MISTAT; + case ERXTX_BANK: + case EPKTCNT_BANK: + default: + return 0; } } /*---------------------------------------------------------------------------*/ @@ -200,8 +200,7 @@ ENC28J60::readreg(uint8_t reg) return r; } /*---------------------------------------------------------------------------*/ -void -ENC28J60::writereg(uint8_t reg, uint8_t data) +void ENC28J60::writereg(uint8_t reg, uint8_t data) { enc28j60_arch_spi_select(); SPI.transfer(0x40 | (reg & 0x1f)); @@ -209,8 +208,7 @@ ENC28J60::writereg(uint8_t reg, uint8_t data) enc28j60_arch_spi_deselect(); } /*---------------------------------------------------------------------------*/ -void -ENC28J60::setregbitfield(uint8_t reg, uint8_t mask) +void ENC28J60::setregbitfield(uint8_t reg, uint8_t mask) { if (is_mac_mii_reg(reg)) { @@ -225,8 +223,7 @@ ENC28J60::setregbitfield(uint8_t reg, uint8_t mask) } } /*---------------------------------------------------------------------------*/ -void -ENC28J60::clearregbitfield(uint8_t reg, uint8_t mask) +void ENC28J60::clearregbitfield(uint8_t reg, uint8_t mask) { if (is_mac_mii_reg(reg)) { @@ -241,15 +238,13 @@ ENC28J60::clearregbitfield(uint8_t reg, uint8_t mask) } } /*---------------------------------------------------------------------------*/ -void -ENC28J60::setregbank(uint8_t new_bank) +void ENC28J60::setregbank(uint8_t new_bank) { writereg(ECON1, (readreg(ECON1) & 0xfc) | (new_bank & 0x03)); _bank = new_bank; } /*---------------------------------------------------------------------------*/ -void -ENC28J60::writedata(const uint8_t *data, int datalen) +void ENC28J60::writedata(const uint8_t* data, int datalen) { int i; enc28j60_arch_spi_select(); @@ -262,14 +257,12 @@ ENC28J60::writedata(const uint8_t *data, int datalen) enc28j60_arch_spi_deselect(); } /*---------------------------------------------------------------------------*/ -void -ENC28J60::writedatabyte(uint8_t byte) +void ENC28J60::writedatabyte(uint8_t byte) { writedata(&byte, 1); } /*---------------------------------------------------------------------------*/ -int -ENC28J60::readdata(uint8_t *buf, int len) +int ENC28J60::readdata(uint8_t* buf, int len) { int i; enc28j60_arch_spi_select(); @@ -292,8 +285,7 @@ ENC28J60::readdatabyte(void) } /*---------------------------------------------------------------------------*/ -void -ENC28J60::softreset(void) +void ENC28J60::softreset(void) { enc28j60_arch_spi_select(); /* The System Command (soft reset) is 1 1 1 1 1 1 1 1 */ @@ -312,20 +304,19 @@ ENC28J60::readrev(void) rev = readreg(EREVID); switch (rev) { - case 2: - return 1; - case 6: - return 7; - default: - return rev; + case 2: + return 1; + case 6: + return 7; + default: + return rev; } } //#endif /*---------------------------------------------------------------------------*/ -bool -ENC28J60::reset(void) +bool ENC28J60::reset(void) { PRINTF("enc28j60: resetting chip\n"); @@ -398,7 +389,9 @@ ENC28J60::reset(void) /* Wait for OST */ PRINTF("waiting for ESTAT_CLKRDY\n"); - while ((readreg(ESTAT) & ESTAT_CLKRDY) == 0) {}; + while ((readreg(ESTAT) & ESTAT_CLKRDY) == 0) + { + }; PRINTF("ESTAT_CLKRDY\n"); setregbank(ERXTX_BANK); @@ -471,7 +464,7 @@ ENC28J60::reset(void) /* Set padding, crc, full duplex */ setregbitfield(MACON3, MACON3_PADCFG_FULL | MACON3_TXCRCEN | MACON3_FULDPX | - MACON3_FRMLNEN); + MACON3_FRMLNEN); /* Don't modify MACON4 */ @@ -532,7 +525,7 @@ ENC28J60::reset(void) } /*---------------------------------------------------------------------------*/ boolean -ENC28J60::begin(const uint8_t *address) +ENC28J60::begin(const uint8_t* address) { _localMac = address; @@ -547,7 +540,7 @@ ENC28J60::begin(const uint8_t *address) /*---------------------------------------------------------------------------*/ uint16_t -ENC28J60::sendFrame(const uint8_t *data, uint16_t datalen) +ENC28J60::sendFrame(const uint8_t* data, uint16_t datalen) { uint16_t dataend; @@ -598,7 +591,8 @@ ENC28J60::sendFrame(const uint8_t *data, uint16_t datalen) /* Send the packet */ setregbitfield(ECON1, ECON1_TXRTS); - while ((readreg(ECON1) & ECON1_TXRTS) > 0); + while ((readreg(ECON1) & ECON1_TXRTS) > 0) + ; #if DEBUG if ((readreg(ESTAT) & ESTAT_TXABRT) != 0) @@ -611,11 +605,13 @@ ENC28J60::sendFrame(const uint8_t *data, uint16_t datalen) readdata(tsv, sizeof(tsv)); writereg(ERDPTL, erdpt & 0xff); writereg(ERDPTH, erdpt >> 8); - PRINTF("enc28j60: tx err: %d: %02x:%02x:%02x:%02x:%02x:%02x\n" - " tsv: %02x%02x%02x%02x%02x%02x%02x\n", datalen, - 0xff & data[0], 0xff & data[1], 0xff & data[2], - 0xff & data[3], 0xff & data[4], 0xff & data[5], - tsv[6], tsv[5], tsv[4], tsv[3], tsv[2], tsv[1], tsv[0]); + PRINTF( + "enc28j60: tx err: %d: %02x:%02x:%02x:%02x:%02x:%02x\n" + " tsv: %02x%02x%02x%02x%02x%02x%02x\n", + datalen, + 0xff & data[0], 0xff & data[1], 0xff & data[2], + 0xff & data[3], 0xff & data[4], 0xff & data[5], + tsv[6], tsv[5], tsv[4], tsv[3], tsv[2], tsv[1], tsv[0]); } else { @@ -633,7 +629,7 @@ ENC28J60::sendFrame(const uint8_t *data, uint16_t datalen) /*---------------------------------------------------------------------------*/ uint16_t -ENC28J60::readFrame(uint8_t *buffer, uint16_t bufsize) +ENC28J60::readFrame(uint8_t* buffer, uint16_t bufsize) { readFrameSize(); return readFrameData(buffer, bufsize); @@ -682,19 +678,17 @@ ENC28J60::readFrameSize() return _len; } -void -ENC28J60::discardFrame(uint16_t framesize) +void ENC28J60::discardFrame(uint16_t framesize) { (void)framesize; (void)readFrameData(nullptr, 0); } uint16_t -ENC28J60::readFrameData(uint8_t *buffer, uint16_t framesize) +ENC28J60::readFrameData(uint8_t* buffer, uint16_t framesize) { if (framesize < _len) { - buffer = nullptr; /* flush rx fifo */ diff --git a/libraries/lwIP_enc28j60/src/utility/enc28j60.h b/libraries/lwIP_enc28j60/src/utility/enc28j60.h index 07ec39e929..fb544e1bfc 100644 --- a/libraries/lwIP_enc28j60/src/utility/enc28j60.h +++ b/libraries/lwIP_enc28j60/src/utility/enc28j60.h @@ -46,8 +46,7 @@ */ class ENC28J60 { - -public: + public: /** Constructor that uses the default hardware SPI pins @param cs the Arduino Chip Select / Slave Select pin (default 10 on Uno) @@ -61,7 +60,7 @@ class ENC28J60 @param address the local MAC address for the Ethernet interface @return Returns true if setting up the Ethernet interface was successful */ - boolean begin(const uint8_t *address); + boolean begin(const uint8_t* address); /** Send an Ethernet frame @@ -69,7 +68,7 @@ class ENC28J60 @param datalen the length of the data in the packet @return the number of bytes transmitted */ - virtual uint16_t sendFrame(const uint8_t *data, uint16_t datalen); + virtual uint16_t sendFrame(const uint8_t* data, uint16_t datalen); /** Read an Ethernet frame @@ -78,10 +77,9 @@ class ENC28J60 @return the length of the received packet or 0 if no packet was received */ - virtual uint16_t readFrame(uint8_t *buffer, uint16_t bufsize); - -protected: + virtual uint16_t readFrame(uint8_t* buffer, uint16_t bufsize); + protected: static constexpr bool interruptIsPossible() { return false; @@ -109,19 +107,18 @@ class ENC28J60 @return the length of the received frame or 0 if a problem occurred */ - uint16_t readFrameData(uint8_t *frame, uint16_t framesize); - -private: + uint16_t readFrameData(uint8_t* frame, uint16_t framesize); + private: uint8_t is_mac_mii_reg(uint8_t reg); uint8_t readreg(uint8_t reg); void writereg(uint8_t reg, uint8_t data); void setregbitfield(uint8_t reg, uint8_t mask); void clearregbitfield(uint8_t reg, uint8_t mask); void setregbank(uint8_t new_bank); - void writedata(const uint8_t *data, int datalen); + void writedata(const uint8_t* data, int datalen); void writedatabyte(uint8_t byte); - int readdata(uint8_t *buf, int len); + int readdata(uint8_t* buf, int len); uint8_t readdatabyte(void); void softreset(void); uint8_t readrev(void); @@ -140,7 +137,7 @@ class ENC28J60 int8_t _cs; SPIClass& _spi; - const uint8_t *_localMac; + const uint8_t* _localMac; /* readFrame*() state */ uint16_t _next, _len; diff --git a/libraries/lwIP_w5100/src/W5100lwIP.h b/libraries/lwIP_w5100/src/W5100lwIP.h index c8f549529d..593625a8d5 100644 --- a/libraries/lwIP_w5100/src/W5100lwIP.h +++ b/libraries/lwIP_w5100/src/W5100lwIP.h @@ -7,4 +7,4 @@ using Wiznet5100lwIP = LwipIntfDev; -#endif // _W5500LWIP_H +#endif // _W5500LWIP_H diff --git a/libraries/lwIP_w5100/src/utility/w5100.cpp b/libraries/lwIP_w5100/src/utility/w5100.cpp index 6377aa5b63..661f2550c3 100644 --- a/libraries/lwIP_w5100/src/utility/w5100.cpp +++ b/libraries/lwIP_w5100/src/utility/w5100.cpp @@ -32,9 +32,8 @@ // original sources: https://github.com/njh/W5100MacRaw -#include #include "w5100.h" - +#include uint8_t Wiznet5100::wizchip_read(uint16_t address) { @@ -42,8 +41,8 @@ uint8_t Wiznet5100::wizchip_read(uint16_t address) wizchip_cs_select(); _spi.transfer(0x0F); - _spi.transfer((address & 0xFF00) >> 8); - _spi.transfer((address & 0x00FF) >> 0); + _spi.transfer((address & 0xFF00) >> 8); + _spi.transfer((address & 0x00FF) >> 0); ret = _spi.transfer(0); wizchip_cs_deselect(); @@ -55,7 +54,6 @@ uint16_t Wiznet5100::wizchip_read_word(uint16_t address) return ((uint16_t)wizchip_read(address) << 8) + wizchip_read(address + 1); } - void Wiznet5100::wizchip_read_buf(uint16_t address, uint8_t* pBuf, uint16_t len) { for (uint16_t i = 0; i < len; i++) @@ -68,16 +66,16 @@ void Wiznet5100::wizchip_write(uint16_t address, uint8_t wb) { wizchip_cs_select(); _spi.transfer(0xF0); - _spi.transfer((address & 0xFF00) >> 8); - _spi.transfer((address & 0x00FF) >> 0); - _spi.transfer(wb); // Data write (write 1byte data) + _spi.transfer((address & 0xFF00) >> 8); + _spi.transfer((address & 0x00FF) >> 0); + _spi.transfer(wb); // Data write (write 1byte data) wizchip_cs_deselect(); } void Wiznet5100::wizchip_write_word(uint16_t address, uint16_t word) { wizchip_write(address, (uint8_t)(word >> 8)); - wizchip_write(address + 1, (uint8_t) word); + wizchip_write(address + 1, (uint8_t)word); } void Wiznet5100::wizchip_write_buf(uint16_t address, const uint8_t* pBuf, uint16_t len) @@ -94,7 +92,8 @@ void Wiznet5100::setSn_CR(uint8_t cr) wizchip_write(Sn_CR, cr); // Now wait for the command to complete - while (wizchip_read(Sn_CR)); + while (wizchip_read(Sn_CR)) + ; } uint16_t Wiznet5100::getSn_TX_FSR() @@ -111,7 +110,6 @@ uint16_t Wiznet5100::getSn_TX_FSR() return val; } - uint16_t Wiznet5100::getSn_RX_RSR() { uint16_t val = 0, val1 = 0; @@ -126,7 +124,7 @@ uint16_t Wiznet5100::getSn_RX_RSR() return val; } -void Wiznet5100::wizchip_send_data(const uint8_t *wizdata, uint16_t len) +void Wiznet5100::wizchip_send_data(const uint8_t* wizdata, uint16_t len) { uint16_t ptr; uint16_t size; @@ -157,7 +155,7 @@ void Wiznet5100::wizchip_send_data(const uint8_t *wizdata, uint16_t len) setSn_TX_WR(ptr); } -void Wiznet5100::wizchip_recv_data(uint8_t *wizdata, uint16_t len) +void Wiznet5100::wizchip_recv_data(uint8_t* wizdata, uint16_t len) { uint16_t ptr; uint16_t size; @@ -169,7 +167,6 @@ void Wiznet5100::wizchip_recv_data(uint8_t *wizdata, uint16_t len) src_mask = ptr & RxBufferMask; src_ptr = RxBufferAddress + src_mask; - if ((src_mask + len) > RxBufferLength) { size = RxBufferLength - src_mask; @@ -201,19 +198,18 @@ void Wiznet5100::wizchip_recv_ignore(uint16_t len) void Wiznet5100::wizchip_sw_reset() { setMR(MR_RST); - getMR(); // for delay + getMR(); // for delay setSHAR(_mac_address); } - -Wiznet5100::Wiznet5100(int8_t cs, SPIClass& spi, int8_t intr): - _spi(spi), _cs(cs) +Wiznet5100::Wiznet5100(int8_t cs, SPIClass& spi, int8_t intr) + : _spi(spi), _cs(cs) { (void)intr; } -boolean Wiznet5100::begin(const uint8_t *mac_address) +boolean Wiznet5100::begin(const uint8_t* mac_address) { memcpy(_mac_address, mac_address, 6); @@ -257,10 +253,11 @@ void Wiznet5100::end() setSn_IR(0xFF); // Wait for socket to change to closed - while (getSn_SR() != SOCK_CLOSED); + while (getSn_SR() != SOCK_CLOSED) + ; } -uint16_t Wiznet5100::readFrame(uint8_t *buffer, uint16_t bufsize) +uint16_t Wiznet5100::readFrame(uint8_t* buffer, uint16_t bufsize) { uint16_t data_len = readFrameSize(); @@ -307,7 +304,7 @@ void Wiznet5100::discardFrame(uint16_t framesize) setSn_CR(Sn_CR_RECV); } -uint16_t Wiznet5100::readFrameData(uint8_t *buffer, uint16_t framesize) +uint16_t Wiznet5100::readFrameData(uint8_t* buffer, uint16_t framesize) { wizchip_recv_data(buffer, framesize); setSn_CR(Sn_CR_RECV); @@ -329,7 +326,7 @@ uint16_t Wiznet5100::readFrameData(uint8_t *buffer, uint16_t framesize) #endif } -uint16_t Wiznet5100::sendFrame(const uint8_t *buf, uint16_t len) +uint16_t Wiznet5100::sendFrame(const uint8_t* buf, uint16_t len) { // Wait for space in the transmit buffer while (1) diff --git a/libraries/lwIP_w5100/src/utility/w5100.h b/libraries/lwIP_w5100/src/utility/w5100.h index 43b9f0b9f3..291d57362a 100644 --- a/libraries/lwIP_w5100/src/utility/w5100.h +++ b/libraries/lwIP_w5100/src/utility/w5100.h @@ -32,18 +32,16 @@ // original sources: https://github.com/njh/W5100MacRaw -#ifndef W5100_H -#define W5100_H +#ifndef W5100_H +#define W5100_H -#include #include #include - +#include class Wiznet5100 { - -public: + public: /** Constructor that uses the default hardware SPI pins @param cs the Arduino Chip Select / Slave Select pin (default 10) @@ -57,7 +55,7 @@ class Wiznet5100 @param address the local MAC address for the Ethernet interface @return Returns true if setting up the Ethernet interface was successful */ - boolean begin(const uint8_t *address); + boolean begin(const uint8_t* address); /** Shut down the Ethernet controlled @@ -70,7 +68,7 @@ class Wiznet5100 @param datalen the length of the data in the packet @return the number of bytes transmitted */ - uint16_t sendFrame(const uint8_t *data, uint16_t datalen); + uint16_t sendFrame(const uint8_t* data, uint16_t datalen); /** Read an Ethernet frame @@ -79,10 +77,9 @@ class Wiznet5100 @return the length of the received packet or 0 if no packet was received */ - uint16_t readFrame(uint8_t *buffer, uint16_t bufsize); - -protected: + uint16_t readFrame(uint8_t* buffer, uint16_t bufsize); + protected: static constexpr bool interruptIsPossible() { return false; @@ -110,20 +107,18 @@ class Wiznet5100 @return the length of the received frame or 0 if a problem occurred */ - uint16_t readFrameData(uint8_t *frame, uint16_t framesize); + uint16_t readFrameData(uint8_t* frame, uint16_t framesize); - -private: - static const uint16_t TxBufferAddress = 0x4000; /* Internal Tx buffer address of the iinchip */ - static const uint16_t RxBufferAddress = 0x6000; /* Internal Rx buffer address of the iinchip */ - static const uint8_t TxBufferSize = 0x3; /* Buffer size configuration: 0=1kb, 1=2kB, 2=4kB, 3=8kB */ - static const uint8_t RxBufferSize = 0x3; /* Buffer size configuration: 0=1kb, 1=2kB, 2=4kB, 3=8kB */ + private: + static const uint16_t TxBufferAddress = 0x4000; /* Internal Tx buffer address of the iinchip */ + static const uint16_t RxBufferAddress = 0x6000; /* Internal Rx buffer address of the iinchip */ + static const uint8_t TxBufferSize = 0x3; /* Buffer size configuration: 0=1kb, 1=2kB, 2=4kB, 3=8kB */ + static const uint8_t RxBufferSize = 0x3; /* Buffer size configuration: 0=1kb, 1=2kB, 2=4kB, 3=8kB */ static const uint16_t TxBufferLength = (1 << TxBufferSize) << 10; /* Length of Tx buffer in bytes */ static const uint16_t RxBufferLength = (1 << RxBufferSize) << 10; /* Length of Rx buffer in bytes */ static const uint16_t TxBufferMask = TxBufferLength - 1; static const uint16_t RxBufferMask = RxBufferLength - 1; - SPIClass& _spi; int8_t _cs; uint8_t _mac_address[6]; @@ -194,7 +189,6 @@ class Wiznet5100 */ void wizchip_write_buf(uint16_t address, const uint8_t* pBuf, uint16_t len); - /** Reset WIZCHIP by softly. */ @@ -212,7 +206,7 @@ class Wiznet5100 @param len Data length @sa wizchip_recv_data() */ - void wizchip_send_data(const uint8_t *wizdata, uint16_t len); + void wizchip_send_data(const uint8_t* wizdata, uint16_t len); /** It copies data to your buffer from internal RX memory @@ -226,7 +220,7 @@ class Wiznet5100 @param len Data length @sa wizchip_send_data() */ - void wizchip_recv_data(uint8_t *wizdata, uint16_t len); + void wizchip_recv_data(uint8_t* wizdata, uint16_t len); /** It discard the received data in RX memory. @@ -247,77 +241,76 @@ class Wiznet5100 */ uint16_t getSn_RX_RSR(); - /** Common registers */ enum { - MR = 0x0000, ///< Mode Register address (R/W) - GAR = 0x0001, ///< Gateway IP Register address (R/W) - SUBR = 0x0005, ///< Subnet mask Register address (R/W) - SHAR = 0x0009, ///< Source MAC Register address (R/W) - SIPR = 0x000F, ///< Source IP Register address (R/W) - IR = 0x0015, ///< Interrupt Register (R/W) - IMR = 0x0016, ///< Socket Interrupt Mask Register (R/W) - RTR = 0x0017, ///< Timeout register address (1 is 100us) (R/W) - RCR = 0x0019, ///< Retry count register (R/W) - RMSR = 0x001A, ///< Receive Memory Size - TMSR = 0x001B, ///< Transmit Memory Size + MR = 0x0000, ///< Mode Register address (R/W) + GAR = 0x0001, ///< Gateway IP Register address (R/W) + SUBR = 0x0005, ///< Subnet mask Register address (R/W) + SHAR = 0x0009, ///< Source MAC Register address (R/W) + SIPR = 0x000F, ///< Source IP Register address (R/W) + IR = 0x0015, ///< Interrupt Register (R/W) + IMR = 0x0016, ///< Socket Interrupt Mask Register (R/W) + RTR = 0x0017, ///< Timeout register address (1 is 100us) (R/W) + RCR = 0x0019, ///< Retry count register (R/W) + RMSR = 0x001A, ///< Receive Memory Size + TMSR = 0x001B, ///< Transmit Memory Size }; /** Socket registers */ enum { - Sn_MR = 0x0400, ///< Socket Mode register(R/W) - Sn_CR = 0x0401, ///< Socket command register (R/W) - Sn_IR = 0x0402, ///< Socket interrupt register (R) - Sn_SR = 0x0403, ///< Socket status register (R) - Sn_PORT = 0x0404, ///< Source port register (R/W) - Sn_DHAR = 0x0406, ///< Peer MAC register address (R/W) - Sn_DIPR = 0x040C, ///< Peer IP register address (R/W) - Sn_DPORT = 0x0410, ///< Peer port register address (R/W) - Sn_MSSR = 0x0412, ///< Maximum Segment Size(Sn_MSSR0) register address (R/W) - Sn_PROTO = 0x0414, ///< IP Protocol(PROTO) Register (R/W) - Sn_TOS = 0x0415, ///< IP Type of Service(TOS) Register (R/W) - Sn_TTL = 0x0416, ///< IP Time to live(TTL) Register (R/W) - Sn_TX_FSR = 0x0420, ///< Transmit free memory size register (R) - Sn_TX_RD = 0x0422, ///< Transmit memory read pointer register address (R) - Sn_TX_WR = 0x0424, ///< Transmit memory write pointer register address (R/W) - Sn_RX_RSR = 0x0426, ///< Received data size register (R) - Sn_RX_RD = 0x0428, ///< Read point of Receive memory (R/W) - Sn_RX_WR = 0x042A, ///< Write point of Receive memory (R) + Sn_MR = 0x0400, ///< Socket Mode register(R/W) + Sn_CR = 0x0401, ///< Socket command register (R/W) + Sn_IR = 0x0402, ///< Socket interrupt register (R) + Sn_SR = 0x0403, ///< Socket status register (R) + Sn_PORT = 0x0404, ///< Source port register (R/W) + Sn_DHAR = 0x0406, ///< Peer MAC register address (R/W) + Sn_DIPR = 0x040C, ///< Peer IP register address (R/W) + Sn_DPORT = 0x0410, ///< Peer port register address (R/W) + Sn_MSSR = 0x0412, ///< Maximum Segment Size(Sn_MSSR0) register address (R/W) + Sn_PROTO = 0x0414, ///< IP Protocol(PROTO) Register (R/W) + Sn_TOS = 0x0415, ///< IP Type of Service(TOS) Register (R/W) + Sn_TTL = 0x0416, ///< IP Time to live(TTL) Register (R/W) + Sn_TX_FSR = 0x0420, ///< Transmit free memory size register (R) + Sn_TX_RD = 0x0422, ///< Transmit memory read pointer register address (R) + Sn_TX_WR = 0x0424, ///< Transmit memory write pointer register address (R/W) + Sn_RX_RSR = 0x0426, ///< Received data size register (R) + Sn_RX_RD = 0x0428, ///< Read point of Receive memory (R/W) + Sn_RX_WR = 0x042A, ///< Write point of Receive memory (R) }; /** Mode register values */ enum { - MR_RST = 0x80, ///< Reset - MR_PB = 0x10, ///< Ping block - MR_AI = 0x02, ///< Address Auto-Increment in Indirect Bus Interface - MR_IND = 0x01, ///< Indirect Bus Interface mode + MR_RST = 0x80, ///< Reset + MR_PB = 0x10, ///< Ping block + MR_AI = 0x02, ///< Address Auto-Increment in Indirect Bus Interface + MR_IND = 0x01, ///< Indirect Bus Interface mode }; /** Socket Mode Register values @ref Sn_MR */ enum { - Sn_MR_CLOSE = 0x00, ///< Unused socket - Sn_MR_TCP = 0x01, ///< TCP - Sn_MR_UDP = 0x02, ///< UDP - Sn_MR_IPRAW = 0x03, ///< IP LAYER RAW SOCK - Sn_MR_MACRAW = 0x04, ///< MAC LAYER RAW SOCK - Sn_MR_ND = 0x20, ///< No Delayed Ack(TCP) flag - Sn_MR_MF = 0x40, ///< Use MAC filter - Sn_MR_MULTI = 0x80, ///< support multicating + Sn_MR_CLOSE = 0x00, ///< Unused socket + Sn_MR_TCP = 0x01, ///< TCP + Sn_MR_UDP = 0x02, ///< UDP + Sn_MR_IPRAW = 0x03, ///< IP LAYER RAW SOCK + Sn_MR_MACRAW = 0x04, ///< MAC LAYER RAW SOCK + Sn_MR_ND = 0x20, ///< No Delayed Ack(TCP) flag + Sn_MR_MF = 0x40, ///< Use MAC filter + Sn_MR_MULTI = 0x80, ///< support multicating }; /** Socket Command Register values */ enum { - Sn_CR_OPEN = 0x01, ///< Initialise or open socket - Sn_CR_CLOSE = 0x10, ///< Close socket - Sn_CR_SEND = 0x20, ///< Update TX buffer pointer and send data - Sn_CR_SEND_MAC = 0x21, ///< Send data with MAC address, so without ARP process - Sn_CR_SEND_KEEP = 0x22, ///< Send keep alive message - Sn_CR_RECV = 0x40, ///< Update RX buffer pointer and receive data + Sn_CR_OPEN = 0x01, ///< Initialise or open socket + Sn_CR_CLOSE = 0x10, ///< Close socket + Sn_CR_SEND = 0x20, ///< Update TX buffer pointer and send data + Sn_CR_SEND_MAC = 0x21, ///< Send data with MAC address, so without ARP process + Sn_CR_SEND_KEEP = 0x22, ///< Send keep alive message + Sn_CR_RECV = 0x40, ///< Update RX buffer pointer and receive data }; /** Socket Interrupt register values */ @@ -333,20 +326,20 @@ class Wiznet5100 /** Socket Status Register values */ enum { - SOCK_CLOSED = 0x00, ///< Closed - SOCK_INIT = 0x13, ///< Initiate state - SOCK_LISTEN = 0x14, ///< Listen state - SOCK_SYNSENT = 0x15, ///< Connection state - SOCK_SYNRECV = 0x16, ///< Connection state - SOCK_ESTABLISHED = 0x17, ///< Success to connect - SOCK_FIN_WAIT = 0x18, ///< Closing state - SOCK_CLOSING = 0x1A, ///< Closing state - SOCK_TIME_WAIT = 0x1B, ///< Closing state - SOCK_CLOSE_WAIT = 0x1C, ///< Closing state - SOCK_LAST_ACK = 0x1D, ///< Closing state - SOCK_UDP = 0x22, ///< UDP socket - SOCK_IPRAW = 0x32, ///< IP raw mode socket - SOCK_MACRAW = 0x42, ///< MAC raw mode socket + SOCK_CLOSED = 0x00, ///< Closed + SOCK_INIT = 0x13, ///< Initiate state + SOCK_LISTEN = 0x14, ///< Listen state + SOCK_SYNSENT = 0x15, ///< Connection state + SOCK_SYNRECV = 0x16, ///< Connection state + SOCK_ESTABLISHED = 0x17, ///< Success to connect + SOCK_FIN_WAIT = 0x18, ///< Closing state + SOCK_CLOSING = 0x1A, ///< Closing state + SOCK_TIME_WAIT = 0x1B, ///< Closing state + SOCK_CLOSE_WAIT = 0x1C, ///< Closing state + SOCK_LAST_ACK = 0x1D, ///< Closing state + SOCK_UDP = 0x22, ///< UDP socket + SOCK_IPRAW = 0x32, ///< IP raw mode socket + SOCK_MACRAW = 0x42, ///< MAC raw mode socket }; /** @@ -496,4 +489,4 @@ class Wiznet5100 } }; -#endif // W5100_H +#endif // W5100_H diff --git a/libraries/lwIP_w5500/src/W5500lwIP.h b/libraries/lwIP_w5500/src/W5500lwIP.h index 1e8f201331..8b708cbf90 100644 --- a/libraries/lwIP_w5500/src/W5500lwIP.h +++ b/libraries/lwIP_w5500/src/W5500lwIP.h @@ -7,4 +7,4 @@ using Wiznet5500lwIP = LwipIntfDev; -#endif // _W5500LWIP_H +#endif // _W5500LWIP_H diff --git a/libraries/lwIP_w5500/src/utility/w5500.cpp b/libraries/lwIP_w5500/src/utility/w5500.cpp index b3c3ce0162..89bc6a9be0 100644 --- a/libraries/lwIP_w5500/src/utility/w5500.cpp +++ b/libraries/lwIP_w5500/src/utility/w5500.cpp @@ -32,9 +32,8 @@ // original sources: https://github.com/njh/W5500MacRaw -#include #include "w5500.h" - +#include uint8_t Wiznet5500::wizchip_read(uint8_t block, uint16_t address) { @@ -95,7 +94,7 @@ void Wiznet5500::wizchip_write(uint8_t block, uint16_t address, uint8_t wb) void Wiznet5500::wizchip_write_word(uint8_t block, uint16_t address, uint16_t word) { wizchip_write(block, address, (uint8_t)(word >> 8)); - wizchip_write(block, address + 1, (uint8_t) word); + wizchip_write(block, address + 1, (uint8_t)word); } void Wiznet5500::wizchip_write_buf(uint8_t block, uint16_t address, const uint8_t* pBuf, uint16_t len) @@ -123,7 +122,8 @@ void Wiznet5500::setSn_CR(uint8_t cr) wizchip_write(BlockSelectSReg, Sn_CR, cr); // Now wait for the command to complete - while (wizchip_read(BlockSelectSReg, Sn_CR)); + while (wizchip_read(BlockSelectSReg, Sn_CR)) + ; } uint16_t Wiznet5500::getSn_TX_FSR() @@ -140,7 +140,6 @@ uint16_t Wiznet5500::getSn_TX_FSR() return val; } - uint16_t Wiznet5500::getSn_RX_RSR() { uint16_t val = 0, val1 = 0; @@ -155,7 +154,7 @@ uint16_t Wiznet5500::getSn_RX_RSR() return val; } -void Wiznet5500::wizchip_send_data(const uint8_t *wizdata, uint16_t len) +void Wiznet5500::wizchip_send_data(const uint8_t* wizdata, uint16_t len) { uint16_t ptr = 0; @@ -171,7 +170,7 @@ void Wiznet5500::wizchip_send_data(const uint8_t *wizdata, uint16_t len) setSn_TX_WR(ptr); } -void Wiznet5500::wizchip_recv_data(uint8_t *wizdata, uint16_t len) +void Wiznet5500::wizchip_recv_data(uint8_t* wizdata, uint16_t len) { uint16_t ptr; @@ -198,7 +197,7 @@ void Wiznet5500::wizchip_recv_ignore(uint16_t len) void Wiznet5500::wizchip_sw_reset() { setMR(MR_RST); - getMR(); // for delay + getMR(); // for delay setSHAR(_mac_address); } @@ -278,14 +277,13 @@ int8_t Wiznet5500::wizphy_setphypmode(uint8_t pmode) return -1; } - -Wiznet5500::Wiznet5500(int8_t cs, SPIClass& spi, int8_t intr): - _spi(spi), _cs(cs) +Wiznet5500::Wiznet5500(int8_t cs, SPIClass& spi, int8_t intr) + : _spi(spi), _cs(cs) { (void)intr; } -boolean Wiznet5500::begin(const uint8_t *mac_address) +boolean Wiznet5500::begin(const uint8_t* mac_address) { memcpy(_mac_address, mac_address, 6); @@ -329,10 +327,11 @@ void Wiznet5500::end() setSn_IR(0xFF); // Wait for socket to change to closed - while (getSn_SR() != SOCK_CLOSED); + while (getSn_SR() != SOCK_CLOSED) + ; } -uint16_t Wiznet5500::readFrame(uint8_t *buffer, uint16_t bufsize) +uint16_t Wiznet5500::readFrame(uint8_t* buffer, uint16_t bufsize) { uint16_t data_len = readFrameSize(); @@ -379,7 +378,7 @@ void Wiznet5500::discardFrame(uint16_t framesize) setSn_CR(Sn_CR_RECV); } -uint16_t Wiznet5500::readFrameData(uint8_t *buffer, uint16_t framesize) +uint16_t Wiznet5500::readFrameData(uint8_t* buffer, uint16_t framesize) { wizchip_recv_data(buffer, framesize); setSn_CR(Sn_CR_RECV); @@ -402,7 +401,7 @@ uint16_t Wiznet5500::readFrameData(uint8_t *buffer, uint16_t framesize) #endif } -uint16_t Wiznet5500::sendFrame(const uint8_t *buf, uint16_t len) +uint16_t Wiznet5500::sendFrame(const uint8_t* buf, uint16_t len) { // Wait for space in the transmit buffer while (1) diff --git a/libraries/lwIP_w5500/src/utility/w5500.h b/libraries/lwIP_w5500/src/utility/w5500.h index 85b253a4bf..23d3159395 100644 --- a/libraries/lwIP_w5500/src/utility/w5500.h +++ b/libraries/lwIP_w5500/src/utility/w5500.h @@ -35,23 +35,19 @@ #ifndef W5500_H #define W5500_H -#include #include #include - - +#include class Wiznet5500 { - -public: + public: /** Constructor that uses the default hardware SPI pins @param cs the Arduino Chip Select / Slave Select pin (default 10) */ Wiznet5500(int8_t cs = SS, SPIClass& spi = SPI, int8_t intr = -1); - /** Initialise the Ethernet controller Must be called before sending or receiving Ethernet frames @@ -59,7 +55,7 @@ class Wiznet5500 @param address the local MAC address for the Ethernet interface @return Returns true if setting up the Ethernet interface was successful */ - boolean begin(const uint8_t *address); + boolean begin(const uint8_t* address); /** Shut down the Ethernet controlled @@ -72,7 +68,7 @@ class Wiznet5500 @param datalen the length of the data in the packet @return the number of bytes transmitted */ - uint16_t sendFrame(const uint8_t *data, uint16_t datalen); + uint16_t sendFrame(const uint8_t* data, uint16_t datalen); /** Read an Ethernet frame @@ -81,10 +77,9 @@ class Wiznet5500 @return the length of the received packet or 0 if no packet was received */ - uint16_t readFrame(uint8_t *buffer, uint16_t bufsize); - -protected: + uint16_t readFrame(uint8_t* buffer, uint16_t bufsize); + protected: static constexpr bool interruptIsPossible() { return false; @@ -112,11 +107,9 @@ class Wiznet5500 @return the length of the received frame or 0 if a problem occurred */ - uint16_t readFrameData(uint8_t *frame, uint16_t framesize); - - -private: + uint16_t readFrameData(uint8_t* frame, uint16_t framesize); + private: //< SPI interface Read operation in Control Phase static const uint8_t AccessModeRead = (0x00 << 2); @@ -135,8 +128,6 @@ class Wiznet5500 //< Socket 0 Rx buffer address block static const uint8_t BlockSelectRxBuf = (0x03 << 3); - - SPIClass& _spi; int8_t _cs; uint8_t _mac_address[6]; @@ -181,7 +172,6 @@ class Wiznet5500 _spi.transfer(wb); } - /** Read a 1 byte value from a register. @param address Register address @@ -240,7 +230,6 @@ class Wiznet5500 */ uint16_t getSn_RX_RSR(); - /** Reset WIZCHIP by softly. */ @@ -279,7 +268,7 @@ class Wiznet5500 @param len Data length @sa wizchip_recv_data() */ - void wizchip_send_data(const uint8_t *wizdata, uint16_t len); + void wizchip_send_data(const uint8_t* wizdata, uint16_t len); /** It copies data to your buffer from internal RX memory @@ -293,7 +282,7 @@ class Wiznet5500 @param len Data length @sa wizchip_send_data() */ - void wizchip_recv_data(uint8_t *wizdata, uint16_t len); + void wizchip_recv_data(uint8_t* wizdata, uint16_t len); /** It discard the received data in RX memory. @@ -302,8 +291,6 @@ class Wiznet5500 */ void wizchip_recv_ignore(uint16_t len); - - /** Common registers */ enum { @@ -371,40 +358,40 @@ class Wiznet5500 /* Interrupt Mask Register values */ enum { - IM_IR7 = 0x80, ///< IP Conflict Interrupt Mask - IM_IR6 = 0x40, ///< Destination unreachable Interrupt Mask - IM_IR5 = 0x20, ///< PPPoE Close Interrupt Mask - IM_IR4 = 0x10, ///< Magic Packet Interrupt Mask + IM_IR7 = 0x80, ///< IP Conflict Interrupt Mask + IM_IR6 = 0x40, ///< Destination unreachable Interrupt Mask + IM_IR5 = 0x20, ///< PPPoE Close Interrupt Mask + IM_IR4 = 0x10, ///< Magic Packet Interrupt Mask }; /** Socket Mode Register values @ref Sn_MR */ enum { - Sn_MR_CLOSE = 0x00, ///< Unused socket - Sn_MR_TCP = 0x01, ///< TCP - Sn_MR_UDP = 0x02, ///< UDP - Sn_MR_MACRAW = 0x04, ///< MAC LAYER RAW SOCK - Sn_MR_UCASTB = 0x10, ///< Unicast Block in UDP Multicasting - Sn_MR_ND = 0x20, ///< No Delayed Ack(TCP), Multicast flag - Sn_MR_BCASTB = 0x40, ///< Broadcast block in UDP Multicasting - Sn_MR_MULTI = 0x80, ///< Support UDP Multicasting - Sn_MR_MIP6B = 0x10, ///< IPv6 packet Blocking in @ref Sn_MR_MACRAW mode - Sn_MR_MMB = 0x20, ///< Multicast Blocking in @ref Sn_MR_MACRAW mode - Sn_MR_MFEN = 0x80, ///< MAC filter enable in @ref Sn_MR_MACRAW mode + Sn_MR_CLOSE = 0x00, ///< Unused socket + Sn_MR_TCP = 0x01, ///< TCP + Sn_MR_UDP = 0x02, ///< UDP + Sn_MR_MACRAW = 0x04, ///< MAC LAYER RAW SOCK + Sn_MR_UCASTB = 0x10, ///< Unicast Block in UDP Multicasting + Sn_MR_ND = 0x20, ///< No Delayed Ack(TCP), Multicast flag + Sn_MR_BCASTB = 0x40, ///< Broadcast block in UDP Multicasting + Sn_MR_MULTI = 0x80, ///< Support UDP Multicasting + Sn_MR_MIP6B = 0x10, ///< IPv6 packet Blocking in @ref Sn_MR_MACRAW mode + Sn_MR_MMB = 0x20, ///< Multicast Blocking in @ref Sn_MR_MACRAW mode + Sn_MR_MFEN = 0x80, ///< MAC filter enable in @ref Sn_MR_MACRAW mode }; /** Socket Command Register values */ enum { - Sn_CR_OPEN = 0x01, ///< Initialise or open socket - Sn_CR_LISTEN = 0x02, ///< Wait connection request in TCP mode (Server mode) - Sn_CR_CONNECT = 0x04, ///< Send connection request in TCP mode (Client mode) - Sn_CR_DISCON = 0x08, ///< Send closing request in TCP mode - Sn_CR_CLOSE = 0x10, ///< Close socket - Sn_CR_SEND = 0x20, ///< Update TX buffer pointer and send data - Sn_CR_SEND_MAC = 0x21, ///< Send data with MAC address, so without ARP process - Sn_CR_SEND_KEEP = 0x22, ///< Send keep alive message - Sn_CR_RECV = 0x40, ///< Update RX buffer pointer and receive data + Sn_CR_OPEN = 0x01, ///< Initialise or open socket + Sn_CR_LISTEN = 0x02, ///< Wait connection request in TCP mode (Server mode) + Sn_CR_CONNECT = 0x04, ///< Send connection request in TCP mode (Client mode) + Sn_CR_DISCON = 0x08, ///< Send closing request in TCP mode + Sn_CR_CLOSE = 0x10, ///< Close socket + Sn_CR_SEND = 0x20, ///< Update TX buffer pointer and send data + Sn_CR_SEND_MAC = 0x21, ///< Send data with MAC address, so without ARP process + Sn_CR_SEND_KEEP = 0x22, ///< Send keep alive message + Sn_CR_RECV = 0x40, ///< Update RX buffer pointer and receive data }; /** Socket Interrupt register values */ @@ -420,27 +407,26 @@ class Wiznet5500 /** Socket Status Register values */ enum { - SOCK_CLOSED = 0x00, ///< Closed - SOCK_INIT = 0x13, ///< Initiate state - SOCK_LISTEN = 0x14, ///< Listen state - SOCK_SYNSENT = 0x15, ///< Connection state - SOCK_SYNRECV = 0x16, ///< Connection state - SOCK_ESTABLISHED = 0x17, ///< Success to connect - SOCK_FIN_WAIT = 0x18, ///< Closing state - SOCK_CLOSING = 0x1A, ///< Closing state - SOCK_TIME_WAIT = 0x1B, ///< Closing state - SOCK_CLOSE_WAIT = 0x1C, ///< Closing state - SOCK_LAST_ACK = 0x1D, ///< Closing state - SOCK_UDP = 0x22, ///< UDP socket - SOCK_MACRAW = 0x42, ///< MAC raw mode socket + SOCK_CLOSED = 0x00, ///< Closed + SOCK_INIT = 0x13, ///< Initiate state + SOCK_LISTEN = 0x14, ///< Listen state + SOCK_SYNSENT = 0x15, ///< Connection state + SOCK_SYNRECV = 0x16, ///< Connection state + SOCK_ESTABLISHED = 0x17, ///< Success to connect + SOCK_FIN_WAIT = 0x18, ///< Closing state + SOCK_CLOSING = 0x1A, ///< Closing state + SOCK_TIME_WAIT = 0x1B, ///< Closing state + SOCK_CLOSE_WAIT = 0x1C, ///< Closing state + SOCK_LAST_ACK = 0x1D, ///< Closing state + SOCK_UDP = 0x22, ///< UDP socket + SOCK_MACRAW = 0x42, ///< MAC raw mode socket }; - /* PHYCFGR register value */ enum { - PHYCFGR_RST = ~(1 << 7), //< For PHY reset, must operate AND mask. - PHYCFGR_OPMD = (1 << 6), // Configre PHY with OPMDC value + PHYCFGR_RST = ~(1 << 7), //< For PHY reset, must operate AND mask. + PHYCFGR_OPMD = (1 << 6), // Configre PHY with OPMDC value PHYCFGR_OPMDC_ALLA = (7 << 3), PHYCFGR_OPMDC_PDOWN = (6 << 3), PHYCFGR_OPMDC_NA = (5 << 3), @@ -469,7 +455,6 @@ class Wiznet5500 PHY_POWER_DOWN = 1, ///< PHY power down mode }; - /** Set Mode Register @param (uint8_t)mr The value to be set. @@ -764,4 +749,4 @@ class Wiznet5500 } }; -#endif // W5500_H +#endif // W5500_H diff --git a/tests/device/libraries/BSTest/src/BSArduino.h b/tests/device/libraries/BSTest/src/BSArduino.h index b9483244a0..f77e6d0f86 100644 --- a/tests/device/libraries/BSTest/src/BSArduino.h +++ b/tests/device/libraries/BSTest/src/BSArduino.h @@ -6,12 +6,13 @@ namespace bs { class ArduinoIOHelper { -public: - ArduinoIOHelper(Stream& stream) : m_stream(stream) + public: + ArduinoIOHelper(Stream& stream) + : m_stream(stream) { } - size_t printf(const char *format, ...) + size_t printf(const char* format, ...) { va_list arg; va_start(arg, format); @@ -30,7 +31,7 @@ class ArduinoIOHelper ets_vsnprintf(buffer, len + 1, format, arg); va_end(arg); } - len = m_stream.write((const uint8_t*) buffer, len); + len = m_stream.write((const uint8_t*)buffer, len); if (buffer != temp) { delete[] buffer; @@ -65,7 +66,7 @@ class ArduinoIOHelper return len; } -protected: + protected: Stream& m_stream; }; @@ -76,6 +77,6 @@ inline void fatal() ESP.restart(); } -} // namespace bs +} // namespace bs -#endif //BS_ARDUINO_H +#endif //BS_ARDUINO_H diff --git a/tests/device/libraries/BSTest/src/BSArgs.h b/tests/device/libraries/BSTest/src/BSArgs.h index ba970f60bc..879085b321 100644 --- a/tests/device/libraries/BSTest/src/BSArgs.h +++ b/tests/device/libraries/BSTest/src/BSArgs.h @@ -7,15 +7,14 @@ #ifndef BS_ARGS_H #define BS_ARGS_H -#include #include +#include #include namespace bs { namespace protocol { - #define SS_FLAG_ESCAPE 0x8 typedef enum @@ -33,12 +32,13 @@ typedef enum } split_state_t; /* helper macro, called when done with an argument */ -#define END_ARG() do { \ - char_out = 0; \ - argv[argc++] = next_arg_start; \ - state = SS_SPACE; \ - } while(0); - +#define END_ARG() \ + do \ + { \ + char_out = 0; \ + argv[argc++] = next_arg_start; \ + state = SS_SPACE; \ + } while (0); /** @brief Split command line into arguments in place @@ -64,18 +64,18 @@ typedef enum @param argv_size number of elements in argv_array (max. number of arguments will be argv_size - 1) @return number of arguments found (argc) */ -inline size_t split_args(char *line, char **argv, size_t argv_size) +inline size_t split_args(char* line, char** argv, size_t argv_size) { const int QUOTE = '"'; const int ESCAPE = '\\'; const int SPACE = ' '; split_state_t state = SS_SPACE; size_t argc = 0; - char *next_arg_start = line; - char *out_ptr = line; - for (char *in_ptr = line; argc < argv_size - 1; ++in_ptr) + char* next_arg_start = line; + char* out_ptr = line; + for (char* in_ptr = line; argc < argv_size - 1; ++in_ptr) { - int char_in = (unsigned char) * in_ptr; + int char_in = (unsigned char)*in_ptr; if (char_in == 0) { break; @@ -84,71 +84,71 @@ inline size_t split_args(char *line, char **argv, size_t argv_size) switch (state) { - case SS_SPACE: - if (char_in == SPACE) - { - /* skip space */ - } - else if (char_in == QUOTE) - { - next_arg_start = out_ptr; - state = SS_QUOTED_ARG; - } - else if (char_in == ESCAPE) - { - next_arg_start = out_ptr; - state = SS_ARG_ESCAPED; - } - else - { - next_arg_start = out_ptr; - state = SS_ARG; - char_out = char_in; - } - break; - - case SS_QUOTED_ARG: - if (char_in == QUOTE) - { - END_ARG(); - } - else if (char_in == ESCAPE) - { - state = SS_QUOTED_ARG_ESCAPED; - } - else - { - char_out = char_in; - } - break; - - case SS_ARG_ESCAPED: - case SS_QUOTED_ARG_ESCAPED: - if (char_in == ESCAPE || char_in == QUOTE || char_in == SPACE) - { - char_out = char_in; - } - else - { - /* unrecognized escape character, skip */ - } - state = (split_state_t)(state & (~SS_FLAG_ESCAPE)); - break; - - case SS_ARG: - if (char_in == SPACE) - { - END_ARG(); - } - else if (char_in == ESCAPE) - { - state = SS_ARG_ESCAPED; - } - else - { - char_out = char_in; - } - break; + case SS_SPACE: + if (char_in == SPACE) + { + /* skip space */ + } + else if (char_in == QUOTE) + { + next_arg_start = out_ptr; + state = SS_QUOTED_ARG; + } + else if (char_in == ESCAPE) + { + next_arg_start = out_ptr; + state = SS_ARG_ESCAPED; + } + else + { + next_arg_start = out_ptr; + state = SS_ARG; + char_out = char_in; + } + break; + + case SS_QUOTED_ARG: + if (char_in == QUOTE) + { + END_ARG(); + } + else if (char_in == ESCAPE) + { + state = SS_QUOTED_ARG_ESCAPED; + } + else + { + char_out = char_in; + } + break; + + case SS_ARG_ESCAPED: + case SS_QUOTED_ARG_ESCAPED: + if (char_in == ESCAPE || char_in == QUOTE || char_in == SPACE) + { + char_out = char_in; + } + else + { + /* unrecognized escape character, skip */ + } + state = (split_state_t)(state & (~SS_FLAG_ESCAPE)); + break; + + case SS_ARG: + if (char_in == SPACE) + { + END_ARG(); + } + else if (char_in == ESCAPE) + { + state = SS_ARG_ESCAPED; + } + else + { + char_out = char_in; + } + break; } /* need to output anything? */ if (char_out >= 0) @@ -170,8 +170,8 @@ inline size_t split_args(char *line, char **argv, size_t argv_size) return argc; } -} // namespace bs +} // namespace protocol -} // namespace protocol +} // namespace bs -#endif //BS_ARGS_H +#endif //BS_ARGS_H diff --git a/tests/device/libraries/BSTest/src/BSProtocol.h b/tests/device/libraries/BSTest/src/BSProtocol.h index afb8bfb023..08400e02ce 100644 --- a/tests/device/libraries/BSTest/src/BSProtocol.h +++ b/tests/device/libraries/BSTest/src/BSProtocol.h @@ -11,62 +11,62 @@ namespace bs { namespace protocol { -template +template void output_test_start(IO& io, const char* file, size_t line, const char* name, const char* desc) { io.printf(BS_LINE_PREFIX "start file=\"%s\" line=%d name=\"%s\" desc=\"%s\"\n", file, line, name, desc); } -template +template void output_check_failure(IO& io, size_t line) { io.printf(BS_LINE_PREFIX "check_failure line=%d\n", line); } -template +template void output_test_end(IO& io, bool success, size_t checks, size_t failed_checks, size_t line = 0) { io.printf(BS_LINE_PREFIX "end line=%d result=%d checks=%d failed_checks=%d\n", line, success, checks, failed_checks); } -template +template void output_menu_begin(IO& io) { io.printf(BS_LINE_PREFIX "menu_begin\n"); } -template +template void output_menu_item(IO& io, int index, const char* name, const char* desc) { io.printf(BS_LINE_PREFIX "item id=%d name=\"%s\" desc=\"%s\"\n", index, name, desc); } -template +template void output_menu_end(IO& io) { io.printf(BS_LINE_PREFIX "menu_end\n"); } -template +template void output_setenv_result(IO& io, const char* key, const char* value) { io.printf(BS_LINE_PREFIX "setenv key=\"%s\" value=\"%s\"\n", key, value); } -template +template void output_getenv_result(IO& io, const char* key, const char* value) { - (void) key; + (void)key; io.printf(BS_LINE_PREFIX "getenv value=\"%s\"\n", value); } -template +template void output_pretest_result(IO& io, bool res) { io.printf(BS_LINE_PREFIX "pretest result=%d\n", res ? 1 : 0); } -template +template bool input_handle(IO& io, char* line_buf, size_t line_buf_size, int& test_num) { int cb_read = io.read_line(line_buf, line_buf_size); @@ -89,7 +89,7 @@ bool input_handle(IO& io, char* line_buf, size_t line_buf_size, int& test_num) setenv(argv[1], argv[2], 1); output_setenv_result(io, argv[1], argv[2]); test_num = -1; - return false; /* we didn't get the test number yet, so return false */ + return false; /* we didn't get the test number yet, so return false */ } if (strcmp(argv[0], "getenv") == 0) { @@ -113,7 +113,7 @@ bool input_handle(IO& io, char* line_buf, size_t line_buf_size, int& test_num) } /* not one of the commands, try to parse as test number */ char* endptr; - test_num = (int) strtol(argv[0], &endptr, 10); + test_num = (int)strtol(argv[0], &endptr, 10); if (endptr != argv[0] + strlen(argv[0])) { return false; @@ -121,7 +121,7 @@ bool input_handle(IO& io, char* line_buf, size_t line_buf_size, int& test_num) return true; } -} // ::protocol -} // ::bs +} // namespace protocol +} // namespace bs -#endif //BS_PROTOCOL_H +#endif //BS_PROTOCOL_H diff --git a/tests/device/libraries/BSTest/src/BSStdio.h b/tests/device/libraries/BSTest/src/BSStdio.h index f804f9750b..97a2c1230c 100644 --- a/tests/device/libraries/BSTest/src/BSStdio.h +++ b/tests/device/libraries/BSTest/src/BSStdio.h @@ -8,12 +8,12 @@ namespace bs { class StdIOHelper { -public: + public: StdIOHelper() { } - size_t printf(const char *format, ...) + size_t printf(const char* format, ...) { va_list arg; va_start(arg, format); @@ -46,6 +46,6 @@ inline void fatal() throw std::runtime_error("fatal error"); } -} // namespace bs +} // namespace bs -#endif //BS_STDIO_H +#endif //BS_STDIO_H diff --git a/tests/device/libraries/BSTest/src/BSTest.h b/tests/device/libraries/BSTest/src/BSTest.h index 6de198cb0c..bc9154a5ae 100644 --- a/tests/device/libraries/BSTest/src/BSTest.h +++ b/tests/device/libraries/BSTest/src/BSTest.h @@ -20,11 +20,11 @@ namespace bs { -typedef void(*test_case_func_t)(); +typedef void (*test_case_func_t)(); class TestCase { -public: + public: TestCase(TestCase* prev, test_case_func_t func, const char* file, size_t line, const char* name, const char* desc) : m_func(func), m_file(file), m_line(line), m_name(name), m_desc(desc) { @@ -64,7 +64,7 @@ class TestCase return (m_desc) ? m_desc : ""; } -protected: + protected: TestCase* m_next = nullptr; test_case_func_t m_func; const char* m_file; @@ -98,12 +98,14 @@ struct Env extern Env g_env; -template +template class Runner { typedef Runner Tself; -public: - Runner(IO& io) : m_io(io) + + public: + Runner(IO& io) + : m_io(io) { g_env.m_check_pass = std::bind(&Tself::check_pass, this); g_env.m_check_fail = std::bind(&Tself::check_fail, this, std::placeholders::_1); @@ -141,7 +143,7 @@ class Runner bs::fatal(); } -protected: + protected: bool do_menu() { protocol::output_menu_begin(m_io); @@ -164,7 +166,8 @@ class Runner return true; } TestCase* tc = g_env.m_registry.m_first; - for (int i = 0; i != id - 1 && tc; ++i, tc = tc->next()); + for (int i = 0; i != id - 1 && tc; ++i, tc = tc->next()) + ; if (!tc) { bs::fatal(); @@ -178,7 +181,7 @@ class Runner } } -protected: + protected: IO& m_io; size_t m_check_pass_count; size_t m_check_fail_count; @@ -186,7 +189,7 @@ class Runner class AutoReg { -public: + public: AutoReg(test_case_func_t func, const char* file, size_t line, const char* name, const char* desc = nullptr) { g_env.m_registry.add(func, file, line, name, desc); @@ -218,22 +221,35 @@ inline void require(bool condition, size_t line) } } -} // ::bs +} // namespace bs -#define BS_NAME_LINE2( name, line ) name##line -#define BS_NAME_LINE( name, line ) BS_NAME_LINE2( name, line ) -#define BS_UNIQUE_NAME( name ) BS_NAME_LINE( name, __LINE__ ) +#define BS_NAME_LINE2(name, line) name##line +#define BS_NAME_LINE(name, line) BS_NAME_LINE2(name, line) +#define BS_UNIQUE_NAME(name) BS_NAME_LINE(name, __LINE__) -#define TEST_CASE( ... ) \ - static void BS_UNIQUE_NAME( TEST_FUNC__ )(); \ - namespace{ bs::AutoReg BS_UNIQUE_NAME( test_autoreg__ )( &BS_UNIQUE_NAME( TEST_FUNC__ ), __FILE__, __LINE__, __VA_ARGS__ ); }\ - static void BS_UNIQUE_NAME( TEST_FUNC__ )() +#define TEST_CASE(...) \ + static void BS_UNIQUE_NAME(TEST_FUNC__)(); \ + namespace \ + { \ + bs::AutoReg BS_UNIQUE_NAME(test_autoreg__)(&BS_UNIQUE_NAME(TEST_FUNC__), __FILE__, __LINE__, __VA_ARGS__); \ + } \ + static void BS_UNIQUE_NAME(TEST_FUNC__)() #define CHECK(condition) bs::check((condition), __LINE__) #define REQUIRE(condition) bs::require((condition), __LINE__) #define FAIL() bs::g_env.m_fail(__LINE__) -#define BS_ENV_DECLARE() namespace bs { Env g_env; } -#define BS_RUN(...) do { bs::IOHelper helper = bs::IOHelper(__VA_ARGS__); bs::Runner runner(helper); runner.run(); } while(0); +#define BS_ENV_DECLARE() \ + namespace bs \ + { \ + Env g_env; \ + } +#define BS_RUN(...) \ + do \ + { \ + bs::IOHelper helper = bs::IOHelper(__VA_ARGS__); \ + bs::Runner runner(helper); \ + runner.run(); \ + } while (0); -#endif //BSTEST_H +#endif //BSTEST_H diff --git a/tests/device/libraries/BSTest/test/test.cpp b/tests/device/libraries/BSTest/test/test.cpp index 25145344fb..48da79d3bd 100644 --- a/tests/device/libraries/BSTest/test/test.cpp +++ b/tests/device/libraries/BSTest/test/test.cpp @@ -1,9 +1,8 @@ -#include "BSTest.h" #include +#include "BSTest.h" BS_ENV_DECLARE(); - int main() { while (true) @@ -21,7 +20,6 @@ int main() return 1; } - TEST_CASE("this test runs successfully", "[bluesmoke]") { CHECK(1 + 1 == 2); @@ -42,16 +40,13 @@ TEST_CASE("another test which fails and crashes", "[bluesmoke][fail]") REQUIRE(false); } - TEST_CASE("third test which should be skipped", "[.]") { FAIL(); } - TEST_CASE("this test also runs successfully", "[bluesmoke]") { - } TEST_CASE("environment variables can be set and read from python", "[bluesmoke]") @@ -61,4 +56,3 @@ TEST_CASE("environment variables can be set and read from python", "[bluesmoke]" CHECK(strcmp(res, "42") == 0); setenv("VAR_FROM_TEST", "24", 1); } - diff --git a/tests/device/test_libc/libm_string.c b/tests/device/test_libc/libm_string.c index 715f7973b2..7b479a7d08 100644 --- a/tests/device/test_libc/libm_string.c +++ b/tests/device/test_libc/libm_string.c @@ -1,9 +1,7 @@ +#include #include -#include #include -#include - - +#include #define memcmp memcmp_P #define memcpy memcpy_P @@ -18,17 +16,14 @@ #define strcmp strcmp_P #define strncmp strncmp_P - -_CONST char *it = ""; /* Routine name for message routines. */ -static int errors = 0; +_CONST char* it = ""; /* Routine name for message routines. */ +static int errors = 0; /* Complain if condition is not true. */ #define check(thing) checkit(thing, __LINE__) static void -_DEFUN(checkit, (ok, l), - int ok _AND - int l) +_DEFUN(checkit, (ok, l), int ok _AND int l) { // newfunc(it); @@ -41,16 +36,11 @@ _DEFUN(checkit, (ok, l), } } - - /* Complain if first two args don't strcmp as equal. */ -#define equal(a, b) funcqual(a,b,__LINE__); +#define equal(a, b) funcqual(a, b, __LINE__); static void -_DEFUN(funcqual, (a, b, l), - char *a _AND - char *b _AND - int l) +_DEFUN(funcqual, (a, b, l), char* a _AND char* b _AND int l) { // newfunc(it); @@ -65,373 +55,369 @@ _DEFUN(funcqual, (a, b, l), } } - - static char one[50]; static char two[50]; - void libm_test_string() { /* Test strcmp first because we use it to test other things. */ it = "strcmp"; - check(strcmp("", "") == 0); /* Trivial case. */ - check(strcmp("a", "a") == 0); /* Identity. */ + check(strcmp("", "") == 0); /* Trivial case. */ + check(strcmp("a", "a") == 0); /* Identity. */ check(strcmp("abc", "abc") == 0); /* Multicharacter. */ check(strcmp("abc", "abcd") < 0); /* Length mismatches. */ check(strcmp("abcd", "abc") > 0); - check(strcmp("abcd", "abce") < 0); /* Honest miscompares. */ + check(strcmp("abcd", "abce") < 0); /* Honest miscompares. */ check(strcmp("abce", "abcd") > 0); check(strcmp("a\103", "a") > 0); /* Tricky if char signed. */ check(strcmp("a\103", "a\003") > 0); /* Test strcpy next because we need it to set up other tests. */ it = "strcpy"; - check(strcpy(one, "abcd") == one); /* Returned value. */ - equal(one, "abcd"); /* Basic test. */ + check(strcpy(one, "abcd") == one); /* Returned value. */ + equal(one, "abcd"); /* Basic test. */ - (void) strcpy(one, "x"); - equal(one, "x"); /* Writeover. */ - equal(one + 2, "cd"); /* Wrote too much? */ + (void)strcpy(one, "x"); + equal(one, "x"); /* Writeover. */ + equal(one + 2, "cd"); /* Wrote too much? */ - (void) strcpy(two, "hi there"); - (void) strcpy(one, two); - equal(one, "hi there"); /* Basic test encore. */ - equal(two, "hi there"); /* Stomped on source? */ + (void)strcpy(two, "hi there"); + (void)strcpy(one, two); + equal(one, "hi there"); /* Basic test encore. */ + equal(two, "hi there"); /* Stomped on source? */ - (void) strcpy(one, ""); - equal(one, ""); /* Boundary condition. */ + (void)strcpy(one, ""); + equal(one, ""); /* Boundary condition. */ /* strcat. */ it = "strcat"; - (void) strcpy(one, "ijk"); + (void)strcpy(one, "ijk"); check(strcat(one, "lmn") == one); /* Returned value. */ - equal(one, "ijklmn"); /* Basic test. */ - - (void) strcpy(one, "x"); - (void) strcat(one, "yz"); - equal(one, "xyz"); /* Writeover. */ - equal(one + 4, "mn"); /* Wrote too much? */ - - (void) strcpy(one, "gh"); - (void) strcpy(two, "ef"); - (void) strcat(one, two); - equal(one, "ghef"); /* Basic test encore. */ - equal(two, "ef"); /* Stomped on source? */ - - (void) strcpy(one, ""); - (void) strcat(one, ""); - equal(one, ""); /* Boundary conditions. */ - (void) strcpy(one, "ab"); - (void) strcat(one, ""); + equal(one, "ijklmn"); /* Basic test. */ + + (void)strcpy(one, "x"); + (void)strcat(one, "yz"); + equal(one, "xyz"); /* Writeover. */ + equal(one + 4, "mn"); /* Wrote too much? */ + + (void)strcpy(one, "gh"); + (void)strcpy(two, "ef"); + (void)strcat(one, two); + equal(one, "ghef"); /* Basic test encore. */ + equal(two, "ef"); /* Stomped on source? */ + + (void)strcpy(one, ""); + (void)strcat(one, ""); + equal(one, ""); /* Boundary conditions. */ + (void)strcpy(one, "ab"); + (void)strcat(one, ""); equal(one, "ab"); - (void) strcpy(one, ""); - (void) strcat(one, "cd"); + (void)strcpy(one, ""); + (void)strcat(one, "cd"); equal(one, "cd"); /* strncat - first test it as strcat, with big counts, then test the count mechanism. */ it = "strncat"; - (void) strcpy(one, "ijk"); + (void)strcpy(one, "ijk"); check(strncat(one, "lmn", 99) == one); /* Returned value. */ - equal(one, "ijklmn"); /* Basic test. */ - - (void) strcpy(one, "x"); - (void) strncat(one, "yz", 99); - equal(one, "xyz"); /* Writeover. */ - equal(one + 4, "mn"); /* Wrote too much? */ - - (void) strcpy(one, "gh"); - (void) strcpy(two, "ef"); - (void) strncat(one, two, 99); - equal(one, "ghef"); /* Basic test encore. */ - equal(two, "ef"); /* Stomped on source? */ - - (void) strcpy(one, ""); - (void) strncat(one, "", 99); - equal(one, ""); /* Boundary conditions. */ - (void) strcpy(one, "ab"); - (void) strncat(one, "", 99); + equal(one, "ijklmn"); /* Basic test. */ + + (void)strcpy(one, "x"); + (void)strncat(one, "yz", 99); + equal(one, "xyz"); /* Writeover. */ + equal(one + 4, "mn"); /* Wrote too much? */ + + (void)strcpy(one, "gh"); + (void)strcpy(two, "ef"); + (void)strncat(one, two, 99); + equal(one, "ghef"); /* Basic test encore. */ + equal(two, "ef"); /* Stomped on source? */ + + (void)strcpy(one, ""); + (void)strncat(one, "", 99); + equal(one, ""); /* Boundary conditions. */ + (void)strcpy(one, "ab"); + (void)strncat(one, "", 99); equal(one, "ab"); - (void) strcpy(one, ""); - (void) strncat(one, "cd", 99); + (void)strcpy(one, ""); + (void)strncat(one, "cd", 99); equal(one, "cd"); - (void) strcpy(one, "ab"); - (void) strncat(one, "cdef", 2); - equal(one, "abcd"); /* Count-limited. */ + (void)strcpy(one, "ab"); + (void)strncat(one, "cdef", 2); + equal(one, "abcd"); /* Count-limited. */ - (void) strncat(one, "gh", 0); - equal(one, "abcd"); /* Zero count. */ + (void)strncat(one, "gh", 0); + equal(one, "abcd"); /* Zero count. */ - (void) strncat(one, "gh", 2); - equal(one, "abcdgh"); /* Count _AND length equal. */ + (void)strncat(one, "gh", 2); + equal(one, "abcdgh"); /* Count _AND length equal. */ it = "strncmp"; /* strncmp - first test as strcmp with big counts";*/ - check(strncmp("", "", 99) == 0); /* Trivial case. */ - check(strncmp("a", "a", 99) == 0); /* Identity. */ + check(strncmp("", "", 99) == 0); /* Trivial case. */ + check(strncmp("a", "a", 99) == 0); /* Identity. */ check(strncmp("abc", "abc", 99) == 0); /* Multicharacter. */ check(strncmp("abc", "abcd", 99) < 0); /* Length unequal. */ check(strncmp("abcd", "abc", 99) > 0); check(strncmp("abcd", "abce", 99) < 0); /* Honestly unequal. */ check(strncmp("abce", "abcd", 99) > 0); check(strncmp("abce", "abcd", 3) == 0); /* Count limited. */ - check(strncmp("abce", "abc", 3) == 0); /* Count == length. */ - check(strncmp("abcd", "abce", 4) < 0); /* Nudging limit. */ - check(strncmp("abc", "def", 0) == 0); /* Zero count. */ + check(strncmp("abce", "abc", 3) == 0); /* Count == length. */ + check(strncmp("abcd", "abce", 4) < 0); /* Nudging limit. */ + check(strncmp("abc", "def", 0) == 0); /* Zero count. */ /* strncpy - testing is a bit different because of odd semantics. */ it = "strncpy"; check(strncpy(one, "abc", 4) == one); /* Returned value. */ - equal(one, "abc"); /* Did the copy go right? */ + equal(one, "abc"); /* Did the copy go right? */ - (void) strcpy(one, "abcdefgh"); - (void) strncpy(one, "xyz", 2); - equal(one, "xycdefgh"); /* Copy cut by count. */ + (void)strcpy(one, "abcdefgh"); + (void)strncpy(one, "xyz", 2); + equal(one, "xycdefgh"); /* Copy cut by count. */ - (void) strcpy(one, "abcdefgh"); - (void) strncpy(one, "xyz", 3); /* Copy cut just before NUL. */ + (void)strcpy(one, "abcdefgh"); + (void)strncpy(one, "xyz", 3); /* Copy cut just before NUL. */ equal(one, "xyzdefgh"); - (void) strcpy(one, "abcdefgh"); - (void) strncpy(one, "xyz", 4); /* Copy just includes NUL. */ + (void)strcpy(one, "abcdefgh"); + (void)strncpy(one, "xyz", 4); /* Copy just includes NUL. */ equal(one, "xyz"); - equal(one + 4, "efgh"); /* Wrote too much? */ + equal(one + 4, "efgh"); /* Wrote too much? */ - (void) strcpy(one, "abcdefgh"); - (void) strncpy(one, "xyz", 5); /* Copy includes padding. */ + (void)strcpy(one, "abcdefgh"); + (void)strncpy(one, "xyz", 5); /* Copy includes padding. */ equal(one, "xyz"); equal(one + 4, ""); equal(one + 5, "fgh"); - (void) strcpy(one, "abc"); - (void) strncpy(one, "xyz", 0); /* Zero-length copy. */ + (void)strcpy(one, "abc"); + (void)strncpy(one, "xyz", 0); /* Zero-length copy. */ equal(one, "abc"); - (void) strncpy(one, "", 2); /* Zero-length source. */ + (void)strncpy(one, "", 2); /* Zero-length source. */ equal(one, ""); equal(one + 1, ""); equal(one + 2, "c"); - (void) strcpy(one, "hi there"); - (void) strncpy(two, one, 9); - equal(two, "hi there"); /* Just paranoia. */ - equal(one, "hi there"); /* Stomped on source? */ + (void)strcpy(one, "hi there"); + (void)strncpy(two, one, 9); + equal(two, "hi there"); /* Just paranoia. */ + equal(one, "hi there"); /* Stomped on source? */ /* strlen. */ it = "strlen"; - check(strlen("") == 0); /* Empty. */ - check(strlen("a") == 1); /* Single char. */ + check(strlen("") == 0); /* Empty. */ + check(strlen("a") == 1); /* Single char. */ check(strlen("abcd") == 4); /* Multiple chars. */ /* strchr. */ it = "strchr"; check(strchr("abcd", 'z') == NULL); /* Not found. */ - (void) strcpy(one, "abcd"); - check(strchr(one, 'c') == one + 2); /* Basic test. */ - check(strchr(one, 'd') == one + 3); /* End of string. */ - check(strchr(one, 'a') == one); /* Beginning. */ - check(strchr(one, '\0') == one + 4); /* Finding NUL. */ - (void) strcpy(one, "ababa"); + (void)strcpy(one, "abcd"); + check(strchr(one, 'c') == one + 2); /* Basic test. */ + check(strchr(one, 'd') == one + 3); /* End of string. */ + check(strchr(one, 'a') == one); /* Beginning. */ + check(strchr(one, '\0') == one + 4); /* Finding NUL. */ + (void)strcpy(one, "ababa"); check(strchr(one, 'b') == one + 1); /* Finding first. */ - (void) strcpy(one, ""); + (void)strcpy(one, ""); check(strchr(one, 'b') == NULL); /* Empty string. */ check(strchr(one, '\0') == one); /* NUL in empty string. */ /* index - just like strchr. */ it = "index"; - check(index("abcd", 'z') == NULL); /* Not found. */ - (void) strcpy(one, "abcd"); - check(index(one, 'c') == one + 2); /* Basic test. */ - check(index(one, 'd') == one + 3); /* End of string. */ - check(index(one, 'a') == one); /* Beginning. */ + check(index("abcd", 'z') == NULL); /* Not found. */ + (void)strcpy(one, "abcd"); + check(index(one, 'c') == one + 2); /* Basic test. */ + check(index(one, 'd') == one + 3); /* End of string. */ + check(index(one, 'a') == one); /* Beginning. */ check(index(one, '\0') == one + 4); /* Finding NUL. */ - (void) strcpy(one, "ababa"); + (void)strcpy(one, "ababa"); check(index(one, 'b') == one + 1); /* Finding first. */ - (void) strcpy(one, ""); + (void)strcpy(one, ""); check(index(one, 'b') == NULL); /* Empty string. */ check(index(one, '\0') == one); /* NUL in empty string. */ /* strrchr. */ it = "strrchr"; check(strrchr("abcd", 'z') == NULL); /* Not found. */ - (void) strcpy(one, "abcd"); - check(strrchr(one, 'c') == one + 2); /* Basic test. */ - check(strrchr(one, 'd') == one + 3); /* End of string. */ - check(strrchr(one, 'a') == one); /* Beginning. */ + (void)strcpy(one, "abcd"); + check(strrchr(one, 'c') == one + 2); /* Basic test. */ + check(strrchr(one, 'd') == one + 3); /* End of string. */ + check(strrchr(one, 'a') == one); /* Beginning. */ check(strrchr(one, '\0') == one + 4); /* Finding NUL. */ - (void) strcpy(one, "ababa"); - check(strrchr(one, 'b') == one + 3); /* Finding last. */ - (void) strcpy(one, ""); + (void)strcpy(one, "ababa"); + check(strrchr(one, 'b') == one + 3); /* Finding last. */ + (void)strcpy(one, ""); check(strrchr(one, 'b') == NULL); /* Empty string. */ check(strrchr(one, '\0') == one); /* NUL in empty string. */ /* rindex - just like strrchr. */ it = "rindex"; check(rindex("abcd", 'z') == NULL); /* Not found. */ - (void) strcpy(one, "abcd"); - check(rindex(one, 'c') == one + 2); /* Basic test. */ - check(rindex(one, 'd') == one + 3); /* End of string. */ - check(rindex(one, 'a') == one); /* Beginning. */ - check(rindex(one, '\0') == one + 4); /* Finding NUL. */ - (void) strcpy(one, "ababa"); + (void)strcpy(one, "abcd"); + check(rindex(one, 'c') == one + 2); /* Basic test. */ + check(rindex(one, 'd') == one + 3); /* End of string. */ + check(rindex(one, 'a') == one); /* Beginning. */ + check(rindex(one, '\0') == one + 4); /* Finding NUL. */ + (void)strcpy(one, "ababa"); check(rindex(one, 'b') == one + 3); /* Finding last. */ - (void) strcpy(one, ""); + (void)strcpy(one, ""); check(rindex(one, 'b') == NULL); /* Empty string. */ check(rindex(one, '\0') == one); /* NUL in empty string. */ /* strpbrk - somewhat like strchr. */ it = "strpbrk"; check(strpbrk("abcd", "z") == NULL); /* Not found. */ - (void) strcpy(one, "abcd"); - check(strpbrk(one, "c") == one + 2); /* Basic test. */ - check(strpbrk(one, "d") == one + 3); /* End of string. */ - check(strpbrk(one, "a") == one); /* Beginning. */ - check(strpbrk(one, "") == NULL); /* Empty search list. */ + (void)strcpy(one, "abcd"); + check(strpbrk(one, "c") == one + 2); /* Basic test. */ + check(strpbrk(one, "d") == one + 3); /* End of string. */ + check(strpbrk(one, "a") == one); /* Beginning. */ + check(strpbrk(one, "") == NULL); /* Empty search list. */ check(strpbrk(one, "cb") == one + 1); /* Multiple search. */ - (void) strcpy(one, "abcabdea"); - check(strpbrk(one, "b") == one + 1); /* Finding first. */ + (void)strcpy(one, "abcabdea"); + check(strpbrk(one, "b") == one + 1); /* Finding first. */ check(strpbrk(one, "cb") == one + 1); /* With multiple search. */ check(strpbrk(one, "db") == one + 1); /* Another variant. */ - (void) strcpy(one, ""); + (void)strcpy(one, ""); check(strpbrk(one, "bc") == NULL); /* Empty string. */ - check(strpbrk(one, "") == NULL); /* Both strings empty. */ + check(strpbrk(one, "") == NULL); /* Both strings empty. */ /* strstr - somewhat like strchr. */ it = "strstr"; - check(strstr("z", "abcd") == NULL); /* Not found. */ + check(strstr("z", "abcd") == NULL); /* Not found. */ check(strstr("abx", "abcd") == NULL); /* Dead end. */ - (void) strcpy(one, "abcd"); - check(strstr(one, "c") == one + 2); /* Basic test. */ - check(strstr(one, "bc") == one + 1); /* Multichar. */ - check(strstr(one, "d") == one + 3); /* End of string. */ - check(strstr(one, "cd") == one + 2); /* Tail of string. */ - check(strstr(one, "abc") == one); /* Beginning. */ - check(strstr(one, "abcd") == one); /* Exact match. */ - check(strstr(one, "de") == NULL); /* Past end. */ - check(strstr(one, "") == one); /* Finding empty. */ - (void) strcpy(one, "ababa"); + (void)strcpy(one, "abcd"); + check(strstr(one, "c") == one + 2); /* Basic test. */ + check(strstr(one, "bc") == one + 1); /* Multichar. */ + check(strstr(one, "d") == one + 3); /* End of string. */ + check(strstr(one, "cd") == one + 2); /* Tail of string. */ + check(strstr(one, "abc") == one); /* Beginning. */ + check(strstr(one, "abcd") == one); /* Exact match. */ + check(strstr(one, "de") == NULL); /* Past end. */ + check(strstr(one, "") == one); /* Finding empty. */ + (void)strcpy(one, "ababa"); check(strstr(one, "ba") == one + 1); /* Finding first. */ - (void) strcpy(one, ""); + (void)strcpy(one, ""); check(strstr(one, "b") == NULL); /* Empty string. */ - check(strstr(one, "") == one); /* Empty in empty string. */ - (void) strcpy(one, "bcbca"); + check(strstr(one, "") == one); /* Empty in empty string. */ + (void)strcpy(one, "bcbca"); check(strstr(one, "bca") == one + 2); /* False start. */ - (void) strcpy(one, "bbbcabbca"); + (void)strcpy(one, "bbbcabbca"); check(strstr(one, "bbca") == one + 1); /* With overlap. */ /* strspn. */ it = "strspn"; check(strspn("abcba", "abc") == 5); /* Whole string. */ - check(strspn("abcba", "ab") == 2); /* Partial. */ - check(strspn("abc", "qx") == 0); /* None. */ - check(strspn("", "ab") == 0); /* Null string. */ - check(strspn("abc", "") == 0); /* Null search list. */ + check(strspn("abcba", "ab") == 2); /* Partial. */ + check(strspn("abc", "qx") == 0); /* None. */ + check(strspn("", "ab") == 0); /* Null string. */ + check(strspn("abc", "") == 0); /* Null search list. */ /* strcspn. */ it = "strcspn"; check(strcspn("abcba", "qx") == 5); /* Whole string. */ check(strcspn("abcba", "cx") == 2); /* Partial. */ - check(strcspn("abc", "abc") == 0); /* None. */ - check(strcspn("", "ab") == 0); /* Null string. */ - check(strcspn("abc", "") == 3); /* Null search list. */ + check(strcspn("abc", "abc") == 0); /* None. */ + check(strcspn("", "ab") == 0); /* Null string. */ + check(strcspn("abc", "") == 3); /* Null search list. */ /* strtok - the hard one. */ it = "strtok"; - (void) strcpy(one, "first, second, third"); - equal(strtok(one, ", "), "first"); /* Basic test. */ + (void)strcpy(one, "first, second, third"); + equal(strtok(one, ", "), "first"); /* Basic test. */ equal(one, "first"); - equal(strtok((char *)NULL, ", "), "second"); - equal(strtok((char *)NULL, ", "), "third"); - check(strtok((char *)NULL, ", ") == NULL); - (void) strcpy(one, ", first, "); - equal(strtok(one, ", "), "first"); /* Extra delims, 1 tok. */ - check(strtok((char *)NULL, ", ") == NULL); - (void) strcpy(one, "1a, 1b; 2a, 2b"); + equal(strtok((char*)NULL, ", "), "second"); + equal(strtok((char*)NULL, ", "), "third"); + check(strtok((char*)NULL, ", ") == NULL); + (void)strcpy(one, ", first, "); + equal(strtok(one, ", "), "first"); /* Extra delims, 1 tok. */ + check(strtok((char*)NULL, ", ") == NULL); + (void)strcpy(one, "1a, 1b; 2a, 2b"); equal(strtok(one, ", "), "1a"); /* Changing delim lists. */ - equal(strtok((char *)NULL, "; "), "1b"); - equal(strtok((char *)NULL, ", "), "2a"); - (void) strcpy(two, "x-y"); + equal(strtok((char*)NULL, "; "), "1b"); + equal(strtok((char*)NULL, ", "), "2a"); + (void)strcpy(two, "x-y"); equal(strtok(two, "-"), "x"); /* New string before done. */ - equal(strtok((char *)NULL, "-"), "y"); - check(strtok((char *)NULL, "-") == NULL); - (void) strcpy(one, "a,b, c,, ,d"); + equal(strtok((char*)NULL, "-"), "y"); + check(strtok((char*)NULL, "-") == NULL); + (void)strcpy(one, "a,b, c,, ,d"); equal(strtok(one, ", "), "a"); /* Different separators. */ - equal(strtok((char *)NULL, ", "), "b"); - equal(strtok((char *)NULL, " ,"), "c"); /* Permute list too. */ - equal(strtok((char *)NULL, " ,"), "d"); - check(strtok((char *)NULL, ", ") == NULL); - check(strtok((char *)NULL, ", ") == NULL); /* Persistence. */ - (void) strcpy(one, ", "); - check(strtok(one, ", ") == NULL); /* No tokens. */ - (void) strcpy(one, ""); - check(strtok(one, ", ") == NULL); /* Empty string. */ - (void) strcpy(one, "abc"); + equal(strtok((char*)NULL, ", "), "b"); + equal(strtok((char*)NULL, " ,"), "c"); /* Permute list too. */ + equal(strtok((char*)NULL, " ,"), "d"); + check(strtok((char*)NULL, ", ") == NULL); + check(strtok((char*)NULL, ", ") == NULL); /* Persistence. */ + (void)strcpy(one, ", "); + check(strtok(one, ", ") == NULL); /* No tokens. */ + (void)strcpy(one, ""); + check(strtok(one, ", ") == NULL); /* Empty string. */ + (void)strcpy(one, "abc"); equal(strtok(one, ", "), "abc"); /* No delimiters. */ - check(strtok((char *)NULL, ", ") == NULL); - (void) strcpy(one, "abc"); + check(strtok((char*)NULL, ", ") == NULL); + (void)strcpy(one, "abc"); equal(strtok(one, ""), "abc"); /* Empty delimiter list. */ - check(strtok((char *)NULL, "") == NULL); - (void) strcpy(one, "abcdefgh"); - (void) strcpy(one, "a,b,c"); + check(strtok((char*)NULL, "") == NULL); + (void)strcpy(one, "abcdefgh"); + (void)strcpy(one, "a,b,c"); equal(strtok(one, ","), "a"); /* Basics again... */ - equal(strtok((char *)NULL, ","), "b"); - equal(strtok((char *)NULL, ","), "c"); - check(strtok((char *)NULL, ",") == NULL); - equal(one + 6, "gh"); /* Stomped past end? */ - equal(one, "a"); /* Stomped old tokens? */ + equal(strtok((char*)NULL, ","), "b"); + equal(strtok((char*)NULL, ","), "c"); + check(strtok((char*)NULL, ",") == NULL); + equal(one + 6, "gh"); /* Stomped past end? */ + equal(one, "a"); /* Stomped old tokens? */ equal(one + 2, "b"); equal(one + 4, "c"); /* memcmp. */ it = "memcmp"; - check(memcmp("a", "a", 1) == 0); /* Identity. */ - check(memcmp("abc", "abc", 3) == 0); /* Multicharacter. */ + check(memcmp("a", "a", 1) == 0); /* Identity. */ + check(memcmp("abc", "abc", 3) == 0); /* Multicharacter. */ check(memcmp("abcd", "abce", 4) < 0); /* Honestly unequal. */ check(memcmp("abce", "abcd", 4)); check(memcmp("alph", "beta", 4) < 0); check(memcmp("abce", "abcd", 3) == 0); /* Count limited. */ - check(memcmp("abc", "def", 0) == 0); /* Zero count. */ + check(memcmp("abc", "def", 0) == 0); /* Zero count. */ /* memcmp should test strings as unsigned */ one[0] = 0xfe; two[0] = 0x03; check(memcmp(one, two, 1) > 0); - /* memchr. */ it = "memchr"; check(memchr("abcd", 'z', 4) == NULL); /* Not found. */ - (void) strcpy(one, "abcd"); - check(memchr(one, 'c', 4) == one + 2); /* Basic test. */ - check(memchr(one, 'd', 4) == one + 3); /* End of string. */ - check(memchr(one, 'a', 4) == one); /* Beginning. */ + (void)strcpy(one, "abcd"); + check(memchr(one, 'c', 4) == one + 2); /* Basic test. */ + check(memchr(one, 'd', 4) == one + 3); /* End of string. */ + check(memchr(one, 'a', 4) == one); /* Beginning. */ check(memchr(one, '\0', 5) == one + 4); /* Finding NUL. */ - (void) strcpy(one, "ababa"); + (void)strcpy(one, "ababa"); check(memchr(one, 'b', 5) == one + 1); /* Finding first. */ - check(memchr(one, 'b', 0) == NULL); /* Zero count. */ - check(memchr(one, 'a', 1) == one); /* Singleton case. */ - (void) strcpy(one, "a\203b"); + check(memchr(one, 'b', 0) == NULL); /* Zero count. */ + check(memchr(one, 'a', 1) == one); /* Singleton case. */ + (void)strcpy(one, "a\203b"); check(memchr(one, 0203, 3) == one + 1); /* Unsignedness. */ /* memcpy - need not work for overlap. */ it = "memcpy"; check(memcpy(one, "abc", 4) == one); /* Returned value. */ - equal(one, "abc"); /* Did the copy go right? */ + equal(one, "abc"); /* Did the copy go right? */ - (void) strcpy(one, "abcdefgh"); - (void) memcpy(one + 1, "xyz", 2); - equal(one, "axydefgh"); /* Basic test. */ + (void)strcpy(one, "abcdefgh"); + (void)memcpy(one + 1, "xyz", 2); + equal(one, "axydefgh"); /* Basic test. */ - (void) strcpy(one, "abc"); - (void) memcpy(one, "xyz", 0); - equal(one, "abc"); /* Zero-length copy. */ + (void)strcpy(one, "abc"); + (void)memcpy(one, "xyz", 0); + equal(one, "abc"); /* Zero-length copy. */ - (void) strcpy(one, "hi there"); - (void) strcpy(two, "foo"); - (void) memcpy(two, one, 9); - equal(two, "hi there"); /* Just paranoia. */ - equal(one, "hi there"); /* Stomped on source? */ + (void)strcpy(one, "hi there"); + (void)strcpy(two, "foo"); + (void)memcpy(two, one, 9); + equal(two, "hi there"); /* Just paranoia. */ + equal(one, "hi there"); /* Stomped on source? */ #if 0 /* memmove - must work on overlap. */ it = "memmove"; @@ -505,61 +491,61 @@ void libm_test_string() #endif /* memset. */ it = "memset"; - (void) strcpy(one, "abcdefgh"); + (void)strcpy(one, "abcdefgh"); check(memset(one + 1, 'x', 3) == one + 1); /* Return value. */ - equal(one, "axxxefgh"); /* Basic test. */ + equal(one, "axxxefgh"); /* Basic test. */ - (void) memset(one + 2, 'y', 0); - equal(one, "axxxefgh"); /* Zero-length set. */ + (void)memset(one + 2, 'y', 0); + equal(one, "axxxefgh"); /* Zero-length set. */ - (void) memset(one + 5, 0, 1); - equal(one, "axxxe"); /* Zero fill. */ - equal(one + 6, "gh"); /* _AND the leftover. */ + (void)memset(one + 5, 0, 1); + equal(one, "axxxe"); /* Zero fill. */ + equal(one + 6, "gh"); /* _AND the leftover. */ - (void) memset(one + 2, 010045, 1); - equal(one, "ax\045xe"); /* Unsigned char convert. */ + (void)memset(one + 2, 010045, 1); + equal(one, "ax\045xe"); /* Unsigned char convert. */ /* bcopy - much like memcpy. Berklix manual is silent about overlap, so don't test it. */ it = "bcopy"; - (void) bcopy("abc", one, 4); - equal(one, "abc"); /* Simple copy. */ + (void)bcopy("abc", one, 4); + equal(one, "abc"); /* Simple copy. */ - (void) strcpy(one, "abcdefgh"); - (void) bcopy("xyz", one + 1, 2); - equal(one, "axydefgh"); /* Basic test. */ + (void)strcpy(one, "abcdefgh"); + (void)bcopy("xyz", one + 1, 2); + equal(one, "axydefgh"); /* Basic test. */ - (void) strcpy(one, "abc"); - (void) bcopy("xyz", one, 0); - equal(one, "abc"); /* Zero-length copy. */ + (void)strcpy(one, "abc"); + (void)bcopy("xyz", one, 0); + equal(one, "abc"); /* Zero-length copy. */ - (void) strcpy(one, "hi there"); - (void) strcpy(two, "foo"); - (void) bcopy(one, two, 9); - equal(two, "hi there"); /* Just paranoia. */ - equal(one, "hi there"); /* Stomped on source? */ + (void)strcpy(one, "hi there"); + (void)strcpy(two, "foo"); + (void)bcopy(one, two, 9); + equal(two, "hi there"); /* Just paranoia. */ + equal(one, "hi there"); /* Stomped on source? */ /* bzero. */ it = "bzero"; - (void) strcpy(one, "abcdef"); + (void)strcpy(one, "abcdef"); bzero(one + 2, 2); - equal(one, "ab"); /* Basic test. */ + equal(one, "ab"); /* Basic test. */ equal(one + 3, ""); equal(one + 4, "ef"); - (void) strcpy(one, "abcdef"); + (void)strcpy(one, "abcdef"); bzero(one + 2, 0); - equal(one, "abcdef"); /* Zero-length copy. */ + equal(one, "abcdef"); /* Zero-length copy. */ /* bcmp - somewhat like memcmp. */ it = "bcmp"; - check(bcmp("a", "a", 1) == 0); /* Identity. */ - check(bcmp("abc", "abc", 3) == 0); /* Multicharacter. */ + check(bcmp("a", "a", 1) == 0); /* Identity. */ + check(bcmp("abc", "abc", 3) == 0); /* Multicharacter. */ check(bcmp("abcd", "abce", 4) != 0); /* Honestly unequal. */ check(bcmp("abce", "abcd", 4)); check(bcmp("alph", "beta", 4) != 0); check(bcmp("abce", "abcd", 3) == 0); /* Count limited. */ - check(bcmp("abc", "def", 0) == 0); /* Zero count. */ + check(bcmp("abc", "def", 0) == 0); /* Zero count. */ if (errors) { @@ -567,7 +553,7 @@ void libm_test_string() } printf("ok\n"); -#if 0 /* strerror - VERY system-dependent. */ +#if 0 /* strerror - VERY system-dependent. */ { extern CONST unsigned int _sys_nerr; extern CONST char *CONST _sys_errlist[]; @@ -579,4 +565,3 @@ void libm_test_string() } #endif } - diff --git a/tests/device/test_libc/memcpy-1.c b/tests/device/test_libc/memcpy-1.c index 4e14bb5810..7ba022115c 100644 --- a/tests/device/test_libc/memcpy-1.c +++ b/tests/device/test_libc/memcpy-1.c @@ -26,11 +26,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include -#include #include - +#include +#include +#include #define memcmp memcmp_P #define memcpy memcpy_P @@ -121,15 +120,16 @@ void memcpy_main(void) dest[j] = 0; } - void *ret = memcpy(dest + START_COPY + da, src + sa, n); + void* ret = memcpy(dest + START_COPY + da, src + sa, n); /* Check return value. */ if (ret != (dest + START_COPY + da)) - print_error("\nFailed: wrong return value in memcpy of %u bytes " - "with src_align %u and dst_align %u. " - "Return value and dest should be the same" - "(ret is %p, dest is %p)\n", - n, sa, da, ret, dest + START_COPY + da); + print_error( + "\nFailed: wrong return value in memcpy of %u bytes " + "with src_align %u and dst_align %u. " + "Return value and dest should be the same" + "(ret is %p, dest is %p)\n", + n, sa, da, ret, dest + START_COPY + da); /* Check that content of the destination buffer is the same as the source buffer, and @@ -138,35 +138,39 @@ void memcpy_main(void) if ((unsigned)j < START_COPY + da) { if (dest[j] != 0) - print_error("\nFailed: after memcpy of %u bytes " - "with src_align %u and dst_align %u, " - "byte %u before the start of dest is not 0.\n", - n, sa, da, START_COPY - j); + print_error( + "\nFailed: after memcpy of %u bytes " + "with src_align %u and dst_align %u, " + "byte %u before the start of dest is not 0.\n", + n, sa, da, START_COPY - j); } else if ((unsigned)j < START_COPY + da + n) { i = j - START_COPY - da; if (dest[j] != (src + sa)[i]) - print_error("\nFailed: after memcpy of %u bytes " - "with src_align %u and dst_align %u, " - "byte %u in dest and src are not the same.\n", - n, sa, da, i); + print_error( + "\nFailed: after memcpy of %u bytes " + "with src_align %u and dst_align %u, " + "byte %u in dest and src are not the same.\n", + n, sa, da, i); } else if (dest[j] != 0) { - print_error("\nFailed: after memcpy of %u bytes " - "with src_align %u and dst_align %u, " - "byte %u after the end of dest is not 0.\n", - n, sa, da, j - START_COPY - da - n); + print_error( + "\nFailed: after memcpy of %u bytes " + "with src_align %u and dst_align %u, " + "byte %u after the end of dest is not 0.\n", + n, sa, da, j - START_COPY - da - n); } /* Check src is not modified. */ for (j = 0; j < BUFF_SIZE; j++) if (src[i] != backup_src[i]) - print_error("\nFailed: after memcpy of %u bytes " - "with src_align %u and dst_align %u, " - "byte %u of src is modified.\n", - n, sa, da, j); + print_error( + "\nFailed: after memcpy of %u bytes " + "with src_align %u and dst_align %u, " + "byte %u of src is modified.\n", + n, sa, da, j); } if (errors != 0) diff --git a/tests/device/test_libc/memmove1.c b/tests/device/test_libc/memmove1.c index 573b476765..96b46d2887 100644 --- a/tests/device/test_libc/memmove1.c +++ b/tests/device/test_libc/memmove1.c @@ -55,19 +55,17 @@ #define TOO_MANY_ERRORS 11 int errors = 0; -#define DEBUGP \ - if (errors == TOO_MANY_ERRORS) \ - printf ("Further errors omitted\n"); \ - else if (errors < TOO_MANY_ERRORS) \ - printf +#define DEBUGP \ + if (errors == TOO_MANY_ERRORS) \ + printf("Further errors omitted\n"); \ + else if (errors < TOO_MANY_ERRORS) \ + printf /* A safe target-independent memmove. */ -void -mymemmove(unsigned char *dest, unsigned char *src, size_t n) +void mymemmove(unsigned char* dest, unsigned char* src, size_t n) { - if ((src <= dest && src + n <= dest) - || src >= dest) + if ((src <= dest && src + n <= dest) || src >= dest) while (n-- > 0) { *dest++ = *src++; @@ -85,14 +83,12 @@ mymemmove(unsigned char *dest, unsigned char *src, size_t n) /* It's either the noinline attribute or forcing the test framework to pass -fno-builtin-memmove. */ -void -xmemmove(unsigned char *dest, unsigned char *src, size_t n) -__attribute__((__noinline__)); +void xmemmove(unsigned char* dest, unsigned char* src, size_t n) + __attribute__((__noinline__)); -void -xmemmove(unsigned char *dest, unsigned char *src, size_t n) +void xmemmove(unsigned char* dest, unsigned char* src, size_t n) { - void *retp; + void* retp; retp = memmove(dest, src, n); if (retp != dest) @@ -103,12 +99,10 @@ xmemmove(unsigned char *dest, unsigned char *src, size_t n) } } - /* Fill the array with something we can associate with a position, but not exactly the same as the position index. */ -void -fill(unsigned char dest[MAX * 3]) +void fill(unsigned char dest[MAX * 3]) { size_t i; for (i = 0; i < MAX * 3; i++) @@ -165,9 +159,10 @@ void memmove_main(void) if (memcmp(to_known, to_test, sizeof(to_known)) != 0) { errors++; - DEBUGP("memmove failed for %d bytes," - " with src %d bytes before dest\n", - i, j); + DEBUGP( + "memmove failed for %d bytes," + " with src %d bytes before dest\n", + i, j); } } } @@ -187,9 +182,10 @@ void memmove_main(void) if (memcmp(to_known, to_test, sizeof(to_known)) != 0) { errors++; - DEBUGP("memmove failed when moving %d bytes," - " with src %d bytes after dest\n", - i, j); + DEBUGP( + "memmove failed when moving %d bytes," + " with src %d bytes after dest\n", + i, j); } } } diff --git a/tests/device/test_libc/strcmp-1.c b/tests/device/test_libc/strcmp-1.c index b2b3649762..b996dc01ce 100644 --- a/tests/device/test_libc/strcmp-1.c +++ b/tests/device/test_libc/strcmp-1.c @@ -26,10 +26,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include -#include #include +#include +#include +#include #define memcmp memcmp_P #define memcpy memcpy_P @@ -46,7 +46,6 @@ #define BUFF_SIZE 256 - /* The macro LONG_TEST controls whether a short or a more comprehensive test of strcmp should be performed. */ #ifdef LONG_TEST @@ -106,11 +105,10 @@ #error "Buffer overrun: MAX_OFFSET + MAX_BLOCK_SIZE + MAX_DIFF + MAX_LEN + MAX_ZEROS >= BUFF_SIZE." #endif - #define TOO_MANY_ERRORS 11 static int errors = 0; -const char *testname = "strcmp"; +const char* testname = "strcmp"; static void print_error(char const* msg, ...) @@ -133,7 +131,6 @@ print_error(char const* msg, ...) } } - extern int rand_seed; void strcmp_main(void) { @@ -146,7 +143,7 @@ void strcmp_main(void) unsigned sa; unsigned da; unsigned n, m, len; - char *p; + char* p; int ret; /* Make calls to strcmp with block sizes ranging between 1 and @@ -155,7 +152,7 @@ void strcmp_main(void) for (da = 0; da <= MAX_OFFSET; da++) for (n = 1; n <= MAX_BLOCK_SIZE; n++) { - for (m = 1; m < n + MAX_DIFF; m++) + for (m = 1; m < n + MAX_DIFF; m++) for (len = 0; len < MAX_LEN; len++) for (zeros = 1; zeros < MAX_ZEROS; zeros++) { @@ -197,53 +194,58 @@ void strcmp_main(void) { if (ret != 0) { - print_error("\nFailed: after %s of %u bytes " - "with src_align %u and dst_align %u, " - "dest after %d bytes is modified for %d bytes, " - "return value is %d, expected 0.\n", - testname, n, sa, da, m, len, ret); + print_error( + "\nFailed: after %s of %u bytes " + "with src_align %u and dst_align %u, " + "dest after %d bytes is modified for %d bytes, " + "return value is %d, expected 0.\n", + testname, n, sa, da, m, len, ret); } } else { if (ret >= 0) - print_error("\nFailed: after %s of %u bytes " - "with src_align %u and dst_align %u, " - "dest after %d bytes is modified for %d bytes, " - "return value is %d, expected negative.\n", - testname, n, sa, da, m, len, ret); + print_error( + "\nFailed: after %s of %u bytes " + "with src_align %u and dst_align %u, " + "dest after %d bytes is modified for %d bytes, " + "return value is %d, expected negative.\n", + testname, n, sa, da, m, len, ret); } } else if (m > n) { if (ret >= 0) { - print_error("\nFailed: after %s of %u bytes " - "with src_align %u and dst_align %u, " - "dest after %d bytes is modified for %d bytes, " - "return value is %d, expected negative.\n", - testname, n, sa, da, m, len, ret); + print_error( + "\nFailed: after %s of %u bytes " + "with src_align %u and dst_align %u, " + "dest after %d bytes is modified for %d bytes, " + "return value is %d, expected negative.\n", + testname, n, sa, da, m, len, ret); } } - else /* m < n */ + else /* m < n */ { if (len == 0) { if (ret <= 0) - print_error("\nFailed: after %s of %u bytes " - "with src_align %u and dst_align %u, " - "dest after %d bytes is modified for %d bytes, " - "return value is %d, expected positive.\n", - testname, n, sa, da, m, len, ret); + print_error( + "\nFailed: after %s of %u bytes " + "with src_align %u and dst_align %u, " + "dest after %d bytes is modified for %d bytes, " + "return value is %d, expected positive.\n", + testname, n, sa, da, m, len, ret); } else { if (ret >= 0) - print_error("\nFailed: after %s of %u bytes " - "with src_align %u and dst_align %u, " - "dest after %d bytes is modified for %d bytes, " - "return value is %d, expected negative.\n", - testname, n, sa, da, m, len, ret); + print_error( + "\nFailed: after %s of %u bytes " + "with src_align %u and dst_align %u, " + "dest after %d bytes is modified for %d bytes, " + "return value is %d, expected negative.\n", + testname, n, sa, da, m, len, ret); } } } diff --git a/tests/device/test_libc/tstring.c b/tests/device/test_libc/tstring.c index c2f2f4075a..451dc4cf6e 100644 --- a/tests/device/test_libc/tstring.c +++ b/tests/device/test_libc/tstring.c @@ -5,10 +5,10 @@ is freely granted, provided that this notice is preserved. */ -#include +#include #include #include -#include +#include #define MAX_1 50 #define memcmp memcmp_P @@ -26,7 +26,7 @@ #define MAX_2 (2 * MAX_1 + MAX_1 / 10) -void eprintf(int line, char *result, char *expected, int size) +void eprintf(int line, char* result, char* expected, int size) { if (size != 0) printf("Failure at line %d, result is <%.*s>, should be <%s> of size %d\n", @@ -36,7 +36,7 @@ void eprintf(int line, char *result, char *expected, int size) line, result, expected); } -void mycopy(char *target, char *source, int size) +void mycopy(char* target, char* source, int size) { int i; @@ -46,7 +46,7 @@ void mycopy(char *target, char *source, int size) } } -void myset(char *target, char ch, int size) +void myset(char* target, char ch, int size) { int i; @@ -88,19 +88,18 @@ void tstring_main(void) tmp2[1] = '\0'; if (memset(target, 'X', 0) != target || - memcpy(target, "Y", 0) != target || - memmove(target, "K", 0) != target || - strncpy(tmp2, "4", 0) != tmp2 || - strncat(tmp2, "123", 0) != tmp2 || - strcat(target, "") != target) + memcpy(target, "Y", 0) != target || + memmove(target, "K", 0) != target || + strncpy(tmp2, "4", 0) != tmp2 || + strncat(tmp2, "123", 0) != tmp2 || + strcat(target, "") != target) { eprintf(__LINE__, target, "A", 0); test_failed = 1; } - if (strcmp(target, "A") || strlen(target) != 1 || memchr(target, 'A', 0) != NULL - || memcmp(target, "J", 0) || strncmp(target, "A", 1) || strncmp(target, "J", 0) || - tmp2[0] != 'Z' || tmp2[1] != '\0') + if (strcmp(target, "A") || strlen(target) != 1 || memchr(target, 'A', 0) != NULL || memcmp(target, "J", 0) || strncmp(target, "A", 1) || strncmp(target, "J", 0) || + tmp2[0] != 'Z' || tmp2[1] != '\0') { eprintf(__LINE__, target, "A", 0); test_failed = 1; @@ -108,15 +107,15 @@ void tstring_main(void) tmp2[2] = 'A'; if (strcpy(target, "") != target || - strncpy(tmp2, "", 4) != tmp2 || - strcat(target, "") != target) + strncpy(tmp2, "", 4) != tmp2 || + strcat(target, "") != target) { eprintf(__LINE__, target, "", 0); test_failed = 1; } if (target[0] != '\0' || strncmp(target, "", 1) || - memcmp(tmp2, "\0\0\0\0", 4)) + memcmp(tmp2, "\0\0\0\0", 4)) { eprintf(__LINE__, target, "", 0); test_failed = 1; @@ -124,38 +123,38 @@ void tstring_main(void) tmp2[2] = 'A'; if (strncat(tmp2, "1", 3) != tmp2 || - memcmp(tmp2, "1\0A", 3)) + memcmp(tmp2, "1\0A", 3)) { eprintf(__LINE__, tmp2, "1\0A", 3); test_failed = 1; } if (strcpy(tmp3, target) != tmp3 || - strcat(tmp3, "X") != tmp3 || - strncpy(tmp2, "X", 2) != tmp2 || - memset(target, tmp2[0], 1) != target) + strcat(tmp3, "X") != tmp3 || + strncpy(tmp2, "X", 2) != tmp2 || + memset(target, tmp2[0], 1) != target) { eprintf(__LINE__, target, "X", 0); test_failed = 1; } if (strcmp(target, "X") || strlen(target) != 1 || - memchr(target, 'X', 2) != target || - strchr(target, 'X') != target || - memchr(target, 'Y', 2) != NULL || - strchr(target, 'Y') != NULL || - strcmp(tmp3, target) || - strncmp(tmp3, target, 2) || - memcmp(target, "K", 0) || - strncmp(target, tmp3, 3)) + memchr(target, 'X', 2) != target || + strchr(target, 'X') != target || + memchr(target, 'Y', 2) != NULL || + strchr(target, 'Y') != NULL || + strcmp(tmp3, target) || + strncmp(tmp3, target, 2) || + memcmp(target, "K", 0) || + strncmp(target, tmp3, 3)) { eprintf(__LINE__, target, "X", 0); test_failed = 1; } if (strcpy(tmp3, "Y") != tmp3 || - strcat(tmp3, "Y") != tmp3 || - memset(target, 'Y', 2) != target) + strcat(tmp3, "Y") != tmp3 || + memset(target, 'Y', 2) != target) { eprintf(__LINE__, target, "Y", 0); test_failed = 1; @@ -163,12 +162,12 @@ void tstring_main(void) target[2] = '\0'; if (memcmp(target, "YY", 2) || strcmp(target, "YY") || - strlen(target) != 2 || memchr(target, 'Y', 2) != target || - strcmp(tmp3, target) || - strncmp(target, tmp3, 3) || - strncmp(target, tmp3, 4) || - strncmp(target, tmp3, 2) || - strchr(target, 'Y') != target) + strlen(target) != 2 || memchr(target, 'Y', 2) != target || + strcmp(tmp3, target) || + strncmp(target, tmp3, 3) || + strncmp(target, tmp3, 4) || + strncmp(target, tmp3, 2) || + strchr(target, 'Y') != target) { eprintf(__LINE__, target, "YY", 2); test_failed = 1; @@ -176,25 +175,25 @@ void tstring_main(void) strcpy(target, "WW"); if (memcmp(target, "WW", 2) || strcmp(target, "WW") || - strlen(target) != 2 || memchr(target, 'W', 2) != target || - strchr(target, 'W') != target) + strlen(target) != 2 || memchr(target, 'W', 2) != target || + strchr(target, 'W') != target) { eprintf(__LINE__, target, "WW", 2); test_failed = 1; } if (strncpy(target, "XX", 16) != target || - memcmp(target, "XX\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16)) + memcmp(target, "XX\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16)) { eprintf(__LINE__, target, "XX\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16); test_failed = 1; } if (strcpy(tmp3, "ZZ") != tmp3 || - strcat(tmp3, "Z") != tmp3 || - memcpy(tmp4, "Z", 2) != tmp4 || - strcat(tmp4, "ZZ") != tmp4 || - memset(target, 'Z', 3) != target) + strcat(tmp3, "Z") != tmp3 || + memcpy(tmp4, "Z", 2) != tmp4 || + strcat(tmp4, "ZZ") != tmp4 || + memset(target, 'Z', 3) != target) { eprintf(__LINE__, target, "ZZZ", 3); test_failed = 1; @@ -204,11 +203,11 @@ void tstring_main(void) tmp5[0] = '\0'; strncat(tmp5, "123", 2); if (memcmp(target, "ZZZ", 3) || strcmp(target, "ZZZ") || - strcmp(tmp3, target) || strcmp(tmp4, target) || - strncmp(target, "ZZZ", 4) || strncmp(target, "ZZY", 3) <= 0 || - strncmp("ZZY", target, 4) >= 0 || - memcmp(tmp5, "12", 3) || - strlen(target) != 3) + strcmp(tmp3, target) || strcmp(tmp4, target) || + strncmp(target, "ZZZ", 4) || strncmp(target, "ZZY", 3) <= 0 || + strncmp("ZZY", target, 4) >= 0 || + memcmp(tmp5, "12", 3) || + strlen(target) != 3) { eprintf(__LINE__, target, "ZZZ", 3); test_failed = 1; @@ -216,10 +215,10 @@ void tstring_main(void) target[2] = 'K'; if (memcmp(target, "ZZZ", 2) || strcmp(target, "ZZZ") >= 0 || - memcmp(target, "ZZZ", 3) >= 0 || strlen(target) != 3 || - memchr(target, 'K', 3) != target + 2 || - strncmp(target, "ZZZ", 2) || strncmp(target, "ZZZ", 4) >= 0 || - strchr(target, 'K') != target + 2) + memcmp(target, "ZZZ", 3) >= 0 || strlen(target) != 3 || + memchr(target, 'K', 3) != target + 2 || + strncmp(target, "ZZZ", 2) || strncmp(target, "ZZZ", 4) >= 0 || + strchr(target, 'K') != target + 2) { eprintf(__LINE__, target, "ZZK", 3); test_failed = 1; @@ -227,8 +226,8 @@ void tstring_main(void) strcpy(target, "AAA"); if (memcmp(target, "AAA", 3) || strcmp(target, "AAA") || - strncmp(target, "AAA", 3) || - strlen(target) != 3) + strncmp(target, "AAA", 3) || + strlen(target) != 3) { eprintf(__LINE__, target, "AAA", 3); test_failed = 1; @@ -287,7 +286,7 @@ void tstring_main(void) } tmp2[i - z] = first_char + 1; if (memmove(tmp2 + z + 1, tmp2 + z, i - z - 1) != tmp2 + z + 1 || - memset(tmp3, first_char, i) != tmp3) + memset(tmp3, first_char, i) != tmp3) { printf("error at line %d\n", __LINE__); test_failed = 1; @@ -296,7 +295,7 @@ void tstring_main(void) myset(tmp4, first_char, i); tmp5[0] = '\0'; if (strncpy(tmp5, tmp1, i + 1) != tmp5 || - strcat(tmp5, tmp1) != tmp5) + strcat(tmp5, tmp1) != tmp5) { printf("error at line %d\n", __LINE__); test_failed = 1; @@ -310,18 +309,18 @@ void tstring_main(void) (void)strchr(tmp1, second_char); if (memcmp(tmp1, expected, i) || strcmp(tmp1, expected) || - strncmp(tmp1, expected, i) || - strncmp(tmp1, expected, i + 1) || - strcmp(tmp1, tmp2) >= 0 || memcmp(tmp1, tmp2, i) >= 0 || - strncmp(tmp1, tmp2, i + 1) >= 0 || - (int)strlen(tmp1) != i || memchr(tmp1, first_char, i) != tmp1 || - strchr(tmp1, first_char) != tmp1 || - memchr(tmp1, second_char, i) != tmp1 + z || - strchr(tmp1, second_char) != tmp1 + z || - strcmp(tmp5, tmp6) || - strncat(tmp7, tmp1, i + 2) != tmp7 || - strcmp(tmp7, tmp6) || - tmp7[2 * i + z] != second_char) + strncmp(tmp1, expected, i) || + strncmp(tmp1, expected, i + 1) || + strcmp(tmp1, tmp2) >= 0 || memcmp(tmp1, tmp2, i) >= 0 || + strncmp(tmp1, tmp2, i + 1) >= 0 || + (int)strlen(tmp1) != i || memchr(tmp1, first_char, i) != tmp1 || + strchr(tmp1, first_char) != tmp1 || + memchr(tmp1, second_char, i) != tmp1 + z || + strchr(tmp1, second_char) != tmp1 + z || + strcmp(tmp5, tmp6) || + strncat(tmp7, tmp1, i + 2) != tmp7 || + strcmp(tmp7, tmp6) || + tmp7[2 * i + z] != second_char) { eprintf(__LINE__, tmp1, expected, 0); printf("x is %d\n", x); @@ -335,7 +334,7 @@ void tstring_main(void) for (k = 1; k <= align_test_iterations && k <= i; ++k) { if (memcmp(tmp3, tmp4, i - k + 1) != 0 || - strncmp(tmp3, tmp4, i - k + 1) != 0) + strncmp(tmp3, tmp4, i - k + 1) != 0) { printf("Failure at line %d, comparing %.*s with %.*s\n", __LINE__, i, tmp3, i, tmp4); @@ -343,9 +342,9 @@ void tstring_main(void) } tmp4[i - k] = first_char + 1; if (memcmp(tmp3, tmp4, i) >= 0 || - strncmp(tmp3, tmp4, i) >= 0 || - memcmp(tmp4, tmp3, i) <= 0 || - strncmp(tmp4, tmp3, i) <= 0) + strncmp(tmp3, tmp4, i) >= 0 || + memcmp(tmp4, tmp3, i) <= 0 || + strncmp(tmp4, tmp3, i) <= 0) { printf("Failure at line %d, comparing %.*s with %.*s\n", __LINE__, i, tmp3, i, tmp4); diff --git a/tests/host/common/Arduino.cpp b/tests/host/common/Arduino.cpp index 3ca0670ae1..eca6b82d32 100644 --- a/tests/host/common/Arduino.cpp +++ b/tests/host/common/Arduino.cpp @@ -21,7 +21,7 @@ #include #include -static struct timeval gtod0 = { 0, 0 }; +static struct timeval gtod0 = {0, 0}; extern "C" unsigned long millis() { @@ -45,7 +45,6 @@ extern "C" unsigned long micros() return ((time.tv_sec - gtod0.tv_sec) * 1000000) + time.tv_usec - gtod0.tv_usec; } - extern "C" void yield() { run_scheduled_recurrent_functions(); diff --git a/tests/host/common/ArduinoCatch.cpp b/tests/host/common/ArduinoCatch.cpp index 1f09607f7b..e15ef335e4 100644 --- a/tests/host/common/ArduinoCatch.cpp +++ b/tests/host/common/ArduinoCatch.cpp @@ -14,7 +14,6 @@ */ #define CATCH_CONFIG_MAIN -#include #include +#include #include "Arduino.h" - diff --git a/tests/host/common/ArduinoMain.cpp b/tests/host/common/ArduinoMain.cpp index e4c966e29b..73ebbcf7e3 100644 --- a/tests/host/common/ArduinoMain.cpp +++ b/tests/host/common/ArduinoMain.cpp @@ -30,14 +30,14 @@ */ #include -#include // wifi_get_ip_info() +#include // wifi_get_ip_info() -#include -#include #include -#include +#include #include #include +#include +#include #define MOCK_PORT_SHIFTER 9000 @@ -83,10 +83,10 @@ static int mock_start_uart(void) } settings = initial_settings; settings.c_lflag &= ~(ignore_sigint ? ISIG : 0); - settings.c_lflag &= ~(ECHO | ICANON); + settings.c_lflag &= ~(ECHO | ICANON); settings.c_iflag &= ~(ICRNL | INLCR | ISTRIP | IXON); - settings.c_oflag |= (ONLCR); - settings.c_cc[VMIN] = 0; + settings.c_oflag |= (ONLCR); + settings.c_cc[VMIN] = 0; settings.c_cc[VTIME] = 0; if (tcsetattr(STDIN, TCSANOW, &settings) < 0) { @@ -113,7 +113,7 @@ static int mock_stop_uart(void) perror("restoring tty: tcsetattr(STDIN)"); return -1; } - printf("\e[?25h"); // show cursor + printf("\e[?25h"); // show cursor return (0); } @@ -145,26 +145,26 @@ void help(const char* argv0, int exitcode) "\t-c - ignore CTRL-C (send it via Serial)\n" "\t-f - no throttle (possibly 100%%CPU)\n" "\t-1 - run loop once then exit (for host testing)\n" - "\t-v - verbose\n" - , argv0, MOCK_PORT_SHIFTER, argv0, spiffs_kb, littlefs_kb); + "\t-v - verbose\n", + argv0, MOCK_PORT_SHIFTER, argv0, spiffs_kb, littlefs_kb); exit(exitcode); } static struct option options[] = -{ - { "help", no_argument, NULL, 'h' }, - { "fast", no_argument, NULL, 'f' }, - { "local", no_argument, NULL, 'l' }, - { "sigint", no_argument, NULL, 'c' }, - { "blockinguart", no_argument, NULL, 'b' }, - { "verbose", no_argument, NULL, 'v' }, - { "timestamp", no_argument, NULL, 'T' }, - { "interface", required_argument, NULL, 'i' }, - { "fspath", required_argument, NULL, 'P' }, - { "spiffskb", required_argument, NULL, 'S' }, - { "littlefskb", required_argument, NULL, 'L' }, - { "portshifter", required_argument, NULL, 's' }, - { "once", no_argument, NULL, '1' }, + { + {"help", no_argument, NULL, 'h'}, + {"fast", no_argument, NULL, 'f'}, + {"local", no_argument, NULL, 'l'}, + {"sigint", no_argument, NULL, 'c'}, + {"blockinguart", no_argument, NULL, 'b'}, + {"verbose", no_argument, NULL, 'v'}, + {"timestamp", no_argument, NULL, 'T'}, + {"interface", required_argument, NULL, 'i'}, + {"fspath", required_argument, NULL, 'P'}, + {"spiffskb", required_argument, NULL, 'S'}, + {"littlefskb", required_argument, NULL, 'L'}, + {"portshifter", required_argument, NULL, 's'}, + {"once", no_argument, NULL, '1'}, }; void cleanup() @@ -208,10 +208,10 @@ void control_c(int sig) user_exit = true; } -int main(int argc, char* const argv []) +int main(int argc, char* const argv[]) { bool fast = false; - blocking_uart = false; // global + blocking_uart = false; // global signal(SIGINT, control_c); signal(SIGTERM, control_c); @@ -233,47 +233,47 @@ int main(int argc, char* const argv []) } switch (n) { - case 'h': - help(argv[0], EXIT_SUCCESS); - break; - case 'i': - host_interface = optarg; - break; - case 'l': - global_ipv4_netfmt = NO_GLOBAL_BINDING; - break; - case 's': - mock_port_shifter = atoi(optarg); - break; - case 'c': - ignore_sigint = true; - break; - case 'f': - fast = true; - break; - case 'S': - spiffs_kb = atoi(optarg); - break; - case 'L': - littlefs_kb = atoi(optarg); - break; - case 'P': - fspath = optarg; - break; - case 'b': - blocking_uart = true; - break; - case 'v': - mockdebug = true; - break; - case 'T': - serial_timestamp = true; - break; - case '1': - run_once = true; - break; - default: - help(argv[0], EXIT_FAILURE); + case 'h': + help(argv[0], EXIT_SUCCESS); + break; + case 'i': + host_interface = optarg; + break; + case 'l': + global_ipv4_netfmt = NO_GLOBAL_BINDING; + break; + case 's': + mock_port_shifter = atoi(optarg); + break; + case 'c': + ignore_sigint = true; + break; + case 'f': + fast = true; + break; + case 'S': + spiffs_kb = atoi(optarg); + break; + case 'L': + littlefs_kb = atoi(optarg); + break; + case 'P': + fspath = optarg; + break; + case 'b': + blocking_uart = true; + break; + case 'v': + mockdebug = true; + break; + case 'T': + serial_timestamp = true; + break; + case '1': + run_once = true; + break; + default: + help(argv[0], EXIT_FAILURE); } } @@ -325,7 +325,7 @@ int main(int argc, char* const argv []) } if (!fast) { - usleep(1000); // not 100% cpu, ~1000 loops per second + usleep(1000); // not 100% cpu, ~1000 loops per second } loop(); loop_end(); diff --git a/tests/host/common/ArduinoMainLittlefs.cpp b/tests/host/common/ArduinoMainLittlefs.cpp index 36a685e50e..a9b7974cf5 100644 --- a/tests/host/common/ArduinoMainLittlefs.cpp +++ b/tests/host/common/ArduinoMainLittlefs.cpp @@ -16,4 +16,3 @@ void mock_stop_littlefs() } littlefs_mock = nullptr; } - diff --git a/tests/host/common/ArduinoMainSpiffs.cpp b/tests/host/common/ArduinoMainSpiffs.cpp index 27e34baee7..8530a316f0 100644 --- a/tests/host/common/ArduinoMainSpiffs.cpp +++ b/tests/host/common/ArduinoMainSpiffs.cpp @@ -16,4 +16,3 @@ void mock_stop_spiffs() } spiffs_mock = nullptr; } - diff --git a/tests/host/common/ClientContextSocket.cpp b/tests/host/common/ClientContextSocket.cpp index 063952ce24..70ec1d5216 100644 --- a/tests/host/common/ClientContextSocket.cpp +++ b/tests/host/common/ClientContextSocket.cpp @@ -31,13 +31,13 @@ */ // separated from lwIP to avoid type conflicts -#include -#include -#include #include -#include -#include #include +#include +#include +#include +#include +#include int mockSockSetup(int sock) { @@ -135,7 +135,7 @@ ssize_t mockPeekBytes(int sock, char* dst, size_t usersize, int timeout_ms, char } if (usersize == 0 && ccinbufsize) - // peekAvailable + // peekAvailable { return ccinbufsize; } @@ -178,7 +178,6 @@ ssize_t mockWrite(int sock, const uint8_t* data, size_t size, int timeout_ms) size_t sent = 0; while (sent < size) { - struct pollfd p; p.fd = sock; p.events = POLLOUT; diff --git a/tests/host/common/ClientContextTools.cpp b/tests/host/common/ClientContextTools.cpp index bf4bc348c0..2574c152d1 100644 --- a/tests/host/common/ClientContextTools.cpp +++ b/tests/host/common/ClientContextTools.cpp @@ -29,15 +29,15 @@ DEALINGS WITH THE SOFTWARE. */ -#include -#include -#include #include #include +#include +#include +#include -#include // gethostbyname +#include // gethostbyname -err_t dns_gethostbyname(const char *hostname, ip_addr_t *addr, dns_found_callback found, void *callback_arg) +err_t dns_gethostbyname(const char* hostname, ip_addr_t* addr, dns_found_callback found, void* callback_arg) { (void)callback_arg; (void)found; diff --git a/tests/host/common/EEPROM.h b/tests/host/common/EEPROM.h index 2e91bc10c1..faeafa590d 100644 --- a/tests/host/common/EEPROM.h +++ b/tests/host/common/EEPROM.h @@ -34,7 +34,7 @@ class EEPROMClass { -public: + public: EEPROMClass(uint32_t sector); EEPROMClass(void); ~EEPROMClass(); @@ -45,7 +45,7 @@ class EEPROMClass bool commit(); void end(); - template + template T& get(int const address, T& t) { if (address < 0 || address + sizeof(T) > _size) @@ -59,7 +59,7 @@ class EEPROMClass return t; } - template + template const T& put(int const address, const T& t) { if (address < 0 || address + sizeof(T) > _size) @@ -84,7 +84,7 @@ class EEPROMClass return read(address); } -protected: + protected: size_t _size = 0; int _fd = -1; }; diff --git a/tests/host/common/HostWiring.cpp b/tests/host/common/HostWiring.cpp index e5c84a40a6..b3c6b6eb9c 100644 --- a/tests/host/common/HostWiring.cpp +++ b/tests/host/common/HostWiring.cpp @@ -39,18 +39,36 @@ void pinMode(uint8_t pin, uint8_t mode) { -#define xxx(mode) case mode: m=STRHELPER(mode); break +#define xxx(mode) \ + case mode: \ + m = STRHELPER(mode); \ + break const char* m; switch (mode) { - case INPUT: m = "INPUT"; break; - case OUTPUT: m = "OUTPUT"; break; - case INPUT_PULLUP: m = "INPUT_PULLUP"; break; - case OUTPUT_OPEN_DRAIN: m = "OUTPUT_OPEN_DRAIN"; break; - case INPUT_PULLDOWN_16: m = "INPUT_PULLDOWN_16"; break; - case WAKEUP_PULLUP: m = "WAKEUP_PULLUP"; break; - case WAKEUP_PULLDOWN: m = "WAKEUP_PULLDOWN"; break; - default: m = "(special)"; + case INPUT: + m = "INPUT"; + break; + case OUTPUT: + m = "OUTPUT"; + break; + case INPUT_PULLUP: + m = "INPUT_PULLUP"; + break; + case OUTPUT_OPEN_DRAIN: + m = "OUTPUT_OPEN_DRAIN"; + break; + case INPUT_PULLDOWN_16: + m = "INPUT_PULLDOWN_16"; + break; + case WAKEUP_PULLUP: + m = "WAKEUP_PULLUP"; + break; + case WAKEUP_PULLDOWN: + m = "WAKEUP_PULLDOWN"; + break; + default: + m = "(special)"; } VERBOSE("gpio%d: mode='%s'\n", pin, m); } diff --git a/tests/host/common/MockDigital.cpp b/tests/host/common/MockDigital.cpp index a94e6f2f20..1c63a3b8df 100644 --- a/tests/host/common/MockDigital.cpp +++ b/tests/host/common/MockDigital.cpp @@ -19,17 +19,17 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #define ARDUINO_MAIN -#include "wiring_private.h" -#include "pins_arduino.h" #include "c_types.h" +#include "core_esp8266_waveform.h" #include "eagle_soc.h" #include "ets_sys.h" -#include "user_interface.h" -#include "core_esp8266_waveform.h" #include "interrupts.h" +#include "pins_arduino.h" +#include "user_interface.h" +#include "wiring_private.h" -extern "C" { - +extern "C" +{ static uint8_t _mode[17]; static uint8_t _gpio[17]; @@ -60,5 +60,4 @@ extern "C" { return 0; } } - }; diff --git a/tests/host/common/MockEEPROM.cpp b/tests/host/common/MockEEPROM.cpp index a4d7e4ac43..e28114a714 100644 --- a/tests/host/common/MockEEPROM.cpp +++ b/tests/host/common/MockEEPROM.cpp @@ -34,11 +34,11 @@ #include -#include +#include #include -#include +#include #include -#include +#include #define EEPROM_FILE_NAME "eeprom" @@ -57,8 +57,7 @@ EEPROMClass::~EEPROMClass() void EEPROMClass::begin(size_t size) { _size = size; - if ((_fd = open(EEPROM_FILE_NAME, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1 - || ftruncate(_fd, size) == -1) + if ((_fd = open(EEPROM_FILE_NAME, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1 || ftruncate(_fd, size) == -1) { fprintf(stderr, MOCK "EEPROM: cannot open/create '%s' for r/w: %s\n\r", EEPROM_FILE_NAME, strerror(errno)); _fd = -1; diff --git a/tests/host/common/MockEsp.cpp b/tests/host/common/MockEsp.cpp index 09e6c9d000..f61333273f 100644 --- a/tests/host/common/MockEsp.cpp +++ b/tests/host/common/MockEsp.cpp @@ -103,7 +103,7 @@ uint32_t EspClass::getChipId() bool EspClass::checkFlashConfig(bool needsEquals) { - (void) needsEquals; + (void)needsEquals; return true; } @@ -132,7 +132,7 @@ uint32_t EspClass::getFreeSketchSpace() return 4 * 1024 * 1024; } -const char *EspClass::getSdkVersion() +const char* EspClass::getSdkVersion() { return "2.5.0"; } @@ -163,7 +163,7 @@ void EspClass::getHeapStats(uint32_t* hfree, uint16_t* hmax, uint8_t* hfrag) bool EspClass::flashEraseSector(uint32_t sector) { - (void) sector; + (void)sector; return true; } @@ -174,11 +174,11 @@ FlashMode_t EspClass::getFlashChipMode() FlashMode_t EspClass::magicFlashChipMode(uint8_t byte) { - (void) byte; + (void)byte; return FM_DOUT; } -bool EspClass::flashWrite(uint32_t offset, const uint32_t *data, size_t size) +bool EspClass::flashWrite(uint32_t offset, const uint32_t* data, size_t size) { (void)offset; (void)data; @@ -186,7 +186,7 @@ bool EspClass::flashWrite(uint32_t offset, const uint32_t *data, size_t size) return true; } -bool EspClass::flashWrite(uint32_t offset, const uint8_t *data, size_t size) +bool EspClass::flashWrite(uint32_t offset, const uint8_t* data, size_t size) { (void)offset; (void)data; @@ -194,7 +194,7 @@ bool EspClass::flashWrite(uint32_t offset, const uint8_t *data, size_t size) return true; } -bool EspClass::flashRead(uint32_t offset, uint32_t *data, size_t size) +bool EspClass::flashRead(uint32_t offset, uint32_t* data, size_t size) { (void)offset; (void)data; @@ -202,7 +202,7 @@ bool EspClass::flashRead(uint32_t offset, uint32_t *data, size_t size) return true; } -bool EspClass::flashRead(uint32_t offset, uint8_t *data, size_t size) +bool EspClass::flashRead(uint32_t offset, uint8_t* data, size_t size) { (void)offset; (void)data; @@ -214,22 +214,22 @@ uint32_t EspClass::magicFlashChipSize(uint8_t byte) { switch (byte & 0x0F) { - case 0x0: // 4 Mbit (512KB) - return (512_kB); - case 0x1: // 2 MBit (256KB) - return (256_kB); - case 0x2: // 8 MBit (1MB) - return (1_MB); - case 0x3: // 16 MBit (2MB) - return (2_MB); - case 0x4: // 32 MBit (4MB) - return (4_MB); - case 0x8: // 64 MBit (8MB) - return (8_MB); - case 0x9: // 128 MBit (16MB) - return (16_MB); - default: // fail? - return 0; + case 0x0: // 4 Mbit (512KB) + return (512_kB); + case 0x1: // 2 MBit (256KB) + return (256_kB); + case 0x2: // 8 MBit (1MB) + return (1_MB); + case 0x3: // 16 MBit (2MB) + return (2_MB); + case 0x4: // 32 MBit (4MB) + return (4_MB); + case 0x8: // 64 MBit (8MB) + return (8_MB); + case 0x9: // 128 MBit (16MB) + return (16_MB); + default: // fail? + return 0; } } diff --git a/tests/host/common/MockTools.cpp b/tests/host/common/MockTools.cpp index a41b7521bc..4a469053f6 100644 --- a/tests/host/common/MockTools.cpp +++ b/tests/host/common/MockTools.cpp @@ -34,7 +34,6 @@ extern "C" { - uint32_t lwip_htonl(uint32_t hostlong) { return htonl(hostlong); @@ -74,9 +73,9 @@ extern "C" return len; } - void stack_thunk_add_ref() { } - void stack_thunk_del_ref() { } - void stack_thunk_repaint() { } + void stack_thunk_add_ref() {} + void stack_thunk_del_ref() {} + void stack_thunk_repaint() {} uint32_t stack_thunk_get_refcnt() { @@ -98,15 +97,13 @@ extern "C" { return 0; } - void stack_thunk_dump_stack() { } + void stack_thunk_dump_stack() {} // Thunking macro #define make_stack_thunk(fcnToThunk) - }; -void configTime(int timezone, int daylightOffset_sec, - const char* server1, const char* server2, const char* server3) +void configTime(int timezone, int daylightOffset_sec, const char* server1, const char* server2, const char* server3) { (void)server1; (void)server2; diff --git a/tests/host/common/MockUART.cpp b/tests/host/common/MockUART.cpp index 19d234cbb9..eec93ca590 100644 --- a/tests/host/common/MockUART.cpp +++ b/tests/host/common/MockUART.cpp @@ -28,29 +28,29 @@ is responsible for feeding the RX FIFO new data by calling uart_new_data(). */ -#include // write -#include // gettimeofday -#include // localtime +#include // gettimeofday +#include // localtime +#include // write #include "Arduino.h" #include "uart.h" //#define UART_DISCARD_NEWEST -extern "C" { - - bool blocking_uart = true; // system default +extern "C" +{ + bool blocking_uart = true; // system default static int s_uart_debug_nr = UART1; - static uart_t *UART[2] = { NULL, NULL }; + static uart_t* UART[2] = {NULL, NULL}; struct uart_rx_buffer_ { size_t size; size_t rpos; size_t wpos; - uint8_t * buffer; + uint8_t* buffer; }; struct uart_ @@ -60,7 +60,7 @@ extern "C" { bool rx_enabled; bool tx_enabled; bool rx_overrun; - struct uart_rx_buffer_ * rx_buffer; + struct uart_rx_buffer_* rx_buffer; }; bool serial_timestamp = false; @@ -101,7 +101,7 @@ extern "C" { static void uart_handle_data(uart_t* uart, uint8_t data) { - struct uart_rx_buffer_ *rx_buffer = uart->rx_buffer; + struct uart_rx_buffer_* rx_buffer = uart->rx_buffer; size_t nextPos = (rx_buffer->wpos + 1) % rx_buffer->size; if (nextPos == rx_buffer->rpos) @@ -135,7 +135,7 @@ extern "C" { } static size_t - uart_rx_available_unsafe(const struct uart_rx_buffer_ * rx_buffer) + uart_rx_available_unsafe(const struct uart_rx_buffer_* rx_buffer) { size_t ret = rx_buffer->wpos - rx_buffer->rpos; @@ -222,9 +222,7 @@ extern "C" { { // pour sw buffer to user's buffer // get largest linear length from sw buffer - size_t chunk = uart->rx_buffer->rpos < uart->rx_buffer->wpos ? - uart->rx_buffer->wpos - uart->rx_buffer->rpos : - uart->rx_buffer->size - uart->rx_buffer->rpos; + size_t chunk = uart->rx_buffer->rpos < uart->rx_buffer->wpos ? uart->rx_buffer->wpos - uart->rx_buffer->rpos : uart->rx_buffer->size - uart->rx_buffer->rpos; if (ret + chunk > usersize) { chunk = usersize - ret; @@ -249,7 +247,7 @@ extern "C" { return uart->rx_buffer->size; } - uint8_t * new_buf = (uint8_t*)malloc(new_size); + uint8_t* new_buf = (uint8_t*)malloc(new_size); if (!new_buf) { return uart->rx_buffer->size; @@ -266,7 +264,7 @@ extern "C" { new_wpos = 0; } - uint8_t * old_buf = uart->rx_buffer->buffer; + uint8_t* old_buf = uart->rx_buffer->buffer; uart->rx_buffer->rpos = 0; uart->rx_buffer->wpos = new_wpos; uart->rx_buffer->size = new_size; @@ -326,7 +324,7 @@ extern "C" { void uart_wait_tx_empty(uart_t* uart) { - (void) uart; + (void)uart; } void @@ -378,10 +376,10 @@ extern "C" { uart_t* uart_init(int uart_nr, int baudrate, int config, int mode, int tx_pin, size_t rx_size, bool invert) { - (void) config; - (void) tx_pin; - (void) invert; - uart_t* uart = (uart_t*) malloc(sizeof(uart_t)); + (void)config; + (void)tx_pin; + (void)invert; + uart_t* uart = (uart_t*)malloc(sizeof(uart_t)); if (uart == NULL) { return NULL; @@ -392,42 +390,42 @@ extern "C" { switch (uart->uart_nr) { - case UART0: - uart->rx_enabled = (mode != UART_TX_ONLY); - uart->tx_enabled = (mode != UART_RX_ONLY); - if (uart->rx_enabled) - { - struct uart_rx_buffer_ * rx_buffer = (struct uart_rx_buffer_ *)malloc(sizeof(struct uart_rx_buffer_)); - if (rx_buffer == NULL) + case UART0: + uart->rx_enabled = (mode != UART_TX_ONLY); + uart->tx_enabled = (mode != UART_RX_ONLY); + if (uart->rx_enabled) { - free(uart); - return NULL; + struct uart_rx_buffer_* rx_buffer = (struct uart_rx_buffer_*)malloc(sizeof(struct uart_rx_buffer_)); + if (rx_buffer == NULL) + { + free(uart); + return NULL; + } + rx_buffer->size = rx_size; //var this + rx_buffer->rpos = 0; + rx_buffer->wpos = 0; + rx_buffer->buffer = (uint8_t*)malloc(rx_buffer->size); + if (rx_buffer->buffer == NULL) + { + free(rx_buffer); + free(uart); + return NULL; + } + uart->rx_buffer = rx_buffer; } - rx_buffer->size = rx_size;//var this - rx_buffer->rpos = 0; - rx_buffer->wpos = 0; - rx_buffer->buffer = (uint8_t *)malloc(rx_buffer->size); - if (rx_buffer->buffer == NULL) - { - free(rx_buffer); - free(uart); - return NULL; - } - uart->rx_buffer = rx_buffer; - } - break; - - case UART1: - // Note: uart_interrupt_handler does not support RX on UART 1. - uart->rx_enabled = false; - uart->tx_enabled = (mode != UART_RX_ONLY); - break; - - case UART_NO: - default: - // big fail! - free(uart); - return NULL; + break; + + case UART1: + // Note: uart_interrupt_handler does not support RX on UART 1. + uart->rx_enabled = false; + uart->tx_enabled = (mode != UART_RX_ONLY); + break; + + case UART_NO: + default: + // big fail! + free(uart); + return NULL; } uart_set_baudrate(uart, baudrate); @@ -456,25 +454,25 @@ extern "C" { bool uart_swap(uart_t* uart, int tx_pin) { - (void) uart; - (void) tx_pin; + (void)uart; + (void)tx_pin; return true; } bool uart_set_tx(uart_t* uart, int tx_pin) { - (void) uart; - (void) tx_pin; + (void)uart; + (void)tx_pin; return true; } bool uart_set_pins(uart_t* uart, int tx, int rx) { - (void) uart; - (void) tx; - (void) rx; + (void)uart; + (void)tx; + (void)rx; return true; } @@ -516,7 +514,7 @@ extern "C" { bool uart_has_rx_error(uart_t* uart) { - (void) uart; + (void)uart; return false; } @@ -535,19 +533,17 @@ extern "C" { void uart_start_detect_baudrate(int uart_nr) { - (void) uart_nr; + (void)uart_nr; } int uart_detect_baudrate(int uart_nr) { - (void) uart_nr; + (void)uart_nr; return 115200; } - }; - size_t uart_peek_available(uart_t* uart) { return 0; @@ -561,4 +557,3 @@ void uart_peek_consume(uart_t* uart, size_t consume) (void)uart; (void)consume; } - diff --git a/tests/host/common/MockWiFiServer.cpp b/tests/host/common/MockWiFiServer.cpp index 3c74927af0..791952fe06 100644 --- a/tests/host/common/MockWiFiServer.cpp +++ b/tests/host/common/MockWiFiServer.cpp @@ -74,4 +74,3 @@ WiFiClient WiFiServer::accept() #include uint32_t UdpContext::staticMCastAddr = 0; - diff --git a/tests/host/common/MockWiFiServerSocket.cpp b/tests/host/common/MockWiFiServerSocket.cpp index 3eff34bfff..4d1254fc73 100644 --- a/tests/host/common/MockWiFiServerSocket.cpp +++ b/tests/host/common/MockWiFiServerSocket.cpp @@ -32,12 +32,12 @@ #include #include -#include -#include +#include +#include #include +#include +#include #include -#include -#include #define int2pcb(x) ((tcp_pcb*)(intptr_t)(x)) #define pcb2int(x) ((int)(intptr_t)(x)) @@ -118,7 +118,6 @@ void WiFiServer::begin() exit(EXIT_FAILURE); } - // store int into pointer _listen_pcb = int2pcb(sock); } diff --git a/tests/host/common/MocklwIP.cpp b/tests/host/common/MocklwIP.cpp index 0b98243217..0b5dfa502b 100644 --- a/tests/host/common/MocklwIP.cpp +++ b/tests/host/common/MocklwIP.cpp @@ -7,12 +7,11 @@ esp8266::AddressListImplementation::AddressList addrList; extern "C" { - extern netif netif0; netif* netif_list = &netif0; - err_t dhcp_renew(struct netif *netif) + err_t dhcp_renew(struct netif* netif) { (void)netif; return ERR_OK; @@ -27,7 +26,7 @@ extern "C" return IP_ADDR_ANY; } - err_t etharp_request(struct netif *netif, const ip4_addr_t *ipaddr) + err_t etharp_request(struct netif* netif, const ip4_addr_t* ipaddr) { (void)netif; (void)ipaddr; @@ -40,14 +39,14 @@ extern "C" return ERR_OK; } - err_t igmp_joingroup_netif(struct netif *netif, const ip4_addr_t *groupaddr) + err_t igmp_joingroup_netif(struct netif* netif, const ip4_addr_t* groupaddr) { (void)netif; (void)groupaddr; return ERR_OK; } - err_t igmp_leavegroup_netif(struct netif *netif, const ip4_addr_t *groupaddr) + err_t igmp_leavegroup_netif(struct netif* netif, const ip4_addr_t* groupaddr) { (void)netif; (void)groupaddr; @@ -60,5 +59,4 @@ extern "C" return &netif0; } - -} // extern "C" +} // extern "C" diff --git a/tests/host/common/MocklwIP.h b/tests/host/common/MocklwIP.h index 47c3d06c6e..19ded4b26a 100644 --- a/tests/host/common/MocklwIP.h +++ b/tests/host/common/MocklwIP.h @@ -4,12 +4,11 @@ extern "C" { - -#include #include +#include extern netif netif0; -} // extern "C" +} // extern "C" -#endif // __MOCKLWIP_H +#endif // __MOCKLWIP_H diff --git a/tests/host/common/UdpContextSocket.cpp b/tests/host/common/UdpContextSocket.cpp index 23f2883c11..ef2294d6b8 100644 --- a/tests/host/common/UdpContextSocket.cpp +++ b/tests/host/common/UdpContextSocket.cpp @@ -29,15 +29,15 @@ DEALINGS WITH THE SOFTWARE. */ -#include -#include -#include #include -#include -#include -#include #include +#include +#include #include +#include +#include +#include +#include int mockUDPSocket() { @@ -82,13 +82,13 @@ bool mockUDPListen(int sock, uint32_t dstaddr, uint16_t port, uint32_t mcast) // Filling server information servaddr.sin_family = AF_INET; - (void) dstaddr; + (void)dstaddr; //servaddr.sin_addr.s_addr = htonl(global_source_address); servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(mockport); // Bind the socket with the server address - if (bind(sock, (const struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) + if (bind(sock, (const struct sockaddr*)&servaddr, sizeof(servaddr)) < 0) { fprintf(stderr, MOCK "UDP bind on port %d failed: %s\n", mockport, strerror(errno)); return false; @@ -100,7 +100,7 @@ bool mockUDPListen(int sock, uint32_t dstaddr, uint16_t port, uint32_t mcast) if (!mcast) { - mcast = inet_addr("224.0.0.1"); // all hosts group + mcast = inet_addr("224.0.0.1"); // all hosts group } if (mcast) { @@ -141,14 +141,13 @@ bool mockUDPListen(int sock, uint32_t dstaddr, uint16_t port, uint32_t mcast) return true; } - size_t mockUDPFillInBuf(int sock, char* ccinbuf, size_t& ccinbufsize, uint8_t& addrsize, uint8_t addr[16], uint16_t& port) { struct sockaddr_storage addrbuf; socklen_t addrbufsize = std::min((socklen_t)sizeof(addrbuf), (socklen_t)16); size_t maxread = CCBUFSIZE - ccinbufsize; - ssize_t ret = ::recvfrom(sock, ccinbuf + ccinbufsize, maxread, 0/*flags*/, (sockaddr*)&addrbuf, &addrbufsize); + ssize_t ret = ::recvfrom(sock, ccinbuf + ccinbufsize, maxread, 0 /*flags*/, (sockaddr*)&addrbuf, &addrbufsize); if (ret == -1) { if (errno != EAGAIN) @@ -177,8 +176,8 @@ size_t mockUDPFillInBuf(int sock, char* ccinbuf, size_t& ccinbufsize, uint8_t& a size_t mockUDPPeekBytes(int sock, char* dst, size_t usersize, int timeout_ms, char* ccinbuf, size_t& ccinbufsize) { - (void) sock; - (void) timeout_ms; + (void)sock; + (void)timeout_ms; if (usersize > CCBUFSIZE) { fprintf(stderr, MOCK "CCBUFSIZE(%d) should be increased by %zd bytes (-> %zd)\n", CCBUFSIZE, usersize - CCBUFSIZE, usersize); @@ -214,13 +213,13 @@ size_t mockUDPRead(int sock, char* dst, size_t size, int timeout_ms, char* ccinb size_t mockUDPWrite(int sock, const uint8_t* data, size_t size, int timeout_ms, uint32_t ipv4, uint16_t port) { - (void) timeout_ms; + (void)timeout_ms; // Filling server information struct sockaddr_in peer; peer.sin_family = AF_INET; - peer.sin_addr.s_addr = ipv4; //XXFIXME should use lwip_htonl? + peer.sin_addr.s_addr = ipv4; //XXFIXME should use lwip_htonl? peer.sin_port = htons(port); - int ret = ::sendto(sock, data, size, 0/*flags*/, (const sockaddr*)&peer, sizeof(peer)); + int ret = ::sendto(sock, data, size, 0 /*flags*/, (const sockaddr*)&peer, sizeof(peer)); if (ret == -1) { fprintf(stderr, MOCK "UDPContext::write: write(%d): %s\n", sock, strerror(errno)); diff --git a/tests/host/common/WMath.cpp b/tests/host/common/WMath.cpp index 8409941db4..dbfce37eb9 100644 --- a/tests/host/common/WMath.cpp +++ b/tests/host/common/WMath.cpp @@ -23,9 +23,10 @@ $Id$ */ -extern "C" { -#include +extern "C" +{ #include +#include } void randomSeed(unsigned long seed) diff --git a/tests/host/common/c_types.h b/tests/host/common/c_types.h index c57b64dd91..fcf7a889a1 100644 --- a/tests/host/common/c_types.h +++ b/tests/host/common/c_types.h @@ -31,46 +31,46 @@ #ifndef _C_TYPES_H_ #define _C_TYPES_H_ -#include -#include #include +#include +#include #include -typedef signed char sint8_t; -typedef signed short sint16_t; -typedef signed long sint32_t; -typedef signed long long sint64_t; +typedef signed char sint8_t; +typedef signed short sint16_t; +typedef signed long sint32_t; +typedef signed long long sint64_t; // CONFLICT typedef unsigned long long u_int64_t; -typedef float real32_t; -typedef double real64_t; +typedef float real32_t; +typedef double real64_t; // CONFLICT typedef unsigned char uint8; -typedef unsigned char u8; -typedef signed char sint8; -typedef signed char int8; -typedef signed char s8; -typedef unsigned short uint16; -typedef unsigned short u16; -typedef signed short sint16; -typedef signed short s16; +typedef unsigned char u8; +typedef signed char sint8; +typedef signed char int8; +typedef signed char s8; +typedef unsigned short uint16; +typedef unsigned short u16; +typedef signed short sint16; +typedef signed short s16; // CONFLICT typedef unsigned int uint32; -typedef unsigned int u_int; -typedef unsigned int u32; -typedef signed int sint32; -typedef signed int s32; -typedef int int32; -typedef signed long long sint64; -typedef unsigned long long uint64; -typedef unsigned long long u64; -typedef float real32; -typedef double real64; +typedef unsigned int u_int; +typedef unsigned int u32; +typedef signed int sint32; +typedef signed int s32; +typedef int int32; +typedef signed long long sint64; +typedef unsigned long long uint64; +typedef unsigned long long u64; +typedef float real32; +typedef double real64; -#define __le16 u16 +#define __le16 u16 -#define LOCAL static +#define LOCAL static #ifndef NULL -#define NULL (void *)0 +#define NULL (void*)0 #endif /* NULL */ /* probably should not put STATUS here */ @@ -83,10 +83,10 @@ typedef enum CANCEL, } STATUS; -#define BIT(nr) (1UL << (nr)) +#define BIT(nr) (1UL << (nr)) -#define REG_SET_BIT(_r, _b) (*(volatile uint32_t*)(_r) |= (_b)) -#define REG_CLR_BIT(_r, _b) (*(volatile uint32_t*)(_r) &= ~(_b)) +#define REG_SET_BIT(_r, _b) (*(volatile uint32_t*)(_r) |= (_b)) +#define REG_CLR_BIT(_r, _b) (*(volatile uint32_t*)(_r) &= ~(_b)) #define DMEM_ATTR __attribute__((section(".bss"))) #define SHMEM_ATTR @@ -94,9 +94,9 @@ typedef enum #ifdef ICACHE_FLASH #define __ICACHE_STRINGIZE_NX(A) #A #define __ICACHE_STRINGIZE(A) __ICACHE_STRINGIZE_NX(A) -#define ICACHE_FLASH_ATTR __attribute__((section("\".irom0.text." __FILE__ "." __ICACHE_STRINGIZE(__LINE__) "." __ICACHE_STRINGIZE(__COUNTER__) "\""))) -#define IRAM_ATTR __attribute__((section("\".iram.text." __FILE__ "." __ICACHE_STRINGIZE(__LINE__) "." __ICACHE_STRINGIZE(__COUNTER__) "\""))) -#define ICACHE_RODATA_ATTR __attribute__((section("\".irom.text." __FILE__ "." __ICACHE_STRINGIZE(__LINE__) "." __ICACHE_STRINGIZE(__COUNTER__) "\""))) +#define ICACHE_FLASH_ATTR __attribute__((section("\".irom0.text." __FILE__ "." __ICACHE_STRINGIZE(__LINE__) "." __ICACHE_STRINGIZE(__COUNTER__) "\""))) +#define IRAM_ATTR __attribute__((section("\".iram.text." __FILE__ "." __ICACHE_STRINGIZE(__LINE__) "." __ICACHE_STRINGIZE(__COUNTER__) "\""))) +#define ICACHE_RODATA_ATTR __attribute__((section("\".irom.text." __FILE__ "." __ICACHE_STRINGIZE(__LINE__) "." __ICACHE_STRINGIZE(__COUNTER__) "\""))) #else #define ICACHE_FLASH_ATTR #define IRAM_ATTR @@ -109,10 +109,9 @@ typedef enum #define STORE_ATTR __attribute__((aligned(4))) #ifndef __cplusplus -#define BOOL bool -#define TRUE true -#define FALSE false - +#define BOOL bool +#define TRUE true +#define FALSE false #endif /* !__cplusplus */ diff --git a/tests/host/common/flash_hal_mock.cpp b/tests/host/common/flash_hal_mock.cpp index 10b9dba023..396d2c6362 100644 --- a/tests/host/common/flash_hal_mock.cpp +++ b/tests/host/common/flash_hal_mock.cpp @@ -12,13 +12,13 @@ extern "C" uint8_t* s_phys_data = nullptr; } -int32_t flash_hal_read(uint32_t addr, uint32_t size, uint8_t *dst) +int32_t flash_hal_read(uint32_t addr, uint32_t size, uint8_t* dst) { memcpy(dst, s_phys_data + addr, size); return 0; } -int32_t flash_hal_write(uint32_t addr, uint32_t size, const uint8_t *src) +int32_t flash_hal_write(uint32_t addr, uint32_t size, const uint8_t* src) { memcpy(s_phys_data + addr, src, size); return 0; @@ -27,7 +27,7 @@ int32_t flash_hal_write(uint32_t addr, uint32_t size, const uint8_t *src) int32_t flash_hal_erase(uint32_t addr, uint32_t size) { if ((size & (FLASH_SECTOR_SIZE - 1)) != 0 || - (addr & (FLASH_SECTOR_SIZE - 1)) != 0) + (addr & (FLASH_SECTOR_SIZE - 1)) != 0) { abort(); } diff --git a/tests/host/common/flash_hal_mock.h b/tests/host/common/flash_hal_mock.h index af5035eaa5..bacd375e2e 100644 --- a/tests/host/common/flash_hal_mock.h +++ b/tests/host/common/flash_hal_mock.h @@ -12,8 +12,8 @@ extern "C" extern uint8_t* s_phys_data; } -extern int32_t flash_hal_read(uint32_t addr, uint32_t size, uint8_t *dst); -extern int32_t flash_hal_write(uint32_t addr, uint32_t size, const uint8_t *src); +extern int32_t flash_hal_read(uint32_t addr, uint32_t size, uint8_t* dst); +extern int32_t flash_hal_write(uint32_t addr, uint32_t size, const uint8_t* src); extern int32_t flash_hal_erase(uint32_t addr, uint32_t size); #endif diff --git a/tests/host/common/include/ClientContext.h b/tests/host/common/include/ClientContext.h index 0c06c889ff..357c0b5b8c 100644 --- a/tests/host/common/include/ClientContext.h +++ b/tests/host/common/include/ClientContext.h @@ -32,17 +32,15 @@ typedef void (*discard_cb_t)(void*, ClientContext*); class ClientContext { -public: - ClientContext(tcp_pcb* pcb, discard_cb_t discard_cb, void* discard_cb_arg) : - _discard_cb(discard_cb), _discard_cb_arg(discard_cb_arg), _refcnt(0), _next(0), - _sync(::getDefaultPrivateGlobalSyncValue()), _sock(-1) + public: + ClientContext(tcp_pcb* pcb, discard_cb_t discard_cb, void* discard_cb_arg) + : _discard_cb(discard_cb), _discard_cb_arg(discard_cb_arg), _refcnt(0), _next(0), _sync(::getDefaultPrivateGlobalSyncValue()), _sock(-1) { (void)pcb; } - ClientContext(int sock) : - _discard_cb(nullptr), _discard_cb_arg(nullptr), _refcnt(0), _next(nullptr), - _sync(::getDefaultPrivateGlobalSyncValue()), _sock(sock) + ClientContext(int sock) + : _discard_cb(nullptr), _discard_cb_arg(nullptr), _refcnt(0), _next(nullptr), _sync(::getDefaultPrivateGlobalSyncValue()), _sock(sock) { } @@ -199,7 +197,7 @@ class ClientContext return peekBytes(&c, 1) ? c : -1; } - size_t peekBytes(char *dst, size_t size) + size_t peekBytes(char* dst, size_t size) { ssize_t ret = mockPeekBytes(_sock, dst, size, _timeout_ms, _inbuf, _inbufsize); if (ret < 0) @@ -223,7 +221,7 @@ class ClientContext uint8_t state() { - (void)getSize(); // read on socket to force detect closed peer + (void)getSize(); // read on socket to force detect closed peer return _sock >= 0 ? ESTABLISHED : CLOSED; } @@ -240,9 +238,9 @@ class ClientContext void keepAlive(uint16_t idle_sec = TCP_DEFAULT_KEEPALIVE_IDLE_SEC, uint16_t intv_sec = TCP_DEFAULT_KEEPALIVE_INTERVAL_SEC, uint8_t count = TCP_DEFAULT_KEEPALIVE_COUNT) { - (void) idle_sec; - (void) intv_sec; - (void) count; + (void)idle_sec; + (void)intv_sec; + (void)count; mockverbose("TODO ClientContext::keepAlive()\n"); } @@ -309,8 +307,7 @@ class ClientContext _inbufsize -= consume; } -private: - + private: discard_cb_t _discard_cb = nullptr; void* _discard_cb_arg = nullptr; @@ -324,8 +321,8 @@ class ClientContext int _sock = -1; int _timeout_ms = 5000; - char _inbuf [CCBUFSIZE]; + char _inbuf[CCBUFSIZE]; size_t _inbufsize = 0; }; -#endif //CLIENTCONTEXT_H +#endif //CLIENTCONTEXT_H diff --git a/tests/host/common/include/UdpContext.h b/tests/host/common/include/UdpContext.h index 725ce89ca1..238d068cfc 100644 --- a/tests/host/common/include/UdpContext.h +++ b/tests/host/common/include/UdpContext.h @@ -23,8 +23,8 @@ #include -#include #include +#include #include class UdpContext; @@ -36,11 +36,11 @@ extern netif netif0; class UdpContext { -public: - + public: typedef std::function rxhandler_t; - UdpContext(): _on_rx(nullptr), _refcnt(0) + UdpContext() + : _on_rx(nullptr), _refcnt(0) { _sock = mockUDPSocket(); } @@ -156,13 +156,13 @@ class UdpContext IPAddress getDestAddress() { mockverbose("TODO: implement UDP getDestAddress\n"); - return 0; //ip_hdr* iphdr = GET_IP_HDR(_rx_buf); + return 0; //ip_hdr* iphdr = GET_IP_HDR(_rx_buf); } uint16_t getLocalPort() { mockverbose("TODO: implement UDP getLocalPort\n"); - return 0; // + return 0; // } bool next() @@ -191,7 +191,7 @@ class UdpContext int peek() { char c; - return mockUDPPeekBytes(_sock, &c, 1, _timeout_ms, _inbuf, _inbufsize) ? : -1; + return mockUDPPeekBytes(_sock, &c, 1, _timeout_ms, _inbuf, _inbufsize) ?: -1; } void flush() @@ -218,7 +218,7 @@ class UdpContext err_t trySend(ip_addr_t* addr = 0, uint16_t port = 0, bool keepBuffer = true) { uint32_t dst = addr ? addr->addr : _dst.addr; - uint16_t dstport = port ? : _dstport; + uint16_t dstport = port ?: _dstport; size_t wrt = mockUDPWrite(_sock, (const uint8_t*)_outbuf, _outbufsize, _timeout_ms, dst, dstport); err_t ret = _outbufsize ? ERR_OK : ERR_ABRT; if (!keepBuffer || wrt == _outbufsize) @@ -238,8 +238,7 @@ class UdpContext return trySend(addr, port, false) == ERR_OK; } - bool sendTimeout(ip_addr_t* addr, uint16_t port, - esp8266::polledTimeout::oneShotFastMs::timeType timeoutMs) + bool sendTimeout(ip_addr_t* addr, uint16_t port, esp8266::polledTimeout::oneShotFastMs::timeType timeoutMs) { err_t err; esp8266::polledTimeout::oneShotFastMs timeout(timeoutMs); @@ -262,12 +261,10 @@ class UdpContext } } -public: - + public: static uint32_t staticMCastAddr; -private: - + private: void translate_addr() { if (addrsize == 4) @@ -291,9 +288,9 @@ class UdpContext ip_addr_t _dst; uint16_t _dstport; - char _inbuf [CCBUFSIZE]; + char _inbuf[CCBUFSIZE]; size_t _inbufsize = 0; - char _outbuf [CCBUFSIZE]; + char _outbuf[CCBUFSIZE]; size_t _outbufsize = 0; int _timeout_ms = 0; @@ -302,11 +299,11 @@ class UdpContext uint8_t addr[16]; }; -extern "C" inline err_t igmp_joingroup(const ip4_addr_t *ifaddr, const ip4_addr_t *groupaddr) +extern "C" inline err_t igmp_joingroup(const ip4_addr_t* ifaddr, const ip4_addr_t* groupaddr) { (void)ifaddr; UdpContext::staticMCastAddr = groupaddr->addr; return ERR_OK; } -#endif//UDPCONTEXT_H +#endif //UDPCONTEXT_H diff --git a/tests/host/common/littlefs_mock.cpp b/tests/host/common/littlefs_mock.cpp index 8377eb3b80..a32b12cd79 100644 --- a/tests/host/common/littlefs_mock.cpp +++ b/tests/host/common/littlefs_mock.cpp @@ -16,20 +16,19 @@ all copies or substantial portions of the Software. */ - #include "littlefs_mock.h" -#include "spiffs_mock.h" -#include "spiffs/spiffs.h" -#include "debug.h" +#include #include #include -#include +#include "debug.h" +#include "spiffs/spiffs.h" +#include "spiffs_mock.h" #include -#include -#include #include +#include +#include #include #include #include "flash_hal_mock.h" @@ -49,11 +48,11 @@ LittleFSMock::LittleFSMock(ssize_t fs_size, size_t fs_block, size_t fs_page, con fprintf(stderr, "LittleFS: %zd bytes\n", fs_size); m_fs.resize(fs_size, 0xff); - s_phys_addr = 0; - s_phys_size = static_cast(fs_size); - s_phys_page = static_cast(fs_page); + s_phys_addr = 0; + s_phys_size = static_cast(fs_size); + s_phys_page = static_cast(fs_page); s_phys_block = static_cast(fs_block); - s_phys_data = m_fs.data(); + s_phys_data = m_fs.data(); reset(); } @@ -66,11 +65,11 @@ void LittleFSMock::reset() LittleFSMock::~LittleFSMock() { save(); - s_phys_addr = 0; - s_phys_size = 0; - s_phys_page = 0; + s_phys_addr = 0; + s_phys_size = 0; + s_phys_page = 0; s_phys_block = 0; - s_phys_data = nullptr; + s_phys_data = nullptr; m_fs.resize(0); LittleFS = FS(FSImplPtr(nullptr)); } @@ -90,7 +89,7 @@ void LittleFSMock::load() } off_t flen = lseek(fs, 0, SEEK_END); - if (flen == (off_t) -1) + if (flen == (off_t)-1) { fprintf(stderr, "LittleFS: checking size of '%s': %s\n", m_storage.c_str(), strerror(errno)); return; diff --git a/tests/host/common/littlefs_mock.h b/tests/host/common/littlefs_mock.h index 283a61f1b5..df6f47f785 100644 --- a/tests/host/common/littlefs_mock.h +++ b/tests/host/common/littlefs_mock.h @@ -19,22 +19,22 @@ #ifndef littlefs_mock_hpp #define littlefs_mock_hpp -#include +#include #include +#include #include -#include #include "flash_hal_mock.h" #define DEFAULT_LITTLEFS_FILE_NAME "littlefs.bin" class LittleFSMock { -public: + public: LittleFSMock(ssize_t fs_size, size_t fs_block, size_t fs_page, const String& storage = emptyString); void reset(); ~LittleFSMock(); -protected: + protected: void load(); void save(); diff --git a/tests/host/common/md5.c b/tests/host/common/md5.c index 195ffa0785..ea2c76c98e 100644 --- a/tests/host/common/md5.c +++ b/tests/host/common/md5.c @@ -32,23 +32,22 @@ This file implements the MD5 algorithm as defined in RFC1321 */ -#include -#include #include +#include +#include #define EXP_FUNC extern #define STDCALL -#define MD5_SIZE 16 +#define MD5_SIZE 16 typedef struct { - uint32_t state[4]; /* state (ABCD) */ - uint32_t count[2]; /* number of bits, modulo 2^64 (lsb first) */ - uint8_t buffer[64]; /* input buffer */ + uint32_t state[4]; /* state (ABCD) */ + uint32_t count[2]; /* number of bits, modulo 2^64 (lsb first) */ + uint8_t buffer[64]; /* input buffer */ } MD5_CTX; - /* Constants for MD5Transform routine. */ #define S11 7 @@ -70,15 +69,14 @@ typedef struct /* ----- static functions ----- */ static void MD5Transform(uint32_t state[4], const uint8_t block[64]); -static void Encode(uint8_t *output, uint32_t *input, uint32_t len); -static void Decode(uint32_t *output, const uint8_t *input, uint32_t len); +static void Encode(uint8_t* output, uint32_t* input, uint32_t len); +static void Decode(uint32_t* output, const uint8_t* input, uint32_t len); static const uint8_t PADDING[64] = -{ - 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; + { + 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; /* F, G, H and I are basic MD5 functions. */ @@ -88,35 +86,39 @@ static const uint8_t PADDING[64] = #define I(x, y, z) ((y) ^ ((x) | (~z))) /* ROTATE_LEFT rotates x left n bits. */ -#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n)))) +#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) /* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. Rotation is separate from addition to prevent recomputation. */ -#define FF(a, b, c, d, x, s, ac) { \ - (a) += F ((b), (c), (d)) + (x) + (uint32_t)(ac); \ - (a) = ROTATE_LEFT ((a), (s)); \ - (a) += (b); \ - } -#define GG(a, b, c, d, x, s, ac) { \ - (a) += G ((b), (c), (d)) + (x) + (uint32_t)(ac); \ - (a) = ROTATE_LEFT ((a), (s)); \ - (a) += (b); \ - } -#define HH(a, b, c, d, x, s, ac) { \ - (a) += H ((b), (c), (d)) + (x) + (uint32_t)(ac); \ - (a) = ROTATE_LEFT ((a), (s)); \ - (a) += (b); \ - } -#define II(a, b, c, d, x, s, ac) { \ - (a) += I ((b), (c), (d)) + (x) + (uint32_t)(ac); \ - (a) = ROTATE_LEFT ((a), (s)); \ - (a) += (b); \ - } +#define FF(a, b, c, d, x, s, ac) \ + { \ + (a) += F((b), (c), (d)) + (x) + (uint32_t)(ac); \ + (a) = ROTATE_LEFT((a), (s)); \ + (a) += (b); \ + } +#define GG(a, b, c, d, x, s, ac) \ + { \ + (a) += G((b), (c), (d)) + (x) + (uint32_t)(ac); \ + (a) = ROTATE_LEFT((a), (s)); \ + (a) += (b); \ + } +#define HH(a, b, c, d, x, s, ac) \ + { \ + (a) += H((b), (c), (d)) + (x) + (uint32_t)(ac); \ + (a) = ROTATE_LEFT((a), (s)); \ + (a) += (b); \ + } +#define II(a, b, c, d, x, s, ac) \ + { \ + (a) += I((b), (c), (d)) + (x) + (uint32_t)(ac); \ + (a) = ROTATE_LEFT((a), (s)); \ + (a) += (b); \ + } /** MD5 initialization - begins an MD5 operation, writing a new ctx. */ -EXP_FUNC void STDCALL MD5Init(MD5_CTX *ctx) +EXP_FUNC void STDCALL MD5Init(MD5_CTX* ctx) { ctx->count[0] = ctx->count[1] = 0; @@ -131,7 +133,7 @@ EXP_FUNC void STDCALL MD5Init(MD5_CTX *ctx) /** Accepts an array of octets as the next portion of the message. */ -EXP_FUNC void STDCALL MD5Update(MD5_CTX *ctx, const uint8_t * msg, int len) +EXP_FUNC void STDCALL MD5Update(MD5_CTX* ctx, const uint8_t* msg, int len) { uint32_t x; int i, partLen; @@ -173,7 +175,7 @@ EXP_FUNC void STDCALL MD5Update(MD5_CTX *ctx, const uint8_t * msg, int len) /** Return the 128-bit message digest into the user's array */ -EXP_FUNC void STDCALL MD5Final(uint8_t *digest, MD5_CTX *ctx) +EXP_FUNC void STDCALL MD5Final(uint8_t* digest, MD5_CTX* ctx) { uint8_t bits[8]; uint32_t x, padLen; @@ -205,76 +207,76 @@ static void MD5Transform(uint32_t state[4], const uint8_t block[64]) Decode(x, block, 64); /* Round 1 */ - FF(a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */ - FF(d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */ - FF(c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */ - FF(b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */ - FF(a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */ - FF(d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */ - FF(c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */ - FF(b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */ - FF(a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */ - FF(d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */ - FF(c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ - FF(b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ - FF(a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ - FF(d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ - FF(c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ - FF(b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ + FF(a, b, c, d, x[0], S11, 0xd76aa478); /* 1 */ + FF(d, a, b, c, x[1], S12, 0xe8c7b756); /* 2 */ + FF(c, d, a, b, x[2], S13, 0x242070db); /* 3 */ + FF(b, c, d, a, x[3], S14, 0xc1bdceee); /* 4 */ + FF(a, b, c, d, x[4], S11, 0xf57c0faf); /* 5 */ + FF(d, a, b, c, x[5], S12, 0x4787c62a); /* 6 */ + FF(c, d, a, b, x[6], S13, 0xa8304613); /* 7 */ + FF(b, c, d, a, x[7], S14, 0xfd469501); /* 8 */ + FF(a, b, c, d, x[8], S11, 0x698098d8); /* 9 */ + FF(d, a, b, c, x[9], S12, 0x8b44f7af); /* 10 */ + FF(c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ + FF(b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ + FF(a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ + FF(d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ + FF(c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ + FF(b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ /* Round 2 */ - GG(a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */ - GG(d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */ - GG(c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ - GG(b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */ - GG(a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */ - GG(d, a, b, c, x[10], S22, 0x2441453); /* 22 */ - GG(c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ - GG(b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */ - GG(a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */ - GG(d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ - GG(c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */ - GG(b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */ - GG(a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ - GG(d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */ - GG(c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */ - GG(b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ + GG(a, b, c, d, x[1], S21, 0xf61e2562); /* 17 */ + GG(d, a, b, c, x[6], S22, 0xc040b340); /* 18 */ + GG(c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ + GG(b, c, d, a, x[0], S24, 0xe9b6c7aa); /* 20 */ + GG(a, b, c, d, x[5], S21, 0xd62f105d); /* 21 */ + GG(d, a, b, c, x[10], S22, 0x2441453); /* 22 */ + GG(c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ + GG(b, c, d, a, x[4], S24, 0xe7d3fbc8); /* 24 */ + GG(a, b, c, d, x[9], S21, 0x21e1cde6); /* 25 */ + GG(d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ + GG(c, d, a, b, x[3], S23, 0xf4d50d87); /* 27 */ + GG(b, c, d, a, x[8], S24, 0x455a14ed); /* 28 */ + GG(a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ + GG(d, a, b, c, x[2], S22, 0xfcefa3f8); /* 30 */ + GG(c, d, a, b, x[7], S23, 0x676f02d9); /* 31 */ + GG(b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ /* Round 3 */ - HH(a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */ - HH(d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */ - HH(c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ - HH(b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ - HH(a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */ - HH(d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */ - HH(c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */ - HH(b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ - HH(a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ - HH(d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */ - HH(c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */ - HH(b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */ - HH(a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */ - HH(d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ - HH(c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ - HH(b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */ + HH(a, b, c, d, x[5], S31, 0xfffa3942); /* 33 */ + HH(d, a, b, c, x[8], S32, 0x8771f681); /* 34 */ + HH(c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ + HH(b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ + HH(a, b, c, d, x[1], S31, 0xa4beea44); /* 37 */ + HH(d, a, b, c, x[4], S32, 0x4bdecfa9); /* 38 */ + HH(c, d, a, b, x[7], S33, 0xf6bb4b60); /* 39 */ + HH(b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ + HH(a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ + HH(d, a, b, c, x[0], S32, 0xeaa127fa); /* 42 */ + HH(c, d, a, b, x[3], S33, 0xd4ef3085); /* 43 */ + HH(b, c, d, a, x[6], S34, 0x4881d05); /* 44 */ + HH(a, b, c, d, x[9], S31, 0xd9d4d039); /* 45 */ + HH(d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ + HH(c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ + HH(b, c, d, a, x[2], S34, 0xc4ac5665); /* 48 */ /* Round 4 */ - II(a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */ - II(d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */ - II(c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ - II(b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */ - II(a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ - II(d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */ - II(c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ - II(b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */ - II(a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */ - II(d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ - II(c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */ - II(b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ - II(a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */ - II(d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ - II(c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */ - II(b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */ + II(a, b, c, d, x[0], S41, 0xf4292244); /* 49 */ + II(d, a, b, c, x[7], S42, 0x432aff97); /* 50 */ + II(c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ + II(b, c, d, a, x[5], S44, 0xfc93a039); /* 52 */ + II(a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ + II(d, a, b, c, x[3], S42, 0x8f0ccc92); /* 54 */ + II(c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ + II(b, c, d, a, x[1], S44, 0x85845dd1); /* 56 */ + II(a, b, c, d, x[8], S41, 0x6fa87e4f); /* 57 */ + II(d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ + II(c, d, a, b, x[6], S43, 0xa3014314); /* 59 */ + II(b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ + II(a, b, c, d, x[4], S41, 0xf7537e82); /* 61 */ + II(d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ + II(c, d, a, b, x[2], S43, 0x2ad7d2bb); /* 63 */ + II(b, c, d, a, x[9], S44, 0xeb86d391); /* 64 */ state[0] += a; state[1] += b; @@ -286,7 +288,7 @@ static void MD5Transform(uint32_t state[4], const uint8_t block[64]) Encodes input (uint32_t) into output (uint8_t). Assumes len is a multiple of 4. */ -static void Encode(uint8_t *output, uint32_t *input, uint32_t len) +static void Encode(uint8_t* output, uint32_t* input, uint32_t len) { uint32_t i, j; @@ -303,7 +305,7 @@ static void Encode(uint8_t *output, uint32_t *input, uint32_t len) Decodes input (uint8_t) into output (uint32_t). Assumes len is a multiple of 4. */ -static void Decode(uint32_t *output, const uint8_t *input, uint32_t len) +static void Decode(uint32_t* output, const uint8_t* input, uint32_t len) { uint32_t i, j; diff --git a/tests/host/common/mock.h b/tests/host/common/mock.h index a0af18f5b7..e30a607cb7 100644 --- a/tests/host/common/mock.h +++ b/tests/host/common/mock.h @@ -30,7 +30,7 @@ */ #define CORE_MOCK 1 -#define MOCK "(mock) " // TODO: provide common logging API instead of adding this string everywhere? +#define MOCK "(mock) " // TODO: provide common logging API instead of adding this string everywhere? // @@ -57,15 +57,15 @@ #include #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -// TODO: #include ? -char* itoa(int val, char *s, int radix); -char* ltoa(long val, char *s, int radix); - + // TODO: #include ? + char* itoa(int val, char* s, int radix); + char* ltoa(long val, char* s, int radix); -size_t strlcat(char *dst, const char *src, size_t size); -size_t strlcpy(char *dst, const char *src, size_t size); + size_t strlcat(char* dst, const char* src, size_t size); + size_t strlcpy(char* dst, const char* src, size_t size); #ifdef __cplusplus } @@ -97,29 +97,30 @@ uint32_t esp_get_cycle_count(); // #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif #include -int ets_printf(const char* fmt, ...) __attribute__((format(printf, 1, 2))); + int ets_printf(const char* fmt, ...) __attribute__((format(printf, 1, 2))); #define os_printf_plus printf #define ets_vsnprintf vsnprintf -inline void ets_putc(char c) -{ - putchar(c); -} + inline void ets_putc(char c) + { + putchar(c); + } -int mockverbose(const char* fmt, ...) __attribute__((format(printf, 1, 2))); + int mockverbose(const char* fmt, ...) __attribute__((format(printf, 1, 2))); -extern const char* host_interface; // cmdline parameter -extern bool serial_timestamp; -extern int mock_port_shifter; -extern bool blocking_uart; -extern uint32_t global_source_address; // 0 = INADDR_ANY by default + extern const char* host_interface; // cmdline parameter + extern bool serial_timestamp; + extern int mock_port_shifter; + extern bool blocking_uart; + extern uint32_t global_source_address; // 0 = INADDR_ANY by default #define NO_GLOBAL_BINDING 0xffffffff -extern uint32_t global_ipv4_netfmt; // selected interface addresse to bind to + extern uint32_t global_ipv4_netfmt; // selected interface addresse to bind to -void loop_end(); + void loop_end(); #ifdef __cplusplus } @@ -135,16 +136,17 @@ void loop_end(); // uart #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -void uart_new_data(const int uart_nr, uint8_t data); + void uart_new_data(const int uart_nr, uint8_t data); #ifdef __cplusplus } #endif // tcp -int mockSockSetup(int sock); -int mockConnect(uint32_t addr, int& sock, int port); +int mockSockSetup(int sock); +int mockConnect(uint32_t addr, int& sock, int port); ssize_t mockFillInBuf(int sock, char* ccinbuf, size_t& ccinbufsize); ssize_t mockPeekBytes(int sock, char* dst, size_t size, int timeout_ms, char* buf, size_t& bufsize); ssize_t mockRead(int sock, char* dst, size_t size, int timeout_ms, char* buf, size_t& bufsize); @@ -177,4 +179,4 @@ void mock_stop_littlefs(); // -#endif // __cplusplus +#endif // __cplusplus diff --git a/tests/host/common/noniso.c b/tests/host/common/noniso.c index 5ef9c85774..718aadb5d4 100644 --- a/tests/host/common/noniso.c +++ b/tests/host/common/noniso.c @@ -13,19 +13,17 @@ all copies or substantial portions of the Software. */ - -#include -#include +#include #include #include -#include +#include +#include #include "stdlib_noniso.h" - void reverse(char* begin, char* end) { - char *is = begin; - char *ie = end - 1; + char* is = begin; + char* ie = end - 1; while (is < ie) { char tmp = *ie; @@ -96,18 +94,17 @@ char* itoa(int value, char* result, int base) int atoi(const char* s) { - return (int) atol(s); + return (int)atol(s); } long atol(const char* s) { - char * tmp; + char* tmp; return strtol(s, &tmp, 10); } double atof(const char* s) { - char * tmp; + char* tmp; return strtod(s, &tmp); } - diff --git a/tests/host/common/pins_arduino.h b/tests/host/common/pins_arduino.h index 5c33e0f119..cba546a2bc 100644 --- a/tests/host/common/pins_arduino.h +++ b/tests/host/common/pins_arduino.h @@ -15,5 +15,4 @@ #ifndef pins_arduino_h #define pins_arduino_h - #endif /* pins_arduino_h */ diff --git a/tests/host/common/queue.h b/tests/host/common/queue.h index 778241d2a5..1a96ce16b1 100644 --- a/tests/host/common/queue.h +++ b/tests/host/common/queue.h @@ -35,9 +35,9 @@ */ #ifndef _SYS_QUEUE_H_ -#define _SYS_QUEUE_H_ +#define _SYS_QUEUE_H_ -#include /* for __offsetof */ +#include /* for __offsetof */ /* This file defines four types of data structures: singly-linked lists, @@ -106,322 +106,390 @@ /* Singly-linked List declarations. */ -#define SLIST_HEAD(name, type) \ -struct name { \ - struct type *slh_first; /* first element */ \ -} - -#define SLIST_HEAD_INITIALIZER(head) \ - { NULL } - -#define SLIST_ENTRY(type) \ -struct { \ - struct type *sle_next; /* next element */ \ -} +#define SLIST_HEAD(name, type) \ + struct name \ + { \ + struct type* slh_first; /* first element */ \ + } + +#define SLIST_HEAD_INITIALIZER(head) \ + { \ + NULL \ + } + +#define SLIST_ENTRY(type) \ + struct \ + { \ + struct type* sle_next; /* next element */ \ + } /* Singly-linked List functions. */ -#define SLIST_EMPTY(head) ((head)->slh_first == NULL) - -#define SLIST_FIRST(head) ((head)->slh_first) - -#define SLIST_FOREACH(var, head, field) \ - for ((var) = SLIST_FIRST((head)); \ - (var); \ - (var) = SLIST_NEXT((var), field)) - -#define SLIST_INIT(head) do { \ - SLIST_FIRST((head)) = NULL; \ -} while (0) - -#define SLIST_INSERT_AFTER(slistelm, elm, field) do { \ - SLIST_NEXT((elm), field) = SLIST_NEXT((slistelm), field); \ - SLIST_NEXT((slistelm), field) = (elm); \ -} while (0) - -#define SLIST_INSERT_HEAD(head, elm, field) do { \ - SLIST_NEXT((elm), field) = SLIST_FIRST((head)); \ - SLIST_FIRST((head)) = (elm); \ -} while (0) - -#define SLIST_NEXT(elm, field) ((elm)->field.sle_next) - -#define SLIST_REMOVE(head, elm, type, field) do { \ - if (SLIST_FIRST((head)) == (elm)) { \ - SLIST_REMOVE_HEAD((head), field); \ - } \ - else { \ - struct type *curelm = SLIST_FIRST((head)); \ - while (SLIST_NEXT(curelm, field) != (elm)) \ - curelm = SLIST_NEXT(curelm, field); \ - SLIST_NEXT(curelm, field) = \ - SLIST_NEXT(SLIST_NEXT(curelm, field), field); \ - } \ -} while (0) - -#define SLIST_REMOVE_HEAD(head, field) do { \ - SLIST_FIRST((head)) = SLIST_NEXT(SLIST_FIRST((head)), field); \ -} while (0) +#define SLIST_EMPTY(head) ((head)->slh_first == NULL) + +#define SLIST_FIRST(head) ((head)->slh_first) + +#define SLIST_FOREACH(var, head, field) \ + for ((var) = SLIST_FIRST((head)); \ + (var); \ + (var) = SLIST_NEXT((var), field)) + +#define SLIST_INIT(head) \ + do \ + { \ + SLIST_FIRST((head)) = NULL; \ + } while (0) + +#define SLIST_INSERT_AFTER(slistelm, elm, field) \ + do \ + { \ + SLIST_NEXT((elm), field) = SLIST_NEXT((slistelm), field); \ + SLIST_NEXT((slistelm), field) = (elm); \ + } while (0) + +#define SLIST_INSERT_HEAD(head, elm, field) \ + do \ + { \ + SLIST_NEXT((elm), field) = SLIST_FIRST((head)); \ + SLIST_FIRST((head)) = (elm); \ + } while (0) + +#define SLIST_NEXT(elm, field) ((elm)->field.sle_next) + +#define SLIST_REMOVE(head, elm, type, field) \ + do \ + { \ + if (SLIST_FIRST((head)) == (elm)) \ + { \ + SLIST_REMOVE_HEAD((head), field); \ + } \ + else \ + { \ + struct type* curelm = SLIST_FIRST((head)); \ + while (SLIST_NEXT(curelm, field) != (elm)) \ + curelm = SLIST_NEXT(curelm, field); \ + SLIST_NEXT(curelm, field) = \ + SLIST_NEXT(SLIST_NEXT(curelm, field), field); \ + } \ + } while (0) + +#define SLIST_REMOVE_HEAD(head, field) \ + do \ + { \ + SLIST_FIRST((head)) = SLIST_NEXT(SLIST_FIRST((head)), field); \ + } while (0) /* Singly-linked Tail queue declarations. */ -#define STAILQ_HEAD(name, type) \ -struct name { \ - struct type *stqh_first;/* first element */ \ - struct type **stqh_last;/* addr of last next element */ \ -} - -#define STAILQ_HEAD_INITIALIZER(head) \ - { NULL, &(head).stqh_first } - -#define STAILQ_ENTRY(type) \ -struct { \ - struct type *stqe_next; /* next element */ \ -} +#define STAILQ_HEAD(name, type) \ + struct name \ + { \ + struct type* stqh_first; /* first element */ \ + struct type** stqh_last; /* addr of last next element */ \ + } + +#define STAILQ_HEAD_INITIALIZER(head) \ + { \ + NULL, &(head).stqh_first \ + } + +#define STAILQ_ENTRY(type) \ + struct \ + { \ + struct type* stqe_next; /* next element */ \ + } /* Singly-linked Tail queue functions. */ -#define STAILQ_CONCAT(head1, head2) do { \ - if (!STAILQ_EMPTY((head2))) { \ - *(head1)->stqh_last = (head2)->stqh_first; \ - (head1)->stqh_last = (head2)->stqh_last; \ - STAILQ_INIT((head2)); \ - } \ -} while (0) - -#define STAILQ_EMPTY(head) ((head)->stqh_first == NULL) - -#define STAILQ_FIRST(head) ((head)->stqh_first) - -#define STAILQ_FOREACH(var, head, field) \ - for((var) = STAILQ_FIRST((head)); \ - (var); \ - (var) = STAILQ_NEXT((var), field)) - -#define STAILQ_INIT(head) do { \ - STAILQ_FIRST((head)) = NULL; \ - (head)->stqh_last = &STAILQ_FIRST((head)); \ -} while (0) - -#define STAILQ_INSERT_AFTER(head, tqelm, elm, field) do { \ - if ((STAILQ_NEXT((elm), field) = STAILQ_NEXT((tqelm), field)) == NULL)\ - (head)->stqh_last = &STAILQ_NEXT((elm), field); \ - STAILQ_NEXT((tqelm), field) = (elm); \ -} while (0) - -#define STAILQ_INSERT_HEAD(head, elm, field) do { \ - if ((STAILQ_NEXT((elm), field) = STAILQ_FIRST((head))) == NULL) \ - (head)->stqh_last = &STAILQ_NEXT((elm), field); \ - STAILQ_FIRST((head)) = (elm); \ -} while (0) - -#define STAILQ_INSERT_TAIL(head, elm, field) do { \ - STAILQ_NEXT((elm), field) = NULL; \ - *(head)->stqh_last = (elm); \ - (head)->stqh_last = &STAILQ_NEXT((elm), field); \ -} while (0) - -#define STAILQ_LAST(head, type, field) \ - (STAILQ_EMPTY((head)) ? \ - NULL : \ - ((struct type *) \ - ((char *)((head)->stqh_last) - __offsetof(struct type, field)))) - -#define STAILQ_NEXT(elm, field) ((elm)->field.stqe_next) - -#define STAILQ_REMOVE(head, elm, type, field) do { \ - if (STAILQ_FIRST((head)) == (elm)) { \ - STAILQ_REMOVE_HEAD((head), field); \ - } \ - else { \ - struct type *curelm = STAILQ_FIRST((head)); \ - while (STAILQ_NEXT(curelm, field) != (elm)) \ - curelm = STAILQ_NEXT(curelm, field); \ - if ((STAILQ_NEXT(curelm, field) = \ - STAILQ_NEXT(STAILQ_NEXT(curelm, field), field)) == NULL)\ - (head)->stqh_last = &STAILQ_NEXT((curelm), field);\ - } \ -} while (0) - -#define STAILQ_REMOVE_HEAD(head, field) do { \ - if ((STAILQ_FIRST((head)) = \ - STAILQ_NEXT(STAILQ_FIRST((head)), field)) == NULL) \ - (head)->stqh_last = &STAILQ_FIRST((head)); \ -} while (0) - -#define STAILQ_REMOVE_HEAD_UNTIL(head, elm, field) do { \ - if ((STAILQ_FIRST((head)) = STAILQ_NEXT((elm), field)) == NULL) \ - (head)->stqh_last = &STAILQ_FIRST((head)); \ -} while (0) +#define STAILQ_CONCAT(head1, head2) \ + do \ + { \ + if (!STAILQ_EMPTY((head2))) \ + { \ + *(head1)->stqh_last = (head2)->stqh_first; \ + (head1)->stqh_last = (head2)->stqh_last; \ + STAILQ_INIT((head2)); \ + } \ + } while (0) + +#define STAILQ_EMPTY(head) ((head)->stqh_first == NULL) + +#define STAILQ_FIRST(head) ((head)->stqh_first) + +#define STAILQ_FOREACH(var, head, field) \ + for ((var) = STAILQ_FIRST((head)); \ + (var); \ + (var) = STAILQ_NEXT((var), field)) + +#define STAILQ_INIT(head) \ + do \ + { \ + STAILQ_FIRST((head)) = NULL; \ + (head)->stqh_last = &STAILQ_FIRST((head)); \ + } while (0) + +#define STAILQ_INSERT_AFTER(head, tqelm, elm, field) \ + do \ + { \ + if ((STAILQ_NEXT((elm), field) = STAILQ_NEXT((tqelm), field)) == NULL) \ + (head)->stqh_last = &STAILQ_NEXT((elm), field); \ + STAILQ_NEXT((tqelm), field) = (elm); \ + } while (0) + +#define STAILQ_INSERT_HEAD(head, elm, field) \ + do \ + { \ + if ((STAILQ_NEXT((elm), field) = STAILQ_FIRST((head))) == NULL) \ + (head)->stqh_last = &STAILQ_NEXT((elm), field); \ + STAILQ_FIRST((head)) = (elm); \ + } while (0) + +#define STAILQ_INSERT_TAIL(head, elm, field) \ + do \ + { \ + STAILQ_NEXT((elm), field) = NULL; \ + *(head)->stqh_last = (elm); \ + (head)->stqh_last = &STAILQ_NEXT((elm), field); \ + } while (0) + +#define STAILQ_LAST(head, type, field) \ + (STAILQ_EMPTY((head)) ? NULL : ((struct type*)((char*)((head)->stqh_last) - __offsetof(struct type, field)))) + +#define STAILQ_NEXT(elm, field) ((elm)->field.stqe_next) + +#define STAILQ_REMOVE(head, elm, type, field) \ + do \ + { \ + if (STAILQ_FIRST((head)) == (elm)) \ + { \ + STAILQ_REMOVE_HEAD((head), field); \ + } \ + else \ + { \ + struct type* curelm = STAILQ_FIRST((head)); \ + while (STAILQ_NEXT(curelm, field) != (elm)) \ + curelm = STAILQ_NEXT(curelm, field); \ + if ((STAILQ_NEXT(curelm, field) = \ + STAILQ_NEXT(STAILQ_NEXT(curelm, field), field)) == NULL) \ + (head)->stqh_last = &STAILQ_NEXT((curelm), field); \ + } \ + } while (0) + +#define STAILQ_REMOVE_HEAD(head, field) \ + do \ + { \ + if ((STAILQ_FIRST((head)) = \ + STAILQ_NEXT(STAILQ_FIRST((head)), field)) == NULL) \ + (head)->stqh_last = &STAILQ_FIRST((head)); \ + } while (0) + +#define STAILQ_REMOVE_HEAD_UNTIL(head, elm, field) \ + do \ + { \ + if ((STAILQ_FIRST((head)) = STAILQ_NEXT((elm), field)) == NULL) \ + (head)->stqh_last = &STAILQ_FIRST((head)); \ + } while (0) /* List declarations. */ -#define LIST_HEAD(name, type) \ -struct name { \ - struct type *lh_first; /* first element */ \ -} - -#define LIST_HEAD_INITIALIZER(head) \ - { NULL } - -#define LIST_ENTRY(type) \ -struct { \ - struct type *le_next; /* next element */ \ - struct type **le_prev; /* address of previous next element */ \ -} +#define LIST_HEAD(name, type) \ + struct name \ + { \ + struct type* lh_first; /* first element */ \ + } + +#define LIST_HEAD_INITIALIZER(head) \ + { \ + NULL \ + } + +#define LIST_ENTRY(type) \ + struct \ + { \ + struct type* le_next; /* next element */ \ + struct type** le_prev; /* address of previous next element */ \ + } /* List functions. */ -#define LIST_EMPTY(head) ((head)->lh_first == NULL) - -#define LIST_FIRST(head) ((head)->lh_first) - -#define LIST_FOREACH(var, head, field) \ - for ((var) = LIST_FIRST((head)); \ - (var); \ - (var) = LIST_NEXT((var), field)) - -#define LIST_INIT(head) do { \ - LIST_FIRST((head)) = NULL; \ -} while (0) - -#define LIST_INSERT_AFTER(listelm, elm, field) do { \ - if ((LIST_NEXT((elm), field) = LIST_NEXT((listelm), field)) != NULL)\ - LIST_NEXT((listelm), field)->field.le_prev = \ - &LIST_NEXT((elm), field); \ - LIST_NEXT((listelm), field) = (elm); \ - (elm)->field.le_prev = &LIST_NEXT((listelm), field); \ -} while (0) - -#define LIST_INSERT_BEFORE(listelm, elm, field) do { \ - (elm)->field.le_prev = (listelm)->field.le_prev; \ - LIST_NEXT((elm), field) = (listelm); \ - *(listelm)->field.le_prev = (elm); \ - (listelm)->field.le_prev = &LIST_NEXT((elm), field); \ -} while (0) - -#define LIST_INSERT_HEAD(head, elm, field) do { \ - if ((LIST_NEXT((elm), field) = LIST_FIRST((head))) != NULL) \ - LIST_FIRST((head))->field.le_prev = &LIST_NEXT((elm), field);\ - LIST_FIRST((head)) = (elm); \ - (elm)->field.le_prev = &LIST_FIRST((head)); \ -} while (0) - -#define LIST_NEXT(elm, field) ((elm)->field.le_next) - -#define LIST_REMOVE(elm, field) do { \ - if (LIST_NEXT((elm), field) != NULL) \ - LIST_NEXT((elm), field)->field.le_prev = \ - (elm)->field.le_prev; \ - *(elm)->field.le_prev = LIST_NEXT((elm), field); \ -} while (0) +#define LIST_EMPTY(head) ((head)->lh_first == NULL) + +#define LIST_FIRST(head) ((head)->lh_first) + +#define LIST_FOREACH(var, head, field) \ + for ((var) = LIST_FIRST((head)); \ + (var); \ + (var) = LIST_NEXT((var), field)) + +#define LIST_INIT(head) \ + do \ + { \ + LIST_FIRST((head)) = NULL; \ + } while (0) + +#define LIST_INSERT_AFTER(listelm, elm, field) \ + do \ + { \ + if ((LIST_NEXT((elm), field) = LIST_NEXT((listelm), field)) != NULL) \ + LIST_NEXT((listelm), field)->field.le_prev = \ + &LIST_NEXT((elm), field); \ + LIST_NEXT((listelm), field) = (elm); \ + (elm)->field.le_prev = &LIST_NEXT((listelm), field); \ + } while (0) + +#define LIST_INSERT_BEFORE(listelm, elm, field) \ + do \ + { \ + (elm)->field.le_prev = (listelm)->field.le_prev; \ + LIST_NEXT((elm), field) = (listelm); \ + *(listelm)->field.le_prev = (elm); \ + (listelm)->field.le_prev = &LIST_NEXT((elm), field); \ + } while (0) + +#define LIST_INSERT_HEAD(head, elm, field) \ + do \ + { \ + if ((LIST_NEXT((elm), field) = LIST_FIRST((head))) != NULL) \ + LIST_FIRST((head))->field.le_prev = &LIST_NEXT((elm), field); \ + LIST_FIRST((head)) = (elm); \ + (elm)->field.le_prev = &LIST_FIRST((head)); \ + } while (0) + +#define LIST_NEXT(elm, field) ((elm)->field.le_next) + +#define LIST_REMOVE(elm, field) \ + do \ + { \ + if (LIST_NEXT((elm), field) != NULL) \ + LIST_NEXT((elm), field)->field.le_prev = \ + (elm)->field.le_prev; \ + *(elm)->field.le_prev = LIST_NEXT((elm), field); \ + } while (0) /* Tail queue declarations. */ -#define TAILQ_HEAD(name, type) \ -struct name { \ - struct type *tqh_first; /* first element */ \ - struct type **tqh_last; /* addr of last next element */ \ -} - -#define TAILQ_HEAD_INITIALIZER(head) \ - { NULL, &(head).tqh_first } - -#define TAILQ_ENTRY(type) \ -struct { \ - struct type *tqe_next; /* next element */ \ - struct type **tqe_prev; /* address of previous next element */ \ -} +#define TAILQ_HEAD(name, type) \ + struct name \ + { \ + struct type* tqh_first; /* first element */ \ + struct type** tqh_last; /* addr of last next element */ \ + } + +#define TAILQ_HEAD_INITIALIZER(head) \ + { \ + NULL, &(head).tqh_first \ + } + +#define TAILQ_ENTRY(type) \ + struct \ + { \ + struct type* tqe_next; /* next element */ \ + struct type** tqe_prev; /* address of previous next element */ \ + } /* Tail queue functions. */ -#define TAILQ_CONCAT(head1, head2, field) do { \ - if (!TAILQ_EMPTY(head2)) { \ - *(head1)->tqh_last = (head2)->tqh_first; \ - (head2)->tqh_first->field.tqe_prev = (head1)->tqh_last; \ - (head1)->tqh_last = (head2)->tqh_last; \ - TAILQ_INIT((head2)); \ - } \ -} while (0) - -#define TAILQ_EMPTY(head) ((head)->tqh_first == NULL) - -#define TAILQ_FIRST(head) ((head)->tqh_first) - -#define TAILQ_FOREACH(var, head, field) \ - for ((var) = TAILQ_FIRST((head)); \ - (var); \ - (var) = TAILQ_NEXT((var), field)) - -#define TAILQ_FOREACH_REVERSE(var, head, headname, field) \ - for ((var) = TAILQ_LAST((head), headname); \ - (var); \ - (var) = TAILQ_PREV((var), headname, field)) - -#define TAILQ_INIT(head) do { \ - TAILQ_FIRST((head)) = NULL; \ - (head)->tqh_last = &TAILQ_FIRST((head)); \ -} while (0) - -#define TAILQ_INSERT_AFTER(head, listelm, elm, field) do { \ - if ((TAILQ_NEXT((elm), field) = TAILQ_NEXT((listelm), field)) != NULL)\ - TAILQ_NEXT((elm), field)->field.tqe_prev = \ - &TAILQ_NEXT((elm), field); \ - else \ - (head)->tqh_last = &TAILQ_NEXT((elm), field); \ - TAILQ_NEXT((listelm), field) = (elm); \ - (elm)->field.tqe_prev = &TAILQ_NEXT((listelm), field); \ -} while (0) - -#define TAILQ_INSERT_BEFORE(listelm, elm, field) do { \ - (elm)->field.tqe_prev = (listelm)->field.tqe_prev; \ - TAILQ_NEXT((elm), field) = (listelm); \ - *(listelm)->field.tqe_prev = (elm); \ - (listelm)->field.tqe_prev = &TAILQ_NEXT((elm), field); \ -} while (0) - -#define TAILQ_INSERT_HEAD(head, elm, field) do { \ - if ((TAILQ_NEXT((elm), field) = TAILQ_FIRST((head))) != NULL) \ - TAILQ_FIRST((head))->field.tqe_prev = \ - &TAILQ_NEXT((elm), field); \ - else \ - (head)->tqh_last = &TAILQ_NEXT((elm), field); \ - TAILQ_FIRST((head)) = (elm); \ - (elm)->field.tqe_prev = &TAILQ_FIRST((head)); \ -} while (0) - -#define TAILQ_INSERT_TAIL(head, elm, field) do { \ - TAILQ_NEXT((elm), field) = NULL; \ - (elm)->field.tqe_prev = (head)->tqh_last; \ - *(head)->tqh_last = (elm); \ - (head)->tqh_last = &TAILQ_NEXT((elm), field); \ -} while (0) - -#define TAILQ_LAST(head, headname) \ - (*(((struct headname *)((head)->tqh_last))->tqh_last)) - -#define TAILQ_NEXT(elm, field) ((elm)->field.tqe_next) - -#define TAILQ_PREV(elm, headname, field) \ - (*(((struct headname *)((elm)->field.tqe_prev))->tqh_last)) - -#define TAILQ_REMOVE(head, elm, field) do { \ - if ((TAILQ_NEXT((elm), field)) != NULL) \ - TAILQ_NEXT((elm), field)->field.tqe_prev = \ - (elm)->field.tqe_prev; \ - else \ - (head)->tqh_last = (elm)->field.tqe_prev; \ - *(elm)->field.tqe_prev = TAILQ_NEXT((elm), field); \ -} while (0) - +#define TAILQ_CONCAT(head1, head2, field) \ + do \ + { \ + if (!TAILQ_EMPTY(head2)) \ + { \ + *(head1)->tqh_last = (head2)->tqh_first; \ + (head2)->tqh_first->field.tqe_prev = (head1)->tqh_last; \ + (head1)->tqh_last = (head2)->tqh_last; \ + TAILQ_INIT((head2)); \ + } \ + } while (0) + +#define TAILQ_EMPTY(head) ((head)->tqh_first == NULL) + +#define TAILQ_FIRST(head) ((head)->tqh_first) + +#define TAILQ_FOREACH(var, head, field) \ + for ((var) = TAILQ_FIRST((head)); \ + (var); \ + (var) = TAILQ_NEXT((var), field)) + +#define TAILQ_FOREACH_REVERSE(var, head, headname, field) \ + for ((var) = TAILQ_LAST((head), headname); \ + (var); \ + (var) = TAILQ_PREV((var), headname, field)) + +#define TAILQ_INIT(head) \ + do \ + { \ + TAILQ_FIRST((head)) = NULL; \ + (head)->tqh_last = &TAILQ_FIRST((head)); \ + } while (0) + +#define TAILQ_INSERT_AFTER(head, listelm, elm, field) \ + do \ + { \ + if ((TAILQ_NEXT((elm), field) = TAILQ_NEXT((listelm), field)) != NULL) \ + TAILQ_NEXT((elm), field)->field.tqe_prev = \ + &TAILQ_NEXT((elm), field); \ + else \ + (head)->tqh_last = &TAILQ_NEXT((elm), field); \ + TAILQ_NEXT((listelm), field) = (elm); \ + (elm)->field.tqe_prev = &TAILQ_NEXT((listelm), field); \ + } while (0) + +#define TAILQ_INSERT_BEFORE(listelm, elm, field) \ + do \ + { \ + (elm)->field.tqe_prev = (listelm)->field.tqe_prev; \ + TAILQ_NEXT((elm), field) = (listelm); \ + *(listelm)->field.tqe_prev = (elm); \ + (listelm)->field.tqe_prev = &TAILQ_NEXT((elm), field); \ + } while (0) + +#define TAILQ_INSERT_HEAD(head, elm, field) \ + do \ + { \ + if ((TAILQ_NEXT((elm), field) = TAILQ_FIRST((head))) != NULL) \ + TAILQ_FIRST((head))->field.tqe_prev = \ + &TAILQ_NEXT((elm), field); \ + else \ + (head)->tqh_last = &TAILQ_NEXT((elm), field); \ + TAILQ_FIRST((head)) = (elm); \ + (elm)->field.tqe_prev = &TAILQ_FIRST((head)); \ + } while (0) + +#define TAILQ_INSERT_TAIL(head, elm, field) \ + do \ + { \ + TAILQ_NEXT((elm), field) = NULL; \ + (elm)->field.tqe_prev = (head)->tqh_last; \ + *(head)->tqh_last = (elm); \ + (head)->tqh_last = &TAILQ_NEXT((elm), field); \ + } while (0) + +#define TAILQ_LAST(head, headname) \ + (*(((struct headname*)((head)->tqh_last))->tqh_last)) + +#define TAILQ_NEXT(elm, field) ((elm)->field.tqe_next) + +#define TAILQ_PREV(elm, headname, field) \ + (*(((struct headname*)((elm)->field.tqe_prev))->tqh_last)) + +#define TAILQ_REMOVE(head, elm, field) \ + do \ + { \ + if ((TAILQ_NEXT((elm), field)) != NULL) \ + TAILQ_NEXT((elm), field)->field.tqe_prev = \ + (elm)->field.tqe_prev; \ + else \ + (head)->tqh_last = (elm)->field.tqe_prev; \ + *(elm)->field.tqe_prev = TAILQ_NEXT((elm), field); \ + } while (0) #ifdef _KERNEL @@ -432,17 +500,17 @@ struct { \ struct quehead { - struct quehead *qh_link; - struct quehead *qh_rlink; + struct quehead* qh_link; + struct quehead* qh_rlink; }; -#ifdef __GNUC__ +#ifdef __GNUC__ static __inline void -insque(void *a, void *b) +insque(void* a, void* b) { - struct quehead *element = (struct quehead *)a, - *head = (struct quehead *)b; + struct quehead *element = (struct quehead*)a, + *head = (struct quehead*)b; element->qh_link = head->qh_link; element->qh_rlink = head; @@ -451,9 +519,9 @@ insque(void *a, void *b) } static __inline void -remque(void *a) +remque(void* a) { - struct quehead *element = (struct quehead *)a; + struct quehead* element = (struct quehead*)a; element->qh_link->qh_rlink = element->qh_rlink; element->qh_rlink->qh_link = element->qh_link; @@ -462,8 +530,8 @@ remque(void *a) #else /* !__GNUC__ */ -void insque(void *a, void *b); -void remque(void *a); +void insque(void* a, void* b); +void remque(void* a); #endif /* __GNUC__ */ diff --git a/tests/host/common/sdfs_mock.cpp b/tests/host/common/sdfs_mock.cpp index 2673ab318f..26143ea4d7 100644 --- a/tests/host/common/sdfs_mock.cpp +++ b/tests/host/common/sdfs_mock.cpp @@ -18,4 +18,4 @@ #define SDSIZE 16LL uint64_t _sdCardSizeB = 0; -uint8_t *_sdCard = nullptr; +uint8_t* _sdCard = nullptr; diff --git a/tests/host/common/sdfs_mock.h b/tests/host/common/sdfs_mock.h index 08a196a846..0b357fa30e 100644 --- a/tests/host/common/sdfs_mock.h +++ b/tests/host/common/sdfs_mock.h @@ -16,14 +16,14 @@ #ifndef sdfs_mock_hpp #define sdfs_mock_hpp -#include +#include #include +#include #include -#include class SDFSMock { -public: + public: SDFSMock(ssize_t fs_size, size_t fs_block, size_t fs_page, const String& storage = emptyString) { (void)fs_size; @@ -31,19 +31,22 @@ class SDFSMock (void)fs_page; (void)storage; } - void reset() { } - ~SDFSMock() { } + void reset() {} + ~SDFSMock() {} }; extern uint64_t _sdCardSizeB; -extern uint8_t *_sdCard; - -#define SDFS_MOCK_DECLARE(size_kb, block_kb, page_b, storage) \ - SDFS.end(); \ - SDFSMock sdfs_mock(size_kb * 1024, block_kb * 1024, page_b, storage); free(_sdCard); \ - _sdCardSizeB = size_kb ? 16 * 1024 * 1024 : 0; \ - if (_sdCardSizeB) _sdCard = (uint8_t*)calloc(_sdCardSizeB, 1); \ - else _sdCard = nullptr; \ +extern uint8_t* _sdCard; + +#define SDFS_MOCK_DECLARE(size_kb, block_kb, page_b, storage) \ + SDFS.end(); \ + SDFSMock sdfs_mock(size_kb * 1024, block_kb * 1024, page_b, storage); \ + free(_sdCard); \ + _sdCardSizeB = size_kb ? 16 * 1024 * 1024 : 0; \ + if (_sdCardSizeB) \ + _sdCard = (uint8_t*)calloc(_sdCardSizeB, 1); \ + else \ + _sdCard = nullptr; \ SDFS.setConfig(SDFSConfig().setAutoFormat(true)); #define SDFS_MOCK_RESET() sdfs_mock.reset() diff --git a/tests/host/common/spiffs_mock.cpp b/tests/host/common/spiffs_mock.cpp index 716b84b60f..eaccb41898 100644 --- a/tests/host/common/spiffs_mock.cpp +++ b/tests/host/common/spiffs_mock.cpp @@ -13,18 +13,17 @@ all copies or substantial portions of the Software. */ - #include "spiffs_mock.h" -#include "spiffs/spiffs.h" -#include "debug.h" #include #include +#include "debug.h" +#include "spiffs/spiffs.h" #include -#include -#include #include +#include +#include #include #include @@ -48,11 +47,11 @@ SpiffsMock::SpiffsMock(ssize_t fs_size, size_t fs_block, size_t fs_page, const S fprintf(stderr, "SPIFFS: %zd bytes\n", fs_size); m_fs.resize(fs_size, 0xff); - s_phys_addr = 0; - s_phys_size = static_cast(fs_size); - s_phys_page = static_cast(fs_page); + s_phys_addr = 0; + s_phys_size = static_cast(fs_size); + s_phys_page = static_cast(fs_page); s_phys_block = static_cast(fs_block); - s_phys_data = m_fs.data(); + s_phys_data = m_fs.data(); reset(); } @@ -65,11 +64,11 @@ void SpiffsMock::reset() SpiffsMock::~SpiffsMock() { save(); - s_phys_addr = 0; - s_phys_size = 0; - s_phys_page = 0; + s_phys_addr = 0; + s_phys_size = 0; + s_phys_page = 0; s_phys_block = 0; - s_phys_data = nullptr; + s_phys_data = nullptr; m_fs.resize(0); SPIFFS = FS(FSImplPtr(nullptr)); } @@ -89,7 +88,7 @@ void SpiffsMock::load() } off_t flen = lseek(fs, 0, SEEK_END); - if (flen == (off_t) -1) + if (flen == (off_t)-1) { fprintf(stderr, "SPIFFS: checking size of '%s': %s\n", m_storage.c_str(), strerror(errno)); return; @@ -144,4 +143,3 @@ void SpiffsMock::save() } #pragma GCC diagnostic pop - diff --git a/tests/host/common/spiffs_mock.h b/tests/host/common/spiffs_mock.h index 12a97f2851..2cf16c7d47 100644 --- a/tests/host/common/spiffs_mock.h +++ b/tests/host/common/spiffs_mock.h @@ -16,22 +16,22 @@ #ifndef spiffs_mock_hpp #define spiffs_mock_hpp -#include +#include #include +#include #include -#include #include "flash_hal_mock.h" #define DEFAULT_SPIFFS_FILE_NAME "spiffs.bin" class SpiffsMock { -public: + public: SpiffsMock(ssize_t fs_size, size_t fs_block, size_t fs_page, const String& storage = emptyString); void reset(); ~SpiffsMock(); -protected: + protected: void load(); void save(); diff --git a/tests/host/common/strl.cpp b/tests/host/common/strl.cpp index 529b9a1edb..95c98913d6 100644 --- a/tests/host/common/strl.cpp +++ b/tests/host/common/strl.cpp @@ -5,25 +5,24 @@ '_cups_strlcat()' - Safely concatenate two strings. */ -size_t /* O - Length of string */ -strlcat(char *dst, /* O - Destination string */ - const char *src, /* I - Source string */ - size_t size) /* I - Size of destination string buffer */ +size_t /* O - Length of string */ +strlcat(char* dst, /* O - Destination string */ + const char* src, /* I - Source string */ + size_t size) /* I - Size of destination string buffer */ { - size_t srclen; /* Length of source string */ - size_t dstlen; /* Length of destination string */ - + size_t srclen; /* Length of source string */ + size_t dstlen; /* Length of destination string */ /* Figure out how much room is left... */ dstlen = strlen(dst); - size -= dstlen + 1; + size -= dstlen + 1; if (!size) { - return (dstlen); /* No room, return immediately... */ + return (dstlen); /* No room, return immediately... */ } /* @@ -53,19 +52,18 @@ strlcat(char *dst, /* O - Destination string */ '_cups_strlcpy()' - Safely copy two strings. */ -size_t /* O - Length of string */ -strlcpy(char *dst, /* O - Destination string */ - const char *src, /* I - Source string */ - size_t size) /* I - Size of destination string buffer */ +size_t /* O - Length of string */ +strlcpy(char* dst, /* O - Destination string */ + const char* src, /* I - Source string */ + size_t size) /* I - Size of destination string buffer */ { - size_t srclen; /* Length of source string */ - + size_t srclen; /* Length of source string */ /* Figure out how much room is needed... */ - size --; + size--; srclen = strlen(src); diff --git a/tests/host/common/user_interface.cpp b/tests/host/common/user_interface.cpp index 2c9bde2453..92313e7f49 100644 --- a/tests/host/common/user_interface.cpp +++ b/tests/host/common/user_interface.cpp @@ -31,19 +31,19 @@ #include -#include -#include -#include +#include #include #include +#include +#include #include -#include +#include #include "MocklwIP.h" #include -bool DhcpServer::set_dhcps_lease(struct dhcps_lease *please) +bool DhcpServer::set_dhcps_lease(struct dhcps_lease* please) { (void)please; return false; @@ -66,7 +66,7 @@ void DhcpServer::end() { } -bool DhcpServer::begin(struct ip_info *info) +bool DhcpServer::begin(struct ip_info* info) { (void)info; return false; @@ -86,9 +86,8 @@ DhcpServer dhcpSoftAP(nullptr); extern "C" { - -#include #include +#include uint8 wifi_get_opmode(void) { @@ -120,7 +119,7 @@ extern "C" return 1; } - bool wifi_station_get_config(struct station_config *config) + bool wifi_station_get_config(struct station_config* config) { strcpy((char*)config->ssid, "emulated-ssid"); strcpy((char*)config->password, "emulated-ssid-password"); @@ -160,21 +159,21 @@ extern "C" (void)type; } - uint32_t global_ipv4_netfmt = 0; // global binding + uint32_t global_ipv4_netfmt = 0; // global binding netif netif0; uint32_t global_source_address = INADDR_ANY; - bool wifi_get_ip_info(uint8 if_index, struct ip_info *info) + bool wifi_get_ip_info(uint8 if_index, struct ip_info* info) { // emulate wifi_get_ip_info() // ignore if_index // use global option -i (host_interface) to select bound interface/address - struct ifaddrs * ifAddrStruct = NULL, * ifa = NULL; + struct ifaddrs *ifAddrStruct = NULL, *ifa = NULL; uint32_t ipv4 = lwip_htonl(0x7f000001); uint32_t mask = lwip_htonl(0xff000000); - global_source_address = INADDR_ANY; // =0 + global_source_address = INADDR_ANY; // =0 if (getifaddrs(&ifAddrStruct) != 0) { @@ -190,14 +189,13 @@ extern "C" for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) { mockverbose("host: interface: %s", ifa->ifa_name); - if (ifa->ifa_addr - && ifa->ifa_addr->sa_family == AF_INET // ip_info is IPv4 only - ) + if (ifa->ifa_addr && ifa->ifa_addr->sa_family == AF_INET // ip_info is IPv4 only + ) { - auto test_ipv4 = lwip_ntohl(*(uint32_t*) & ((struct sockaddr_in*)ifa->ifa_addr)->sin_addr); + auto test_ipv4 = lwip_ntohl(*(uint32_t*)&((struct sockaddr_in*)ifa->ifa_addr)->sin_addr); mockverbose(" IPV4 (0x%08lx)", test_ipv4); if ((test_ipv4 & 0xff000000) == 0x7f000000) - // 127./8 + // 127./8 { mockverbose(" (local, ignored)"); } @@ -206,8 +204,8 @@ extern "C" if (!host_interface || (host_interface && strcmp(ifa->ifa_name, host_interface) == 0)) { // use the first non-local interface, or, if specified, the one selected by user on cmdline - ipv4 = *(uint32_t*) & ((struct sockaddr_in*)ifa->ifa_addr)->sin_addr; - mask = *(uint32_t*) & ((struct sockaddr_in*)ifa->ifa_netmask)->sin_addr; + ipv4 = *(uint32_t*)&((struct sockaddr_in*)ifa->ifa_addr)->sin_addr; + mask = *(uint32_t*)&((struct sockaddr_in*)ifa->ifa_netmask)->sin_addr; mockverbose(" (selected)\n"); if (host_interface) { @@ -255,7 +253,7 @@ extern "C" return 1; } - bool wifi_get_macaddr(uint8 if_index, uint8 *macaddr) + bool wifi_get_macaddr(uint8 if_index, uint8* macaddr) { (void)if_index; macaddr[0] = 0xde; @@ -279,7 +277,7 @@ extern "C" return MIN_SLEEP_T; } -#endif // nonos-sdk-pre-3 +#endif // nonos-sdk-pre-3 sleep_type_t wifi_get_sleep_type(void) { @@ -299,7 +297,7 @@ extern "C" mockverbose("TODO: wifi_set_event_handler_cb set\n"); } - bool wifi_set_ip_info(uint8 if_index, struct ip_info *info) + bool wifi_set_ip_info(uint8 if_index, struct ip_info* info) { (void)if_index; (void)info; @@ -364,12 +362,12 @@ extern "C" return true; } - bool wifi_station_get_config_default(struct station_config *config) + bool wifi_station_get_config_default(struct station_config* config) { return wifi_station_get_config(config); } - char wifi_station_get_hostname_str [128]; + char wifi_station_get_hostname_str[128]; const char* wifi_station_get_hostname(void) { return strcpy(wifi_station_get_hostname_str, "esposix"); @@ -390,19 +388,19 @@ extern "C" return set != 0; } - bool wifi_station_set_config(struct station_config *config) + bool wifi_station_set_config(struct station_config* config) { (void)config; return true; } - bool wifi_station_set_config_current(struct station_config *config) + bool wifi_station_set_config_current(struct station_config* config) { (void)config; return true; } - bool wifi_station_set_hostname(const char *name) + bool wifi_station_set_hostname(const char* name) { (void)name; return true; @@ -434,7 +432,7 @@ extern "C" return true; } - bool wifi_softap_get_config(struct softap_config *config) + bool wifi_softap_get_config(struct softap_config* config) { strcpy((char*)config->ssid, "apssid"); strcpy((char*)config->password, "appasswd"); @@ -447,7 +445,7 @@ extern "C" return true; } - bool wifi_softap_get_config_default(struct softap_config *config) + bool wifi_softap_get_config_default(struct softap_config* config) { return wifi_softap_get_config(config); } @@ -457,19 +455,19 @@ extern "C" return 2; } - bool wifi_softap_set_config(struct softap_config *config) + bool wifi_softap_set_config(struct softap_config* config) { (void)config; return true; } - bool wifi_softap_set_config_current(struct softap_config *config) + bool wifi_softap_set_config_current(struct softap_config* config) { (void)config; return true; } - bool wifi_softap_set_dhcps_lease(struct dhcps_lease *please) + bool wifi_softap_set_dhcps_lease(struct dhcps_lease* please) { (void)please; return true; @@ -488,7 +486,7 @@ extern "C" return true; } - bool wifi_station_scan(struct scan_config *config, scan_done_cb_t cb) + bool wifi_station_scan(struct scan_config* config, scan_done_cb_t cb) { (void)config; cb(nullptr, FAIL); @@ -510,7 +508,7 @@ extern "C" (void)intr; } - void dns_setserver(u8_t numdns, ip_addr_t *dnsserver) + void dns_setserver(u8_t numdns, ip_addr_t* dnsserver) { (void)numdns; (void)dnsserver; @@ -519,11 +517,10 @@ extern "C" ip_addr_t dns_getserver(u8_t numdns) { (void)numdns; - ip_addr_t addr = { 0x7f000001 }; + ip_addr_t addr = {0x7f000001}; return addr; } - #include bool smartconfig_start(sc_callback_t cb, ...) { @@ -542,4 +539,4 @@ extern "C" return NONE_SLEEP_T; } -} // extern "C" +} // extern "C" diff --git a/tests/host/core/test_PolledTimeout.cpp b/tests/host/core/test_PolledTimeout.cpp index 3645123827..ac39477feb 100644 --- a/tests/host/core/test_PolledTimeout.cpp +++ b/tests/host/core/test_PolledTimeout.cpp @@ -2,10 +2,10 @@ #include "PolledTimeout.h" #define mockverbose printf -#include "common/MockEsp.cpp" // getCycleCount +#include "common/MockEsp.cpp" // getCycleCount //This won't work for -template +template inline bool fuzzycomp(argT a, argT b) { @@ -34,7 +34,6 @@ TEST_CASE("OneShot Timeout 500000000ns (0.5s)", "[polledTimeout]") REQUIRE(fuzzycomp(delta / 1000, (timeType)500)); - Serial.print("reset\n"); timeout.reset(); @@ -72,7 +71,6 @@ TEST_CASE("OneShot Timeout 3000000us", "[polledTimeout]") REQUIRE(fuzzycomp(delta / 1000, (timeType)3000)); - Serial.print("reset\n"); timeout.reset(); @@ -110,7 +108,6 @@ TEST_CASE("OneShot Timeout 3000ms", "[polledTimeout]") REQUIRE(fuzzycomp(delta, (timeType)3000)); - Serial.print("reset\n"); timeout.reset(); @@ -148,7 +145,6 @@ TEST_CASE("OneShot Timeout 3000ms reset to 1000ms", "[polledTimeout]") REQUIRE(fuzzycomp(delta, (timeType)3000)); - Serial.print("reset\n"); timeout.reset(1000); @@ -241,10 +237,10 @@ TEST_CASE("OneShot Timeout 3000ms reset to 1000ms custom yield", "[polledTimeout Serial.println("OneShot Timeout 3000ms"); - oneShotMsYield timeout(3000); before = millis(); - while (!timeout.expired()); + while (!timeout.expired()) + ; after = millis(); delta = after - before; @@ -252,12 +248,12 @@ TEST_CASE("OneShot Timeout 3000ms reset to 1000ms custom yield", "[polledTimeout REQUIRE(fuzzycomp(delta, (timeType)3000)); - Serial.print("reset\n"); timeout.reset(1000); before = millis(); - while (!timeout); + while (!timeout) + ; after = millis(); delta = after - before; @@ -265,4 +261,3 @@ TEST_CASE("OneShot Timeout 3000ms reset to 1000ms custom yield", "[polledTimeout REQUIRE(fuzzycomp(delta, (timeType)1000)); } - diff --git a/tests/host/core/test_Print.cpp b/tests/host/core/test_Print.cpp index 33baead1b0..86197afcf6 100644 --- a/tests/host/core/test_Print.cpp +++ b/tests/host/core/test_Print.cpp @@ -13,12 +13,12 @@ all copies or substantial portions of the Software. */ -#include -#include #include #include -#include "../common/littlefs_mock.h" #include +#include +#include +#include "../common/littlefs_mock.h" // Use a LittleFS file because we can't instantiate a virtual class like Print TEST_CASE("Print::write overrides all compile properly", "[core][Print]") @@ -27,18 +27,18 @@ TEST_CASE("Print::write overrides all compile properly", "[core][Print]") REQUIRE(LittleFS.begin()); auto p = LittleFS.open("test.bin", "w"); REQUIRE(p); - uint8_t uint8 = 1; - uint16_t uint16 = 2; - uint32_t uint32 = 3; - size_t size = 4; - int8_t int8 = 1; - int16_t int16 = 2; - int32_t int32 = 3; - char c = 'h'; - int i = 10; - long l = 11; + uint8_t uint8 = 1; + uint16_t uint16 = 2; + uint32_t uint32 = 3; + size_t size = 4; + int8_t int8 = 1; + int16_t int16 = 2; + int32_t int32 = 3; + char c = 'h'; + int i = 10; + long l = 11; unsigned char uc = 20; - unsigned int ui = 21; + unsigned int ui = 21; unsigned long ul = 22; p.write(uint8); p.write(uint16); diff --git a/tests/host/core/test_Updater.cpp b/tests/host/core/test_Updater.cpp index ab8941694b..edd84741f5 100644 --- a/tests/host/core/test_Updater.cpp +++ b/tests/host/core/test_Updater.cpp @@ -13,14 +13,13 @@ all copies or substantial portions of the Software. */ -#include #include - +#include // Use a SPIFFS file because we can't instantiate a virtual class like Print TEST_CASE("Updater fails when writes overflow requested size", "[core][Updater]") { - UpdaterClass *u; + UpdaterClass* u; uint8_t buff[6000]; memset(buff, 0, sizeof(buff)); u = new UpdaterClass(); diff --git a/tests/host/core/test_md5builder.cpp b/tests/host/core/test_md5builder.cpp index 6f8075fe93..bb788c3d35 100644 --- a/tests/host/core/test_md5builder.cpp +++ b/tests/host/core/test_md5builder.cpp @@ -13,10 +13,10 @@ all copies or substantial portions of the Software. */ -#include -#include #include #include +#include +#include TEST_CASE("MD5Builder::add works as expected", "[core][MD5Builder]") { @@ -32,14 +32,13 @@ TEST_CASE("MD5Builder::add works as expected", "[core][MD5Builder]") REQUIRE(builder.toString() == "9edb67f2b22c604fab13e2fd1d6056d7"); } - TEST_CASE("MD5Builder::addHexString works as expected", "[core][MD5Builder]") { WHEN("A char array is parsed") { MD5Builder builder; builder.begin(); - const char * myPayload = "1234567890abcdeffedcba98765432106469676974616c7369676e61747572656170706c69636174696F6e73"; + const char* myPayload = "1234567890abcdeffedcba98765432106469676974616c7369676e61747572656170706c69636174696F6e73"; builder.addHexString(myPayload); builder.calculate(); REQUIRE(builder.toString() == "47b937a6f9f12a4c389fa5854e023efb"); diff --git a/tests/host/core/test_pgmspace.cpp b/tests/host/core/test_pgmspace.cpp index 28fa6ca0f1..dc44b55374 100644 --- a/tests/host/core/test_pgmspace.cpp +++ b/tests/host/core/test_pgmspace.cpp @@ -13,9 +13,9 @@ all copies or substantial portions of the Software. */ -#include -#include #include +#include +#include TEST_CASE("strstr_P works as strstr", "[core][pgmspace]") { diff --git a/tests/host/core/test_string.cpp b/tests/host/core/test_string.cpp index e2eaba3a99..9aa770a8a9 100644 --- a/tests/host/core/test_string.cpp +++ b/tests/host/core/test_string.cpp @@ -13,11 +13,11 @@ all copies or substantial portions of the Software. */ -#include -#include +#include #include #include -#include +#include +#include TEST_CASE("String::move", "[core][String]") { @@ -78,12 +78,12 @@ TEST_CASE("String constructors", "[core][String]") REQUIRE(ib == "3e7"); String lb((unsigned long)3000000000, 8); REQUIRE(lb == "26264057000"); - String sl1((long) -2000000000, 10); + String sl1((long)-2000000000, 10); REQUIRE(sl1 == "-2000000000"); String s1("abcd"); String s2(s1); REQUIRE(s1 == s2); - String *s3 = new String("manos"); + String* s3 = new String("manos"); s2 = *s3; delete s3; REQUIRE(s2 == "manos"); @@ -124,11 +124,11 @@ TEST_CASE("String concantenation", "[core][String]") REQUIRE(str == "abcdeabcde9872147483647-214748364869"); str += (unsigned int)1969; REQUIRE(str == "abcdeabcde9872147483647-2147483648691969"); - str += (long) -123; + str += (long)-123; REQUIRE(str == "abcdeabcde9872147483647-2147483648691969-123"); str += (unsigned long)321; REQUIRE(str == "abcdeabcde9872147483647-2147483648691969-123321"); - str += (float) -1.01; + str += (float)-1.01; REQUIRE(str == "abcdeabcde9872147483647-2147483648691969-123321-1.01"); str += (double)1.01; REQUIRE(str == "abcdeabcde9872147483647-2147483648691969-123321-1.011.01"); @@ -146,24 +146,24 @@ TEST_CASE("String concantenation", "[core][String]") REQUIRE(str.concat(str) == true); REQUIRE(str == "cleanclean"); // non-decimal negative #s should be as if they were unsigned - str = String((int) -100, 16); + str = String((int)-100, 16); REQUIRE(str == "ffffff9c"); - str = String((long) -101, 16); + str = String((long)-101, 16); REQUIRE(str == "ffffff9b"); - str = String((int) -100, 10); + str = String((int)-100, 10); REQUIRE(str == "-100"); - str = String((long) -100, 10); + str = String((long)-100, 10); REQUIRE(str == "-100"); // Non-zero-terminated array concatenation const char buff[] = "abcdefg"; String n; - n = "1234567890"; // Make it a SSO string, fill with non-0 data - n = "1"; // Overwrite [1] with 0, but leave old junk in SSO space still + n = "1234567890"; // Make it a SSO string, fill with non-0 data + n = "1"; // Overwrite [1] with 0, but leave old junk in SSO space still n.concat(buff, 3); - REQUIRE(n == "1abc"); // Ensure the trailing 0 is always present even w/this funky concat + REQUIRE(n == "1abc"); // Ensure the trailing 0 is always present even w/this funky concat for (int i = 0; i < 20; i++) { - n.concat(buff, 1); // Add 20 'a's to go from SSO to normal string + n.concat(buff, 1); // Add 20 'a's to go from SSO to normal string } REQUIRE(n == "1abcaaaaaaaaaaaaaaaaaaaa"); n = ""; @@ -172,7 +172,7 @@ TEST_CASE("String concantenation", "[core][String]") n.concat(buff, i); } REQUIRE(n == "aababcabcdabcde"); - n.concat(buff, 0); // And check no add'n + n.concat(buff, 0); // And check no add'n REQUIRE(n == "aababcabcdabcde"); } @@ -330,7 +330,7 @@ TEST_CASE("String SSO works", "[core][String]") s += "0"; REQUIRE(s == "0"); REQUIRE(s.length() == 1); - const char *savesso = s.c_str(); + const char* savesso = s.c_str(); s += 1; REQUIRE(s.c_str() == savesso); REQUIRE(s == "01"); @@ -433,13 +433,12 @@ void repl(const String& key, const String& val, String& s, boolean useURLencode) s.replace(key, val); } - TEST_CASE("String SSO handles junk in memory", "[core][String]") { // We fill the SSO space with garbage then construct an object in it and check consistency // This is NOT how you want to use Strings outside of this testing! unsigned char space[64]; - String *s = (String*)space; + String* s = (String*)space; memset(space, 0xff, 64); new (s) String; REQUIRE(*s == ""); @@ -447,8 +446,8 @@ TEST_CASE("String SSO handles junk in memory", "[core][String]") // Tests from #5883 bool useURLencode = false; - const char euro[4] = {(char)0xe2, (char)0x82, (char)0xac, 0}; // Unicode euro symbol - const char yen[3] = {(char)0xc2, (char)0xa5, 0}; // Unicode yen symbol + const char euro[4] = {(char)0xe2, (char)0x82, (char)0xac, 0}; // Unicode euro symbol + const char yen[3] = {(char)0xc2, (char)0xa5, 0}; // Unicode yen symbol memset(space, 0xff, 64); new (s) String("%ssid%"); @@ -484,7 +483,6 @@ TEST_CASE("String SSO handles junk in memory", "[core][String]") s->~String(); } - TEST_CASE("Issue #5949 - Overlapping src/dest in replace", "[core][String]") { String blah = "blah"; @@ -496,7 +494,6 @@ TEST_CASE("Issue #5949 - Overlapping src/dest in replace", "[core][String]") REQUIRE(blah == "blah"); } - TEST_CASE("Issue #2736 - StreamString SSO fix", "[core][StreamString]") { StreamString s; @@ -513,19 +510,19 @@ TEST_CASE("Strings with NULs", "[core][String]") // Fits in SSO... String str("01234567"); REQUIRE(str.length() == 8); - char *ptr = (char *)str.c_str(); + char* ptr = (char*)str.c_str(); ptr[3] = 0; String str2; str2 = str; REQUIRE(str2.length() == 8); // Needs a buffer pointer str = "0123456789012345678901234567890123456789"; - ptr = (char *)str.c_str(); + ptr = (char*)str.c_str(); ptr[3] = 0; str2 = str; REQUIRE(str2.length() == 40); String str3("a"); - ptr = (char *)str3.c_str(); + ptr = (char*)str3.c_str(); *ptr = 0; REQUIRE(str3.length() == 1); str3 += str3; @@ -541,7 +538,7 @@ TEST_CASE("Strings with NULs", "[core][String]") str3 += str3; REQUIRE(str3.length() == 64); static char zeros[64] = {0}; - const char *p = str3.c_str(); + const char* p = str3.c_str(); REQUIRE(!memcmp(p, zeros, 64)); } @@ -550,7 +547,7 @@ TEST_CASE("Replace and string expansion", "[core][String]") String s, l; // Make these large enough to span SSO and non SSO String whole = "#123456789012345678901234567890"; - const char *res = "abcde123456789012345678901234567890"; + const char* res = "abcde123456789012345678901234567890"; for (size_t i = 1; i < whole.length(); i++) { s = whole.substring(0, i); @@ -566,13 +563,11 @@ TEST_CASE("Replace and string expansion", "[core][String]") TEST_CASE("String chaining", "[core][String]") { - const char* chunks[] - { + const char* chunks[]{ "~12345", "67890", "qwertyuiopasdfghjkl", - "zxcvbnm" - }; + "zxcvbnm"}; String all; for (auto* chunk : chunks) @@ -607,7 +602,7 @@ TEST_CASE("String chaining", "[core][String]") TEST_CASE("String concat OOB #8198", "[core][String]") { - char *p = (char*)malloc(16); + char* p = (char*)malloc(16); memset(p, 'x', 16); String s = "abcd"; s.concat(p, 16); diff --git a/tests/host/fs/test_fs.cpp b/tests/host/fs/test_fs.cpp index dad26483a6..5ea8e94a67 100644 --- a/tests/host/fs/test_fs.cpp +++ b/tests/host/fs/test_fs.cpp @@ -13,17 +13,16 @@ all copies or substantial portions of the Software. */ +#include +#include +#include #include #include -#include -#include "../common/spiffs_mock.h" +#include "../../../libraries/SD/src/SD.h" +#include "../../../libraries/SDFS/src/SDFS.h" #include "../common/littlefs_mock.h" #include "../common/sdfs_mock.h" -#include -#include -#include "../../../libraries/SDFS/src/SDFS.h" -#include "../../../libraries/SD/src/SD.h" - +#include "../common/spiffs_mock.h" namespace spiffs_test { @@ -60,8 +59,7 @@ TEST_CASE("SPIFFS checks the config object passed in", "[fs]") } #pragma GCC diagnostic pop -}; - +}; // namespace spiffs_test namespace littlefs_test { @@ -95,7 +93,7 @@ TEST_CASE("LittleFS checks the config object passed in", "[fs]") REQUIRE(LittleFS.setConfig(l)); } -}; +}; // namespace littlefs_test namespace sdfs_test { @@ -103,10 +101,11 @@ namespace sdfs_test #define TESTPRE "SDFS - " #define TESTPAT "[sdfs]" // SDFS supports long paths (MAXPATH) -#define TOOLONGFILENAME "/" \ - "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" \ - "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" \ - "12345678901234567890123456789012345678901234567890123456" +#define TOOLONGFILENAME \ + "/" \ + "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" \ + "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" \ + "12345678901234567890123456789012345678901234567890123456" #define FS_MOCK_DECLARE SDFS_MOCK_DECLARE #define FS_MOCK_RESET SDFS_MOCK_RESET #define FS_HAS_DIRS @@ -165,4 +164,4 @@ TEST_CASE("SD.h FILE_WRITE macro is append", "[fs]") REQUIRE(u == 0); } -}; +}; // namespace sdfs_test diff --git a/tests/host/sys/pgmspace.h b/tests/host/sys/pgmspace.h index 5426685bf8..6ccd881a8c 100644 --- a/tests/host/sys/pgmspace.h +++ b/tests/host/sys/pgmspace.h @@ -15,11 +15,11 @@ #endif #ifndef PGM_P -#define PGM_P const char * +#define PGM_P const char* #endif #ifndef PGM_VOID_P -#define PGM_VOID_P const void * +#define PGM_VOID_P const void* #endif #ifndef PSTR @@ -27,46 +27,46 @@ #endif #ifdef __cplusplus -#define pgm_read_byte(addr) (*reinterpret_cast(addr)) -#define pgm_read_word(addr) (*reinterpret_cast(addr)) -#define pgm_read_dword(addr) (*reinterpret_cast(addr)) -#define pgm_read_float(addr) (*reinterpret_cast(addr)) -#define pgm_read_ptr(addr) (*reinterpret_cast(addr)) +#define pgm_read_byte(addr) (*reinterpret_cast(addr)) +#define pgm_read_word(addr) (*reinterpret_cast(addr)) +#define pgm_read_dword(addr) (*reinterpret_cast(addr)) +#define pgm_read_float(addr) (*reinterpret_cast(addr)) +#define pgm_read_ptr(addr) (*reinterpret_cast(addr)) #else -#define pgm_read_byte(addr) (*(const uint8_t*)(addr)) -#define pgm_read_word(addr) (*(const uint16_t*)(addr)) -#define pgm_read_dword(addr) (*(const uint32_t*)(addr)) -#define pgm_read_float(addr) (*(const float)(addr)) -#define pgm_read_ptr(addr) (*(const void* const *)(addr)) +#define pgm_read_byte(addr) (*(const uint8_t*)(addr)) +#define pgm_read_word(addr) (*(const uint16_t*)(addr)) +#define pgm_read_dword(addr) (*(const uint32_t*)(addr)) +#define pgm_read_float(addr) (*(const float)(addr)) +#define pgm_read_ptr(addr) (*(const void* const*)(addr)) #endif -#define pgm_read_byte_near(addr) pgm_read_byte(addr) -#define pgm_read_word_near(addr) pgm_read_word(addr) -#define pgm_read_dword_near(addr) pgm_read_dword(addr) -#define pgm_read_float_near(addr) pgm_read_float(addr) -#define pgm_read_ptr_near(addr) pgm_read_ptr(addr) -#define pgm_read_byte_far(addr) pgm_read_byte(addr) -#define pgm_read_word_far(addr) pgm_read_word(addr) -#define pgm_read_dword_far(addr) pgm_read_dword(addr) -#define pgm_read_float_far(addr) pgm_read_float(addr) -#define pgm_read_ptr_far(addr) pgm_read_ptr(addr) +#define pgm_read_byte_near(addr) pgm_read_byte(addr) +#define pgm_read_word_near(addr) pgm_read_word(addr) +#define pgm_read_dword_near(addr) pgm_read_dword(addr) +#define pgm_read_float_near(addr) pgm_read_float(addr) +#define pgm_read_ptr_near(addr) pgm_read_ptr(addr) +#define pgm_read_byte_far(addr) pgm_read_byte(addr) +#define pgm_read_word_far(addr) pgm_read_word(addr) +#define pgm_read_dword_far(addr) pgm_read_dword(addr) +#define pgm_read_float_far(addr) pgm_read_float(addr) +#define pgm_read_ptr_far(addr) pgm_read_ptr(addr) // Wrapper inlines for _P functions #include #include -inline const char *strstr_P(const char *haystack, const char *needle) +inline const char* strstr_P(const char* haystack, const char* needle) { return strstr(haystack, needle); } -inline char *strcpy_P(char *dest, const char *src) +inline char* strcpy_P(char* dest, const char* src) { return strcpy(dest, src); } -inline size_t strlen_P(const char *s) +inline size_t strlen_P(const char* s) { return strlen(s); } -inline int vsnprintf_P(char *str, size_t size, const char *format, va_list ap) +inline int vsnprintf_P(char* str, size_t size, const char* format, va_list ap) { return vsnprintf(str, size, format, ap); } diff --git a/tests/restyle.sh b/tests/restyle.sh index e7fdbc6c28..12d031d21e 100755 --- a/tests/restyle.sh +++ b/tests/restyle.sh @@ -29,14 +29,11 @@ for d in $all; do if [ -d "$d" ]; then echo "-------- directory $d:" for e in c cpp h; do - find $d -name "*.$e" -exec \ - astyle \ - --suffix=none \ - --options=${org}/astyle_core.conf {} \; + find $d -name "*.$e" -exec clang-format -i {} \; done else echo "-------- file $d:" - astyle --suffix=none --options=${org}/astyle_core.conf "$d" + clang-format -i ${d} fi done diff --git a/tools/sdk/lwip2/builder b/tools/sdk/lwip2/builder index 450bb63c1b..7421258237 160000 --- a/tools/sdk/lwip2/builder +++ b/tools/sdk/lwip2/builder @@ -1 +1 @@ -Subproject commit 450bb63c1bc8b35770ca7f246945cf383569f52f +Subproject commit 7421258237b7c8f61629226961af498a0a6e0096 From 01e6b9645eac241e3350995e4a593bbd2f407036 Mon Sep 17 00:00:00 2001 From: David Gauchard Date: Wed, 19 Jan 2022 18:03:55 +0100 Subject: [PATCH 03/15] revert submodule update --- tools/sdk/lwip2/builder | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/sdk/lwip2/builder b/tools/sdk/lwip2/builder index 7421258237..450bb63c1b 160000 --- a/tools/sdk/lwip2/builder +++ b/tools/sdk/lwip2/builder @@ -1 +1 @@ -Subproject commit 7421258237b7c8f61629226961af498a0a6e0096 +Subproject commit 450bb63c1bc8b35770ca7f246945cf383569f52f From c5ecc72544deb37bc230fc323383a527a26e8c25 Mon Sep 17 00:00:00 2001 From: David Gauchard Date: Wed, 19 Jan 2022 18:22:56 +0100 Subject: [PATCH 04/15] use clang-format-12 instead of 10 --- .github/workflows/pull-request.yml | 2 +- tests/restyle.sh | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 2606963a83..5cf15ddcf3 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -242,7 +242,7 @@ jobs: TRAVIS_TAG: ${{ github.ref }} run: | sudo apt update - sudo apt install astyle clang-format + sudo apt install astyle clang-format-12 bash ./tests/ci/style_check.sh diff --git a/tests/restyle.sh b/tests/restyle.sh index 12d031d21e..b8438e089b 100755 --- a/tests/restyle.sh +++ b/tests/restyle.sh @@ -29,11 +29,11 @@ for d in $all; do if [ -d "$d" ]; then echo "-------- directory $d:" for e in c cpp h; do - find $d -name "*.$e" -exec clang-format -i {} \; + find $d -name "*.$e" -exec clang-format-12 -i {} \; done else echo "-------- file $d:" - clang-format -i ${d} + clang-format-12 -i ${d} fi done From 9a353ccd22dfcfe7cd2a2080a3553c27577aa4a5 Mon Sep 17 00:00:00 2001 From: David Gauchard Date: Wed, 19 Jan 2022 18:30:44 +0100 Subject: [PATCH 05/15] unsort #include order --- .clang-format | 1 + 1 file changed, 1 insertion(+) diff --git a/.clang-format b/.clang-format index a54f0962b7..0bde5080d7 100644 --- a/.clang-format +++ b/.clang-format @@ -5,3 +5,4 @@ ColumnLimit: 0 IndentWidth: 4 KeepEmptyLinesAtTheStartOfBlocks: false SpacesBeforeTrailingComments: 2 +SortIncludes: false From f2dae5f1232128528e0a2ef7400640df4712a7d3 Mon Sep 17 00:00:00 2001 From: David Gauchard Date: Wed, 19 Jan 2022 18:35:09 +0100 Subject: [PATCH 06/15] apply new clang-format configuration --- cores/esp8266/LwipDhcpServer.cpp | 6 +- cores/esp8266/LwipIntf.cpp | 8 +- cores/esp8266/LwipIntf.h | 2 +- cores/esp8266/LwipIntfDev.h | 12 +- cores/esp8266/StreamString.h | 2 +- cores/esp8266/core_esp8266_si2c.cpp | 6 +- cores/esp8266/debug.cpp | 2 +- libraries/ESP8266mDNS/src/LEAmDNS.cpp | 6 +- libraries/ESP8266mDNS/src/LEAmDNS.h | 8 +- libraries/ESP8266mDNS/src/LEAmDNS_Control.cpp | 8 +- libraries/ESP8266mDNS/src/LEAmDNS_Helpers.cpp | 2 +- .../ESP8266mDNS/src/LEAmDNS_Transfer.cpp | 2 +- .../Netdump/examples/Netdump/Netdump.ino | 66 ++--- libraries/Netdump/src/Netdump.h | 8 +- libraries/Netdump/src/NetdumpIP.h | 6 +- libraries/Netdump/src/NetdumpPacket.cpp | 2 +- libraries/Netdump/src/NetdumpPacket.h | 4 +- libraries/Wire/Wire.cpp | 4 +- libraries/lwIP_PPP/src/PPPServer.cpp | 2 +- .../lwIP_enc28j60/src/utility/enc28j60.cpp | 2 +- libraries/lwIP_w5100/src/utility/w5100.cpp | 2 +- libraries/lwIP_w5100/src/utility/w5100.h | 2 +- libraries/lwIP_w5500/src/utility/w5500.cpp | 2 +- libraries/lwIP_w5500/src/utility/w5500.h | 2 +- tests/device/libraries/BSTest/src/BSArgs.h | 58 ++--- tests/device/libraries/BSTest/test/test.cpp | 2 +- tests/device/test_libc/libm_string.c | 168 +++++++------ tests/device/test_libc/memcpy-1.c | 72 +++--- tests/device/test_libc/memmove1.c | 82 +++---- tests/device/test_libc/strcmp-1.c | 78 +++--- tests/device/test_libc/tstring.c | 24 +- tests/host/common/Arduino.cpp | 28 +-- tests/host/common/ArduinoCatch.cpp | 26 +- tests/host/common/ArduinoMain.cpp | 82 +++---- tests/host/common/ArduinoMainLittlefs.cpp | 2 - tests/host/common/ArduinoMainSpiffs.cpp | 2 - tests/host/common/ArduinoMainUdp.cpp | 60 +++-- tests/host/common/ClientContextSocket.cpp | 76 +++--- tests/host/common/ClientContextTools.cpp | 64 +++-- tests/host/common/EEPROM.h | 64 ++--- tests/host/common/HostWiring.cpp | 46 ++-- tests/host/common/MockDigital.cpp | 36 +-- tests/host/common/MockEEPROM.cpp | 72 +++--- tests/host/common/MockEsp.cpp | 62 +++-- tests/host/common/MockSPI.cpp | 56 ++--- tests/host/common/MockTools.cpp | 108 +++----- tests/host/common/MockUART.cpp | 94 ++----- tests/host/common/MockWiFiServer.cpp | 58 +++-- tests/host/common/MockWiFiServerSocket.cpp | 70 +++--- tests/host/common/MocklwIP.h | 2 +- tests/host/common/UdpContextSocket.cpp | 90 +++---- tests/host/common/WMath.cpp | 44 ++-- tests/host/common/c_types.h | 48 ++-- tests/host/common/include/ClientContext.h | 36 ++- tests/host/common/include/UdpContext.h | 12 +- tests/host/common/littlefs_mock.cpp | 48 ++-- tests/host/common/littlefs_mock.h | 34 +-- tests/host/common/md5.c | 118 +++++---- tests/host/common/mock.h | 56 ++--- tests/host/common/noniso.c | 32 ++- tests/host/common/pins_arduino.h | 26 +- tests/host/common/queue.h | 230 +++++++++--------- tests/host/common/sdfs_mock.cpp | 20 +- tests/host/common/sdfs_mock.h | 28 +-- tests/host/common/spiffs_mock.cpp | 44 ++-- tests/host/common/spiffs_mock.h | 28 +-- tests/host/common/user_interface.cpp | 24 +- tests/host/core/test_PolledTimeout.cpp | 22 -- tests/host/core/test_Print.cpp | 28 +-- tests/host/core/test_Updater.cpp | 24 +- tests/host/core/test_md5builder.cpp | 26 +- tests/host/core/test_pgmspace.cpp | 26 +- tests/host/core/test_string.cpp | 32 ++- tests/host/fs/test_fs.cpp | 36 +-- 74 files changed, 1234 insertions(+), 1536 deletions(-) diff --git a/cores/esp8266/LwipDhcpServer.cpp b/cores/esp8266/LwipDhcpServer.cpp index 869c9350a9..cbf151f767 100644 --- a/cores/esp8266/LwipDhcpServer.cpp +++ b/cores/esp8266/LwipDhcpServer.cpp @@ -40,17 +40,17 @@ #define USE_DNS -#include "lwip/err.h" #include "lwip/inet.h" -#include "lwip/mem.h" +#include "lwip/err.h" #include "lwip/pbuf.h" #include "lwip/udp.h" +#include "lwip/mem.h" #include "osapi.h" #include "LwipDhcpServer.h" -#include "mem.h" #include "user_interface.h" +#include "mem.h" typedef struct dhcps_state { diff --git a/cores/esp8266/LwipIntf.cpp b/cores/esp8266/LwipIntf.cpp index e549270623..71dec259a4 100644 --- a/cores/esp8266/LwipIntf.cpp +++ b/cores/esp8266/LwipIntf.cpp @@ -1,11 +1,11 @@ extern "C" { -#include "lwip/dhcp.h" -#include "lwip/dns.h" #include "lwip/err.h" -#include "lwip/init.h" // LWIP_VERSION_ #include "lwip/ip_addr.h" +#include "lwip/dns.h" +#include "lwip/dhcp.h" +#include "lwip/init.h" // LWIP_VERSION_ #if LWIP_IPV6 #include "lwip/netif.h" // struct netif #endif @@ -13,8 +13,8 @@ extern "C" #include } -#include "LwipIntf.h" #include "debug.h" +#include "LwipIntf.h" // args | esp order arduino order // ---- + --------- ------------- diff --git a/cores/esp8266/LwipIntf.h b/cores/esp8266/LwipIntf.h index 5eef15305a..778785b7fd 100644 --- a/cores/esp8266/LwipIntf.h +++ b/cores/esp8266/LwipIntf.h @@ -2,8 +2,8 @@ #ifndef _LWIPINTF_H #define _LWIPINTF_H -#include #include +#include #include diff --git a/cores/esp8266/LwipIntfDev.h b/cores/esp8266/LwipIntfDev.h index 82dd4e653f..3ec06c55f6 100644 --- a/cores/esp8266/LwipIntfDev.h +++ b/cores/esp8266/LwipIntfDev.h @@ -6,19 +6,19 @@ // remove all Serial.print // unchain pbufs -#include -#include -#include -#include +#include #include #include -#include +#include +#include +#include +#include #include // wifi_get_macaddr() -#include "LwipIntf.h" #include "SPI.h" #include "Schedule.h" +#include "LwipIntf.h" #include "wl_definitions.h" #ifndef DEFAULT_MTU diff --git a/cores/esp8266/StreamString.h b/cores/esp8266/StreamString.h index 3f7f5dc89c..4af6f5653c 100644 --- a/cores/esp8266/StreamString.h +++ b/cores/esp8266/StreamString.h @@ -23,8 +23,8 @@ #ifndef __STREAMSTRING_H #define __STREAMSTRING_H -#include #include +#include #include "Stream.h" #include "WString.h" diff --git a/cores/esp8266/core_esp8266_si2c.cpp b/cores/esp8266/core_esp8266_si2c.cpp index 28b6f99f40..e8f0ddb9c1 100644 --- a/cores/esp8266/core_esp8266_si2c.cpp +++ b/cores/esp8266/core_esp8266_si2c.cpp @@ -19,15 +19,15 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Modified January 2017 by Bjorn Hammarberg (bjoham@esp8266.com) - i2c slave support */ -#include "PolledTimeout.h" -#include "pins_arduino.h" #include "twi.h" +#include "pins_arduino.h" #include "wiring_private.h" +#include "PolledTimeout.h" extern "C" { -#include "ets_sys.h" #include "twi_util.h" +#include "ets_sys.h" }; // Inline helpers diff --git a/cores/esp8266/debug.cpp b/cores/esp8266/debug.cpp index 7173c29ab7..327aace64e 100644 --- a/cores/esp8266/debug.cpp +++ b/cores/esp8266/debug.cpp @@ -18,8 +18,8 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -#include "debug.h" #include "Arduino.h" +#include "debug.h" #include "osapi.h" #ifdef DEBUG_ESP_CORE diff --git a/libraries/ESP8266mDNS/src/LEAmDNS.cpp b/libraries/ESP8266mDNS/src/LEAmDNS.cpp index c6ed0fe997..611c3dfc38 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS.cpp +++ b/libraries/ESP8266mDNS/src/LEAmDNS.cpp @@ -22,14 +22,14 @@ */ -#include #include +#include +#include "ESP8266mDNS.h" +#include "LEAmDNS_Priv.h" #include // LwipIntf::stateUpCB() #include #include -#include "ESP8266mDNS.h" -#include "LEAmDNS_Priv.h" namespace esp8266 { diff --git a/libraries/ESP8266mDNS/src/LEAmDNS.h b/libraries/ESP8266mDNS/src/LEAmDNS.h index 7d7b8b7287..48ceab3b09 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS.h +++ b/libraries/ESP8266mDNS/src/LEAmDNS.h @@ -102,14 +102,14 @@ #ifndef MDNS_H #define MDNS_H -#include #include // for UdpContext.h -#include -#include #include "WiFiUdp.h" +#include "lwip/udp.h" #include "debug.h" #include "include/UdpContext.h" -#include "lwip/udp.h" +#include +#include +#include #include "ESP8266WiFi.h" diff --git a/libraries/ESP8266mDNS/src/LEAmDNS_Control.cpp b/libraries/ESP8266mDNS/src/LEAmDNS_Control.cpp index 54f31c998b..7b66d086af 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS_Control.cpp +++ b/libraries/ESP8266mDNS/src/LEAmDNS_Control.cpp @@ -22,11 +22,11 @@ */ -#include +#include #include -#include +#include #include -#include +#include #include /* @@ -39,8 +39,8 @@ extern "C" } #include "ESP8266mDNS.h" -#include "LEAmDNS_Priv.h" #include "LEAmDNS_lwIPdefs.h" +#include "LEAmDNS_Priv.h" namespace esp8266 { diff --git a/libraries/ESP8266mDNS/src/LEAmDNS_Helpers.cpp b/libraries/ESP8266mDNS/src/LEAmDNS_Helpers.cpp index 7a7f3e5104..74255552e6 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS_Helpers.cpp +++ b/libraries/ESP8266mDNS/src/LEAmDNS_Helpers.cpp @@ -26,8 +26,8 @@ #include // strrstr() #include "ESP8266mDNS.h" -#include "LEAmDNS_Priv.h" #include "LEAmDNS_lwIPdefs.h" +#include "LEAmDNS_Priv.h" namespace esp8266 { diff --git a/libraries/ESP8266mDNS/src/LEAmDNS_Transfer.cpp b/libraries/ESP8266mDNS/src/LEAmDNS_Transfer.cpp index 4248b582a8..6509e42b05 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS_Transfer.cpp +++ b/libraries/ESP8266mDNS/src/LEAmDNS_Transfer.cpp @@ -28,8 +28,8 @@ extern "C" } #include "ESP8266mDNS.h" -#include "LEAmDNS_Priv.h" #include "LEAmDNS_lwIPdefs.h" +#include "LEAmDNS_Priv.h" namespace esp8266 { diff --git a/libraries/Netdump/examples/Netdump/Netdump.ino b/libraries/Netdump/examples/Netdump/Netdump.ino index 86523705b1..dbba63869b 100644 --- a/libraries/Netdump/examples/Netdump/Netdump.ino +++ b/libraries/Netdump/examples/Netdump/Netdump.ino @@ -1,9 +1,9 @@ #include "Arduino.h" -#include +#include "Netdump.h" #include +#include #include -#include "Netdump.h" //#include #include #include @@ -12,7 +12,7 @@ using namespace NetCapture; #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* ssid = STASSID; @@ -24,8 +24,8 @@ Netdump nd; FS* filesystem = &LittleFS; ESP8266WebServer webServer(80); // Used for sending commands -WiFiServer tcpServer(8000); // Used to show netcat option. -File tracefile; +WiFiServer tcpServer(8000); // Used to show netcat option. +File tracefile; std::map packetCount; @@ -37,23 +37,25 @@ enum class SerialOption : uint8_t { void startSerial(SerialOption option) { switch (option) { - case SerialOption::AllFull: //All Packets, show packet summary. + case SerialOption::AllFull : //All Packets, show packet summary. nd.printDump(Serial, Packet::PacketDetail::FULL); break; - case SerialOption::LocalNone: // Only local IP traffic, full details + case SerialOption::LocalNone : // Only local IP traffic, full details nd.printDump(Serial, Packet::PacketDetail::NONE, [](Packet n) { return (n.hasIP(WiFi.localIP())); - }); + } + ); break; - case SerialOption::HTTPChar: // Only HTTP traffic, show packet content as chars + case SerialOption::HTTPChar : // Only HTTP traffic, show packet content as chars nd.printDump(Serial, Packet::PacketDetail::CHAR, [](Packet n) { return (n.isHTTP()); - }); + } + ); break; - default: + default : Serial.printf("No valid SerialOption provided\r\n"); }; } @@ -97,14 +99,16 @@ void setup(void) { d.concat("
  • " + dir.fileName() + "
  • "); } webServer.send(200, "text.html", d); - }); + } + ); webServer.on("/req", []() { static int rq = 0; String a = "

    You are connected, Number of requests = " + String(rq++) + "

    "; webServer.send(200, "text/html", a); - }); + } + ); webServer.on("/reset", []() { @@ -112,12 +116,13 @@ void setup(void) { tracefile.close(); tcpServer.close(); webServer.send(200, "text.html", "

    Netdump session reset

    "); - }); + } + ); webServer.serveStatic("/", *filesystem, "/"); webServer.begin(); - startSerial(SerialOption::AllFull); // Serial output examples, use enum SerialOption for selection + startSerial(SerialOption::AllFull); // Serial output examples, use enum SerialOption for selection // startTcpDump(); // tcpdump option // startTracefile(); // output to SPIFFS or LittleFS @@ -125,21 +130,21 @@ void setup(void) { // use a self provide callback, this count network packets /* nd.setCallback( - [](Packet p) - { - Serial.printf("PKT : %s : ",p.sourceIP().toString().c_str()); - for ( auto pp : p.allPacketTypes()) - { - Serial.printf("%s ",pp.toString().c_str()); - packetCount[pp]++; - } - Serial.printf("\r\n CNT "); - for (auto pc : packetCount) - { - Serial.printf("%s %d ", pc.first.toString().c_str(),pc.second); - } - Serial.printf("\r\n"); - } + [](Packet p) + { + Serial.printf("PKT : %s : ",p.sourceIP().toString().c_str()); + for ( auto pp : p.allPacketTypes()) + { + Serial.printf("%s ",pp.toString().c_str()); + packetCount[pp]++; + } + Serial.printf("\r\n CNT "); + for (auto pc : packetCount) + { + Serial.printf("%s %d ", pc.first.toString().c_str(),pc.second); + } + Serial.printf("\r\n"); + } ); */ } @@ -148,3 +153,4 @@ void loop(void) { webServer.handleClient(); MDNS.update(); } + diff --git a/libraries/Netdump/src/Netdump.h b/libraries/Netdump/src/Netdump.h index dd5a3d124c..2dead84551 100644 --- a/libraries/Netdump/src/Netdump.h +++ b/libraries/Netdump/src/Netdump.h @@ -22,13 +22,13 @@ #ifndef __NETDUMP_H #define __NETDUMP_H -#include -#include #include -#include #include -#include "CallBackList.h" +#include +#include #include "NetdumpPacket.h" +#include +#include "CallBackList.h" namespace NetCapture { diff --git a/libraries/Netdump/src/NetdumpIP.h b/libraries/Netdump/src/NetdumpIP.h index ae8efc7e94..bf93c7c940 100644 --- a/libraries/Netdump/src/NetdumpIP.h +++ b/libraries/Netdump/src/NetdumpIP.h @@ -8,10 +8,10 @@ #ifndef LIBRARIES_ESPGOODIES_HR_SRC_NETDUMP_NETDUMPIP_H_ #define LIBRARIES_ESPGOODIES_HR_SRC_NETDUMP_NETDUMPIP_H_ -#include -#include -#include #include +#include +#include +#include namespace NetCapture { diff --git a/libraries/Netdump/src/NetdumpPacket.cpp b/libraries/Netdump/src/NetdumpPacket.cpp index 9efad50490..0af8292bb2 100644 --- a/libraries/Netdump/src/NetdumpPacket.cpp +++ b/libraries/Netdump/src/NetdumpPacket.cpp @@ -19,8 +19,8 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -#include #include "Netdump.h" +#include namespace NetCapture { diff --git a/libraries/Netdump/src/NetdumpPacket.h b/libraries/Netdump/src/NetdumpPacket.h index 8cf13169e0..f143ea832e 100644 --- a/libraries/Netdump/src/NetdumpPacket.h +++ b/libraries/Netdump/src/NetdumpPacket.h @@ -22,12 +22,12 @@ #ifndef __NETDUMP_PACKET_H #define __NETDUMP_PACKET_H +#include #include #include -#include -#include #include "NetdumpIP.h" #include "PacketType.h" +#include namespace NetCapture { diff --git a/libraries/Wire/Wire.cpp b/libraries/Wire/Wire.cpp index f389a7b24e..495978b421 100644 --- a/libraries/Wire/Wire.cpp +++ b/libraries/Wire/Wire.cpp @@ -24,13 +24,13 @@ extern "C" { -#include #include #include +#include } -#include "Wire.h" #include "twi.h" +#include "Wire.h" //Some boards don't have these pins available, and hence don't support Wire. //Check here for compile-time error. diff --git a/libraries/lwIP_PPP/src/PPPServer.cpp b/libraries/lwIP_PPP/src/PPPServer.cpp index ef0e571ec5..04512102fd 100644 --- a/libraries/lwIP_PPP/src/PPPServer.cpp +++ b/libraries/lwIP_PPP/src/PPPServer.cpp @@ -10,8 +10,8 @@ // using NAT instead (see in example) #include -#include #include +#include #include #include "PPPServer.h" diff --git a/libraries/lwIP_enc28j60/src/utility/enc28j60.cpp b/libraries/lwIP_enc28j60/src/utility/enc28j60.cpp index a1ac345a3c..0fa4ca0989 100644 --- a/libraries/lwIP_enc28j60/src/utility/enc28j60.cpp +++ b/libraries/lwIP_enc28j60/src/utility/enc28j60.cpp @@ -35,9 +35,9 @@ #include #include -#include #include #include +#include #include #include "enc28j60.h" diff --git a/libraries/lwIP_w5100/src/utility/w5100.cpp b/libraries/lwIP_w5100/src/utility/w5100.cpp index 661f2550c3..1251579744 100644 --- a/libraries/lwIP_w5100/src/utility/w5100.cpp +++ b/libraries/lwIP_w5100/src/utility/w5100.cpp @@ -32,8 +32,8 @@ // original sources: https://github.com/njh/W5100MacRaw -#include "w5100.h" #include +#include "w5100.h" uint8_t Wiznet5100::wizchip_read(uint16_t address) { diff --git a/libraries/lwIP_w5100/src/utility/w5100.h b/libraries/lwIP_w5100/src/utility/w5100.h index 291d57362a..f099b22ea1 100644 --- a/libraries/lwIP_w5100/src/utility/w5100.h +++ b/libraries/lwIP_w5100/src/utility/w5100.h @@ -35,9 +35,9 @@ #ifndef W5100_H #define W5100_H +#include #include #include -#include class Wiznet5100 { diff --git a/libraries/lwIP_w5500/src/utility/w5500.cpp b/libraries/lwIP_w5500/src/utility/w5500.cpp index 89bc6a9be0..90f607f0cf 100644 --- a/libraries/lwIP_w5500/src/utility/w5500.cpp +++ b/libraries/lwIP_w5500/src/utility/w5500.cpp @@ -32,8 +32,8 @@ // original sources: https://github.com/njh/W5500MacRaw -#include "w5500.h" #include +#include "w5500.h" uint8_t Wiznet5500::wizchip_read(uint8_t block, uint16_t address) { diff --git a/libraries/lwIP_w5500/src/utility/w5500.h b/libraries/lwIP_w5500/src/utility/w5500.h index 23d3159395..8b41529610 100644 --- a/libraries/lwIP_w5500/src/utility/w5500.h +++ b/libraries/lwIP_w5500/src/utility/w5500.h @@ -35,9 +35,9 @@ #ifndef W5500_H #define W5500_H +#include #include #include -#include class Wiznet5500 { diff --git a/tests/device/libraries/BSTest/src/BSArgs.h b/tests/device/libraries/BSTest/src/BSArgs.h index 879085b321..e939f55534 100644 --- a/tests/device/libraries/BSTest/src/BSArgs.h +++ b/tests/device/libraries/BSTest/src/BSArgs.h @@ -1,14 +1,14 @@ -/* Splitting string into tokens, taking quotes and escape sequences into account. - From https://github.com/espressif/esp-idf/blob/master/components/console/split_argv.c - Copyright 2016-2017 Espressif Systems (Shanghai) PTE LTD - Licensed under the Apache License 2.0. -*/ +/* Splitting string into tokens, taking quotes and escape sequences into account. + * From https://github.com/espressif/esp-idf/blob/master/components/console/split_argv.c + * Copyright 2016-2017 Espressif Systems (Shanghai) PTE LTD + * Licensed under the Apache License 2.0. + */ #ifndef BS_ARGS_H #define BS_ARGS_H -#include #include +#include #include namespace bs @@ -41,29 +41,29 @@ typedef enum } while (0); /** - @brief Split command line into arguments in place - - - This function finds whitespace-separated arguments in the given input line. - - 'abc def 1 20 .3' -> [ 'abc', 'def', '1', '20', '.3' ] - - - Argument which include spaces may be surrounded with quotes. In this case - spaces are preserved and quotes are stripped. - - 'abc "123 456" def' -> [ 'abc', '123 456', 'def' ] - - - Escape sequences may be used to produce backslash, double quote, and space: - - 'a\ b\\c\"' -> [ 'a b\c"' ] - - Pointers to at most argv_size - 1 arguments are returned in argv array. - The pointer after the last one (i.e. argv[argc]) is set to NULL. - - @param line pointer to buffer to parse; it is modified in place - @param argv array where the pointers to arguments are written - @param argv_size number of elements in argv_array (max. number of arguments will be argv_size - 1) - @return number of arguments found (argc) -*/ + * @brief Split command line into arguments in place + * + * - This function finds whitespace-separated arguments in the given input line. + * + * 'abc def 1 20 .3' -> [ 'abc', 'def', '1', '20', '.3' ] + * + * - Argument which include spaces may be surrounded with quotes. In this case + * spaces are preserved and quotes are stripped. + * + * 'abc "123 456" def' -> [ 'abc', '123 456', 'def' ] + * + * - Escape sequences may be used to produce backslash, double quote, and space: + * + * 'a\ b\\c\"' -> [ 'a b\c"' ] + * + * Pointers to at most argv_size - 1 arguments are returned in argv array. + * The pointer after the last one (i.e. argv[argc]) is set to NULL. + * + * @param line pointer to buffer to parse; it is modified in place + * @param argv array where the pointers to arguments are written + * @param argv_size number of elements in argv_array (max. number of arguments will be argv_size - 1) + * @return number of arguments found (argc) + */ inline size_t split_args(char* line, char** argv, size_t argv_size) { const int QUOTE = '"'; diff --git a/tests/device/libraries/BSTest/test/test.cpp b/tests/device/libraries/BSTest/test/test.cpp index 48da79d3bd..553f8013be 100644 --- a/tests/device/libraries/BSTest/test/test.cpp +++ b/tests/device/libraries/BSTest/test/test.cpp @@ -1,5 +1,5 @@ -#include #include "BSTest.h" +#include BS_ENV_DECLARE(); diff --git a/tests/device/test_libc/libm_string.c b/tests/device/test_libc/libm_string.c index 7b479a7d08..68b9c5e139 100644 --- a/tests/device/test_libc/libm_string.c +++ b/tests/device/test_libc/libm_string.c @@ -1,7 +1,7 @@ -#include #include -#include #include +#include +#include #define memcmp memcmp_P #define memcpy memcpy_P @@ -46,9 +46,7 @@ _DEFUN(funcqual, (a, b, l), char* a _AND char* b _AND int l) // line(l); if (a == NULL && b == NULL) - { return; - } if (strcmp(a, b)) { printf("string.c:%d (%s)\n", l, it); @@ -116,8 +114,8 @@ void libm_test_string() (void)strcat(one, "cd"); equal(one, "cd"); - /* strncat - first test it as strcat, with big counts, - then test the count mechanism. */ + /* strncat - first test it as strcat, with big counts, + then test the count mechanism. */ it = "strncat"; (void)strcpy(one, "ijk"); check(strncat(one, "lmn", 99) == one); /* Returned value. */ @@ -419,75 +417,75 @@ void libm_test_string() equal(two, "hi there"); /* Just paranoia. */ equal(one, "hi there"); /* Stomped on source? */ #if 0 - /* memmove - must work on overlap. */ - it = "memmove"; - check(memmove(one, "abc", 4) == one); /* Returned value. */ - equal(one, "abc"); /* Did the copy go right? */ - - (void) strcpy(one, "abcdefgh"); - (void) memmove(one + 1, "xyz", 2); - equal(one, "axydefgh"); /* Basic test. */ - - (void) strcpy(one, "abc"); - (void) memmove(one, "xyz", 0); - equal(one, "abc"); /* Zero-length copy. */ - - (void) strcpy(one, "hi there"); - (void) strcpy(two, "foo"); - (void) memmove(two, one, 9); - equal(two, "hi there"); /* Just paranoia. */ - equal(one, "hi there"); /* Stomped on source? */ - - (void) strcpy(one, "abcdefgh"); - (void) memmove(one + 1, one, 9); - equal(one, "aabcdefgh"); /* Overlap, right-to-left. */ - - (void) strcpy(one, "abcdefgh"); - (void) memmove(one + 1, one + 2, 7); - equal(one, "acdefgh"); /* Overlap, left-to-right. */ - - (void) strcpy(one, "abcdefgh"); - (void) memmove(one, one, 9); - equal(one, "abcdefgh"); /* 100% overlap. */ + /* memmove - must work on overlap. */ + it = "memmove"; + check(memmove(one, "abc", 4) == one); /* Returned value. */ + equal(one, "abc"); /* Did the copy go right? */ + + (void) strcpy(one, "abcdefgh"); + (void) memmove(one+1, "xyz", 2); + equal(one, "axydefgh"); /* Basic test. */ + + (void) strcpy(one, "abc"); + (void) memmove(one, "xyz", 0); + equal(one, "abc"); /* Zero-length copy. */ + + (void) strcpy(one, "hi there"); + (void) strcpy(two, "foo"); + (void) memmove(two, one, 9); + equal(two, "hi there"); /* Just paranoia. */ + equal(one, "hi there"); /* Stomped on source? */ + + (void) strcpy(one, "abcdefgh"); + (void) memmove(one+1, one, 9); + equal(one, "aabcdefgh"); /* Overlap, right-to-left. */ + + (void) strcpy(one, "abcdefgh"); + (void) memmove(one+1, one+2, 7); + equal(one, "acdefgh"); /* Overlap, left-to-right. */ + + (void) strcpy(one, "abcdefgh"); + (void) memmove(one, one, 9); + equal(one, "abcdefgh"); /* 100% overlap. */ #endif #if 0 - /* memccpy - first test like memcpy, then the search part - The SVID, the only place where memccpy is mentioned, says - overlap might fail, so we don't try it. Besides, it's hard - to see the rationale for a non-left-to-right memccpy. */ - it = "memccpy"; - check(memccpy(one, "abc", 'q', 4) == NULL); /* Returned value. */ - equal(one, "abc"); /* Did the copy go right? */ - - (void) strcpy(one, "abcdefgh"); - (void) memccpy(one + 1, "xyz", 'q', 2); - equal(one, "axydefgh"); /* Basic test. */ - - (void) strcpy(one, "abc"); - (void) memccpy(one, "xyz", 'q', 0); - equal(one, "abc"); /* Zero-length copy. */ - - (void) strcpy(one, "hi there"); - (void) strcpy(two, "foo"); - (void) memccpy(two, one, 'q', 9); - equal(two, "hi there"); /* Just paranoia. */ - equal(one, "hi there"); /* Stomped on source? */ - - (void) strcpy(one, "abcdefgh"); - (void) strcpy(two, "horsefeathers"); - check(memccpy(two, one, 'f', 9) == two + 6); /* Returned value. */ - equal(one, "abcdefgh"); /* Source intact? */ - equal(two, "abcdefeathers"); /* Copy correct? */ - - (void) strcpy(one, "abcd"); - (void) strcpy(two, "bumblebee"); - check(memccpy(two, one, 'a', 4) == two + 1); /* First char. */ - equal(two, "aumblebee"); - check(memccpy(two, one, 'd', 4) == two + 4); /* Last char. */ - equal(two, "abcdlebee"); - (void) strcpy(one, "xyz"); - check(memccpy(two, one, 'x', 1) == two + 1); /* Singleton. */ - equal(two, "xbcdlebee"); + /* memccpy - first test like memcpy, then the search part + The SVID, the only place where memccpy is mentioned, says + overlap might fail, so we don't try it. Besides, it's hard + to see the rationale for a non-left-to-right memccpy. */ + it = "memccpy"; + check(memccpy(one, "abc", 'q', 4) == NULL); /* Returned value. */ + equal(one, "abc"); /* Did the copy go right? */ + + (void) strcpy(one, "abcdefgh"); + (void) memccpy(one+1, "xyz", 'q', 2); + equal(one, "axydefgh"); /* Basic test. */ + + (void) strcpy(one, "abc"); + (void) memccpy(one, "xyz", 'q', 0); + equal(one, "abc"); /* Zero-length copy. */ + + (void) strcpy(one, "hi there"); + (void) strcpy(two, "foo"); + (void) memccpy(two, one, 'q', 9); + equal(two, "hi there"); /* Just paranoia. */ + equal(one, "hi there"); /* Stomped on source? */ + + (void) strcpy(one, "abcdefgh"); + (void) strcpy(two, "horsefeathers"); + check(memccpy(two, one, 'f', 9) == two+6); /* Returned value. */ + equal(one, "abcdefgh"); /* Source intact? */ + equal(two, "abcdefeathers"); /* Copy correct? */ + + (void) strcpy(one, "abcd"); + (void) strcpy(two, "bumblebee"); + check(memccpy(two, one, 'a', 4) == two+1); /* First char. */ + equal(two, "aumblebee"); + check(memccpy(two, one, 'd', 4) == two+4); /* Last char. */ + equal(two, "abcdlebee"); + (void) strcpy(one, "xyz"); + check(memccpy(two, one, 'x', 1) == two+1); /* Singleton. */ + equal(two, "xbcdlebee"); #endif /* memset. */ it = "memset"; @@ -505,8 +503,8 @@ void libm_test_string() (void)memset(one + 2, 010045, 1); equal(one, "ax\045xe"); /* Unsigned char convert. */ - /* bcopy - much like memcpy. - Berklix manual is silent about overlap, so don't test it. */ + /* bcopy - much like memcpy. + Berklix manual is silent about overlap, so don't test it. */ it = "bcopy"; (void)bcopy("abc", one, 4); equal(one, "abc"); /* Simple copy. */ @@ -548,20 +546,18 @@ void libm_test_string() check(bcmp("abc", "def", 0) == 0); /* Zero count. */ if (errors) - { abort(); - } printf("ok\n"); #if 0 /* strerror - VERY system-dependent. */ - { - extern CONST unsigned int _sys_nerr; - extern CONST char *CONST _sys_errlist[]; - int f; - it = "strerror"; - f = open("/", O_WRONLY); /* Should always fail. */ - check(f < 0 && errno > 0 && errno < _sys_nerr); - equal(strerror(errno), _sys_errlist[errno]); - } +{ + extern CONST unsigned int _sys_nerr; + extern CONST char *CONST _sys_errlist[]; + int f; + it = "strerror"; + f = open("/", O_WRONLY); /* Should always fail. */ + check(f < 0 && errno > 0 && errno < _sys_nerr); + equal(strerror(errno), _sys_errlist[errno]); +} #endif } diff --git a/tests/device/test_libc/memcpy-1.c b/tests/device/test_libc/memcpy-1.c index 7ba022115c..b16d1bd4ed 100644 --- a/tests/device/test_libc/memcpy-1.c +++ b/tests/device/test_libc/memcpy-1.c @@ -1,35 +1,35 @@ /* - Copyright (c) 2011 ARM Ltd - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - 3. The name of the company may not be used to endorse or promote - products derived from this software without specific prior written - permission. - - THIS SOFTWARE IS PROVIDED BY ARM LTD ``AS IS'' AND ANY EXPRESS OR IMPLIED - WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - IN NO EVENT SHALL ARM LTD BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + * Copyright (c) 2011 ARM Ltd + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the company may not be used to endorse or promote + * products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY ARM LTD ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL ARM LTD BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ -#include -#include -#include #include +#include +#include +#include #define memcmp memcmp_P #define memcpy memcpy_P @@ -107,8 +107,8 @@ void memcpy_main(void) backup_src[i] = src[i]; } - /* Make calls to memcpy with block sizes ranging between 1 and - MAX_BLOCK_SIZE bytes, aligned and misaligned source and destination. */ + /* Make calls to memcpy with block sizes ranging between 1 and + MAX_BLOCK_SIZE bytes, aligned and misaligned source and destination. */ for (sa = 0; sa <= MAX_OFFSET; sa++) for (da = 0; da <= MAX_OFFSET; da++) for (n = 1; n <= MAX_BLOCK_SIZE; n++) @@ -116,9 +116,7 @@ void memcpy_main(void) //printf ("."); /* Zero dest so we can check it properly after the copying. */ for (j = 0; j < BUFF_SIZE; j++) - { dest[j] = 0; - } void* ret = memcpy(dest + START_COPY + da, src + sa, n); @@ -131,9 +129,9 @@ void memcpy_main(void) "(ret is %p, dest is %p)\n", n, sa, da, ret, dest + START_COPY + da); - /* Check that content of the destination buffer - is the same as the source buffer, and - memory outside destination buffer is not modified. */ + /* Check that content of the destination buffer + is the same as the source buffer, and + memory outside destination buffer is not modified. */ for (j = 0; j < BUFF_SIZE; j++) if ((unsigned)j < START_COPY + da) { @@ -174,9 +172,7 @@ void memcpy_main(void) } if (errors != 0) - { abort(); - } printf("ok\n"); } diff --git a/tests/device/test_libc/memmove1.c b/tests/device/test_libc/memmove1.c index 96b46d2887..8aadfb7753 100644 --- a/tests/device/test_libc/memmove1.c +++ b/tests/device/test_libc/memmove1.c @@ -1,38 +1,38 @@ -/* A minor test-program for memmove. - Copyright (C) 2005 Axis Communications. - All rights reserved. +/* A minor test-program for memmove. + Copyright (C) 2005 Axis Communications. + All rights reserved. - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: - 1. Redistributions of source code must retain the above copyright + 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - 2. Neither the name of Axis Communications nor the names of its + 2. Neither the name of Axis Communications nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - THIS SOFTWARE IS PROVIDED BY AXIS COMMUNICATIONS AND ITS CONTRIBUTORS - ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL AXIS - COMMUNICATIONS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, - STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING - IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. */ - -/* Test moves of 0..MAX bytes; overlapping-src-higher, - overlapping-src-lower and non-overlapping. The overlap varies with - 1..N where N is the size moved. This means an order of MAX**2 - iterations. The size of an octet may seem appropriate for MAX and - makes an upper limit for simple testing. For the CRIS simulator, - making this 256 added 90s to the test-run (2GHz P4) while 64 (4s) was - enough to spot the bugs that had crept in, hence the number chosen. */ + THIS SOFTWARE IS PROVIDED BY AXIS COMMUNICATIONS AND ITS CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL AXIS + COMMUNICATIONS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. */ + +/* Test moves of 0..MAX bytes; overlapping-src-higher, + overlapping-src-lower and non-overlapping. The overlap varies with + 1..N where N is the size moved. This means an order of MAX**2 + iterations. The size of an octet may seem appropriate for MAX and + makes an upper limit for simple testing. For the CRIS simulator, + making this 256 added 90s to the test-run (2GHz P4) while 64 (4s) was + enough to spot the bugs that had crept in, hence the number chosen. */ #define MAX 64 #include @@ -67,22 +67,18 @@ void mymemmove(unsigned char* dest, unsigned char* src, size_t n) { if ((src <= dest && src + n <= dest) || src >= dest) while (n-- > 0) - { *dest++ = *src++; - } else { dest += n; src += n; while (n-- > 0) - { *--dest = *--src; - } } } -/* It's either the noinline attribute or forcing the test framework to - pass -fno-builtin-memmove. */ +/* It's either the noinline attribute or forcing the test framework to + pass -fno-builtin-memmove. */ void xmemmove(unsigned char* dest, unsigned char* src, size_t n) __attribute__((__noinline__)); @@ -99,16 +95,14 @@ void xmemmove(unsigned char* dest, unsigned char* src, size_t n) } } -/* Fill the array with something we can associate with a position, but - not exactly the same as the position index. */ +/* Fill the array with something we can associate with a position, but + not exactly the same as the position index. */ void fill(unsigned char dest[MAX * 3]) { size_t i; for (i = 0; i < MAX * 3; i++) - { dest[i] = (10 + i) % MAX; - } } void memmove_main(void) @@ -116,9 +110,9 @@ void memmove_main(void) size_t i; int errors = 0; - /* Leave some room before and after the area tested, so we can detect - overwrites of up to N bytes, N being the amount tested. If you - want to test using valgrind, make these malloced instead. */ + /* Leave some room before and after the area tested, so we can detect + overwrites of up to N bytes, N being the amount tested. If you + want to test using valgrind, make these malloced instead. */ unsigned char from_test[MAX * 3]; unsigned char to_test[MAX * 3]; unsigned char from_known[MAX * 3]; @@ -127,8 +121,8 @@ void memmove_main(void) /* Non-overlap. */ for (i = 0; i < MAX; i++) { - /* Do the memmove first before setting the known array, so we know - it didn't change any of the known array. */ + /* Do the memmove first before setting the known array, so we know + it didn't change any of the known array. */ fill(from_test); fill(to_test); xmemmove(to_test + MAX, 1 + from_test + MAX, i); @@ -191,8 +185,6 @@ void memmove_main(void) } if (errors != 0) - { abort(); - } printf("ok\n"); } diff --git a/tests/device/test_libc/strcmp-1.c b/tests/device/test_libc/strcmp-1.c index b996dc01ce..bfabf8e967 100644 --- a/tests/device/test_libc/strcmp-1.c +++ b/tests/device/test_libc/strcmp-1.c @@ -1,35 +1,35 @@ /* - Copyright (c) 2011 ARM Ltd - All rights reserved. + * Copyright (c) 2011 ARM Ltd + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the company may not be used to endorse or promote + * products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY ARM LTD ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL ARM LTD BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - 3. The name of the company may not be used to endorse or promote - products derived from this software without specific prior written - permission. - - THIS SOFTWARE IS PROVIDED BY ARM LTD ``AS IS'' AND ANY EXPRESS OR IMPLIED - WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - IN NO EVENT SHALL ARM LTD BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#include -#include -#include #include +#include +#include +#include #define memcmp memcmp_P #define memcpy memcpy_P @@ -46,8 +46,8 @@ #define BUFF_SIZE 256 -/* The macro LONG_TEST controls whether a short or a more comprehensive test - of strcmp should be performed. */ +/* The macro LONG_TEST controls whether a short or a more comprehensive test + of strcmp should be performed. */ #ifdef LONG_TEST #ifndef BUFF_SIZE #define BUFF_SIZE 1024 @@ -146,8 +146,8 @@ void strcmp_main(void) char* p; int ret; - /* Make calls to strcmp with block sizes ranging between 1 and - MAX_BLOCK_SIZE bytes, aligned and misaligned source and destination. */ + /* Make calls to strcmp with block sizes ranging between 1 and + MAX_BLOCK_SIZE bytes, aligned and misaligned source and destination. */ for (sa = 0; sa <= MAX_OFFSET; sa++) for (da = 0; da <= MAX_OFFSET; da++) for (n = 1; n <= MAX_BLOCK_SIZE; n++) @@ -157,9 +157,7 @@ void strcmp_main(void) for (zeros = 1; zeros < MAX_ZEROS; zeros++) { if (n - m > MAX_DIFF) - { continue; - } /* Make a copy of the source. */ for (i = 0; i < BUFF_SIZE; i++) { @@ -179,9 +177,7 @@ void strcmp_main(void) /* Modify dest. */ p = dest + da + m - 1; for (j = 0; j < (int)len; j++) - { *p++ = 'x'; - } /* Make dest 0-terminated. */ *p = '\0'; @@ -265,34 +261,26 @@ void strcmp_main(void) dest[0] = 0x41; ret = strcmp(src, dest); if (ret <= 0) - { print_error("\nFailed: expected positive, return %d\n", ret); - } src[0] = 0x01; dest[0] = 0x82; ret = strcmp(src, dest); if (ret >= 0) - { print_error("\nFailed: expected negative, return %d\n", ret); - } dest[0] = src[0] = 'D'; src[3] = 0xc1; dest[3] = 0x41; ret = strcmp(src, dest); if (ret <= 0) - { print_error("\nFailed: expected positive, return %d\n", ret); - } src[3] = 0x01; dest[3] = 0x82; ret = strcmp(src, dest); if (ret >= 0) - { print_error("\nFailed: expected negative, return %d\n", ret); - } //printf ("\n"); if (errors != 0) diff --git a/tests/device/test_libc/tstring.c b/tests/device/test_libc/tstring.c index 451dc4cf6e..fd6e16842e 100644 --- a/tests/device/test_libc/tstring.c +++ b/tests/device/test_libc/tstring.c @@ -1,14 +1,14 @@ /* - Copyright (C) 2002 by Red Hat, Incorporated. All rights reserved. + * Copyright (C) 2002 by Red Hat, Incorporated. All rights reserved. + * + * Permission to use, copy, modify, and distribute this software + * is freely granted, provided that this notice is preserved. + */ - Permission to use, copy, modify, and distribute this software - is freely granted, provided that this notice is preserved. -*/ - -#include +#include #include #include -#include +#include #define MAX_1 50 #define memcmp memcmp_P @@ -238,19 +238,15 @@ void tstring_main(void) { for (i = j - 1; i <= j + 1; ++i) { - /* don't bother checking unaligned data in the larger - sizes since it will waste time without performing additional testing */ + /* don't bother checking unaligned data in the larger + sizes since it will waste time without performing additional testing */ if ((size_t)i <= 16 * sizeof(long)) { align_test_iterations = 2 * sizeof(long); if ((size_t)i <= 2 * sizeof(long) + 1) - { z = 2; - } else - { z = 2 * sizeof(long); - } } else { @@ -358,9 +354,7 @@ void tstring_main(void) } if (test_failed) - { abort(); - } printf("ok\n"); } diff --git a/tests/host/common/Arduino.cpp b/tests/host/common/Arduino.cpp index eca6b82d32..2662fc3b5c 100644 --- a/tests/host/common/Arduino.cpp +++ b/tests/host/common/Arduino.cpp @@ -1,16 +1,16 @@ /* - Arduino.cpp - Mocks for common Arduino APIs - Copyright © 2016 Ivan Grokhotkov - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. + Arduino.cpp - Mocks for common Arduino APIs + Copyright © 2016 Ivan Grokhotkov + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. */ #include @@ -28,9 +28,7 @@ extern "C" unsigned long millis() timeval time; gettimeofday(&time, NULL); if (gtod0.tv_sec == 0) - { memcpy(>od0, &time, sizeof gtod0); - } return ((time.tv_sec - gtod0.tv_sec) * 1000) + ((time.tv_usec - gtod0.tv_usec) / 1000); } @@ -39,9 +37,7 @@ extern "C" unsigned long micros() timeval time; gettimeofday(&time, NULL); if (gtod0.tv_sec == 0) - { memcpy(>od0, &time, sizeof gtod0); - } return ((time.tv_sec - gtod0.tv_sec) * 1000000) + time.tv_usec - gtod0.tv_usec; } diff --git a/tests/host/common/ArduinoCatch.cpp b/tests/host/common/ArduinoCatch.cpp index e15ef335e4..c0e835495d 100644 --- a/tests/host/common/ArduinoCatch.cpp +++ b/tests/host/common/ArduinoCatch.cpp @@ -1,19 +1,19 @@ /* - Arduino.cpp - Mocks for common Arduino APIs - Copyright © 2016 Ivan Grokhotkov - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. + Arduino.cpp - Mocks for common Arduino APIs + Copyright © 2016 Ivan Grokhotkov + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. */ #define CATCH_CONFIG_MAIN -#include #include +#include #include "Arduino.h" diff --git a/tests/host/common/ArduinoMain.cpp b/tests/host/common/ArduinoMain.cpp index 73ebbcf7e3..f8f0e9d13e 100644 --- a/tests/host/common/ArduinoMain.cpp +++ b/tests/host/common/ArduinoMain.cpp @@ -1,43 +1,43 @@ /* - Arduino emulator main loop - Copyright (c) 2018 david gauchard. All rights reserved. - - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the "Software"), - to deal with the Software without restriction, including without limitation - the rights to use, copy, modify, merge, publish, distribute, sublicense, - and/or sell copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following conditions: - - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimers. - - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimers in the - documentation and/or other materials provided with the distribution. - - - The names of its contributors may not be used to endorse or promote - products derived from this Software without specific prior written - permission. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS WITH THE SOFTWARE. + Arduino emulator main loop + Copyright (c) 2018 david gauchard. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal with the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + - The names of its contributors may not be used to endorse or promote + products derived from this Software without specific prior written + permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. */ #include #include // wifi_get_ip_info() -#include #include +#include +#include +#include #include #include -#include -#include #define MOCK_PORT_SHIFTER 9000 @@ -61,9 +61,7 @@ int mockverbose(const char* fmt, ...) va_list ap; va_start(ap, fmt); if (mockdebug) - { return fprintf(stderr, MOCK) + vfprintf(stderr, fmt, ap); - } return 0; } @@ -100,9 +98,7 @@ static int mock_start_uart(void) static int mock_stop_uart(void) { if (!restore_tty) - { return 0; - } if (!isatty(STDIN)) { perror("restoring tty: isatty(STDIN)"); @@ -182,17 +178,13 @@ void make_fs_filename(String& name, const char* fspath, const char* argv0) int lastSlash = -1; for (int i = 0; argv0[i]; i++) if (argv0[i] == '/') - { lastSlash = i; - } name = fspath; name += '/'; name += &argv0[lastSlash + 1]; } else - { name = argv0; - } } void control_c(int sig) @@ -216,21 +208,15 @@ int main(int argc, char* const argv[]) signal(SIGINT, control_c); signal(SIGTERM, control_c); if (geteuid() == 0) - { mock_port_shifter = 0; - } else - { mock_port_shifter = MOCK_PORT_SHIFTER; - } for (;;) { int n = getopt_long(argc, argv, "hlcfbvTi:S:s:L:P:1", options, NULL); if (n < 0) - { break; - } switch (n) { case 'h': @@ -320,21 +306,15 @@ int main(int argc, char* const argv[]) uint8_t data = mock_read_uart(); if (data) - { uart_new_data(UART0, data); - } if (!fast) - { usleep(1000); // not 100% cpu, ~1000 loops per second - } loop(); loop_end(); check_incoming_udp(); if (run_once) - { user_exit = true; - } } cleanup(); diff --git a/tests/host/common/ArduinoMainLittlefs.cpp b/tests/host/common/ArduinoMainLittlefs.cpp index a9b7974cf5..c85e0b9dbc 100644 --- a/tests/host/common/ArduinoMainLittlefs.cpp +++ b/tests/host/common/ArduinoMainLittlefs.cpp @@ -11,8 +11,6 @@ void mock_start_littlefs(const String& fname, size_t size_kb, size_t block_kb, s void mock_stop_littlefs() { if (littlefs_mock) - { delete littlefs_mock; - } littlefs_mock = nullptr; } diff --git a/tests/host/common/ArduinoMainSpiffs.cpp b/tests/host/common/ArduinoMainSpiffs.cpp index 8530a316f0..035cc9e752 100644 --- a/tests/host/common/ArduinoMainSpiffs.cpp +++ b/tests/host/common/ArduinoMainSpiffs.cpp @@ -11,8 +11,6 @@ void mock_start_spiffs(const String& fname, size_t size_kb, size_t block_kb, siz void mock_stop_spiffs() { if (spiffs_mock) - { delete spiffs_mock; - } spiffs_mock = nullptr; } diff --git a/tests/host/common/ArduinoMainUdp.cpp b/tests/host/common/ArduinoMainUdp.cpp index 2c0bb90841..18d3c591fe 100644 --- a/tests/host/common/ArduinoMainUdp.cpp +++ b/tests/host/common/ArduinoMainUdp.cpp @@ -1,32 +1,32 @@ /* - Arduino emulator main loop - Copyright (c) 2018 david gauchard. All rights reserved. - - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the "Software"), - to deal with the Software without restriction, including without limitation - the rights to use, copy, modify, merge, publish, distribute, sublicense, - and/or sell copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following conditions: - - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimers. - - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimers in the - documentation and/or other materials provided with the distribution. - - - The names of its contributors may not be used to endorse or promote - products derived from this Software without specific prior written - permission. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS WITH THE SOFTWARE. + Arduino emulator main loop + Copyright (c) 2018 david gauchard. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal with the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + - The names of its contributors may not be used to endorse or promote + products derived from this Software without specific prior written + permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. */ #include @@ -38,13 +38,9 @@ std::map udps; void register_udp(int sock, UdpContext* udp) { if (udp) - { udps[sock] = udp; - } else - { udps.erase(sock); - } } void check_incoming_udp() diff --git a/tests/host/common/ClientContextSocket.cpp b/tests/host/common/ClientContextSocket.cpp index 70ec1d5216..34dcde16d8 100644 --- a/tests/host/common/ClientContextSocket.cpp +++ b/tests/host/common/ClientContextSocket.cpp @@ -1,43 +1,43 @@ /* - Arduino emulation - socket part of ClientContext - Copyright (c) 2018 david gauchard. All rights reserved. - - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the "Software"), - to deal with the Software without restriction, including without limitation - the rights to use, copy, modify, merge, publish, distribute, sublicense, - and/or sell copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following conditions: - - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimers. - - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimers in the - documentation and/or other materials provided with the distribution. - - - The names of its contributors may not be used to endorse or promote - products derived from this Software without specific prior written - permission. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS WITH THE SOFTWARE. + Arduino emulation - socket part of ClientContext + Copyright (c) 2018 david gauchard. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal with the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + - The names of its contributors may not be used to endorse or promote + products derived from this Software without specific prior written + permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. */ // separated from lwIP to avoid type conflicts -#include -#include -#include +#include +#include #include +#include #include -#include -#include +#include +#include int mockSockSetup(int sock) { @@ -113,9 +113,7 @@ ssize_t mockPeekBytes(int sock, char* dst, size_t usersize, int timeout_ms, char // usersize==0: peekAvailable() if (usersize > CCBUFSIZE) - { mockverbose("CCBUFSIZE(%d) should be increased by %zd bytes (-> %zd)\n", CCBUFSIZE, usersize - CCBUFSIZE, usersize); - } struct pollfd p; size_t retsize = 0; @@ -135,10 +133,8 @@ ssize_t mockPeekBytes(int sock, char* dst, size_t usersize, int timeout_ms, char } if (usersize == 0 && ccinbufsize) - // peekAvailable - { + // peekAvailable return ccinbufsize; - } if (usersize <= ccinbufsize) { @@ -164,9 +160,7 @@ ssize_t mockRead(int sock, char* dst, size_t size, int timeout_ms, char* ccinbuf { ssize_t copied = mockPeekBytes(sock, dst, size, timeout_ms, ccinbuf, ccinbufsize); if (copied < 0) - { return -1; - } // swallow (XXX use a circular buffer) memmove(ccinbuf, ccinbuf + copied, ccinbufsize - copied); ccinbufsize -= copied; @@ -201,9 +195,7 @@ ssize_t mockWrite(int sock, const uint8_t* data, size_t size, int timeout_ms) } sent += ret; if (sent < size) - { fprintf(stderr, MOCK "ClientContext::write: sent %d bytes (%zd / %zd)\n", ret, sent, size); - } } } #ifdef DEBUG_ESP_WIFI diff --git a/tests/host/common/ClientContextTools.cpp b/tests/host/common/ClientContextTools.cpp index 2574c152d1..b3236d9f41 100644 --- a/tests/host/common/ClientContextTools.cpp +++ b/tests/host/common/ClientContextTools.cpp @@ -1,39 +1,39 @@ /* - Arduino emulation - part of ClientContext - Copyright (c) 2018 david gauchard. All rights reserved. - - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the "Software"), - to deal with the Software without restriction, including without limitation - the rights to use, copy, modify, merge, publish, distribute, sublicense, - and/or sell copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following conditions: - - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimers. - - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimers in the - documentation and/or other materials provided with the distribution. - - - The names of its contributors may not be used to endorse or promote - products derived from this Software without specific prior written - permission. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS WITH THE SOFTWARE. + Arduino emulation - part of ClientContext + Copyright (c) 2018 david gauchard. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal with the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + - The names of its contributors may not be used to endorse or promote + products derived from this Software without specific prior written + permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. */ -#include -#include #include -#include #include +#include +#include +#include #include // gethostbyname @@ -43,9 +43,7 @@ err_t dns_gethostbyname(const char* hostname, ip_addr_t* addr, dns_found_callbac (void)found; struct hostent* hbn = gethostbyname(hostname); if (!hbn) - { return ERR_TIMEOUT; - } addr->addr = *(uint32_t*)hbn->h_addr_list[0]; return ERR_OK; } diff --git a/tests/host/common/EEPROM.h b/tests/host/common/EEPROM.h index faeafa590d..669d60bfaf 100644 --- a/tests/host/common/EEPROM.h +++ b/tests/host/common/EEPROM.h @@ -1,32 +1,32 @@ /* - Arduino EEPROM emulation - Copyright (c) 2018 david gauchard. All rights reserved. + Arduino EEPROM emulation + Copyright (c) 2018 david gauchard. All rights reserved. - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the "Software"), - to deal with the Software without restriction, including without limitation - the rights to use, copy, modify, merge, publish, distribute, sublicense, - and/or sell copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal with the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimers. + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimers in the - documentation and/or other materials provided with the distribution. + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. - - The names of its contributors may not be used to endorse or promote - products derived from this Software without specific prior written - permission. + - The names of its contributors may not be used to endorse or promote + products derived from this Software without specific prior written + permission. - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS WITH THE SOFTWARE. + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. */ #ifndef EEPROM_MOCK @@ -49,13 +49,9 @@ class EEPROMClass T& get(int const address, T& t) { if (address < 0 || address + sizeof(T) > _size) - { return t; - } for (size_t i = 0; i < sizeof(T); i++) - { ((uint8_t*)&t)[i] = read(i); - } return t; } @@ -63,26 +59,16 @@ class EEPROMClass const T& put(int const address, const T& t) { if (address < 0 || address + sizeof(T) > _size) - { return t; - } for (size_t i = 0; i < sizeof(T); i++) - { write(i, ((uint8_t*)&t)[i]); - } return t; } - size_t length() - { - return _size; - } + size_t length() { return _size; } //uint8_t& operator[](int const address) { return read(address); } - uint8_t operator[](int address) - { - return read(address); - } + uint8_t operator[](int address) { return read(address); } protected: size_t _size = 0; diff --git a/tests/host/common/HostWiring.cpp b/tests/host/common/HostWiring.cpp index b3c6b6eb9c..892b336b2c 100644 --- a/tests/host/common/HostWiring.cpp +++ b/tests/host/common/HostWiring.cpp @@ -1,32 +1,32 @@ /* - Arduino: wire emulation - Copyright (c) 2018 david gauchard. All rights reserved. + Arduino: wire emulation + Copyright (c) 2018 david gauchard. All rights reserved. - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the "Software"), - to deal with the Software without restriction, including without limitation - the rights to use, copy, modify, merge, publish, distribute, sublicense, - and/or sell copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal with the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimers. + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimers in the - documentation and/or other materials provided with the distribution. + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. - - The names of its contributors may not be used to endorse or promote - products derived from this Software without specific prior written - permission. + - The names of its contributors may not be used to endorse or promote + products derived from this Software without specific prior written + permission. - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS WITH THE SOFTWARE. + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. */ #include diff --git a/tests/host/common/MockDigital.cpp b/tests/host/common/MockDigital.cpp index 1c63a3b8df..0820ea63f1 100644 --- a/tests/host/common/MockDigital.cpp +++ b/tests/host/common/MockDigital.cpp @@ -1,32 +1,32 @@ /* - digital.c - wiring digital implementation for esp8266 + digital.c - wiring digital implementation for esp8266 - Copyright (c) 2015 Hristo Gochkov. All rights reserved. - This file is part of the esp8266 core for Arduino environment. + Copyright (c) 2015 Hristo Gochkov. All rights reserved. + This file is part of the esp8266 core for Arduino environment. - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #define ARDUINO_MAIN +#include "wiring_private.h" +#include "pins_arduino.h" #include "c_types.h" -#include "core_esp8266_waveform.h" #include "eagle_soc.h" #include "ets_sys.h" -#include "interrupts.h" -#include "pins_arduino.h" #include "user_interface.h" -#include "wiring_private.h" +#include "core_esp8266_waveform.h" +#include "interrupts.h" extern "C" { diff --git a/tests/host/common/MockEEPROM.cpp b/tests/host/common/MockEEPROM.cpp index e28114a714..5dcb0ac18a 100644 --- a/tests/host/common/MockEEPROM.cpp +++ b/tests/host/common/MockEEPROM.cpp @@ -1,32 +1,32 @@ /* - Arduino emulation - EEPROM - Copyright (c) 2018 david gauchard. All rights reserved. - - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the "Software"), - to deal with the Software without restriction, including without limitation - the rights to use, copy, modify, merge, publish, distribute, sublicense, - and/or sell copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following conditions: - - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimers. - - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimers in the - documentation and/or other materials provided with the distribution. - - - The names of its contributors may not be used to endorse or promote - products derived from this Software without specific prior written - permission. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS WITH THE SOFTWARE. + Arduino emulation - EEPROM + Copyright (c) 2018 david gauchard. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal with the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + - The names of its contributors may not be used to endorse or promote + products derived from this Software without specific prior written + permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. */ #ifndef __EEPROM_H @@ -34,11 +34,11 @@ #include -#include -#include #include -#include +#include #include +#include +#include #define EEPROM_FILE_NAME "eeprom" @@ -49,9 +49,7 @@ EEPROMClass::EEPROMClass() EEPROMClass::~EEPROMClass() { if (_fd >= 0) - { close(_fd); - } } void EEPROMClass::begin(size_t size) @@ -67,9 +65,7 @@ void EEPROMClass::begin(size_t size) void EEPROMClass::end() { if (_fd != -1) - { close(_fd); - } } bool EEPROMClass::commit() @@ -81,22 +77,16 @@ uint8_t EEPROMClass::read(int x) { char c = 0; if (pread(_fd, &c, 1, x) != 1) - { fprintf(stderr, MOCK "eeprom: %s\n\r", strerror(errno)); - } return c; } void EEPROMClass::write(int x, uint8_t c) { if (x > (int)_size) - { fprintf(stderr, MOCK "### eeprom beyond\r\n"); - } else if (pwrite(_fd, &c, 1, x) != 1) - { fprintf(stderr, MOCK "eeprom: %s\n\r", strerror(errno)); - } } #if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_EEPROM) diff --git a/tests/host/common/MockEsp.cpp b/tests/host/common/MockEsp.cpp index f61333273f..21908ba447 100644 --- a/tests/host/common/MockEsp.cpp +++ b/tests/host/common/MockEsp.cpp @@ -1,32 +1,32 @@ /* - Arduino emulation - esp8266's core - Copyright (c) 2018 david gauchard. All rights reserved. - - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the "Software"), - to deal with the Software without restriction, including without limitation - the rights to use, copy, modify, merge, publish, distribute, sublicense, - and/or sell copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following conditions: - - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimers. - - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimers in the - documentation and/or other materials provided with the distribution. - - - The names of its contributors may not be used to endorse or promote - products derived from this Software without specific prior written - permission. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS WITH THE SOFTWARE. + Arduino emulation - esp8266's core + Copyright (c) 2018 david gauchard. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal with the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + - The names of its contributors may not be used to endorse or promote + products derived from this Software without specific prior written + permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. */ #include @@ -148,17 +148,11 @@ void EspClass::getHeapStats(uint32_t* hfree, uint16_t* hmax, uint8_t* hfrag) float hm = 1 * 1024; if (hfree) - { *hfree = hf; - } if (hmax) - { *hmax = hm; - } if (hfrag) - { *hfrag = 100 - (sqrt(hm) * 100) / hf; - } } bool EspClass::flashEraseSector(uint32_t sector) diff --git a/tests/host/common/MockSPI.cpp b/tests/host/common/MockSPI.cpp index 3efef67ac9..629970f436 100644 --- a/tests/host/common/MockSPI.cpp +++ b/tests/host/common/MockSPI.cpp @@ -1,32 +1,32 @@ /* - Arduino emulation - spi - Copyright (c) 2018 david gauchard. All rights reserved. - - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the "Software"), - to deal with the Software without restriction, including without limitation - the rights to use, copy, modify, merge, publish, distribute, sublicense, - and/or sell copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following conditions: - - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimers. - - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimers in the - documentation and/or other materials provided with the distribution. - - - The names of its contributors may not be used to endorse or promote - products derived from this Software without specific prior written - permission. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS WITH THE SOFTWARE. + Arduino emulation - spi + Copyright (c) 2018 david gauchard. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal with the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + - The names of its contributors may not be used to endorse or promote + products derived from this Software without specific prior written + permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. */ #include diff --git a/tests/host/common/MockTools.cpp b/tests/host/common/MockTools.cpp index 4a469053f6..fda6895949 100644 --- a/tests/host/common/MockTools.cpp +++ b/tests/host/common/MockTools.cpp @@ -1,32 +1,32 @@ /* - Arduino emulation - tools - Copyright (c) 2018 david gauchard. All rights reserved. + Arduino emulation - tools + Copyright (c) 2018 david gauchard. All rights reserved. - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the "Software"), - to deal with the Software without restriction, including without limitation - the rights to use, copy, modify, merge, publish, distribute, sublicense, - and/or sell copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal with the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimers. + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimers in the - documentation and/or other materials provided with the distribution. + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. - - The names of its contributors may not be used to endorse or promote - products derived from this Software without specific prior written - permission. + - The names of its contributors may not be used to endorse or promote + products derived from this Software without specific prior written + permission. - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS WITH THE SOFTWARE. + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. */ #include @@ -34,35 +34,14 @@ extern "C" { - uint32_t lwip_htonl(uint32_t hostlong) - { - return htonl(hostlong); - } - uint16_t lwip_htons(uint16_t hostshort) - { - return htons(hostshort); - } - uint32_t lwip_ntohl(uint32_t netlong) - { - return ntohl(netlong); - } - uint16_t lwip_ntohs(uint16_t netshort) - { - return ntohs(netshort); - } + uint32_t lwip_htonl(uint32_t hostlong) { return htonl(hostlong); } + uint16_t lwip_htons(uint16_t hostshort) { return htons(hostshort); } + uint32_t lwip_ntohl(uint32_t netlong) { return ntohl(netlong); } + uint16_t lwip_ntohs(uint16_t netshort) { return ntohs(netshort); } - char* ets_strcpy(char* d, const char* s) - { - return strcpy(d, s); - } - char* ets_strncpy(char* d, const char* s, size_t n) - { - return strncpy(d, s, n); - } - size_t ets_strlen(const char* s) - { - return strlen(s); - } + char* ets_strcpy(char* d, const char* s) { return strcpy(d, s); } + char* ets_strncpy(char* d, const char* s, size_t n) { return strncpy(d, s, n); } + size_t ets_strlen(const char* s) { return strlen(s); } int ets_printf(const char* fmt, ...) { @@ -77,29 +56,14 @@ extern "C" void stack_thunk_del_ref() {} void stack_thunk_repaint() {} - uint32_t stack_thunk_get_refcnt() - { - return 0; - } - uint32_t stack_thunk_get_stack_top() - { - return 0; - } - uint32_t stack_thunk_get_stack_bot() - { - return 0; - } - uint32_t stack_thunk_get_cont_sp() - { - return 0; - } - uint32_t stack_thunk_get_max_usage() - { - return 0; - } + uint32_t stack_thunk_get_refcnt() { return 0; } + uint32_t stack_thunk_get_stack_top() { return 0; } + uint32_t stack_thunk_get_stack_bot() { return 0; } + uint32_t stack_thunk_get_cont_sp() { return 0; } + uint32_t stack_thunk_get_max_usage() { return 0; } void stack_thunk_dump_stack() {} - // Thunking macro +// Thunking macro #define make_stack_thunk(fcnToThunk) }; diff --git a/tests/host/common/MockUART.cpp b/tests/host/common/MockUART.cpp index eec93ca590..4ea89cddc1 100644 --- a/tests/host/common/MockUART.cpp +++ b/tests/host/common/MockUART.cpp @@ -1,36 +1,36 @@ /* - MockUART.cpp - esp8266 UART HAL EMULATION + MockUART.cpp - esp8266 UART HAL EMULATION - Copyright (c) 2019 Clemens Kirchgatterer. All rights reserved. - This file is part of the esp8266 core for Arduino environment. + Copyright (c) 2019 Clemens Kirchgatterer. All rights reserved. + This file is part of the esp8266 core for Arduino environment. - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ /* - This UART driver is directly derived from the ESP8266 UART HAL driver - Copyright (c) 2014 Ivan Grokhotkov. It provides the same API as the - original driver and was striped from all HW dependent interfaces. + This UART driver is directly derived from the ESP8266 UART HAL driver + Copyright (c) 2014 Ivan Grokhotkov. It provides the same API as the + original driver and was striped from all HW dependent interfaces. - UART0 writes got to stdout, while UART1 writes got to stderr. The user - is responsible for feeding the RX FIFO new data by calling uart_new_data(). -*/ + UART0 writes got to stdout, while UART1 writes got to stderr. The user + is responsible for feeding the RX FIFO new data by calling uart_new_data(). + */ +#include // write #include // gettimeofday #include // localtime -#include // write #include "Arduino.h" #include "uart.h" @@ -111,9 +111,7 @@ extern "C" return; #else if (++rx_buffer->rpos == rx_buffer->size) - { rx_buffer->rpos = 0; - } #endif } rx_buffer->buffer[rx_buffer->wpos] = data; @@ -140,9 +138,7 @@ extern "C" size_t ret = rx_buffer->wpos - rx_buffer->rpos; if (rx_buffer->wpos < rx_buffer->rpos) - { ret = (rx_buffer->wpos + rx_buffer->size) - rx_buffer->rpos; - } return ret; } @@ -170,9 +166,7 @@ extern "C" uart_rx_available(uart_t* uart) { if (uart == NULL || !uart->rx_enabled) - { return 0; - } return uart_rx_available_unsafe(uart->rx_buffer); } @@ -181,14 +175,10 @@ extern "C" uart_peek_char(uart_t* uart) { if (uart == NULL || !uart->rx_enabled) - { return -1; - } if (!uart_rx_available_unsafe(uart->rx_buffer)) - { return -1; - } return uart->rx_buffer->buffer[uart->rx_buffer->rpos]; } @@ -204,17 +194,13 @@ extern "C" uart_read(uart_t* uart, char* userbuffer, size_t usersize) { if (uart == NULL || !uart->rx_enabled) - { return 0; - } if (!blocking_uart) { char c; if (read(0, &c, 1) == 1) - { uart_new_data(0, c); - } } size_t ret = 0; @@ -224,9 +210,7 @@ extern "C" // get largest linear length from sw buffer size_t chunk = uart->rx_buffer->rpos < uart->rx_buffer->wpos ? uart->rx_buffer->wpos - uart->rx_buffer->rpos : uart->rx_buffer->size - uart->rx_buffer->rpos; if (ret + chunk > usersize) - { chunk = usersize - ret; - } memcpy(userbuffer + ret, uart->rx_buffer->buffer + uart->rx_buffer->rpos, chunk); uart->rx_buffer->rpos = (uart->rx_buffer->rpos + chunk) % uart->rx_buffer->size; ret += chunk; @@ -238,31 +222,21 @@ extern "C" uart_resize_rx_buffer(uart_t* uart, size_t new_size) { if (uart == NULL || !uart->rx_enabled) - { return 0; - } if (uart->rx_buffer->size == new_size) - { return uart->rx_buffer->size; - } uint8_t* new_buf = (uint8_t*)malloc(new_size); if (!new_buf) - { return uart->rx_buffer->size; - } size_t new_wpos = 0; // if uart_rx_available_unsafe() returns non-0, uart_read_char_unsafe() can't return -1 while (uart_rx_available_unsafe(uart->rx_buffer) && new_wpos < new_size) - { new_buf[new_wpos++] = uart_read_char_unsafe(uart); - } if (new_wpos == new_size) - { new_wpos = 0; - } uint8_t* old_buf = uart->rx_buffer->buffer; uart->rx_buffer->rpos = 0; @@ -283,9 +257,7 @@ extern "C" uart_write_char(uart_t* uart, char c) { if (uart == NULL || !uart->tx_enabled) - { return 0; - } uart_do_write_char(uart->uart_nr, c); @@ -296,16 +268,12 @@ extern "C" uart_write(uart_t* uart, const char* buf, size_t size) { if (uart == NULL || !uart->tx_enabled) - { return 0; - } size_t ret = size; const int uart_nr = uart->uart_nr; while (size--) - { uart_do_write_char(uart_nr, *buf++); - } return ret; } @@ -314,9 +282,7 @@ extern "C" uart_tx_free(uart_t* uart) { if (uart == NULL || !uart->tx_enabled) - { return 0; - } return UART_TX_FIFO_SIZE; } @@ -331,9 +297,7 @@ extern "C" uart_flush(uart_t* uart) { if (uart == NULL) - { return; - } if (uart->rx_enabled) { @@ -346,9 +310,7 @@ extern "C" uart_set_baudrate(uart_t* uart, int baud_rate) { if (uart == NULL) - { return; - } uart->baud_rate = baud_rate; } @@ -357,9 +319,7 @@ extern "C" uart_get_baudrate(uart_t* uart) { if (uart == NULL) - { return 0; - } return uart->baud_rate; } @@ -381,9 +341,7 @@ extern "C" (void)invert; uart_t* uart = (uart_t*)malloc(sizeof(uart_t)); if (uart == NULL) - { return NULL; - } uart->uart_nr = uart_nr; uart->rx_overrun = false; @@ -439,9 +397,7 @@ extern "C" uart_uninit(uart_t* uart) { if (uart == NULL) - { return; - } if (uart->rx_enabled) { @@ -480,9 +436,7 @@ extern "C" uart_tx_enabled(uart_t* uart) { if (uart == NULL) - { return false; - } return uart->tx_enabled; } @@ -491,9 +445,7 @@ extern "C" uart_rx_enabled(uart_t* uart) { if (uart == NULL) - { return false; - } return uart->rx_enabled; } @@ -502,9 +454,7 @@ extern "C" uart_has_overrun(uart_t* uart) { if (uart == NULL || !uart->rx_overrun) - { return false; - } // clear flag uart->rx_overrun = false; diff --git a/tests/host/common/MockWiFiServer.cpp b/tests/host/common/MockWiFiServer.cpp index 791952fe06..f199a2b588 100644 --- a/tests/host/common/MockWiFiServer.cpp +++ b/tests/host/common/MockWiFiServer.cpp @@ -1,32 +1,32 @@ /* - Arduino emulation - WiFiServer - Copyright (c) 2018 david gauchard. All rights reserved. - - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the "Software"), - to deal with the Software without restriction, including without limitation - the rights to use, copy, modify, merge, publish, distribute, sublicense, - and/or sell copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following conditions: - - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimers. - - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimers in the - documentation and/or other materials provided with the distribution. - - - The names of its contributors may not be used to endorse or promote - products derived from this Software without specific prior written - permission. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS WITH THE SOFTWARE. + Arduino emulation - WiFiServer + Copyright (c) 2018 david gauchard. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal with the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + - The names of its contributors may not be used to endorse or promote + products derived from this Software without specific prior written + permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. */ #include @@ -64,9 +64,7 @@ WiFiClient WiFiServer::available(uint8_t* status) WiFiClient WiFiServer::accept() { if (hasClient()) - { return WiFiClient(new ClientContext(serverAccept(pcb2int(_listen_pcb)))); - } return WiFiClient(); } diff --git a/tests/host/common/MockWiFiServerSocket.cpp b/tests/host/common/MockWiFiServerSocket.cpp index 4d1254fc73..aee0ad817e 100644 --- a/tests/host/common/MockWiFiServerSocket.cpp +++ b/tests/host/common/MockWiFiServerSocket.cpp @@ -1,43 +1,43 @@ /* - Arduino emulation - WiFiServer socket side - Copyright (c) 2018 david gauchard. All rights reserved. - - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the "Software"), - to deal with the Software without restriction, including without limitation - the rights to use, copy, modify, merge, publish, distribute, sublicense, - and/or sell copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following conditions: - - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimers. - - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimers in the - documentation and/or other materials provided with the distribution. - - - The names of its contributors may not be used to endorse or promote - products derived from this Software without specific prior written - permission. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS WITH THE SOFTWARE. + Arduino emulation - WiFiServer socket side + Copyright (c) 2018 david gauchard. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal with the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + - The names of its contributors may not be used to endorse or promote + products derived from this Software without specific prior written + permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. */ #include #include -#include -#include -#include -#include #include +#include +#include #include +#include +#include #define int2pcb(x) ((tcp_pcb*)(intptr_t)(x)) #define pcb2int(x) ((int)(intptr_t)(x)) @@ -66,9 +66,7 @@ void WiFiServer::begin(uint16_t port) void WiFiServer::begin(uint16_t port, uint8_t backlog) { if (!backlog) - { return; - } _port = port; return begin(); } @@ -86,9 +84,7 @@ void WiFiServer::begin() fprintf(stderr, MOCK "=====> WiFiServer port: %d shifted to %d (use option -s) <=====\n", _port, mockport); } else - { fprintf(stderr, MOCK "=====> WiFiServer port: %d <=====\n", mockport); - } if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) { @@ -133,9 +129,7 @@ bool WiFiServer::hasClient() void WiFiServer::close() { if (pcb2int(_listen_pcb) >= 0) - { ::close(pcb2int(_listen_pcb)); - } _listen_pcb = int2pcb(-1); } diff --git a/tests/host/common/MocklwIP.h b/tests/host/common/MocklwIP.h index 19ded4b26a..9f0b4718f5 100644 --- a/tests/host/common/MocklwIP.h +++ b/tests/host/common/MocklwIP.h @@ -4,8 +4,8 @@ extern "C" { -#include #include +#include extern netif netif0; diff --git a/tests/host/common/UdpContextSocket.cpp b/tests/host/common/UdpContextSocket.cpp index ef2294d6b8..0b8a17a706 100644 --- a/tests/host/common/UdpContextSocket.cpp +++ b/tests/host/common/UdpContextSocket.cpp @@ -1,43 +1,43 @@ /* - Arduino emulation - UdpContext emulation - socket part - Copyright (c) 2018 david gauchard. All rights reserved. - - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the "Software"), - to deal with the Software without restriction, including without limitation - the rights to use, copy, modify, merge, publish, distribute, sublicense, - and/or sell copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following conditions: - - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimers. - - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimers in the - documentation and/or other materials provided with the distribution. - - - The names of its contributors may not be used to endorse or promote - products derived from this Software without specific prior written - permission. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS WITH THE SOFTWARE. + Arduino emulation - UdpContext emulation - socket part + Copyright (c) 2018 david gauchard. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal with the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + - The names of its contributors may not be used to endorse or promote + products derived from this Software without specific prior written + permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. */ +#include +#include +#include #include -#include -#include +#include #include +#include +#include #include -#include -#include -#include -#include int mockUDPSocket() { @@ -62,20 +62,14 @@ bool mockUDPListen(int sock, uint32_t dstaddr, uint16_t port, uint32_t mcast) fprintf(stderr, MOCK "=====> UdpServer port: %d shifted to %d (use option -s) <=====\n", port, mockport); } else - { fprintf(stderr, MOCK "=====> UdpServer port: %d <=====\n", mockport); - } optval = 1; if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval)) == -1) - { fprintf(stderr, MOCK "SO_REUSEPORT failed\n"); - } optval = 1; if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) == -1) - { fprintf(stderr, MOCK "SO_REUSEADDR failed\n"); - } struct sockaddr_in servaddr; memset(&servaddr, 0, sizeof(servaddr)); @@ -94,14 +88,10 @@ bool mockUDPListen(int sock, uint32_t dstaddr, uint16_t port, uint32_t mcast) return false; } else - { mockverbose("UDP server on port %d (sock=%d)\n", mockport, sock); - } if (!mcast) - { mcast = inet_addr("224.0.0.1"); // all hosts group - } if (mcast) { // https://web.cs.wpi.edu/~claypool/courses/4514-B99/samples/multicast.c @@ -122,9 +112,7 @@ bool mockUDPListen(int sock, uint32_t dstaddr, uint16_t port, uint32_t mcast) #endif fprintf(stderr, MOCK "UDP multicast: can't setup bind/output on interface %s: %s\n", host_interface, strerror(errno)); if (setsockopt(sock, IPPROTO_IP, IP_MULTICAST_IF, &mreq.imr_interface, sizeof(struct in_addr)) == -1) - { fprintf(stderr, MOCK "UDP multicast: can't setup bind/input on interface %s: %s\n", host_interface, strerror(errno)); - } } if (setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) @@ -133,9 +121,7 @@ bool mockUDPListen(int sock, uint32_t dstaddr, uint16_t port, uint32_t mcast) return false; } else - { mockverbose("joined multicast group addr %08lx\n", (long)ntohl(mcast)); - } } return true; @@ -151,9 +137,7 @@ size_t mockUDPFillInBuf(int sock, char* ccinbuf, size_t& ccinbufsize, uint8_t& a if (ret == -1) { if (errno != EAGAIN) - { fprintf(stderr, MOCK "UDPContext::(read/peek): filling buffer for %zd bytes: %s\n", maxread, strerror(errno)); - } ret = 0; } @@ -161,9 +145,7 @@ size_t mockUDPFillInBuf(int sock, char* ccinbuf, size_t& ccinbufsize, uint8_t& a { port = ntohs(((sockaddr_in*)&addrbuf)->sin_port); if (addrbuf.ss_family == AF_INET) - { memcpy(&addr[0], &(((sockaddr_in*)&addrbuf)->sin_addr.s_addr), addrsize = 4); - } else { fprintf(stderr, MOCK "TODO UDP+IPv6\n"); @@ -179,9 +161,7 @@ size_t mockUDPPeekBytes(int sock, char* dst, size_t usersize, int timeout_ms, ch (void)sock; (void)timeout_ms; if (usersize > CCBUFSIZE) - { fprintf(stderr, MOCK "CCBUFSIZE(%d) should be increased by %zd bytes (-> %zd)\n", CCBUFSIZE, usersize - CCBUFSIZE, usersize); - } size_t retsize = 0; if (ccinbufsize) @@ -189,9 +169,7 @@ size_t mockUDPPeekBytes(int sock, char* dst, size_t usersize, int timeout_ms, ch // data already buffered retsize = usersize; if (retsize > ccinbufsize) - { retsize = ccinbufsize; - } } memcpy(dst, ccinbuf, retsize); return retsize; diff --git a/tests/host/common/WMath.cpp b/tests/host/common/WMath.cpp index dbfce37eb9..99b83a31f0 100644 --- a/tests/host/common/WMath.cpp +++ b/tests/host/common/WMath.cpp @@ -1,32 +1,32 @@ /* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* - Part of the Wiring project - http://wiring.org.co - Copyright (c) 2004-06 Hernando Barragan - Modified 13 August 2006, David A. Mellis for Arduino - http://www.arduino.cc/ - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General - Public License along with this library; if not, write to the - Free Software Foundation, Inc., 59 Temple Place, Suite 330, - Boston, MA 02111-1307 USA - - $Id$ -*/ + Part of the Wiring project - http://wiring.org.co + Copyright (c) 2004-06 Hernando Barragan + Modified 13 August 2006, David A. Mellis for Arduino - http://www.arduino.cc/ + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA + + $Id$ + */ extern "C" { -#include #include +#include } void randomSeed(unsigned long seed) diff --git a/tests/host/common/c_types.h b/tests/host/common/c_types.h index fcf7a889a1..f8a665ee91 100644 --- a/tests/host/common/c_types.h +++ b/tests/host/common/c_types.h @@ -6,34 +6,34 @@ // diff -u common/c_types.h ../../tools/sdk/include/c_types.h /* - ESPRESSIF MIT License - - Copyright (c) 2016 - - Permission is hereby granted for use on ESPRESSIF SYSTEMS ESP8266 only, in which case, - it is free of charge, to any person obtaining a copy of this software and associated - documentation files (the "Software"), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, - and/or sell copies of the Software, and to permit persons to whom the Software is furnished - to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or - substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -*/ + * ESPRESSIF MIT License + * + * Copyright (c) 2016 + * + * Permission is hereby granted for use on ESPRESSIF SYSTEMS ESP8266 only, in which case, + * it is free of charge, to any person obtaining a copy of this software and associated + * documentation files (the "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the Software is furnished + * to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ #ifndef _C_TYPES_H_ #define _C_TYPES_H_ -#include -#include #include +#include +#include #include typedef signed char sint8_t; diff --git a/tests/host/common/include/ClientContext.h b/tests/host/common/include/ClientContext.h index 357c0b5b8c..cec57b3030 100644 --- a/tests/host/common/include/ClientContext.h +++ b/tests/host/common/include/ClientContext.h @@ -1,23 +1,23 @@ /* - ClientContext.h - emulation of TCP connection handling on top of lwIP + ClientContext.h - emulation of TCP connection handling on top of lwIP - Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. - This file is part of the esp8266 core for Arduino environment. + Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. + This file is part of the esp8266 core for Arduino environment. - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ #ifndef CLIENTCONTEXT_H #define CLIENTCONTEXT_H @@ -91,9 +91,7 @@ class ClientContext discard_received(); close(); if (_discard_cb) - { _discard_cb(_discard_cb_arg, this); - } DEBUGV(":del\r\n"); delete this; } @@ -158,13 +156,9 @@ class ClientContext size_t getSize() { if (_sock < 0) - { return 0; - } if (_inbufsize) - { return _inbufsize; - } ssize_t ret = mockFillInBuf(_sock, _inbuf, _inbufsize); if (ret < 0) { diff --git a/tests/host/common/include/UdpContext.h b/tests/host/common/include/UdpContext.h index 238d068cfc..bbb079739a 100644 --- a/tests/host/common/include/UdpContext.h +++ b/tests/host/common/include/UdpContext.h @@ -23,8 +23,8 @@ #include -#include #include +#include #include class UdpContext; @@ -222,9 +222,7 @@ class UdpContext size_t wrt = mockUDPWrite(_sock, (const uint8_t*)_outbuf, _outbufsize, _timeout_ms, dst, dstport); err_t ret = _outbufsize ? ERR_OK : ERR_ABRT; if (!keepBuffer || wrt == _outbufsize) - { cancelBuffer(); - } return ret; } @@ -243,22 +241,16 @@ class UdpContext err_t err; esp8266::polledTimeout::oneShotFastMs timeout(timeoutMs); while (((err = trySend(addr, port)) != ERR_OK) && !timeout) - { delay(0); - } if (err != ERR_OK) - { cancelBuffer(); - } return err == ERR_OK; } void mock_cb(void) { if (_on_rx) - { _on_rx(); - } } public: @@ -276,9 +268,7 @@ class UdpContext //ip4_addr_set_u32(&ip_2_ip4(_dst), *(uint32_t*)addr); } else - { mockverbose("TODO unhandled udp address of size %d\n", (int)addrsize); - } } int _sock = -1; diff --git a/tests/host/common/littlefs_mock.cpp b/tests/host/common/littlefs_mock.cpp index a32b12cd79..ae5aa03be0 100644 --- a/tests/host/common/littlefs_mock.cpp +++ b/tests/host/common/littlefs_mock.cpp @@ -1,34 +1,34 @@ /* - littlefs_mock.cpp - LittleFS mock for host side testing - Copyright © 2019 Earle F. Philhower, III + littlefs_mock.cpp - LittleFS mock for host side testing + Copyright © 2019 Earle F. Philhower, III - Based off spiffs_mock.cpp: - Copyright © 2016 Ivan Grokhotkov + Based off spiffs_mock.cpp: + Copyright © 2016 Ivan Grokhotkov - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. */ #include "littlefs_mock.h" -#include +#include "spiffs_mock.h" +#include "spiffs/spiffs.h" +#include "debug.h" #include #include -#include "debug.h" -#include "spiffs/spiffs.h" -#include "spiffs_mock.h" +#include #include -#include -#include #include +#include +#include #include #include #include "flash_hal_mock.h" @@ -41,9 +41,7 @@ LittleFSMock::LittleFSMock(ssize_t fs_size, size_t fs_block, size_t fs_page, con { m_storage = storage; if ((m_overwrite = (fs_size < 0))) - { fs_size = -fs_size; - } fprintf(stderr, "LittleFS: %zd bytes\n", fs_size); @@ -77,9 +75,7 @@ LittleFSMock::~LittleFSMock() void LittleFSMock::load() { if (!m_fs.size() || !m_storage.length()) - { return; - } int fs = ::open(m_storage.c_str(), O_RDONLY); if (fs == -1) @@ -111,9 +107,7 @@ void LittleFSMock::load() fprintf(stderr, "LittleFS: loading %zi bytes from '%s'\n", m_fs.size(), m_storage.c_str()); ssize_t r = ::read(fs, m_fs.data(), m_fs.size()); if (r != (ssize_t)m_fs.size()) - { fprintf(stderr, "LittleFS: reading %zi bytes: returned %zd: %s\n", m_fs.size(), r, strerror(errno)); - } } ::close(fs); } @@ -121,9 +115,7 @@ void LittleFSMock::load() void LittleFSMock::save() { if (!m_fs.size() || !m_storage.length()) - { return; - } int fs = ::open(m_storage.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644); if (fs == -1) @@ -134,11 +126,7 @@ void LittleFSMock::save() fprintf(stderr, "LittleFS: saving %zi bytes to '%s'\n", m_fs.size(), m_storage.c_str()); if (::write(fs, m_fs.data(), m_fs.size()) != (ssize_t)m_fs.size()) - { fprintf(stderr, "LittleFS: writing %zi bytes: %s\n", m_fs.size(), strerror(errno)); - } if (::close(fs) == -1) - { fprintf(stderr, "LittleFS: closing %s: %s\n", m_storage.c_str(), strerror(errno)); - } } diff --git a/tests/host/common/littlefs_mock.h b/tests/host/common/littlefs_mock.h index df6f47f785..bbbbe7c0cb 100644 --- a/tests/host/common/littlefs_mock.h +++ b/tests/host/common/littlefs_mock.h @@ -1,28 +1,28 @@ /* - littlefs_mock.h - LittleFS HAL mock for host side testing - Copyright © 2019 Earle F. Philhower, III - - Based on spiffs_mock: - Copyright © 2016 Ivan Grokhotkov - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. + littlefs_mock.h - LittleFS HAL mock for host side testing + Copyright © 2019 Earle F. Philhower, III + + Based on spiffs_mock: + Copyright © 2016 Ivan Grokhotkov + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. */ #ifndef littlefs_mock_hpp #define littlefs_mock_hpp -#include -#include #include +#include #include +#include #include "flash_hal_mock.h" #define DEFAULT_LITTLEFS_FILE_NAME "littlefs.bin" diff --git a/tests/host/common/md5.c b/tests/host/common/md5.c index ea2c76c98e..8b84713aa4 100644 --- a/tests/host/common/md5.c +++ b/tests/host/common/md5.c @@ -1,40 +1,40 @@ /* - Copyright (c) 2007, Cameron Rich - - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - * * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * * Neither the name of the axTLS project nor the names of its contributors - may be used to endorse or promote products derived from this software - without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + * Copyright (c) 2007, Cameron Rich + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the axTLS project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ /** - This file implements the MD5 algorithm as defined in RFC1321 -*/ + * This file implements the MD5 algorithm as defined in RFC1321 + */ -#include -#include #include +#include +#include #define EXP_FUNC extern #define STDCALL @@ -48,8 +48,8 @@ typedef struct uint8_t buffer[64]; /* input buffer */ } MD5_CTX; -/* Constants for MD5Transform routine. -*/ +/* Constants for MD5Transform routine. + */ #define S11 7 #define S12 12 #define S13 17 @@ -78,8 +78,8 @@ static const uint8_t PADDING[64] = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; -/* F, G, H and I are basic MD5 functions. -*/ +/* F, G, H and I are basic MD5 functions. + */ #define F(x, y, z) (((x) & (y)) | ((~x) & (z))) #define G(x, y, z) (((x) & (z)) | ((y) & (~z))) #define H(x, y, z) ((x) ^ (y) ^ (z)) @@ -88,8 +88,8 @@ static const uint8_t PADDING[64] = /* ROTATE_LEFT rotates x left n bits. */ #define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) -/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. - Rotation is separate from addition to prevent recomputation. */ +/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. + Rotation is separate from addition to prevent recomputation. */ #define FF(a, b, c, d, x, s, ac) \ { \ (a) += F((b), (c), (d)) + (x) + (uint32_t)(ac); \ @@ -116,14 +116,14 @@ static const uint8_t PADDING[64] = } /** - MD5 initialization - begins an MD5 operation, writing a new ctx. -*/ + * MD5 initialization - begins an MD5 operation, writing a new ctx. + */ EXP_FUNC void STDCALL MD5Init(MD5_CTX* ctx) { ctx->count[0] = ctx->count[1] = 0; - /* Load magic initialization constants. - */ + /* Load magic initialization constants. + */ ctx->state[0] = 0x67452301; ctx->state[1] = 0xefcdab89; ctx->state[2] = 0x98badcfe; @@ -131,8 +131,8 @@ EXP_FUNC void STDCALL MD5Init(MD5_CTX* ctx) } /** - Accepts an array of octets as the next portion of the message. -*/ + * Accepts an array of octets as the next portion of the message. + */ EXP_FUNC void STDCALL MD5Update(MD5_CTX* ctx, const uint8_t* msg, int len) { uint32_t x; @@ -143,9 +143,7 @@ EXP_FUNC void STDCALL MD5Update(MD5_CTX* ctx, const uint8_t* msg, int len) /* Update number of bits */ if ((ctx->count[0] += ((uint32_t)len << 3)) < ((uint32_t)len << 3)) - { ctx->count[1]++; - } ctx->count[1] += ((uint32_t)len >> 29); partLen = 64 - x; @@ -157,24 +155,20 @@ EXP_FUNC void STDCALL MD5Update(MD5_CTX* ctx, const uint8_t* msg, int len) MD5Transform(ctx->state, ctx->buffer); for (i = partLen; i + 63 < len; i += 64) - { MD5Transform(ctx->state, &msg[i]); - } x = 0; } else - { i = 0; - } /* Buffer remaining input */ memcpy(&ctx->buffer[x], &msg[i], len - i); } /** - Return the 128-bit message digest into the user's array -*/ + * Return the 128-bit message digest into the user's array + */ EXP_FUNC void STDCALL MD5Final(uint8_t* digest, MD5_CTX* ctx) { uint8_t bits[8]; @@ -183,8 +177,8 @@ EXP_FUNC void STDCALL MD5Final(uint8_t* digest, MD5_CTX* ctx) /* Save number of bits */ Encode(bits, ctx->count, 8); - /* Pad out to 56 mod 64. - */ + /* Pad out to 56 mod 64. + */ x = (uint32_t)((ctx->count[0] >> 3) & 0x3f); padLen = (x < 56) ? (56 - x) : (120 - x); MD5Update(ctx, PADDING, padLen); @@ -197,8 +191,8 @@ EXP_FUNC void STDCALL MD5Final(uint8_t* digest, MD5_CTX* ctx) } /** - MD5 basic transformation. Transforms state based on block. -*/ + * MD5 basic transformation. Transforms state based on block. + */ static void MD5Transform(uint32_t state[4], const uint8_t block[64]) { uint32_t a = state[0], b = state[1], c = state[2], @@ -285,9 +279,9 @@ static void MD5Transform(uint32_t state[4], const uint8_t block[64]) } /** - Encodes input (uint32_t) into output (uint8_t). Assumes len is - a multiple of 4. -*/ + * Encodes input (uint32_t) into output (uint8_t). Assumes len is + * a multiple of 4. + */ static void Encode(uint8_t* output, uint32_t* input, uint32_t len) { uint32_t i, j; @@ -302,9 +296,9 @@ static void Encode(uint8_t* output, uint32_t* input, uint32_t len) } /** - Decodes input (uint8_t) into output (uint32_t). Assumes len is - a multiple of 4. -*/ + * Decodes input (uint8_t) into output (uint32_t). Assumes len is + * a multiple of 4. + */ static void Decode(uint32_t* output, const uint8_t* input, uint32_t len) { uint32_t i, j; diff --git a/tests/host/common/mock.h b/tests/host/common/mock.h index e30a607cb7..c9a6493468 100644 --- a/tests/host/common/mock.h +++ b/tests/host/common/mock.h @@ -1,32 +1,32 @@ /* - Arduino emulation - common to all emulated code - Copyright (c) 2018 david gauchard. All rights reserved. - - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the "Software"), - to deal with the Software without restriction, including without limitation - the rights to use, copy, modify, merge, publish, distribute, sublicense, - and/or sell copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following conditions: - - - Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimers. - - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimers in the - documentation and/or other materials provided with the distribution. - - - The names of its contributors may not be used to endorse or promote - products derived from this Software without specific prior written - permission. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS WITH THE SOFTWARE. + Arduino emulation - common to all emulated code + Copyright (c) 2018 david gauchard. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal with the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + - The names of its contributors may not be used to endorse or promote + products derived from this Software without specific prior written + permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. */ #define CORE_MOCK 1 diff --git a/tests/host/common/noniso.c b/tests/host/common/noniso.c index 718aadb5d4..19343a5728 100644 --- a/tests/host/common/noniso.c +++ b/tests/host/common/noniso.c @@ -1,23 +1,23 @@ /* - noniso.cpp - replacements for non-ISO functions used by Arduino core - Copyright © 2016 Ivan Grokhotkov - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. + noniso.cpp - replacements for non-ISO functions used by Arduino core + Copyright © 2016 Ivan Grokhotkov + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. */ -#include -#include -#include #include #include +#include +#include +#include #include "stdlib_noniso.h" void reverse(char* begin, char* end) @@ -83,9 +83,7 @@ char* itoa(int value, char* result, int base) // Apply negative sign if (value < 0) - { *out++ = '-'; - } reverse(result, out); *out = 0; diff --git a/tests/host/common/pins_arduino.h b/tests/host/common/pins_arduino.h index cba546a2bc..c3a66453b7 100644 --- a/tests/host/common/pins_arduino.h +++ b/tests/host/common/pins_arduino.h @@ -1,17 +1,17 @@ /* - pins_arduino.h - Copyright © 2016 Ivan Grokhotkov - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. -*/ + pins_arduino.h + Copyright © 2016 Ivan Grokhotkov + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + */ #ifndef pins_arduino_h #define pins_arduino_h diff --git a/tests/host/common/queue.h b/tests/host/common/queue.h index 1a96ce16b1..2c2d89ba34 100644 --- a/tests/host/common/queue.h +++ b/tests/host/common/queue.h @@ -1,38 +1,38 @@ /* - Copyright (c) 1991, 1993 - 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 - are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - 3. All advertising materials mentioning features or use of this software - must display the following acknowledgement: - This product includes software developed by the University of - California, Berkeley and its contributors. - 4. Neither the name of the University nor the names of its contributors - may be used to endorse or promote products derived from this software - without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - SUCH DAMAGE. - - @(#)queue.h 8.5 (Berkeley) 8/20/94 - $FreeBSD: src/sys/sys/queue.h,v 1.48 2002/04/17 14:00:37 tmm Exp $ -*/ + * Copyright (c) 1991, 1993 + * 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 + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)queue.h 8.5 (Berkeley) 8/20/94 + * $FreeBSD: src/sys/sys/queue.h,v 1.48 2002/04/17 14:00:37 tmm Exp $ + */ #ifndef _SYS_QUEUE_H_ #define _SYS_QUEUE_H_ @@ -40,72 +40,72 @@ #include /* for __offsetof */ /* - This file defines four types of data structures: singly-linked lists, - singly-linked tail queues, lists and tail queues. - - A singly-linked list is headed by a single forward pointer. The elements - are singly linked for minimum space and pointer manipulation overhead at - the expense of O(n) removal for arbitrary elements. New elements can be - added to the list after an existing element or at the head of the list. - Elements being removed from the head of the list should use the explicit - macro for this purpose for optimum efficiency. A singly-linked list may - only be traversed in the forward direction. Singly-linked lists are ideal - for applications with large datasets and few or no removals or for - implementing a LIFO queue. - - A singly-linked tail queue is headed by a pair of pointers, one to the - head of the list and the other to the tail of the list. The elements are - singly linked for minimum space and pointer manipulation overhead at the - expense of O(n) removal for arbitrary elements. New elements can be added - to the list after an existing element, at the head of the list, or at the - end of the list. Elements being removed from the head of the tail queue - should use the explicit macro for this purpose for optimum efficiency. - A singly-linked tail queue may only be traversed in the forward direction. - Singly-linked tail queues are ideal for applications with large datasets - and few or no removals or for implementing a FIFO queue. - - A list is headed by a single forward pointer (or an array of forward - pointers for a hash table header). The elements are doubly linked - so that an arbitrary element can be removed without a need to - traverse the list. New elements can be added to the list before - or after an existing element or at the head of the list. A list - may only be traversed in the forward direction. - - A tail queue is headed by a pair of pointers, one to the head of the - list and the other to the tail of the list. The elements are doubly - linked so that an arbitrary element can be removed without a need to - traverse the list. New elements can be added to the list before or - after an existing element, at the head of the list, or at the end of - the list. A tail queue may be traversed in either direction. - - For details on the use of these macros, see the queue(3) manual page. - - - SLIST LIST STAILQ TAILQ - _HEAD + + + + - _HEAD_INITIALIZER + + + + - _ENTRY + + + + - _INIT + + + + - _EMPTY + + + + - _FIRST + + + + - _NEXT + + + + - _PREV - - - + - _LAST - - + + - _FOREACH + + + + - _FOREACH_REVERSE - - - + - _INSERT_HEAD + + + + - _INSERT_BEFORE - + - + - _INSERT_AFTER + + + + - _INSERT_TAIL - - + + - _CONCAT - - + + - _REMOVE_HEAD + - + - - _REMOVE + + + + - -*/ + * This file defines four types of data structures: singly-linked lists, + * singly-linked tail queues, lists and tail queues. + * + * A singly-linked list is headed by a single forward pointer. The elements + * are singly linked for minimum space and pointer manipulation overhead at + * the expense of O(n) removal for arbitrary elements. New elements can be + * added to the list after an existing element or at the head of the list. + * Elements being removed from the head of the list should use the explicit + * macro for this purpose for optimum efficiency. A singly-linked list may + * only be traversed in the forward direction. Singly-linked lists are ideal + * for applications with large datasets and few or no removals or for + * implementing a LIFO queue. + * + * A singly-linked tail queue is headed by a pair of pointers, one to the + * head of the list and the other to the tail of the list. The elements are + * singly linked for minimum space and pointer manipulation overhead at the + * expense of O(n) removal for arbitrary elements. New elements can be added + * to the list after an existing element, at the head of the list, or at the + * end of the list. Elements being removed from the head of the tail queue + * should use the explicit macro for this purpose for optimum efficiency. + * A singly-linked tail queue may only be traversed in the forward direction. + * Singly-linked tail queues are ideal for applications with large datasets + * and few or no removals or for implementing a FIFO queue. + * + * A list is headed by a single forward pointer (or an array of forward + * pointers for a hash table header). The elements are doubly linked + * so that an arbitrary element can be removed without a need to + * traverse the list. New elements can be added to the list before + * or after an existing element or at the head of the list. A list + * may only be traversed in the forward direction. + * + * A tail queue is headed by a pair of pointers, one to the head of the + * list and the other to the tail of the list. The elements are doubly + * linked so that an arbitrary element can be removed without a need to + * traverse the list. New elements can be added to the list before or + * after an existing element, at the head of the list, or at the end of + * the list. A tail queue may be traversed in either direction. + * + * For details on the use of these macros, see the queue(3) manual page. + * + * + * SLIST LIST STAILQ TAILQ + * _HEAD + + + + + * _HEAD_INITIALIZER + + + + + * _ENTRY + + + + + * _INIT + + + + + * _EMPTY + + + + + * _FIRST + + + + + * _NEXT + + + + + * _PREV - - - + + * _LAST - - + + + * _FOREACH + + + + + * _FOREACH_REVERSE - - - + + * _INSERT_HEAD + + + + + * _INSERT_BEFORE - + - + + * _INSERT_AFTER + + + + + * _INSERT_TAIL - - + + + * _CONCAT - - + + + * _REMOVE_HEAD + - + - + * _REMOVE + + + + + * + */ /* - Singly-linked List declarations. -*/ + * Singly-linked List declarations. + */ #define SLIST_HEAD(name, type) \ struct name \ { \ @@ -124,8 +124,8 @@ } /* - Singly-linked List functions. -*/ + * Singly-linked List functions. + */ #define SLIST_EMPTY(head) ((head)->slh_first == NULL) #define SLIST_FIRST(head) ((head)->slh_first) @@ -181,8 +181,8 @@ } while (0) /* - Singly-linked Tail queue declarations. -*/ + * Singly-linked Tail queue declarations. + */ #define STAILQ_HEAD(name, type) \ struct name \ { \ @@ -202,8 +202,8 @@ } /* - Singly-linked Tail queue functions. -*/ + * Singly-linked Tail queue functions. + */ #define STAILQ_CONCAT(head1, head2) \ do \ { \ @@ -294,8 +294,8 @@ } while (0) /* - List declarations. -*/ + * List declarations. + */ #define LIST_HEAD(name, type) \ struct name \ { \ @@ -315,8 +315,8 @@ } /* - List functions. -*/ + * List functions. + */ #define LIST_EMPTY(head) ((head)->lh_first == NULL) @@ -373,8 +373,8 @@ } while (0) /* - Tail queue declarations. -*/ + * Tail queue declarations. + */ #define TAILQ_HEAD(name, type) \ struct name \ { \ @@ -395,8 +395,8 @@ } /* - Tail queue functions. -*/ + * Tail queue functions. + */ #define TAILQ_CONCAT(head1, head2, field) \ do \ { \ @@ -494,9 +494,9 @@ #ifdef _KERNEL /* - XXX insque() and remque() are an old way of handling certain queues. - They bogusly assumes that all queue heads look alike. -*/ + * XXX insque() and remque() are an old way of handling certain queues. + * They bogusly assumes that all queue heads look alike. + */ struct quehead { diff --git a/tests/host/common/sdfs_mock.cpp b/tests/host/common/sdfs_mock.cpp index 26143ea4d7..8410fa7f8a 100644 --- a/tests/host/common/sdfs_mock.cpp +++ b/tests/host/common/sdfs_mock.cpp @@ -1,16 +1,16 @@ /* - sdfs_mock.cpp - SDFS HAL mock for host side testing - Copyright (c) 2019 Earle F. Philhower, III + sdfs_mock.cpp - SDFS HAL mock for host side testing + Copyright (c) 2019 Earle F. Philhower, III - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. */ #include "sdfs_mock.h" diff --git a/tests/host/common/sdfs_mock.h b/tests/host/common/sdfs_mock.h index 0b357fa30e..462d8fffe1 100644 --- a/tests/host/common/sdfs_mock.h +++ b/tests/host/common/sdfs_mock.h @@ -1,25 +1,25 @@ /* - sdfs.h - SDFS mock for host side testing - Copyright (c) 2019 Earle F. Philhower, III - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. + sdfs.h - SDFS mock for host side testing + Copyright (c) 2019 Earle F. Philhower, III + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. */ #ifndef sdfs_mock_hpp #define sdfs_mock_hpp -#include -#include #include +#include #include +#include class SDFSMock { diff --git a/tests/host/common/spiffs_mock.cpp b/tests/host/common/spiffs_mock.cpp index eaccb41898..c6452a98f6 100644 --- a/tests/host/common/spiffs_mock.cpp +++ b/tests/host/common/spiffs_mock.cpp @@ -1,29 +1,29 @@ /* - spiffs_mock.cpp - SPIFFS HAL mock for host side testing - Copyright © 2016 Ivan Grokhotkov - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. + spiffs_mock.cpp - SPIFFS HAL mock for host side testing + Copyright © 2016 Ivan Grokhotkov + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. */ #include "spiffs_mock.h" +#include "spiffs/spiffs.h" +#include "debug.h" #include #include -#include "debug.h" -#include "spiffs/spiffs.h" #include -#include -#include #include +#include +#include #include #include @@ -40,9 +40,7 @@ SpiffsMock::SpiffsMock(ssize_t fs_size, size_t fs_block, size_t fs_page, const S { m_storage = storage; if ((m_overwrite = (fs_size < 0))) - { fs_size = -fs_size; - } fprintf(stderr, "SPIFFS: %zd bytes\n", fs_size); @@ -76,9 +74,7 @@ SpiffsMock::~SpiffsMock() void SpiffsMock::load() { if (!m_fs.size() || !m_storage.length()) - { return; - } int fs = ::open(m_storage.c_str(), O_RDONLY); if (fs == -1) @@ -110,9 +106,7 @@ void SpiffsMock::load() fprintf(stderr, "SPIFFS: loading %zi bytes from '%s'\n", m_fs.size(), m_storage.c_str()); ssize_t r = ::read(fs, m_fs.data(), m_fs.size()); if (r != (ssize_t)m_fs.size()) - { fprintf(stderr, "SPIFFS: reading %zi bytes: returned %zd: %s\n", m_fs.size(), r, strerror(errno)); - } } ::close(fs); } @@ -120,9 +114,7 @@ void SpiffsMock::load() void SpiffsMock::save() { if (!m_fs.size() || !m_storage.length()) - { return; - } int fs = ::open(m_storage.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644); if (fs == -1) @@ -133,13 +125,9 @@ void SpiffsMock::save() fprintf(stderr, "SPIFFS: saving %zi bytes to '%s'\n", m_fs.size(), m_storage.c_str()); if (::write(fs, m_fs.data(), m_fs.size()) != (ssize_t)m_fs.size()) - { fprintf(stderr, "SPIFFS: writing %zi bytes: %s\n", m_fs.size(), strerror(errno)); - } if (::close(fs) == -1) - { fprintf(stderr, "SPIFFS: closing %s: %s\n", m_storage.c_str(), strerror(errno)); - } } #pragma GCC diagnostic pop diff --git a/tests/host/common/spiffs_mock.h b/tests/host/common/spiffs_mock.h index 2cf16c7d47..098f73c3f4 100644 --- a/tests/host/common/spiffs_mock.h +++ b/tests/host/common/spiffs_mock.h @@ -1,25 +1,25 @@ /* - spiffs_mock.h - SPIFFS HAL mock for host side testing - Copyright © 2016 Ivan Grokhotkov - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. + spiffs_mock.h - SPIFFS HAL mock for host side testing + Copyright © 2016 Ivan Grokhotkov + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. */ #ifndef spiffs_mock_hpp #define spiffs_mock_hpp -#include -#include #include +#include #include +#include #include "flash_hal_mock.h" #define DEFAULT_SPIFFS_FILE_NAME "spiffs.bin" diff --git a/tests/host/common/user_interface.cpp b/tests/host/common/user_interface.cpp index 92313e7f49..0091d77ba6 100644 --- a/tests/host/common/user_interface.cpp +++ b/tests/host/common/user_interface.cpp @@ -31,13 +31,13 @@ #include -#include +#include +#include +#include #include #include -#include -#include #include -#include +#include #include "MocklwIP.h" @@ -86,8 +86,8 @@ DhcpServer dhcpSoftAP(nullptr); extern "C" { -#include #include +#include uint8 wifi_get_opmode(void) { @@ -125,9 +125,7 @@ extern "C" strcpy((char*)config->password, "emulated-ssid-password"); config->bssid_set = 0; for (int i = 0; i < 6; i++) - { config->bssid[i] = i; - } config->threshold.rssi = 1; config->threshold.authmode = AUTH_WPA_PSK; #ifdef NONOSDK3V0 @@ -182,9 +180,7 @@ extern "C" } if (host_interface) - { mockverbose("host: looking for interface '%s':\n", host_interface); - } for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) { @@ -195,10 +191,8 @@ extern "C" auto test_ipv4 = lwip_ntohl(*(uint32_t*)&((struct sockaddr_in*)ifa->ifa_addr)->sin_addr); mockverbose(" IPV4 (0x%08lx)", test_ipv4); if ((test_ipv4 & 0xff000000) == 0x7f000000) - // 127./8 - { + // 127./8 mockverbose(" (local, ignored)"); - } else { if (!host_interface || (host_interface && strcmp(ifa->ifa_name, host_interface) == 0)) @@ -208,9 +202,7 @@ extern "C" mask = *(uint32_t*)&((struct sockaddr_in*)ifa->ifa_netmask)->sin_addr; mockverbose(" (selected)\n"); if (host_interface) - { global_source_address = ntohl(ipv4); - } break; } } @@ -219,18 +211,14 @@ extern "C" } if (ifAddrStruct != NULL) - { freeifaddrs(ifAddrStruct); - } (void)if_index; //if (if_index != STATION_IF) // fprintf(stderr, "we are not AP"); if (global_ipv4_netfmt == NO_GLOBAL_BINDING) - { global_ipv4_netfmt = ipv4; - } if (info) { diff --git a/tests/host/core/test_PolledTimeout.cpp b/tests/host/core/test_PolledTimeout.cpp index ac39477feb..b2c7a212b0 100644 --- a/tests/host/core/test_PolledTimeout.cpp +++ b/tests/host/core/test_PolledTimeout.cpp @@ -24,9 +24,7 @@ TEST_CASE("OneShot Timeout 500000000ns (0.5s)", "[polledTimeout]") oneShotFastNs timeout(500000000); before = micros(); while (!timeout.expired()) - { yield(); - } after = micros(); delta = after - before; @@ -39,9 +37,7 @@ TEST_CASE("OneShot Timeout 500000000ns (0.5s)", "[polledTimeout]") timeout.reset(); before = micros(); while (!timeout) - { yield(); - } after = micros(); delta = after - before; @@ -61,9 +57,7 @@ TEST_CASE("OneShot Timeout 3000000us", "[polledTimeout]") oneShotFastUs timeout(3000000); before = micros(); while (!timeout.expired()) - { yield(); - } after = micros(); delta = after - before; @@ -76,9 +70,7 @@ TEST_CASE("OneShot Timeout 3000000us", "[polledTimeout]") timeout.reset(); before = micros(); while (!timeout) - { yield(); - } after = micros(); delta = after - before; @@ -98,9 +90,7 @@ TEST_CASE("OneShot Timeout 3000ms", "[polledTimeout]") oneShotMs timeout(3000); before = millis(); while (!timeout.expired()) - { yield(); - } after = millis(); delta = after - before; @@ -113,9 +103,7 @@ TEST_CASE("OneShot Timeout 3000ms", "[polledTimeout]") timeout.reset(); before = millis(); while (!timeout) - { yield(); - } after = millis(); delta = after - before; @@ -135,9 +123,7 @@ TEST_CASE("OneShot Timeout 3000ms reset to 1000ms", "[polledTimeout]") oneShotMs timeout(3000); before = millis(); while (!timeout.expired()) - { yield(); - } after = millis(); delta = after - before; @@ -150,9 +136,7 @@ TEST_CASE("OneShot Timeout 3000ms reset to 1000ms", "[polledTimeout]") timeout.reset(1000); before = millis(); while (!timeout) - { yield(); - } after = millis(); delta = after - before; @@ -172,9 +156,7 @@ TEST_CASE("Periodic Timeout 1T 3000ms", "[polledTimeout]") periodicMs timeout(3000); before = millis(); while (!timeout) - { yield(); - } after = millis(); delta = after - before; @@ -186,9 +168,7 @@ TEST_CASE("Periodic Timeout 1T 3000ms", "[polledTimeout]") before = millis(); while (!timeout) - { yield(); - } after = millis(); delta = after - before; @@ -215,9 +195,7 @@ TEST_CASE("Periodic Timeout 10T 1000ms", "[polledTimeout]") { Serial.print("*"); if (!--counter) - { break; - } yield(); } } diff --git a/tests/host/core/test_Print.cpp b/tests/host/core/test_Print.cpp index 86197afcf6..8e7f34729e 100644 --- a/tests/host/core/test_Print.cpp +++ b/tests/host/core/test_Print.cpp @@ -1,24 +1,24 @@ /* - test_pgmspace.cpp - pgmspace tests - Copyright © 2016 Ivan Grokhotkov + test_pgmspace.cpp - pgmspace tests + Copyright © 2016 Ivan Grokhotkov - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. -*/ + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + */ +#include +#include #include #include -#include -#include -#include #include "../common/littlefs_mock.h" +#include // Use a LittleFS file because we can't instantiate a virtual class like Print TEST_CASE("Print::write overrides all compile properly", "[core][Print]") diff --git a/tests/host/core/test_Updater.cpp b/tests/host/core/test_Updater.cpp index edd84741f5..29447e2b21 100644 --- a/tests/host/core/test_Updater.cpp +++ b/tests/host/core/test_Updater.cpp @@ -1,20 +1,20 @@ /* - test_Updater.cpp - Updater tests - Copyright © 2019 Earle F. Philhower, III + test_Updater.cpp - Updater tests + Copyright © 2019 Earle F. Philhower, III - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. -*/ + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + */ -#include #include +#include // Use a SPIFFS file because we can't instantiate a virtual class like Print TEST_CASE("Updater fails when writes overflow requested size", "[core][Updater]") diff --git a/tests/host/core/test_md5builder.cpp b/tests/host/core/test_md5builder.cpp index bb788c3d35..53e76790e7 100644 --- a/tests/host/core/test_md5builder.cpp +++ b/tests/host/core/test_md5builder.cpp @@ -1,22 +1,22 @@ /* - test_md5builder.cpp - MD5Builder tests - Copyright © 2016 Ivan Grokhotkov + test_md5builder.cpp - MD5Builder tests + Copyright © 2016 Ivan Grokhotkov - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. -*/ + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + */ +#include +#include #include #include -#include -#include TEST_CASE("MD5Builder::add works as expected", "[core][MD5Builder]") { diff --git a/tests/host/core/test_pgmspace.cpp b/tests/host/core/test_pgmspace.cpp index dc44b55374..5ebbf4c425 100644 --- a/tests/host/core/test_pgmspace.cpp +++ b/tests/host/core/test_pgmspace.cpp @@ -1,21 +1,21 @@ /* - test_pgmspace.cpp - pgmspace tests - Copyright © 2016 Ivan Grokhotkov + test_pgmspace.cpp - pgmspace tests + Copyright © 2016 Ivan Grokhotkov - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. -*/ + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + */ -#include -#include #include +#include +#include TEST_CASE("strstr_P works as strstr", "[core][pgmspace]") { diff --git a/tests/host/core/test_string.cpp b/tests/host/core/test_string.cpp index 9aa770a8a9..db6244a059 100644 --- a/tests/host/core/test_string.cpp +++ b/tests/host/core/test_string.cpp @@ -1,23 +1,23 @@ /* - test_string.cpp - String tests - Copyright © 2018 Earle F. Philhower, III + test_string.cpp - String tests + Copyright © 2018 Earle F. Philhower, III - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. -*/ + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + */ -#include +#include +#include #include #include -#include -#include +#include TEST_CASE("String::move", "[core][String]") { @@ -162,15 +162,11 @@ TEST_CASE("String concantenation", "[core][String]") n.concat(buff, 3); REQUIRE(n == "1abc"); // Ensure the trailing 0 is always present even w/this funky concat for (int i = 0; i < 20; i++) - { n.concat(buff, 1); // Add 20 'a's to go from SSO to normal string - } REQUIRE(n == "1abcaaaaaaaaaaaaaaaaaaaa"); n = ""; for (int i = 0; i <= 5; i++) - { n.concat(buff, i); - } REQUIRE(n == "aababcabcdabcde"); n.concat(buff, 0); // And check no add'n REQUIRE(n == "aababcabcdabcde"); diff --git a/tests/host/fs/test_fs.cpp b/tests/host/fs/test_fs.cpp index 5ea8e94a67..be7b26ad14 100644 --- a/tests/host/fs/test_fs.cpp +++ b/tests/host/fs/test_fs.cpp @@ -1,28 +1,28 @@ /* - test_fs.cpp - host side file system tests - Copyright © 2016 Ivan Grokhotkov - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. + test_fs.cpp - host side file system tests + Copyright © 2016 Ivan Grokhotkov + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. */ -#include -#include -#include #include #include -#include "../../../libraries/SD/src/SD.h" -#include "../../../libraries/SDFS/src/SDFS.h" +#include +#include "../common/spiffs_mock.h" #include "../common/littlefs_mock.h" #include "../common/sdfs_mock.h" -#include "../common/spiffs_mock.h" +#include +#include +#include "../../../libraries/SDFS/src/SDFS.h" +#include "../../../libraries/SD/src/SD.h" namespace spiffs_test { From 015aacff06f53930ee023846ea27132557c3ae19 Mon Sep 17 00:00:00 2001 From: david gauchard Date: Thu, 20 Jan 2022 00:13:16 +0100 Subject: [PATCH 07/15] clang-format: based on WebKit style, added Arduino ino style --- .github/workflows/pull-request.yml | 2 +- cores/esp8266/LwipDhcpServer.cpp | 162 +- cores/esp8266/LwipDhcpServer.h | 12 +- cores/esp8266/LwipIntf.cpp | 2 +- cores/esp8266/LwipIntf.h | 4 +- cores/esp8266/LwipIntfCB.cpp | 10 +- cores/esp8266/LwipIntfDev.h | 41 +- cores/esp8266/StreamSend.cpp | 6 +- cores/esp8266/StreamString.h | 84 +- cores/esp8266/core_esp8266_si2c.cpp | 275 +- .../ArduinoOTA/examples/BasicOTA/BasicOTA.ino | 2 +- .../ArduinoOTA/examples/OTALeds/OTALeds.ino | 5 +- .../CaptivePortalAdvanced.ino | 13 +- .../CaptivePortalAdvanced/handleHttp.ino | 77 +- .../examples/CaptivePortalAdvanced/tools.ino | 1 - .../Arduino_Wifi_AVRISP.ino | 26 +- .../examples/Authorization/Authorization.ino | 3 - .../BasicHttpClient/BasicHttpClient.ino | 4 +- .../BasicHttpsClient/BasicHttpsClient.ino | 6 +- .../DigestAuthorization.ino | 25 +- .../PostHttpClient/PostHttpClient.ino | 3 +- .../ReuseConnectionV2/ReuseConnectionV2.ino | 4 +- .../StreamHttpClient/StreamHttpClient.ino | 3 +- .../StreamHttpsClient/StreamHttpsClient.ino | 4 +- .../SecureBearSSLUpdater.ino | 20 +- .../SecureWebUpdater/SecureWebUpdater.ino | 2 +- .../examples/WebUpdater/WebUpdater.ino | 2 +- .../LLMNR_Web_Server/LLMNR_Web_Server.ino | 2 +- .../examples/ESP_NBNST/ESP_NBNST.ino | 3 +- libraries/ESP8266SSDP/examples/SSDP/SSDP.ino | 2 +- .../AdvancedWebServer/AdvancedWebServer.ino | 12 +- .../examples/FSBrowser/FSBrowser.ino | 22 +- .../ESP8266WebServer/examples/Graph/Graph.ino | 7 +- .../examples/HelloServer/HelloServer.ino | 14 +- .../HelloServerBearSSL/HelloServerBearSSL.ino | 50 +- .../HttpAdvancedAuth/HttpAdvancedAuth.ino | 16 +- .../examples/HttpBasicAuth/HttpBasicAuth.ino | 2 +- .../HttpHashCredAuth/HttpHashCredAuth.ino | 78 +- .../examples/PathArgServer/PathArgServer.ino | 6 +- .../examples/PostServer/PostServer.ino | 4 +- .../ServerSentEvents/ServerSentEvents.ino | 38 +- .../SimpleAuthentication.ino | 5 +- .../examples/WebServer/WebServer.ino | 134 +- .../examples/WebUpdate/WebUpdate.ino | 11 +- .../BearSSL_CertStore/BearSSL_CertStore.ino | 15 +- .../BearSSL_MaxFragmentLength.ino | 8 +- .../BearSSL_Server/BearSSL_Server.ino | 49 +- .../BearSSL_ServerClientCert.ino | 42 +- .../BearSSL_Sessions/BearSSL_Sessions.ino | 14 +- .../BearSSL_Validation/BearSSL_Validation.ino | 13 +- .../examples/HTTPSRequest/HTTPSRequest.ino | 7 +- libraries/ESP8266WiFi/examples/IPv6/IPv6.ino | 33 +- .../examples/NTPClient/NTPClient.ino | 34 +- .../examples/PagerServer/PagerServer.ino | 4 +- .../RangeExtender-NAPT/RangeExtender-NAPT.ino | 17 +- .../examples/StaticLease/StaticLease.ino | 10 +- libraries/ESP8266WiFi/examples/Udp/Udp.ino | 16 +- .../WiFiAccessPoint/WiFiAccessPoint.ino | 6 +- .../examples/WiFiClient/WiFiClient.ino | 4 +- .../WiFiClientBasic/WiFiClientBasic.ino | 6 +- .../examples/WiFiEcho/WiFiEcho.ino | 72 +- .../examples/WiFiEvents/WiFiEvents.ino | 6 +- .../WiFiManualWebServer.ino | 2 +- .../examples/WiFiScan/WiFiScan.ino | 16 +- .../examples/WiFiShutdown/WiFiShutdown.ino | 4 +- .../WiFiTelnetToSerial/WiFiTelnetToSerial.ino | 4 +- .../examples/HelloEspnow/HelloEspnow.ino | 61 +- .../examples/HelloMesh/HelloMesh.ino | 16 +- .../examples/HelloTcpIp/HelloTcpIp.ino | 32 +- .../examples/httpUpdate/httpUpdate.ino | 6 +- .../httpUpdateLittleFS/httpUpdateLittleFS.ino | 4 +- .../httpUpdateSecure/httpUpdateSecure.ino | 7 +- .../httpUpdateSigned/httpUpdateSigned.ino | 18 +- .../LEAmDNS/mDNS_Clock/mDNS_Clock.ino | 45 +- .../mDNS_ServiceMonitor.ino | 48 +- .../OTA-mDNS-LittleFS/OTA-mDNS-LittleFS.ino | 18 +- .../mDNS-SD_Extended/mDNS-SD_Extended.ino | 6 +- .../mDNS_Web_Server/mDNS_Web_Server.ino | 4 +- libraries/ESP8266mDNS/src/LEAmDNS.cpp | 1587 +++++----- libraries/ESP8266mDNS/src/LEAmDNS.h | 2091 +++++++------ libraries/ESP8266mDNS/src/LEAmDNS_Control.cpp | 2706 ++++++++-------- libraries/ESP8266mDNS/src/LEAmDNS_Helpers.cpp | 859 +++--- libraries/ESP8266mDNS/src/LEAmDNS_Priv.h | 2 +- libraries/ESP8266mDNS/src/LEAmDNS_Structs.cpp | 2746 ++++++++--------- .../ESP8266mDNS/src/LEAmDNS_Transfer.cpp | 2111 ++++++------- .../InputSerialPlotter/InputSerialPlotter.ino | 3 +- .../I2S/examples/SimpleTone/SimpleTone.ino | 4 +- .../LittleFS_Timestamp/LittleFS_Timestamp.ino | 27 +- .../LittleFS/examples/SpeedTest/SpeedTest.ino | 7 +- .../Netdump/examples/Netdump/Netdump.ino | 72 +- libraries/Netdump/src/Netdump.cpp | 16 +- libraries/Netdump/src/Netdump.h | 4 +- libraries/Netdump/src/NetdumpIP.cpp | 128 +- libraries/Netdump/src/NetdumpIP.h | 8 +- libraries/Netdump/src/NetdumpPacket.cpp | 242 +- libraries/Netdump/src/NetdumpPacket.h | 11 +- libraries/Netdump/src/PacketType.cpp | 76 +- libraries/Netdump/src/PacketType.h | 6 +- .../SD/examples/Datalogger/Datalogger.ino | 9 - libraries/SD/examples/DumpFile/DumpFile.ino | 1 - libraries/SD/examples/Files/Files.ino | 3 - libraries/SD/examples/ReadWrite/ReadWrite.ino | 2 - libraries/SD/examples/listfiles/listfiles.ino | 6 +- .../SPISlave_Master/SPISlave_Master.ino | 106 +- .../SPISlave_SafeMaster.ino | 117 +- .../examples/SPISlave_Test/SPISlave_Test.ino | 10 +- libraries/Servo/examples/Sweep/Sweep.ino | 14 +- .../examples/drawCircle/drawCircle.ino | 13 +- .../examples/drawLines/drawLines.ino | 11 +- .../examples/drawNumber/drawNumber.ino | 20 +- .../examples/drawRectangle/drawRectangle.ino | 5 +- .../examples/paint/paint.ino | 6 +- .../examples/shapes/shapes.ino | 8 +- .../examples/text/text.ino | 19 +- .../examples/tftbmp/tftbmp.ino | 44 +- .../examples/tftbmp2/tftbmp2.ino | 65 +- .../examples/TickerBasic/TickerBasic.ino | 4 +- .../TickerFunctional/TickerFunctional.ino | 38 +- libraries/Wire/Wire.cpp | 2 +- libraries/Wire/Wire.h | 4 +- .../examples/master_reader/master_reader.ino | 9 +- .../examples/master_writer/master_writer.ino | 7 +- .../slave_receiver/slave_receiver.ino | 11 +- .../examples/slave_sender/slave_sender.ino | 3 +- libraries/esp8266/examples/Blink/Blink.ino | 10 +- .../BlinkPolledTimeout/BlinkPolledTimeout.ino | 11 +- .../BlinkWithoutDelay/BlinkWithoutDelay.ino | 4 +- .../examples/CallBackList/CallBackGeneric.ino | 26 +- .../examples/CheckFlashCRC/CheckFlashCRC.ino | 3 +- .../CheckFlashConfig/CheckFlashConfig.ino | 5 +- .../examples/ConfigFile/ConfigFile.ino | 1 - .../FadePolledTimeout/FadePolledTimeout.ino | 5 +- .../examples/HeapMetric/HeapMetric.ino | 9 +- .../examples/HelloCrypto/HelloCrypto.ino | 4 - .../examples/HwdtStackDump/HwdtStackDump.ino | 15 +- .../examples/HwdtStackDump/ProcessKey.ino | 23 +- .../examples/I2STransmit/I2STransmit.ino | 7 +- .../examples/IramReserve/IramReserve.ino | 12 +- .../examples/IramReserve/ProcessKey.ino | 23 +- .../examples/LowPowerDemo/LowPowerDemo.ino | 230 +- libraries/esp8266/examples/MMU48K/MMU48K.ino | 138 +- .../examples/NTP-TZ-DST/NTP-TZ-DST.ino | 46 +- .../examples/RTCUserMemory/RTCUserMemory.ino | 14 +- .../SerialDetectBaudrate.ino | 4 +- .../examples/SerialStress/SerialStress.ino | 25 +- .../SigmaDeltaDemo/SigmaDeltaDemo.ino | 2 - .../examples/StreamString/StreamString.ino | 5 +- .../examples/TestEspApi/TestEspApi.ino | 46 +- .../examples/UartDownload/UartDownload.ino | 22 +- .../examples/interactive/interactive.ino | 90 +- .../esp8266/examples/irammem/irammem.ino | 134 +- .../examples/virtualmem/virtualmem.ino | 18 +- .../lwIP_PPP/examples/PPPServer/PPPServer.ino | 15 +- libraries/lwIP_PPP/src/PPPServer.cpp | 120 +- libraries/lwIP_PPP/src/PPPServer.h | 4 +- .../lwIP_enc28j60/src/utility/enc28j60.cpp | 43 +- .../lwIP_enc28j60/src/utility/enc28j60.h | 6 +- libraries/lwIP_w5100/src/utility/w5100.cpp | 3 +- libraries/lwIP_w5100/src/utility/w5100.h | 6 +- libraries/lwIP_w5500/src/utility/w5500.cpp | 3 +- libraries/lwIP_w5500/src/utility/w5500.h | 6 +- tests/astyle_core.conf | 32 - tests/astyle_examples.conf | 44 - tests/clang-format-arduino | 5 + .clang-format => tests/clang-format-core | 2 +- tests/device/libraries/BSTest/src/BSArduino.h | 4 +- tests/device/libraries/BSTest/src/BSArgs.h | 94 +- .../device/libraries/BSTest/src/BSProtocol.h | 174 +- tests/device/libraries/BSTest/src/BSStdio.h | 2 +- tests/device/libraries/BSTest/src/BSTest.h | 32 +- tests/device/test_libc/memmove1.c | 2 +- tests/device/test_libc/tstring.c | 113 +- tests/host/common/Arduino.cpp | 2 +- tests/host/common/ArduinoMain.cpp | 111 +- tests/host/common/EEPROM.h | 4 +- tests/host/common/HostWiring.cpp | 46 +- tests/host/common/MockEsp.cpp | 32 +- tests/host/common/MockTools.cpp | 8 +- tests/host/common/MockUART.cpp | 70 +- tests/host/common/flash_hal_mock.cpp | 3 +- tests/host/common/include/ClientContext.h | 18 +- tests/host/common/include/UdpContext.h | 9 +- tests/host/common/littlefs_mock.h | 4 +- tests/host/common/md5.c | 13 +- tests/host/common/queue.h | 154 +- tests/host/common/sdfs_mock.h | 6 +- tests/host/common/spiffs_mock.h | 4 +- tests/host/common/strl.cpp | 16 +- tests/host/common/user_interface.cpp | 2 +- tests/host/core/test_string.cpp | 13 +- tests/host/fs/test_fs.cpp | 2 +- tests/restyle.sh | 7 +- 192 files changed, 8398 insertions(+), 8862 deletions(-) mode change 100755 => 100644 libraries/ESP8266NetBIOS/examples/ESP_NBNST/ESP_NBNST.ino delete mode 100644 tests/astyle_core.conf delete mode 100644 tests/astyle_examples.conf create mode 100644 tests/clang-format-arduino rename .clang-format => tests/clang-format-core (88%) diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 5cf15ddcf3..62e7e0e09f 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -242,7 +242,7 @@ jobs: TRAVIS_TAG: ${{ github.ref }} run: | sudo apt update - sudo apt install astyle clang-format-12 + sudo apt install clang-format-12 bash ./tests/ci/style_check.sh diff --git a/cores/esp8266/LwipDhcpServer.cpp b/cores/esp8266/LwipDhcpServer.cpp index cbf151f767..c5b5342fef 100644 --- a/cores/esp8266/LwipDhcpServer.cpp +++ b/cores/esp8266/LwipDhcpServer.cpp @@ -197,12 +197,11 @@ DhcpServer::DhcpServer(netif* netif) // 1. `fw_has_started_softap_dhcps` is already initialized to 1 // 2. global ctor DhcpServer's `dhcpSoftAP(&netif_git[SOFTAP_IF])` is called // 3. (that's here) => begin(legacy-values) is called - ip_info ip = - { - {0x0104a8c0}, // IP 192.168.4.1 - {0x00ffffff}, // netmask 255.255.255.0 - {0} // gateway 0.0.0.0 - }; + ip_info ip = { + { 0x0104a8c0 }, // IP 192.168.4.1 + { 0x00ffffff }, // netmask 255.255.255.0 + { 0 } // gateway 0.0.0.0 + }; begin(&ip); fw_has_started_softap_dhcps = 2; // not 1, ending initial boot sequence } @@ -737,32 +736,32 @@ uint8_t DhcpServer::parse_options(uint8_t* optptr, sint16_t len) #endif switch ((sint16_t)*optptr) { - case DHCP_OPTION_MSG_TYPE: //53 - type = *(optptr + 2); - break; + case DHCP_OPTION_MSG_TYPE: //53 + type = *(optptr + 2); + break; - case DHCP_OPTION_REQ_IPADDR: //50 - //os_printf("dhcps:0x%08x,0x%08x\n",client.addr,*(uint32*)(optptr+2)); - if (memcmp((char*)&client.addr, (char*)optptr + 2, 4) == 0) - { + case DHCP_OPTION_REQ_IPADDR: //50 + //os_printf("dhcps:0x%08x,0x%08x\n",client.addr,*(uint32*)(optptr+2)); + if (memcmp((char*)&client.addr, (char*)optptr + 2, 4) == 0) + { #if DHCPS_DEBUG - os_printf("dhcps: DHCP_OPTION_REQ_IPADDR = 0 ok\n"); + os_printf("dhcps: DHCP_OPTION_REQ_IPADDR = 0 ok\n"); #endif - s.state = DHCPS_STATE_ACK; - } - else - { + s.state = DHCPS_STATE_ACK; + } + else + { #if DHCPS_DEBUG - os_printf("dhcps: DHCP_OPTION_REQ_IPADDR != 0 err\n"); + os_printf("dhcps: DHCP_OPTION_REQ_IPADDR != 0 err\n"); #endif - s.state = DHCPS_STATE_NAK; - } - break; - case DHCP_OPTION_END: - { - is_dhcp_parse_end = true; + s.state = DHCPS_STATE_NAK; } break; + case DHCP_OPTION_END: + { + is_dhcp_parse_end = true; + } + break; } if (is_dhcp_parse_end) @@ -775,43 +774,43 @@ uint8_t DhcpServer::parse_options(uint8_t* optptr, sint16_t len) switch (type) { - case DHCPDISCOVER: //1 - s.state = DHCPS_STATE_OFFER; + case DHCPDISCOVER: //1 + s.state = DHCPS_STATE_OFFER; #if DHCPS_DEBUG - os_printf("dhcps: DHCPD_STATE_OFFER\n"); + os_printf("dhcps: DHCPD_STATE_OFFER\n"); #endif - break; + break; - case DHCPREQUEST: //3 - if (!(s.state == DHCPS_STATE_ACK || s.state == DHCPS_STATE_NAK)) + case DHCPREQUEST: //3 + if (!(s.state == DHCPS_STATE_ACK || s.state == DHCPS_STATE_NAK)) + { + if (renew == true) { - if (renew == true) - { - s.state = DHCPS_STATE_ACK; - } - else - { - s.state = DHCPS_STATE_NAK; - } + s.state = DHCPS_STATE_ACK; + } + else + { + s.state = DHCPS_STATE_NAK; + } #if DHCPS_DEBUG - os_printf("dhcps: DHCPD_STATE_NAK\n"); + os_printf("dhcps: DHCPD_STATE_NAK\n"); #endif - } - break; + } + break; - case DHCPDECLINE: //4 - s.state = DHCPS_STATE_IDLE; + case DHCPDECLINE: //4 + s.state = DHCPS_STATE_IDLE; #if DHCPS_DEBUG - os_printf("dhcps: DHCPD_STATE_IDLE\n"); + os_printf("dhcps: DHCPD_STATE_IDLE\n"); #endif - break; + break; - case DHCPRELEASE: //7 - s.state = DHCPS_STATE_RELEASE; + case DHCPRELEASE: //7 + s.state = DHCPS_STATE_RELEASE; #if DHCPS_DEBUG - os_printf("dhcps: DHCPD_STATE_IDLE\n"); + os_printf("dhcps: DHCPD_STATE_IDLE\n"); #endif - break; + break; } #if DHCPS_DEBUG os_printf("dhcps: return s.state = %d\n", s.state); @@ -823,8 +822,9 @@ uint8_t DhcpServer::parse_options(uint8_t* optptr, sint16_t len) sint16_t DhcpServer::parse_msg(struct dhcps_msg* m, u16_t len) { if (memcmp((char*)m->options, - &magic_cookie, - sizeof(magic_cookie)) == 0) + &magic_cookie, + sizeof(magic_cookie)) + == 0) { struct ipv4_addr ip; memcpy(&ip.addr, m->ciaddr, sizeof(ip.addr)); @@ -856,10 +856,10 @@ sint16_t DhcpServer::parse_msg(struct dhcps_msg* m, u16_t len) /////////////////////////////////////////////////////////////////////////////////// void DhcpServer::S_handle_dhcp(void* arg, - struct udp_pcb* pcb, - struct pbuf* p, - const ip_addr_t* addr, - uint16_t port) + struct udp_pcb* pcb, + struct pbuf* p, + const ip_addr_t* addr, + uint16_t port) { DhcpServer* instance = reinterpret_cast(arg); instance->handle_dhcp(pcb, p, addr, port); @@ -931,30 +931,30 @@ void DhcpServer::handle_dhcp( switch (parse_msg(pmsg_dhcps, tlen - 240)) { - case DHCPS_STATE_OFFER: //1 + case DHCPS_STATE_OFFER: //1 #if DHCPS_DEBUG - os_printf("dhcps: handle_dhcp-> DHCPD_STATE_OFFER\n"); + os_printf("dhcps: handle_dhcp-> DHCPD_STATE_OFFER\n"); #endif - send_offer(pmsg_dhcps); - break; - case DHCPS_STATE_ACK: //3 + send_offer(pmsg_dhcps); + break; + case DHCPS_STATE_ACK: //3 #if DHCPS_DEBUG - os_printf("dhcps: handle_dhcp-> DHCPD_STATE_ACK\n"); + os_printf("dhcps: handle_dhcp-> DHCPD_STATE_ACK\n"); #endif - send_ack(pmsg_dhcps); - if (_netif->num == SOFTAP_IF) - { - wifi_softap_set_station_info(pmsg_dhcps->chaddr, &client_address); - } - break; - case DHCPS_STATE_NAK: //4 + send_ack(pmsg_dhcps); + if (_netif->num == SOFTAP_IF) + { + wifi_softap_set_station_info(pmsg_dhcps->chaddr, &client_address); + } + break; + case DHCPS_STATE_NAK: //4 #if DHCPS_DEBUG - os_printf("dhcps: handle_dhcp-> DHCPD_STATE_NAK\n"); + os_printf("dhcps: handle_dhcp-> DHCPD_STATE_NAK\n"); #endif - send_nak(pmsg_dhcps); - break; - default: - break; + send_nak(pmsg_dhcps); + break; + default: + break; } #if DHCPS_DEBUG os_printf("dhcps: handle_dhcp-> pbuf_free(p)\n"); @@ -1299,13 +1299,13 @@ bool DhcpServer::set_dhcps_offer_option(uint8 level, void* optarg) switch (level) { - case OFFER_ROUTER: - offer = (*(uint8*)optarg) & 0x01; - offer_flag = true; - break; - default: - offer_flag = false; - break; + case OFFER_ROUTER: + offer = (*(uint8*)optarg) & 0x01; + offer_flag = true; + break; + default: + offer_flag = false; + break; } return offer_flag; } diff --git a/cores/esp8266/LwipDhcpServer.h b/cores/esp8266/LwipDhcpServer.h index 51c4bf86f9..74fa3a4018 100644 --- a/cores/esp8266/LwipDhcpServer.h +++ b/cores/esp8266/LwipDhcpServer.h @@ -35,7 +35,7 @@ class DhcpServer { - public: +public: DhcpServer(netif* netif); ~DhcpServer(); @@ -63,7 +63,7 @@ class DhcpServer void dhcps_set_dns(int num, const ipv4_addr_t* dns); - protected: +protected: // legacy C structure and API to eventually turn into C++ typedef struct _list_node @@ -84,10 +84,10 @@ class DhcpServer uint8_t parse_options(uint8_t* optptr, sint16_t len); sint16_t parse_msg(struct dhcps_msg* m, u16_t len); static void S_handle_dhcp(void* arg, - struct udp_pcb* pcb, - struct pbuf* p, - const ip_addr_t* addr, - uint16_t port); + struct udp_pcb* pcb, + struct pbuf* p, + const ip_addr_t* addr, + uint16_t port); void handle_dhcp( struct udp_pcb* pcb, struct pbuf* p, diff --git a/cores/esp8266/LwipIntf.cpp b/cores/esp8266/LwipIntf.cpp index 71dec259a4..10d42aaf23 100644 --- a/cores/esp8266/LwipIntf.cpp +++ b/cores/esp8266/LwipIntf.cpp @@ -153,7 +153,7 @@ bool LwipIntf::hostname(const char* aHostname) if (lwipret != ERR_OK) { DEBUGV("WiFi.hostname(%s): lwIP error %d on interface %c%c (index %d)\n", - intf->hostname, (int)lwipret, intf->name[0], intf->name[1], intf->num); + intf->hostname, (int)lwipret, intf->name[0], intf->name[1], intf->num); ret = false; } } diff --git a/cores/esp8266/LwipIntf.h b/cores/esp8266/LwipIntf.h index 778785b7fd..7943c6cb5a 100644 --- a/cores/esp8266/LwipIntf.h +++ b/cores/esp8266/LwipIntf.h @@ -9,7 +9,7 @@ class LwipIntf { - public: +public: using CBType = std::function; static bool stateUpCB(LwipIntf::CBType&& cb); @@ -38,7 +38,7 @@ class LwipIntf } const char* getHostname(); - protected: +protected: static bool stateChangeSysCB(LwipIntf::CBType&& cb); }; diff --git a/cores/esp8266/LwipIntfCB.cpp b/cores/esp8266/LwipIntfCB.cpp index 7271416300..71047dcdd1 100644 --- a/cores/esp8266/LwipIntfCB.cpp +++ b/cores/esp8266/LwipIntfCB.cpp @@ -34,9 +34,9 @@ bool LwipIntf::stateChangeSysCB(LwipIntf::CBType&& cb) bool LwipIntf::stateUpCB(LwipIntf::CBType&& cb) { return stateChangeSysCB([cb](netif* nif) - { - if (netif_is_up(nif)) - schedule_function([cb, nif]() - { cb(nif); }); - }); + { + if (netif_is_up(nif)) + schedule_function([cb, nif]() + { cb(nif); }); + }); } diff --git a/cores/esp8266/LwipIntfDev.h b/cores/esp8266/LwipIntfDev.h index 3ec06c55f6..bebba74266 100644 --- a/cores/esp8266/LwipIntfDev.h +++ b/cores/esp8266/LwipIntfDev.h @@ -28,13 +28,13 @@ template class LwipIntfDev : public LwipIntf, public RawDev { - public: +public: LwipIntfDev(int8_t cs = SS, SPIClass& spi = SPI, int8_t intr = -1) - : RawDev(cs, spi, intr), - _mtu(DEFAULT_MTU), - _intrPin(intr), - _started(false), - _default(false) + : RawDev(cs, spi, intr) + , _mtu(DEFAULT_MTU) + , _intrPin(intr) + , _started(false) + , _default(false) { memset(&_netif, 0, sizeof(_netif)); } @@ -74,7 +74,7 @@ class LwipIntfDev : public LwipIntf, public RawDev wl_status_t status(); - protected: +protected: err_t netif_init(); void netif_status_callback(); @@ -190,15 +190,15 @@ boolean LwipIntfDev::begin(const uint8_t* macAddress, const uint16_t mtu { switch (dhcp_start(&_netif)) { - case ERR_OK: - break; + case ERR_OK: + break; - case ERR_IF: - return false; + case ERR_IF: + return false; - default: - netif_remove(&_netif); - return false; + default: + netif_remove(&_netif); + return false; } } @@ -218,11 +218,11 @@ boolean LwipIntfDev::begin(const uint8_t* macAddress, const uint16_t mtu } if (_intrPin < 0 && !schedule_recurrent_function_us([&]() - { - this->handlePackets(); - return true; - }, - 100)) + { + this->handlePackets(); + return true; + }, + 100)) { netif_remove(&_netif); return false; @@ -278,8 +278,7 @@ err_t LwipIntfDev::netif_init() _netif.name[1] = '0' + _netif.num; _netif.mtu = _mtu; _netif.chksum_flags = NETIF_CHECKSUM_ENABLE_ALL; - _netif.flags = - NETIF_FLAG_ETHARP | NETIF_FLAG_IGMP | NETIF_FLAG_BROADCAST | NETIF_FLAG_LINK_UP; + _netif.flags = NETIF_FLAG_ETHARP | NETIF_FLAG_IGMP | NETIF_FLAG_BROADCAST | NETIF_FLAG_LINK_UP; // lwIP's doc: This function typically first resolves the hardware // address, then sends the packet. For ethernet physical layer, this is diff --git a/cores/esp8266/StreamSend.cpp b/cores/esp8266/StreamSend.cpp index d84a4bf961..948e46e5fb 100644 --- a/cores/esp8266/StreamSend.cpp +++ b/cores/esp8266/StreamSend.cpp @@ -23,9 +23,9 @@ #include size_t Stream::sendGeneric(Print* to, - const ssize_t len, - const int readUntilChar, - const esp8266::polledTimeout::oneShotFastMs::timeType timeoutMs) + const ssize_t len, + const int readUntilChar, + const esp8266::polledTimeout::oneShotFastMs::timeType timeoutMs) { setReport(Report::Success); diff --git a/cores/esp8266/StreamString.h b/cores/esp8266/StreamString.h index 4af6f5653c..7bda5dde68 100644 --- a/cores/esp8266/StreamString.h +++ b/cores/esp8266/StreamString.h @@ -34,14 +34,16 @@ class S2Stream : public Stream { - public: +public: S2Stream(String& string, int peekPointer = -1) - : string(&string), peekPointer(peekPointer) + : string(&string) + , peekPointer(peekPointer) { } S2Stream(String* string, int peekPointer = -1) - : string(string), peekPointer(peekPointer) + : string(string) + , peekPointer(peekPointer) { } @@ -205,7 +207,7 @@ class S2Stream : public Stream peekPointer = pointer; } - protected: +protected: String* string; int peekPointer; // -1:String is consumed / >=0:resettable pointer }; @@ -214,7 +216,7 @@ class S2Stream : public Stream class StreamString : public String, public S2Stream { - protected: +protected: void resetpp() { if (peekPointer > 0) @@ -223,39 +225,81 @@ class StreamString : public String, public S2Stream } } - public: +public: StreamString(StreamString&& bro) - : String(bro), S2Stream(this) {} + : String(bro) + , S2Stream(this) + { + } StreamString(const StreamString& bro) - : String(bro), S2Stream(this) {} + : String(bro) + , S2Stream(this) + { + } // duplicate String constructors and operator=: StreamString(const char* text = nullptr) - : String(text), S2Stream(this) {} + : String(text) + , S2Stream(this) + { + } StreamString(const String& string) - : String(string), S2Stream(this) {} + : String(string) + , S2Stream(this) + { + } StreamString(const __FlashStringHelper* str) - : String(str), S2Stream(this) {} + : String(str) + , S2Stream(this) + { + } StreamString(String&& string) - : String(string), S2Stream(this) {} + : String(string) + , S2Stream(this) + { + } explicit StreamString(char c) - : String(c), S2Stream(this) {} + : String(c) + , S2Stream(this) + { + } explicit StreamString(unsigned char c, unsigned char base = 10) - : String(c, base), S2Stream(this) {} + : String(c, base) + , S2Stream(this) + { + } explicit StreamString(int i, unsigned char base = 10) - : String(i, base), S2Stream(this) {} + : String(i, base) + , S2Stream(this) + { + } explicit StreamString(unsigned int i, unsigned char base = 10) - : String(i, base), S2Stream(this) {} + : String(i, base) + , S2Stream(this) + { + } explicit StreamString(long l, unsigned char base = 10) - : String(l, base), S2Stream(this) {} + : String(l, base) + , S2Stream(this) + { + } explicit StreamString(unsigned long l, unsigned char base = 10) - : String(l, base), S2Stream(this) {} + : String(l, base) + , S2Stream(this) + { + } explicit StreamString(float f, unsigned char decimalPlaces = 2) - : String(f, decimalPlaces), S2Stream(this) {} + : String(f, decimalPlaces) + , S2Stream(this) + { + } explicit StreamString(double d, unsigned char decimalPlaces = 2) - : String(d, decimalPlaces), S2Stream(this) {} + : String(d, decimalPlaces) + , S2Stream(this) + { + } StreamString& operator=(const StreamString& rhs) { diff --git a/cores/esp8266/core_esp8266_si2c.cpp b/cores/esp8266/core_esp8266_si2c.cpp index e8f0ddb9c1..e56b8b5fba 100644 --- a/cores/esp8266/core_esp8266_si2c.cpp +++ b/cores/esp8266/core_esp8266_si2c.cpp @@ -59,7 +59,7 @@ static inline __attribute__((always_inline)) bool SCL_READ(const int twi_scl) // Implement as a class to reduce code size by allowing access to many global variables with a single base pointer class Twi { - private: +private: unsigned int preferred_si2c_clock = 100000; uint32_t twi_dcount = 18; unsigned char twi_sda = 0; @@ -72,25 +72,27 @@ class Twi // byte-wide ones, and since these emums are used everywhere, the difference adds up fast. There is only a single // instance of the class, though, so the extra 12 bytes of RAM used here saves a lot more IRAM. volatile enum { TWIPM_UNKNOWN = 0, - TWIPM_IDLE, - TWIPM_ADDRESSED, - TWIPM_WAIT } twip_mode = TWIPM_IDLE; + TWIPM_IDLE, + TWIPM_ADDRESSED, + TWIPM_WAIT } twip_mode + = TWIPM_IDLE; volatile enum { TWIP_UNKNOWN = 0, - TWIP_IDLE, - TWIP_START, - TWIP_SEND_ACK, - TWIP_WAIT_ACK, - TWIP_WAIT_STOP, - TWIP_SLA_W, - TWIP_SLA_R, - TWIP_REP_START, - TWIP_READ, - TWIP_STOP, - TWIP_REC_ACK, - TWIP_READ_ACK, - TWIP_RWAIT_ACK, - TWIP_WRITE, - TWIP_BUS_ERR } twip_state = TWIP_IDLE; + TWIP_IDLE, + TWIP_START, + TWIP_SEND_ACK, + TWIP_WAIT_ACK, + TWIP_WAIT_STOP, + TWIP_SLA_W, + TWIP_SLA_R, + TWIP_REP_START, + TWIP_READ, + TWIP_STOP, + TWIP_REC_ACK, + TWIP_READ_ACK, + TWIP_RWAIT_ACK, + TWIP_WRITE, + TWIP_BUS_ERR } twip_state + = TWIP_IDLE; volatile int twip_status = TW_NO_INFO; volatile int bitCount = 0; @@ -100,10 +102,11 @@ class Twi volatile int twi_timeout_ms = 10; volatile enum { TWI_READY = 0, - TWI_MRX, - TWI_MTX, - TWI_SRX, - TWI_STX } twi_state = TWI_READY; + TWI_MRX, + TWI_MTX, + TWI_SRX, + TWI_STX } twi_state + = TWI_READY; volatile uint8_t twi_error = 0xFF; uint8_t twi_txBuffer[TWI_BUFFER_LENGTH]; @@ -167,7 +170,7 @@ class Twi // Generate a clock "valley" (at the end of a segment, just before a repeated start) void twi_scl_valley(void); - public: +public: void setClock(unsigned int freq); void setClockStretchLimit(uint32_t limit); void init(unsigned char sda, unsigned char scl); @@ -540,105 +543,105 @@ void IRAM_ATTR Twi::onTwipEvent(uint8_t status) twip_status = status; switch (status) { - // Slave Receiver - case TW_SR_SLA_ACK: // addressed, returned ack - case TW_SR_GCALL_ACK: // addressed generally, returned ack - case TW_SR_ARB_LOST_SLA_ACK: // lost arbitration, returned ack - case TW_SR_ARB_LOST_GCALL_ACK: // lost arbitration, returned ack - // enter slave receiver mode - twi_state = TWI_SRX; - // indicate that rx buffer can be overwritten and ack - twi_rxBufferIndex = 0; + // Slave Receiver + case TW_SR_SLA_ACK: // addressed, returned ack + case TW_SR_GCALL_ACK: // addressed generally, returned ack + case TW_SR_ARB_LOST_SLA_ACK: // lost arbitration, returned ack + case TW_SR_ARB_LOST_GCALL_ACK: // lost arbitration, returned ack + // enter slave receiver mode + twi_state = TWI_SRX; + // indicate that rx buffer can be overwritten and ack + twi_rxBufferIndex = 0; + reply(1); + break; + case TW_SR_DATA_ACK: // data received, returned ack + case TW_SR_GCALL_DATA_ACK: // data received generally, returned ack + // if there is still room in the rx buffer + if (twi_rxBufferIndex < TWI_BUFFER_LENGTH) + { + // put byte in buffer and ack + twi_rxBuffer[twi_rxBufferIndex++] = twi_data; reply(1); - break; - case TW_SR_DATA_ACK: // data received, returned ack - case TW_SR_GCALL_DATA_ACK: // data received generally, returned ack - // if there is still room in the rx buffer - if (twi_rxBufferIndex < TWI_BUFFER_LENGTH) - { - // put byte in buffer and ack - twi_rxBuffer[twi_rxBufferIndex++] = twi_data; - reply(1); - } - else - { - // otherwise nack - reply(0); - } - break; - case TW_SR_STOP: // stop or repeated start condition received - // put a null char after data if there's room - if (twi_rxBufferIndex < TWI_BUFFER_LENGTH) - { - twi_rxBuffer[twi_rxBufferIndex] = '\0'; - } - // callback to user-defined callback over event task to allow for non-RAM-residing code - //twi_rxBufferLock = true; // This may be necessary - ets_post(EVENTTASK_QUEUE_PRIO, TWI_SIG_RX, twi_rxBufferIndex); - - // since we submit rx buffer to "wire" library, we can reset it - twi_rxBufferIndex = 0; - break; - - case TW_SR_DATA_NACK: // data received, returned nack - case TW_SR_GCALL_DATA_NACK: // data received generally, returned nack - // nack back at master + } + else + { + // otherwise nack reply(0); - break; - - // Slave Transmitter - case TW_ST_SLA_ACK: // addressed, returned ack - case TW_ST_ARB_LOST_SLA_ACK: // arbitration lost, returned ack - // enter slave transmitter mode - twi_state = TWI_STX; - // ready the tx buffer index for iteration - twi_txBufferIndex = 0; - // set tx buffer length to be zero, to verify if user changes it - twi_txBufferLength = 0; - // callback to user-defined callback over event task to allow for non-RAM-residing code - // request for txBuffer to be filled and length to be set - // note: user must call twi_transmit(bytes, length) to do this - ets_post(EVENTTASK_QUEUE_PRIO, TWI_SIG_TX, 0); - break; - - case TW_ST_DATA_ACK: // byte sent, ack returned - // copy data to output register - twi_data = twi_txBuffer[twi_txBufferIndex++]; - - bitCount = 8; - bitCount--; - if (twi_data & 0x80) - { - SDA_HIGH(twi.twi_sda); - } - else - { - SDA_LOW(twi.twi_sda); - } - twi_data <<= 1; + } + break; + case TW_SR_STOP: // stop or repeated start condition received + // put a null char after data if there's room + if (twi_rxBufferIndex < TWI_BUFFER_LENGTH) + { + twi_rxBuffer[twi_rxBufferIndex] = '\0'; + } + // callback to user-defined callback over event task to allow for non-RAM-residing code + //twi_rxBufferLock = true; // This may be necessary + ets_post(EVENTTASK_QUEUE_PRIO, TWI_SIG_RX, twi_rxBufferIndex); + + // since we submit rx buffer to "wire" library, we can reset it + twi_rxBufferIndex = 0; + break; + + case TW_SR_DATA_NACK: // data received, returned nack + case TW_SR_GCALL_DATA_NACK: // data received generally, returned nack + // nack back at master + reply(0); + break; + + // Slave Transmitter + case TW_ST_SLA_ACK: // addressed, returned ack + case TW_ST_ARB_LOST_SLA_ACK: // arbitration lost, returned ack + // enter slave transmitter mode + twi_state = TWI_STX; + // ready the tx buffer index for iteration + twi_txBufferIndex = 0; + // set tx buffer length to be zero, to verify if user changes it + twi_txBufferLength = 0; + // callback to user-defined callback over event task to allow for non-RAM-residing code + // request for txBuffer to be filled and length to be set + // note: user must call twi_transmit(bytes, length) to do this + ets_post(EVENTTASK_QUEUE_PRIO, TWI_SIG_TX, 0); + break; + + case TW_ST_DATA_ACK: // byte sent, ack returned + // copy data to output register + twi_data = twi_txBuffer[twi_txBufferIndex++]; + + bitCount = 8; + bitCount--; + if (twi_data & 0x80) + { + SDA_HIGH(twi.twi_sda); + } + else + { + SDA_LOW(twi.twi_sda); + } + twi_data <<= 1; - // if there is more to send, ack, otherwise nack - if (twi_txBufferIndex < twi_txBufferLength) - { - reply(1); - } - else - { - reply(0); - } - break; - case TW_ST_DATA_NACK: // received nack, we are done - case TW_ST_LAST_DATA: // received ack, but we are done already! - // leave slave receiver state - releaseBus(); - break; - - // All - case TW_NO_INFO: // no state information - break; - case TW_BUS_ERROR: // bus error, illegal stop/start - twi_error = TW_BUS_ERROR; - break; + // if there is more to send, ack, otherwise nack + if (twi_txBufferIndex < twi_txBufferLength) + { + reply(1); + } + else + { + reply(0); + } + break; + case TW_ST_DATA_NACK: // received nack, we are done + case TW_ST_LAST_DATA: // received ack, but we are done already! + // leave slave receiver state + releaseBus(); + break; + + // All + case TW_NO_INFO: // no state information + break; + case TW_BUS_ERROR: // bus error, illegal stop/start + twi_error = TW_BUS_ERROR; + break; } } @@ -660,26 +663,26 @@ void Twi::eventTask(ETSEvent* e) switch (e->sig) { - case TWI_SIG_TX: - twi.twi_onSlaveTransmit(); + case TWI_SIG_TX: + twi.twi_onSlaveTransmit(); - // if they didn't change buffer & length, initialize it - if (twi.twi_txBufferLength == 0) - { - twi.twi_txBufferLength = 1; - twi.twi_txBuffer[0] = 0x00; - } + // if they didn't change buffer & length, initialize it + if (twi.twi_txBufferLength == 0) + { + twi.twi_txBufferLength = 1; + twi.twi_txBuffer[0] = 0x00; + } - // Initiate transmission - twi.onTwipEvent(TW_ST_DATA_ACK); + // Initiate transmission + twi.onTwipEvent(TW_ST_DATA_ACK); - break; + break; - case TWI_SIG_RX: - // ack future responses and leave slave receiver state - twi.releaseBus(); - twi.twi_onSlaveReceive(twi.twi_rxBuffer, e->par); - break; + case TWI_SIG_RX: + // ack future responses and leave slave receiver state + twi.releaseBus(); + twi.twi_onSlaveReceive(twi.twi_rxBuffer, e->par); + break; } } diff --git a/libraries/ArduinoOTA/examples/BasicOTA/BasicOTA.ino b/libraries/ArduinoOTA/examples/BasicOTA/BasicOTA.ino index ddc5629741..95c1c4efac 100644 --- a/libraries/ArduinoOTA/examples/BasicOTA/BasicOTA.ino +++ b/libraries/ArduinoOTA/examples/BasicOTA/BasicOTA.ino @@ -5,7 +5,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* ssid = STASSID; diff --git a/libraries/ArduinoOTA/examples/OTALeds/OTALeds.ino b/libraries/ArduinoOTA/examples/OTALeds/OTALeds.ino index 7d05074e15..7c72b122e4 100644 --- a/libraries/ArduinoOTA/examples/OTALeds/OTALeds.ino +++ b/libraries/ArduinoOTA/examples/OTALeds/OTALeds.ino @@ -5,7 +5,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* ssid = STASSID; @@ -14,7 +14,7 @@ const char* host = "OTA-LEDS"; int led_pin = 13; #define N_DIMMERS 3 -int dimmer_pin[] = {14, 5, 15}; +int dimmer_pin[] = { 14, 5, 15 }; void setup() { Serial.begin(115200); @@ -67,7 +67,6 @@ void setup() { /* setup the OTA server */ ArduinoOTA.begin(); Serial.println("Ready"); - } void loop() { diff --git a/libraries/DNSServer/examples/CaptivePortalAdvanced/CaptivePortalAdvanced.ino b/libraries/DNSServer/examples/CaptivePortalAdvanced/CaptivePortalAdvanced.ino index 5f1f5020a1..27bfab06ce 100644 --- a/libraries/DNSServer/examples/CaptivePortalAdvanced/CaptivePortalAdvanced.ino +++ b/libraries/DNSServer/examples/CaptivePortalAdvanced/CaptivePortalAdvanced.ino @@ -20,14 +20,14 @@ /* Set these to your desired softAP credentials. They are not configurable at runtime */ #ifndef APSSID #define APSSID "ESP_ap" -#define APPSK "12345678" +#define APPSK "12345678" #endif -const char *softAP_ssid = APSSID; -const char *softAP_password = APPSK; +const char* softAP_ssid = APSSID; +const char* softAP_password = APPSK; /* hostname for mDNS. Should work at least on windows. Try http://esp8266.local */ -const char *myHostname = "esp8266"; +const char* myHostname = "esp8266"; /* Don't set this wifi credentials. They are configurated at runtime and stored on EEPROM */ char ssid[33] = ""; @@ -44,7 +44,6 @@ ESP8266WebServer server(80); IPAddress apIP(172, 217, 28, 1); IPAddress netMsk(255, 255, 255, 0); - /** Should I connect to WLAN asap? */ boolean connect; @@ -74,8 +73,8 @@ void setup() { server.on("/", handleRoot); server.on("/wifi", handleWifi); server.on("/wifisave", handleWifiSave); - server.on("/generate_204", handleRoot); //Android captive portal. Maybe not needed. Might be handled by notFound handler. - server.on("/fwlink", handleRoot); //Microsoft captive portal. Maybe not needed. Might be handled by notFound handler. + server.on("/generate_204", handleRoot); //Android captive portal. Maybe not needed. Might be handled by notFound handler. + server.on("/fwlink", handleRoot); //Microsoft captive portal. Maybe not needed. Might be handled by notFound handler. server.onNotFound(handleNotFound); server.begin(); // Web server start Serial.println("HTTP server started"); diff --git a/libraries/DNSServer/examples/CaptivePortalAdvanced/handleHttp.ino b/libraries/DNSServer/examples/CaptivePortalAdvanced/handleHttp.ino index dc286c1840..276aad2a2d 100644 --- a/libraries/DNSServer/examples/CaptivePortalAdvanced/handleHttp.ino +++ b/libraries/DNSServer/examples/CaptivePortalAdvanced/handleHttp.ino @@ -9,18 +9,18 @@ void handleRoot() { String Page; Page += F( - "" - "" - "CaptivePortal" - "

    HELLO WORLD!!

    "); + "" + "" + "CaptivePortal" + "

    HELLO WORLD!!

    "); if (server.client().localIP() == apIP) { Page += String(F("

    You are connected through the soft AP: ")) + softAP_ssid + F("

    "); } else { Page += String(F("

    You are connected through the wifi network: ")) + ssid + F("

    "); } Page += F( - "

    You may want to config the wifi connection.

    " - ""); + "

    You may want to config the wifi connection.

    " + ""); server.send(200, "text/html", Page); } @@ -30,7 +30,7 @@ boolean captivePortal() { if (!isIp(server.hostHeader()) && server.hostHeader() != (String(myHostname) + ".local")) { Serial.println("Request redirected to captive portal"); server.sendHeader("Location", String("http://") + toStringIp(server.client().localIP()), true); - server.send(302, "text/plain", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. + server.send(302, "text/plain", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. server.client().stop(); // Stop is needed because we sent no content length return true; } @@ -45,37 +45,32 @@ void handleWifi() { String Page; Page += F( - "" - "" - "CaptivePortal" - "

    Wifi config

    "); + "" + "" + "CaptivePortal" + "

    Wifi config

    "); if (server.client().localIP() == apIP) { Page += String(F("

    You are connected through the soft AP: ")) + softAP_ssid + F("

    "); } else { Page += String(F("

    You are connected through the wifi network: ")) + ssid + F("

    "); } - Page += - String(F( - "\r\n
    " - "" - "" - "" - "
    SoftAP config
    SSID ")) + - String(softAP_ssid) + - F("
    IP ") + - toStringIp(WiFi.softAPIP()) + - F("
    " - "\r\n
    " - "" - "" - "" - "
    WLAN config
    SSID ") + - String(ssid) + - F("
    IP ") + - toStringIp(WiFi.localIP()) + - F("
    " - "\r\n
    " - ""); + Page += String(F( + "\r\n
    " + "
    WLAN list (refresh if any missing)
    " + "" + "" + "
    SoftAP config
    SSID ")) + + String(softAP_ssid) + F("
    IP ") + + toStringIp(WiFi.softAPIP()) + F("
    " + "\r\n
    " + "" + "" + "" + "
    WLAN config
    SSID ") + + String(ssid) + F("
    IP ") + + toStringIp(WiFi.localIP()) + F("
    " + "\r\n
    " + ""); Serial.println("scan start"); int n = WiFi.scanNetworks(); Serial.println("scan done"); @@ -87,13 +82,13 @@ void handleWifi() { Page += F(""); } Page += F( - "
    WLAN list (refresh if any missing)
    No WLAN found
    " - "\r\n

    Connect to network:

    " - "" - "
    " - "
    " - "

    You may want to return to the home page.

    " - ""); + "" + "\r\n

    Connect to network:

    " + "" + "
    " + "
    " + "

    You may want to return to the home page.

    " + ""); server.send(200, "text/html", Page); server.client().stop(); // Stop is needed because we sent no content length } @@ -107,7 +102,7 @@ void handleWifiSave() { server.sendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); server.sendHeader("Pragma", "no-cache"); server.sendHeader("Expires", "-1"); - server.send(302, "text/plain", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. + server.send(302, "text/plain", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. server.client().stop(); // Stop is needed because we sent no content length saveCredentials(); connect = strlen(ssid) > 0; // Request WLAN connect with new credentials if there is a SSID diff --git a/libraries/DNSServer/examples/CaptivePortalAdvanced/tools.ino b/libraries/DNSServer/examples/CaptivePortalAdvanced/tools.ino index e4840a1c12..6ed7b05b7d 100644 --- a/libraries/DNSServer/examples/CaptivePortalAdvanced/tools.ino +++ b/libraries/DNSServer/examples/CaptivePortalAdvanced/tools.ino @@ -18,4 +18,3 @@ String toStringIp(IPAddress ip) { res += String(((ip >> 8 * 3)) & 0xFF); return res; } - diff --git a/libraries/ESP8266AVRISP/examples/Arduino_Wifi_AVRISP/Arduino_Wifi_AVRISP.ino b/libraries/ESP8266AVRISP/examples/Arduino_Wifi_AVRISP/Arduino_Wifi_AVRISP.ino index fdc34cff2b..01b7388bb2 100644 --- a/libraries/ESP8266AVRISP/examples/Arduino_Wifi_AVRISP/Arduino_Wifi_AVRISP.ino +++ b/libraries/ESP8266AVRISP/examples/Arduino_Wifi_AVRISP/Arduino_Wifi_AVRISP.ino @@ -5,7 +5,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* host = "esp8266-avrisp"; @@ -52,20 +52,20 @@ void loop() { if (last_state != new_state) { switch (new_state) { case AVRISP_STATE_IDLE: { - Serial.printf("[AVRISP] now idle\r\n"); - // Use the SPI bus for other purposes - break; - } + Serial.printf("[AVRISP] now idle\r\n"); + // Use the SPI bus for other purposes + break; + } case AVRISP_STATE_PENDING: { - Serial.printf("[AVRISP] connection pending\r\n"); - // Clean up your other purposes and prepare for programming mode - break; - } + Serial.printf("[AVRISP] connection pending\r\n"); + // Clean up your other purposes and prepare for programming mode + break; + } case AVRISP_STATE_ACTIVE: { - Serial.printf("[AVRISP] programming mode\r\n"); - // Stand by for completion - break; - } + Serial.printf("[AVRISP] programming mode\r\n"); + // Stand by for completion + break; + } } last_state = new_state; } diff --git a/libraries/ESP8266HTTPClient/examples/Authorization/Authorization.ino b/libraries/ESP8266HTTPClient/examples/Authorization/Authorization.ino index 9de3077ff4..878cab95b5 100644 --- a/libraries/ESP8266HTTPClient/examples/Authorization/Authorization.ino +++ b/libraries/ESP8266HTTPClient/examples/Authorization/Authorization.ino @@ -33,7 +33,6 @@ void setup() { WiFi.mode(WIFI_STA); WiFiMulti.addAP("SSID", "PASSWORD"); - } void loop() { @@ -47,7 +46,6 @@ void loop() { Serial.print("[HTTP] begin...\n"); // configure traged server and url - http.begin(client, "http://guest:guest@jigsaw.w3.org/HTTP/Basic/"); /* @@ -60,7 +58,6 @@ void loop() { http.setAuthorization("Z3Vlc3Q6Z3Vlc3Q="); */ - Serial.print("[HTTP] GET...\n"); // start connection and send HTTP header int httpCode = http.GET(); diff --git a/libraries/ESP8266HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino b/libraries/ESP8266HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino index 21a97172ef..18f225b797 100644 --- a/libraries/ESP8266HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino +++ b/libraries/ESP8266HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino @@ -33,7 +33,6 @@ void setup() { WiFi.mode(WIFI_STA); WiFiMulti.addAP("SSID", "PASSWORD"); - } void loop() { @@ -45,8 +44,7 @@ void loop() { HTTPClient http; Serial.print("[HTTP] begin...\n"); - if (http.begin(client, "http://jigsaw.w3.org/HTTP/connection.html")) { // HTTP - + if (http.begin(client, "http://jigsaw.w3.org/HTTP/connection.html")) { // HTTP Serial.print("[HTTP] GET...\n"); // start connection and send HTTP header diff --git a/libraries/ESP8266HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino b/libraries/ESP8266HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino index aaa4af2b4d..efb653fc76 100644 --- a/libraries/ESP8266HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino +++ b/libraries/ESP8266HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino @@ -14,7 +14,7 @@ #include // Fingerprint for demo URL, expires on June 2, 2021, needs to be updated well before this date -const uint8_t fingerprint[20] = {0x40, 0xaf, 0x00, 0x6b, 0xec, 0x90, 0x22, 0x41, 0x8e, 0xa3, 0xad, 0xfa, 0x1a, 0xe8, 0x25, 0x41, 0x1d, 0x1a, 0x54, 0xb3}; +const uint8_t fingerprint[20] = { 0x40, 0xaf, 0x00, 0x6b, 0xec, 0x90, 0x22, 0x41, 0x8e, 0xa3, 0xad, 0xfa, 0x1a, 0xe8, 0x25, 0x41, 0x1d, 0x1a, 0x54, 0xb3 }; ESP8266WiFiMulti WiFiMulti; @@ -41,7 +41,7 @@ void loop() { // wait for WiFi connection if ((WiFiMulti.run() == WL_CONNECTED)) { - std::unique_ptrclient(new BearSSL::WiFiClientSecure); + std::unique_ptr client(new BearSSL::WiFiClientSecure); client->setFingerprint(fingerprint); // Or, if you happy to ignore the SSL certificate, then use the following line instead: @@ -50,7 +50,7 @@ void loop() { HTTPClient https; Serial.print("[HTTPS] begin...\n"); - if (https.begin(*client, "https://jigsaw.w3.org/HTTP/connection.html")) { // HTTPS + if (https.begin(*client, "https://jigsaw.w3.org/HTTP/connection.html")) { // HTTPS Serial.print("[HTTPS] GET...\n"); // start connection and send HTTP header diff --git a/libraries/ESP8266HTTPClient/examples/DigestAuthorization/DigestAuthorization.ino b/libraries/ESP8266HTTPClient/examples/DigestAuthorization/DigestAuthorization.ino index db8fe8cbd4..a538fd4799 100644 --- a/libraries/ESP8266HTTPClient/examples/DigestAuthorization/DigestAuthorization.ino +++ b/libraries/ESP8266HTTPClient/examples/DigestAuthorization/DigestAuthorization.ino @@ -13,17 +13,17 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* ssid = STASSID; const char* ssidPassword = STAPSK; -const char *username = "admin"; -const char *password = "admin"; +const char* username = "admin"; +const char* password = "admin"; -const char *server = "http://httpbin.org"; -const char *uri = "/digest-auth/auth/admin/admin/MD5"; +const char* server = "http://httpbin.org"; +const char* uri = "/digest-auth/auth/admin/admin/MD5"; String exractParam(String& authReq, const String& param, const char delimit) { int _begin = authReq.indexOf(param); @@ -34,10 +34,9 @@ String exractParam(String& authReq, const String& param, const char delimit) { } String getCNonce(const int len) { - static const char alphanum[] = - "0123456789" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz"; + static const char alphanum[] = "0123456789" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz"; String s = ""; for (int i = 0; i < len; ++i) { @@ -59,7 +58,7 @@ String getDigestAuth(String& authReq, const String& username, const String& pass // parameters for the RFC 2617 newer Digest MD5Builder md5; md5.begin(); - md5.add(username + ":" + realm + ":" + password); // md5 of the user:realm:user + md5.add(username + ":" + realm + ":" + password); // md5 of the user:realm:user md5.calculate(); String h1 = md5.toString(); @@ -73,8 +72,7 @@ String getDigestAuth(String& authReq, const String& username, const String& pass md5.calculate(); String response = md5.toString(); - String authorization = "Digest username=\"" + username + "\", realm=\"" + realm + "\", nonce=\"" + nonce + - "\", uri=\"" + uri + "\", algorithm=\"MD5\", qop=auth, nc=" + String(nc) + ", cnonce=\"" + cNonce + "\", response=\"" + response + "\""; + String authorization = "Digest username=\"" + username + "\", realm=\"" + realm + "\", nonce=\"" + nonce + "\", uri=\"" + uri + "\", algorithm=\"MD5\", qop=auth, nc=" + String(nc) + ", cnonce=\"" + cNonce + "\", response=\"" + response + "\""; Serial.println(authorization); return authorization; @@ -107,8 +105,7 @@ void loop() { // configure traged server and url http.begin(client, String(server) + String(uri)); - - const char *keys[] = {"WWW-Authenticate"}; + const char* keys[] = { "WWW-Authenticate" }; http.collectHeaders(keys, 1); Serial.print("[HTTP] GET...\n"); diff --git a/libraries/ESP8266HTTPClient/examples/PostHttpClient/PostHttpClient.ino b/libraries/ESP8266HTTPClient/examples/PostHttpClient/PostHttpClient.ino index 936e235eeb..01f7c34eff 100644 --- a/libraries/ESP8266HTTPClient/examples/PostHttpClient/PostHttpClient.ino +++ b/libraries/ESP8266HTTPClient/examples/PostHttpClient/PostHttpClient.ino @@ -20,7 +20,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif void setup() { @@ -40,7 +40,6 @@ void setup() { Serial.println(""); Serial.print("Connected! IP address: "); Serial.println(WiFi.localIP()); - } void loop() { diff --git a/libraries/ESP8266HTTPClient/examples/ReuseConnectionV2/ReuseConnectionV2.ino b/libraries/ESP8266HTTPClient/examples/ReuseConnectionV2/ReuseConnectionV2.ino index 42a89beced..4cfc3911bf 100644 --- a/libraries/ESP8266HTTPClient/examples/ReuseConnectionV2/ReuseConnectionV2.ino +++ b/libraries/ESP8266HTTPClient/examples/ReuseConnectionV2/ReuseConnectionV2.ino @@ -6,14 +6,13 @@ This example reuses the http connection and also restores the connection if the connection is lost */ - #include #include #include #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif ESP8266WiFiMulti WiFiMulti; @@ -43,7 +42,6 @@ void setup() { // allow reuse (if server supports it) http.setReuse(true); - http.begin(client, "http://jigsaw.w3.org/HTTP/connection.html"); //http.begin(client, "jigsaw.w3.org", 80, "/HTTP/connection.html"); } diff --git a/libraries/ESP8266HTTPClient/examples/StreamHttpClient/StreamHttpClient.ino b/libraries/ESP8266HTTPClient/examples/StreamHttpClient/StreamHttpClient.ino index 7e1593f52b..7a813c7e10 100644 --- a/libraries/ESP8266HTTPClient/examples/StreamHttpClient/StreamHttpClient.ino +++ b/libraries/ESP8266HTTPClient/examples/StreamHttpClient/StreamHttpClient.ino @@ -31,7 +31,6 @@ void setup() { WiFi.mode(WIFI_STA); WiFiMulti.addAP("SSID", "PASSWORD"); - } void loop() { @@ -70,7 +69,7 @@ void loop() { // or "by hand" // get tcp stream - WiFiClient * stream = &client; + WiFiClient* stream = &client; // read all data from server while (http.connected() && (len > 0 || len == -1)) { diff --git a/libraries/ESP8266HTTPClient/examples/StreamHttpsClient/StreamHttpsClient.ino b/libraries/ESP8266HTTPClient/examples/StreamHttpsClient/StreamHttpsClient.ino index 8098986650..9ba575bd78 100644 --- a/libraries/ESP8266HTTPClient/examples/StreamHttpsClient/StreamHttpsClient.ino +++ b/libraries/ESP8266HTTPClient/examples/StreamHttpsClient/StreamHttpsClient.ino @@ -31,7 +31,6 @@ void setup() { WiFi.mode(WIFI_STA); WiFiMulti.addAP("SSID", "PASSWORD"); - } void loop() { @@ -50,7 +49,7 @@ void loop() { Serial.print("[HTTPS] begin...\n"); // configure server and url - const uint8_t fingerprint[20] = {0x15, 0x77, 0xdc, 0x04, 0x7c, 0x00, 0xf8, 0x70, 0x09, 0x34, 0x24, 0xf4, 0xd3, 0xa1, 0x7a, 0x6c, 0x1e, 0xa3, 0xe0, 0x2a}; + const uint8_t fingerprint[20] = { 0x15, 0x77, 0xdc, 0x04, 0x7c, 0x00, 0xf8, 0x70, 0x09, 0x34, 0x24, 0xf4, 0xd3, 0xa1, 0x7a, 0x6c, 0x1e, 0xa3, 0xe0, 0x2a }; client->setFingerprint(fingerprint); @@ -95,7 +94,6 @@ void loop() { Serial.println(); Serial.print("[HTTPS] connection closed or file end.\n"); - } } else { Serial.printf("[HTTPS] GET... failed, error: %s\n", https.errorToString(httpCode).c_str()); diff --git a/libraries/ESP8266HTTPUpdateServer/examples/SecureBearSSLUpdater/SecureBearSSLUpdater.ino b/libraries/ESP8266HTTPUpdateServer/examples/SecureBearSSLUpdater/SecureBearSSLUpdater.ino index a2514e171d..d849181a6c 100644 --- a/libraries/ESP8266HTTPUpdateServer/examples/SecureBearSSLUpdater/SecureBearSSLUpdater.ino +++ b/libraries/ESP8266HTTPUpdateServer/examples/SecureBearSSLUpdater/SecureBearSSLUpdater.ino @@ -21,7 +21,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* host = "esp8266-webupdate"; @@ -57,7 +57,7 @@ JfUvYadSYxh3nblvA4OL+iEZiW8NE3hbW6WPXxvS7Euge0uWMPc4uEcnsE0ZVG3m -----END CERTIFICATE----- )EOF"; -static const char serverKey[] PROGMEM = R"EOF( +static const char serverKey[] PROGMEM = R"EOF( -----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEA9UoHBtn4oNKXjRgIOQ/rLxK/iI0a8Q5mDxhfuwa9//FkftSI IFY8UhGk2YNJpnfKOyYWqbqwuJhIZJ2sEIWp2301OnavuGBrpKOgBJJljgH2l/4Z @@ -87,9 +87,7 @@ gz5JWYhbD6c38khSzJb0pNXCo3EuYAVa36kDM96k1BtWuhRS10Q1VXk= -----END RSA PRIVATE KEY----- )EOF"; - -void setup() -{ +void setup() { Serial.begin(115200); Serial.println(); @@ -97,7 +95,7 @@ void setup() WiFi.mode(WIFI_AP_STA); WiFi.begin(ssid, password); - while(WiFi.waitForConnectResult() != WL_CONNECTED){ + while (WiFi.waitForConnectResult() != WL_CONNECTED) { WiFi.begin(ssid, password); Serial.println("WiFi failed, retrying."); } @@ -111,13 +109,13 @@ void setup() httpServer.begin(); MDNS.addService("https", "tcp", 443); - Serial.printf("BearSSLUpdateServer ready!\nOpen https://%s.local%s in "\ - "your browser and login with username '%s' and password "\ - "'%s'\n", host, update_path, update_username, update_password); + Serial.printf("BearSSLUpdateServer ready!\nOpen https://%s.local%s in " + "your browser and login with username '%s' and password " + "'%s'\n", + host, update_path, update_username, update_password); } -void loop() -{ +void loop() { httpServer.handleClient(); MDNS.update(); } diff --git a/libraries/ESP8266HTTPUpdateServer/examples/SecureWebUpdater/SecureWebUpdater.ino b/libraries/ESP8266HTTPUpdateServer/examples/SecureWebUpdater/SecureWebUpdater.ino index 11e23a929d..d37ef3f1f6 100644 --- a/libraries/ESP8266HTTPUpdateServer/examples/SecureWebUpdater/SecureWebUpdater.ino +++ b/libraries/ESP8266HTTPUpdateServer/examples/SecureWebUpdater/SecureWebUpdater.ino @@ -10,7 +10,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* host = "esp8266-webupdate"; diff --git a/libraries/ESP8266HTTPUpdateServer/examples/WebUpdater/WebUpdater.ino b/libraries/ESP8266HTTPUpdateServer/examples/WebUpdater/WebUpdater.ino index fea3c4023a..89b5f62a90 100644 --- a/libraries/ESP8266HTTPUpdateServer/examples/WebUpdater/WebUpdater.ino +++ b/libraries/ESP8266HTTPUpdateServer/examples/WebUpdater/WebUpdater.ino @@ -10,7 +10,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* host = "esp8266-webupdate"; diff --git a/libraries/ESP8266LLMNR/examples/LLMNR_Web_Server/LLMNR_Web_Server.ino b/libraries/ESP8266LLMNR/examples/LLMNR_Web_Server/LLMNR_Web_Server.ino index 6b29bb5141..f36da85aeb 100644 --- a/libraries/ESP8266LLMNR/examples/LLMNR_Web_Server/LLMNR_Web_Server.ino +++ b/libraries/ESP8266LLMNR/examples/LLMNR_Web_Server/LLMNR_Web_Server.ino @@ -62,7 +62,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* ssid = STASSID; diff --git a/libraries/ESP8266NetBIOS/examples/ESP_NBNST/ESP_NBNST.ino b/libraries/ESP8266NetBIOS/examples/ESP_NBNST/ESP_NBNST.ino old mode 100755 new mode 100644 index 57f5529850..4d7998667b --- a/libraries/ESP8266NetBIOS/examples/ESP_NBNST/ESP_NBNST.ino +++ b/libraries/ESP8266NetBIOS/examples/ESP_NBNST/ESP_NBNST.ino @@ -4,7 +4,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* ssid = STASSID; @@ -40,7 +40,6 @@ void setup() { Serial.print("IP address: "); Serial.println(WiFi.localIP()); - wwwserver.on("/", handleRoot); wwwserver.begin(); diff --git a/libraries/ESP8266SSDP/examples/SSDP/SSDP.ino b/libraries/ESP8266SSDP/examples/SSDP/SSDP.ino index 28b0ca977b..c081869696 100644 --- a/libraries/ESP8266SSDP/examples/SSDP/SSDP.ino +++ b/libraries/ESP8266SSDP/examples/SSDP/SSDP.ino @@ -4,7 +4,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* ssid = STASSID; diff --git a/libraries/ESP8266WebServer/examples/AdvancedWebServer/AdvancedWebServer.ino b/libraries/ESP8266WebServer/examples/AdvancedWebServer/AdvancedWebServer.ino index 2fc8508ca0..c20d1ddb15 100644 --- a/libraries/ESP8266WebServer/examples/AdvancedWebServer/AdvancedWebServer.ino +++ b/libraries/ESP8266WebServer/examples/AdvancedWebServer/AdvancedWebServer.ino @@ -35,11 +35,11 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char *ssid = STASSID; -const char *password = STAPSK; +const char* ssid = STASSID; +const char* password = STAPSK; ESP8266WebServer server(80); @@ -54,7 +54,7 @@ void handleRoot() { snprintf(temp, 400, - "\ + "\ \ \ ESP8266 Demo\ @@ -69,8 +69,7 @@ void handleRoot() { \ ", - hr, min % 60, sec % 60 - ); + hr, min % 60, sec % 60); server.send(200, "text/html", temp); digitalWrite(led, 0); } @@ -151,4 +150,3 @@ void loop(void) { server.handleClient(); MDNS.update(); } - diff --git a/libraries/ESP8266WebServer/examples/FSBrowser/FSBrowser.ino b/libraries/ESP8266WebServer/examples/FSBrowser/FSBrowser.ino index 39f69fe3ff..686f4327ed 100644 --- a/libraries/ESP8266WebServer/examples/FSBrowser/FSBrowser.ino +++ b/libraries/ESP8266WebServer/examples/FSBrowser/FSBrowser.ino @@ -67,12 +67,11 @@ SDFSConfig fileSystemConfig = SDFSConfig(); #error Please select a filesystem first by uncommenting one of the "#define USE_xxx" lines at the beginning of the sketch. #endif - #define DBG_OUTPUT_PORT Serial #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* ssid = STASSID; @@ -135,7 +134,6 @@ String checkForUnsupportedPath(String filename) { } #endif - //////////////////////////////// // Request handlers @@ -168,7 +166,6 @@ void handleStatus() { server.send(200, "application/json", json); } - /* Return the list of files in the directory specified by the "dir" query string parameter. Also demonstrates the use of chunked responses. @@ -242,7 +239,6 @@ void handleFileList() { server.chunkedResponseFinalize(); } - /* Read the given file from the filesystem and stream it back to the client */ @@ -280,7 +276,6 @@ bool handleFileRead(String path) { return false; } - /* As some FS (e.g. LittleFS) delete the parent folder when the last child has been removed, return the path of the closest parent still existing @@ -290,7 +285,7 @@ String lastExistingParent(String path) { if (path.lastIndexOf('/') > 0) { path = path.substring(0, path.lastIndexOf('/')); } else { - path = String(); // No slash => the top folder does not exist + path = String(); // No slash => the top folder does not exist } } DBG_OUTPUT_PORT.println(String("Last existing parent: ") + path); @@ -345,7 +340,7 @@ void handleFileCreate() { // Create a file File file = fileSystem->open(path, "w"); if (file) { - file.write((const char *)0); + file.write((const char*)0); file.close(); } else { return replyServerError(F("CREATE FAILED")); @@ -379,7 +374,6 @@ void handleFileCreate() { } } - /* Delete the file or folder designed by the given path. If it's a file, delete it. @@ -411,7 +405,6 @@ void deleteRecursive(String path) { fileSystem->rmdir(path); } - /* Handle a file deletion request Operation | req.responseText @@ -477,7 +470,6 @@ void handleFileUpload() { } } - /* The "Not Found" handler catches all URI not explicitly declared in code First try to find and return the requested file from the filesystem, @@ -536,7 +528,6 @@ void handleGetEdit() { #else replyNotFound(FPSTR(FILE_NOT_FOUND)); #endif - } void setup(void) { @@ -609,15 +600,15 @@ void setup(void) { server.on("/edit", HTTP_GET, handleGetEdit); // Create file - server.on("/edit", HTTP_PUT, handleFileCreate); + server.on("/edit", HTTP_PUT, handleFileCreate); // Delete file - server.on("/edit", HTTP_DELETE, handleFileDelete); + server.on("/edit", HTTP_DELETE, handleFileDelete); // Upload file // - first callback is called after the request has ended with all parsed arguments // - second callback handles file upload at that location - server.on("/edit", HTTP_POST, replyOK, handleFileUpload); + server.on("/edit", HTTP_POST, replyOK, handleFileUpload); // Default handler for all URIs not defined above // Use it to read files from filesystem @@ -628,7 +619,6 @@ void setup(void) { DBG_OUTPUT_PORT.println("HTTP server started"); } - void loop(void) { server.handleClient(); MDNS.update(); diff --git a/libraries/ESP8266WebServer/examples/Graph/Graph.ino b/libraries/ESP8266WebServer/examples/Graph/Graph.ino index b0eb5f847b..d4915f201f 100644 --- a/libraries/ESP8266WebServer/examples/Graph/Graph.ino +++ b/libraries/ESP8266WebServer/examples/Graph/Graph.ino @@ -53,12 +53,11 @@ SDFSConfig fileSystemConfig = SDFSConfig(); #error Please select a filesystem first by uncommenting one of the "#define USE_xxx" lines at the beginning of the sketch. #endif - #define DBG_OUTPUT_PORT Serial #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif // Indicate which digital I/Os should be displayed on the chart. @@ -132,7 +131,6 @@ bool handleFileRead(String path) { return false; } - /* The "Not Found" handler catches all URI not explicitly declared in code First try to find and return the requested file from the filesystem, @@ -240,7 +238,6 @@ void setup(void) { // Use it to read files from filesystem server.onNotFound(handleNotFound); - // Start server server.begin(); DBG_OUTPUT_PORT.println("HTTP server started"); @@ -249,7 +246,6 @@ void setup(void) { DBG_OUTPUT_PORT.println(" 0 (OFF): outputs are off and hidden from chart"); DBG_OUTPUT_PORT.println(" 1 (AUTO): outputs are rotated automatically every second"); DBG_OUTPUT_PORT.println(" 2 (MANUAL): outputs can be toggled from the web page"); - } // Return default GPIO mask, that is all I/Os except SD card ones @@ -329,4 +325,3 @@ void loop(void) { break; } } - diff --git a/libraries/ESP8266WebServer/examples/HelloServer/HelloServer.ino b/libraries/ESP8266WebServer/examples/HelloServer/HelloServer.ino index 7fdee1667a..68096d29ad 100644 --- a/libraries/ESP8266WebServer/examples/HelloServer/HelloServer.ino +++ b/libraries/ESP8266WebServer/examples/HelloServer/HelloServer.ino @@ -5,7 +5,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* ssid = STASSID; @@ -89,17 +89,17 @@ void setup(void) { ///////////////////////////////////////////////////////// // Hook examples - server.addHook([](const String & method, const String & url, WiFiClient * client, ESP8266WebServer::ContentTypeFunction contentType) { - (void)method; // GET, PUT, ... - (void)url; // example: /root/myfile.html - (void)client; // the webserver tcp client connection + server.addHook([](const String& method, const String& url, WiFiClient* client, ESP8266WebServer::ContentTypeFunction contentType) { + (void)method; // GET, PUT, ... + (void)url; // example: /root/myfile.html + (void)client; // the webserver tcp client connection (void)contentType; // contentType(".html") => "text/html" Serial.printf("A useless web hook has passed\n"); Serial.printf("(this hook is in 0x%08x area (401x=IRAM 402x=FLASH))\n", esp_get_program_counter()); return ESP8266WebServer::CLIENT_REQUEST_CAN_CONTINUE; }); - server.addHook([](const String&, const String & url, WiFiClient*, ESP8266WebServer::ContentTypeFunction) { + server.addHook([](const String&, const String& url, WiFiClient*, ESP8266WebServer::ContentTypeFunction) { if (url.startsWith("/fail")) { Serial.printf("An always failing web hook has been triggered\n"); return ESP8266WebServer::CLIENT_MUST_STOP; @@ -107,7 +107,7 @@ void setup(void) { return ESP8266WebServer::CLIENT_REQUEST_CAN_CONTINUE; }); - server.addHook([](const String&, const String & url, WiFiClient * client, ESP8266WebServer::ContentTypeFunction) { + server.addHook([](const String&, const String& url, WiFiClient* client, ESP8266WebServer::ContentTypeFunction) { if (url.startsWith("/dump")) { Serial.printf("The dumper web hook is on the run\n"); diff --git a/libraries/ESP8266WebServer/examples/HelloServerBearSSL/HelloServerBearSSL.ino b/libraries/ESP8266WebServer/examples/HelloServerBearSSL/HelloServerBearSSL.ino index 185914f305..18d397249b 100644 --- a/libraries/ESP8266WebServer/examples/HelloServerBearSSL/HelloServerBearSSL.ino +++ b/libraries/ESP8266WebServer/examples/HelloServerBearSSL/HelloServerBearSSL.ino @@ -18,7 +18,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* ssid = STASSID; @@ -50,7 +50,7 @@ JfUvYadSYxh3nblvA4OL+iEZiW8NE3hbW6WPXxvS7Euge0uWMPc4uEcnsE0ZVG3m -----END CERTIFICATE----- )EOF"; -static const char serverKey[] PROGMEM = R"EOF( +static const char serverKey[] PROGMEM = R"EOF( -----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEA9UoHBtn4oNKXjRgIOQ/rLxK/iI0a8Q5mDxhfuwa9//FkftSI IFY8UhGk2YNJpnfKOyYWqbqwuJhIZJ2sEIWp2301OnavuGBrpKOgBJJljgH2l/4Z @@ -80,7 +80,6 @@ gz5JWYhbD6c38khSzJb0pNXCo3EuYAVa36kDM96k1BtWuhRS10Q1VXk= -----END RSA PRIVATE KEY----- )EOF"; - const int led = 13; void handleRoot() { @@ -89,24 +88,24 @@ void handleRoot() { digitalWrite(led, 0); } -void handleNotFound(){ +void handleNotFound() { digitalWrite(led, 1); String message = "File Not Found\n\n"; message += "URI: "; message += server.uri(); message += "\nMethod: "; - message += (server.method() == HTTP_GET)?"GET":"POST"; + message += (server.method() == HTTP_GET) ? "GET" : "POST"; message += "\nArguments: "; message += server.args(); message += "\n"; - for (uint8_t i=0; i 0) { diff --git a/libraries/ESP8266WebServer/examples/HttpAdvancedAuth/HttpAdvancedAuth.ino b/libraries/ESP8266WebServer/examples/HttpAdvancedAuth/HttpAdvancedAuth.ino index 857048cf0b..a3a01d4ced 100644 --- a/libraries/ESP8266WebServer/examples/HttpAdvancedAuth/HttpAdvancedAuth.ino +++ b/libraries/ESP8266WebServer/examples/HttpAdvancedAuth/HttpAdvancedAuth.ino @@ -11,7 +11,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* ssid = STASSID; @@ -39,13 +39,13 @@ void setup() { server.on("/", []() { if (!server.authenticate(www_username, www_password)) - //Basic Auth Method with Custom realm and Failure Response - //return server.requestAuthentication(BASIC_AUTH, www_realm, authFailResponse); - //Digest Auth Method with realm="Login Required" and empty Failure Response - //return server.requestAuthentication(DIGEST_AUTH); - //Digest Auth Method with Custom realm and empty Failure Response - //return server.requestAuthentication(DIGEST_AUTH, www_realm); - //Digest Auth Method with Custom realm and Failure Response + //Basic Auth Method with Custom realm and Failure Response + //return server.requestAuthentication(BASIC_AUTH, www_realm, authFailResponse); + //Digest Auth Method with realm="Login Required" and empty Failure Response + //return server.requestAuthentication(DIGEST_AUTH); + //Digest Auth Method with Custom realm and empty Failure Response + //return server.requestAuthentication(DIGEST_AUTH, www_realm); + //Digest Auth Method with Custom realm and Failure Response { return server.requestAuthentication(DIGEST_AUTH, www_realm, authFailResponse); } diff --git a/libraries/ESP8266WebServer/examples/HttpBasicAuth/HttpBasicAuth.ino b/libraries/ESP8266WebServer/examples/HttpBasicAuth/HttpBasicAuth.ino index 7c06637caf..b7d5c16f41 100644 --- a/libraries/ESP8266WebServer/examples/HttpBasicAuth/HttpBasicAuth.ino +++ b/libraries/ESP8266WebServer/examples/HttpBasicAuth/HttpBasicAuth.ino @@ -5,7 +5,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* ssid = STASSID; diff --git a/libraries/ESP8266WebServer/examples/HttpHashCredAuth/HttpHashCredAuth.ino b/libraries/ESP8266WebServer/examples/HttpHashCredAuth/HttpHashCredAuth.ino index c2ceaca53d..2a9657e2fc 100644 --- a/libraries/ESP8266WebServer/examples/HttpHashCredAuth/HttpHashCredAuth.ino +++ b/libraries/ESP8266WebServer/examples/HttpHashCredAuth/HttpHashCredAuth.ino @@ -18,14 +18,14 @@ //Unfortunately it is not possible to have persistent WiFi credentials stored as anything but plain text. Obfuscation would be the only feasible barrier. #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* ssid = STASSID; const char* wifi_pw = STAPSK; const String file_credentials = R"(/credentials.txt)"; // LittleFS file name for the saved credentials -const String change_creds = "changecreds"; // Address for a credential change +const String change_creds = "changecreds"; // Address for a credential change //The ESP8266WebServerSecure requires an encryption certificate and matching key. //These can generated with the bash script available in the ESP8266 Arduino repository. @@ -52,7 +52,7 @@ JfUvYadSYxh3nblvA4OL+iEZiW8NE3hbW6WPXxvS7Euge0uWMPc4uEcnsE0ZVG3m 5tAF1D5vAAwA8nfPysumlLsIjohJZo4lgnhB++AlOg== -----END CERTIFICATE----- )EOF"; -static const char serverKey[] PROGMEM = R"EOF( +static const char serverKey[] PROGMEM = R"EOF( -----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEA9UoHBtn4oNKXjRgIOQ/rLxK/iI0a8Q5mDxhfuwa9//FkftSI IFY8UhGk2YNJpnfKOyYWqbqwuJhIZJ2sEIWp2301OnavuGBrpKOgBJJljgH2l/4Z @@ -94,10 +94,10 @@ void setup() { Serial.begin(115200); //Initialize LittleFS to save credentials - if(!LittleFS.begin()){ - Serial.println("LittleFS initialization error, programmer flash configured?"); + if (!LittleFS.begin()) { + Serial.println("LittleFS initialization error, programmer flash configured?"); ESP.restart(); - } + } //Attempt to load credentials. If the file does not yet exist, they will be set to the default values above loadcredentials(); @@ -112,8 +112,8 @@ void setup() { } server.getServer().setRSACert(new BearSSL::X509List(serverCert), new BearSSL::PrivateKey(serverKey)); - server.on("/",showcredentialpage); //for this simple example, just show a simple page for changing credentials at the root - server.on("/" + change_creds,handlecredentialchange); //handles submission of credentials from the client + server.on("/", showcredentialpage); //for this simple example, just show a simple page for changing credentials at the root + server.on("/" + change_creds, handlecredentialchange); //handles submission of credentials from the client server.onNotFound(redirect); server.begin(); @@ -128,12 +128,12 @@ void loop() { } //This function redirects home -void redirect(){ +void redirect() { String url = "https://" + WiFi.localIP().toString(); Serial.println("Redirect called. Redirecting to " + url); server.sendHeader("Location", url, true); Serial.println("Header sent."); - server.send( 302, "text/plain", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. + server.send(302, "text/plain", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. Serial.println("Empty page sent."); server.client().stop(); // Stop is needed because we sent no content length Serial.println("Client stopped."); @@ -142,21 +142,21 @@ void redirect(){ //This function checks whether the current session has been authenticated. If not, a request for credentials is sent. bool session_authenticated() { Serial.println("Checking authentication."); - if (server.authenticateDigest(login,H1)) { + if (server.authenticateDigest(login, H1)) { Serial.println("Authentication confirmed."); return true; - } else { + } else { Serial.println("Not authenticated. Requesting credentials."); - server.requestAuthentication(DIGEST_AUTH,realm.c_str(),authentication_failed); + server.requestAuthentication(DIGEST_AUTH, realm.c_str(), authentication_failed); redirect(); return false; } } //This function sends a simple webpage for changing login credentials to the client -void showcredentialpage(){ +void showcredentialpage() { Serial.println("Show credential page called."); - if(!session_authenticated()){ + if (!session_authenticated()) { return; } @@ -165,11 +165,12 @@ void showcredentialpage(){ String page; page = R"()"; - page+= - R"( + page += + R"(

    Login Credentials


    -
    + Login:

    Password:
    @@ -178,8 +179,7 @@ void showcredentialpage(){


    - )" - ; + )"; page += R"()"; @@ -189,16 +189,15 @@ void showcredentialpage(){ } //Saves credentials to LittleFS -void savecredentials(String new_login, String new_password) -{ +void savecredentials(String new_login, String new_password) { //Set global variables to new values - login=new_login; - H1=ESP8266WebServer::credentialHash(new_login,realm,new_password); + login = new_login; + H1 = ESP8266WebServer::credentialHash(new_login, realm, new_password); //Save new values to LittleFS for loading on next reboot Serial.println("Saving credentials."); - File f=LittleFS.open(file_credentials,"w"); //open as a brand new file, discard old contents - if(f){ + File f = LittleFS.open(file_credentials, "w"); //open as a brand new file, discard old contents + if (f) { Serial.println("Modifying credentials in file system."); f.println(login); f.println(H1); @@ -210,18 +209,17 @@ void savecredentials(String new_login, String new_password) } //loads credentials from LittleFS -void loadcredentials() -{ +void loadcredentials() { Serial.println("Searching for credentials."); File f; - f=LittleFS.open(file_credentials,"r"); - if(f){ + f = LittleFS.open(file_credentials, "r"); + if (f) { Serial.println("Loading credentials from file system."); - String mod=f.readString(); //read the file to a String - int index_1=mod.indexOf('\n',0); //locate the first line break - int index_2=mod.indexOf('\n',index_1+1); //locate the second line break - login=mod.substring(0,index_1-1); //get the first line (excluding the line break) - H1=mod.substring(index_1+1,index_2-1); //get the second line (excluding the line break) + String mod = f.readString(); //read the file to a String + int index_1 = mod.indexOf('\n', 0); //locate the first line break + int index_2 = mod.indexOf('\n', index_1 + 1); //locate the second line break + login = mod.substring(0, index_1 - 1); //get the first line (excluding the line break) + H1 = mod.substring(index_1 + 1, index_2 - 1); //get the second line (excluding the line break) f.close(); } else { String default_login = "admin"; @@ -229,15 +227,15 @@ void loadcredentials() Serial.println("None found. Setting to default credentials."); Serial.println("user:" + default_login); Serial.println("password:" + default_password); - login=default_login; - H1=ESP8266WebServer::credentialHash(default_login,realm,default_password); + login = default_login; + H1 = ESP8266WebServer::credentialHash(default_login, realm, default_password); } } //This function handles a credential change from a client. void handlecredentialchange() { Serial.println("Handle credential change called."); - if(!session_authenticated()){ + if (!session_authenticated()) { return; } @@ -247,9 +245,9 @@ void handlecredentialchange() { String pw1 = server.arg("password"); String pw2 = server.arg("password_duplicate"); - if(login != "" && pw1 != "" && pw1 == pw2){ + if (login != "" && pw1 != "" && pw1 == pw2) { - savecredentials(login,pw1); + savecredentials(login, pw1); server.send(200, "text/plain", "Credentials updated"); redirect(); } else { diff --git a/libraries/ESP8266WebServer/examples/PathArgServer/PathArgServer.ino b/libraries/ESP8266WebServer/examples/PathArgServer/PathArgServer.ino index dc998986e5..e27973cab2 100644 --- a/libraries/ESP8266WebServer/examples/PathArgServer/PathArgServer.ino +++ b/libraries/ESP8266WebServer/examples/PathArgServer/PathArgServer.ino @@ -8,11 +8,11 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char *ssid = STASSID; -const char *password = STAPSK; +const char* ssid = STASSID; +const char* password = STAPSK; ESP8266WebServer server(80); diff --git a/libraries/ESP8266WebServer/examples/PostServer/PostServer.ino b/libraries/ESP8266WebServer/examples/PostServer/PostServer.ino index da1703807a..6c787794e5 100644 --- a/libraries/ESP8266WebServer/examples/PostServer/PostServer.ino +++ b/libraries/ESP8266WebServer/examples/PostServer/PostServer.ino @@ -5,10 +5,10 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char* ssid = STASSID; +const char* ssid = STASSID; const char* password = STAPSK; ESP8266WebServer server(80); diff --git a/libraries/ESP8266WebServer/examples/ServerSentEvents/ServerSentEvents.ino b/libraries/ESP8266WebServer/examples/ServerSentEvents/ServerSentEvents.ino index 77ae1e958e..c2fe34bb9c 100644 --- a/libraries/ESP8266WebServer/examples/ServerSentEvents/ServerSentEvents.ino +++ b/libraries/ESP8266WebServer/examples/ServerSentEvents/ServerSentEvents.ino @@ -42,7 +42,7 @@ extern "C" { #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* ssid = STASSID; @@ -51,7 +51,7 @@ const unsigned int port = 80; ESP8266WebServer server(port); -#define SSE_MAX_CHANNELS 8 // in this simplified example, only eight SSE clients subscription allowed +#define SSE_MAX_CHANNELS 8 // in this simplified example, only eight SSE clients subscription allowed struct SSESubscription { IPAddress clientIP; WiFiClient client; @@ -60,7 +60,7 @@ struct SSESubscription { uint8_t subscriptionCount = 0; typedef struct { - const char *name; + const char* name; unsigned short value; Ticker update; } sensorType; @@ -89,7 +89,7 @@ void SSEKeepAlive() { } if (subscription[i].client.connected()) { Serial.printf_P(PSTR("SSEKeepAlive - client is still listening on channel %d\n"), i); - subscription[i].client.println(F("event: event\ndata: { \"TYPE\":\"KEEP-ALIVE\" }\n")); // Extra newline required by SSE standard + subscription[i].client.println(F("event: event\ndata: { \"TYPE\":\"KEEP-ALIVE\" }\n")); // Extra newline required by SSE standard } else { Serial.printf_P(PSTR("SSEKeepAlive - client not listening on channel %d, remove subscription\n"), i); subscription[i].keepAliveTimer.detach(); @@ -105,7 +105,7 @@ void SSEKeepAlive() { // every 60 seconds it sends a keep alive event via Ticker void SSEHandler(uint8_t channel) { WiFiClient client = server.client(); - SSESubscription &s = subscription[channel]; + SSESubscription& s = subscription[channel]; if (s.clientIP != client.remoteIP()) { // IP addresses don't match, reject this client Serial.printf_P(PSTR("SSEHandler - unregistered client with IP %s tries to listen\n"), server.client().remoteIP().toString().c_str()); return handleNotFound(); @@ -116,12 +116,12 @@ void SSEHandler(uint8_t channel) { s.client = client; // capture SSE server client connection server.setContentLength(CONTENT_LENGTH_UNKNOWN); // the payload can go on forever server.sendContent_P(PSTR("HTTP/1.1 200 OK\nContent-Type: text/event-stream;\nConnection: keep-alive\nCache-Control: no-cache\nAccess-Control-Allow-Origin: *\n\n")); - s.keepAliveTimer.attach_scheduled(30.0, SSEKeepAlive); // Refresh time every 30s for demo + s.keepAliveTimer.attach_scheduled(30.0, SSEKeepAlive); // Refresh time every 30s for demo } void handleAll() { - const char *uri = server.uri().c_str(); - const char *restEvents = PSTR("/rest/events/"); + const char* uri = server.uri().c_str(); + const char* restEvents = PSTR("/rest/events/"); if (strncmp_P(uri, restEvents, strlen_P(restEvents))) { return handleNotFound(); } @@ -133,7 +133,7 @@ void handleAll() { handleNotFound(); }; -void SSEBroadcastState(const char *sensorName, unsigned short prevSensorValue, unsigned short sensorValue) { +void SSEBroadcastState(const char* sensorName, unsigned short prevSensorValue, unsigned short sensorValue) { for (uint8_t i = 0; i < SSE_MAX_CHANNELS; i++) { if (!(subscription[i].clientIP)) { continue; @@ -141,9 +141,9 @@ void SSEBroadcastState(const char *sensorName, unsigned short prevSensorValue, u String IPaddrstr = IPAddress(subscription[i].clientIP).toString(); if (subscription[i].client.connected()) { Serial.printf_P(PSTR("broadcast status change to client IP %s on channel %d for %s with new state %d\n"), - IPaddrstr.c_str(), i, sensorName, sensorValue); + IPaddrstr.c_str(), i, sensorName, sensorValue); subscription[i].client.printf_P(PSTR("event: event\ndata: {\"TYPE\":\"STATE\", \"%s\":{\"state\":%d, \"prevState\":%d}}\n\n"), - sensorName, sensorValue, prevSensorValue); + sensorName, sensorValue, prevSensorValue); } else { Serial.printf_P(PSTR("SSEBroadcastState - client %s registered on channel %d but not listening\n"), IPaddrstr.c_str(), i); } @@ -151,23 +151,23 @@ void SSEBroadcastState(const char *sensorName, unsigned short prevSensorValue, u } // Simulate sensors -void updateSensor(sensorType &sensor) { +void updateSensor(sensorType& sensor) { unsigned short newVal = (unsigned short)RANDOM_REG32; // (not so good) random value for the sensor Serial.printf_P(PSTR("update sensor %s - previous state: %d, new state: %d\n"), sensor.name, sensor.value, newVal); if (sensor.value != newVal) { - SSEBroadcastState(sensor.name, sensor.value, newVal); // only broadcast if state is different + SSEBroadcastState(sensor.name, sensor.value, newVal); // only broadcast if state is different } sensor.value = newVal; - sensor.update.once(rand() % 20 + 10, std::bind(updateSensor, sensor)); // randomly update sensor + sensor.update.once(rand() % 20 + 10, std::bind(updateSensor, sensor)); // randomly update sensor } void handleSubscribe() { if (subscriptionCount == SSE_MAX_CHANNELS - 1) { - return handleNotFound(); // We ran out of channels + return handleNotFound(); // We ran out of channels } uint8_t channel; - IPAddress clientIP = server.client().remoteIP(); // get IP address of client + IPAddress clientIP = server.client().remoteIP(); // get IP address of client String SSEurl = F("http://"); SSEurl += WiFi.localIP().toString(); SSEurl += F(":"); @@ -180,7 +180,7 @@ void handleSubscribe() { if (!subscription[channel].clientIP) { break; } - subscription[channel] = {clientIP, server.client(), Ticker()}; + subscription[channel] = { clientIP, server.client(), Ticker() }; SSEurl += channel; Serial.printf_P(PSTR("Allocated channel %d, on uri %s\n"), channel, SSEurl.substring(offset).c_str()); //server.on(SSEurl.substring(offset), std::bind(SSEHandler, &(subscription[channel]))); @@ -200,7 +200,7 @@ void setup(void) { WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); Serial.println(""); - while (WiFi.status() != WL_CONNECTED) { // Wait for connection + while (WiFi.status() != WL_CONNECTED) { // Wait for connection delay(500); Serial.print("."); } @@ -209,7 +209,7 @@ void setup(void) { Serial.println("MDNS responder started"); } - startServers(); // start web and SSE servers + startServers(); // start web and SSE servers sensor[0].name = "sensorA"; sensor[1].name = "sensorB"; updateSensor(sensor[0]); diff --git a/libraries/ESP8266WebServer/examples/SimpleAuthentication/SimpleAuthentication.ino b/libraries/ESP8266WebServer/examples/SimpleAuthentication/SimpleAuthentication.ino index 2cba08fe9c..a2b7bc9275 100644 --- a/libraries/ESP8266WebServer/examples/SimpleAuthentication/SimpleAuthentication.ino +++ b/libraries/ESP8266WebServer/examples/SimpleAuthentication/SimpleAuthentication.ino @@ -4,7 +4,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* ssid = STASSID; @@ -45,7 +45,7 @@ void handleLogin() { return; } if (server.hasArg("USERNAME") && server.hasArg("PASSWORD")) { - if (server.arg("USERNAME") == "admin" && server.arg("PASSWORD") == "admin") { + if (server.arg("USERNAME") == "admin" && server.arg("PASSWORD") == "admin") { server.sendHeader("Location", "/"); server.sendHeader("Cache-Control", "no-cache"); server.sendHeader("Set-Cookie", "ESPSESSIONID=1"); @@ -115,7 +115,6 @@ void setup(void) { Serial.print("IP address: "); Serial.println(WiFi.localIP()); - server.on("/", handleRoot); server.on("/login", handleLogin); server.on("/inline", []() { diff --git a/libraries/ESP8266WebServer/examples/WebServer/WebServer.ino b/libraries/ESP8266WebServer/examples/WebServer/WebServer.ino index 08107586fd..be875048ee 100644 --- a/libraries/ESP8266WebServer/examples/WebServer/WebServer.ino +++ b/libraries/ESP8266WebServer/examples/WebServer/WebServer.ino @@ -11,7 +11,7 @@ #include "secrets.h" // add WLAN Credentials in here. -#include // File System for Web Server Files +#include // File System for Web Server Files #include // This file system is used. // mark parameters not used in example @@ -32,7 +32,6 @@ ESP8266WebServer server(80); // The text of builtin files are in this header file #include "builtinfiles.h" - // ===== Simple functions used to answer simple GET requests ===== // This function is called when the WebServer was requested without giving a filename. @@ -49,7 +48,6 @@ void handleRedirect() { server.send(302); } // handleRedirect() - // This function is called when the WebServer was requested to list all existing files in the filesystem. // a JSON array with file information is returned. void handleListFiles() { @@ -73,7 +71,6 @@ void handleListFiles() { server.send(200, "text/javascript; charset=utf-8", result); } // handleListFiles() - // This function is called when the sysInfo service was requested. void handleSysInfo() { String result; @@ -92,91 +89,85 @@ void handleSysInfo() { server.send(200, "text/javascript; charset=utf-8", result); } // handleSysInfo() - // ===== Request Handler class used to answer more complex requests ===== // The FileServerHandler is registered to the web server to support DELETE and UPLOAD of files into the filesystem. class FileServerHandler : public RequestHandler { public: - // @brief Construct a new File Server Handler object - // @param fs The file system to be used. - // @param path Path to the root folder in the file system that is used for serving static data down and upload. - // @param cache_header Cache Header to be used in replies. - FileServerHandler() { - TRACE("FileServerHandler is registered\n"); - } - - - // @brief check incoming request. Can handle POST for uploads and DELETE. - // @param requestMethod method of the http request line. - // @param requestUri request ressource from the http request line. - // @return true when method can be handled. - bool canHandle(HTTPMethod requestMethod, const String UNUSED &_uri) override { - return ((requestMethod == HTTP_POST) || (requestMethod == HTTP_DELETE)); - } // canHandle() - + // @brief Construct a new File Server Handler object + // @param fs The file system to be used. + // @param path Path to the root folder in the file system that is used for serving static data down and upload. + // @param cache_header Cache Header to be used in replies. + FileServerHandler() { + TRACE("FileServerHandler is registered\n"); + } - bool canUpload(const String &uri) override { - // only allow upload on root fs level. - return (uri == "/"); - } // canUpload() + // @brief check incoming request. Can handle POST for uploads and DELETE. + // @param requestMethod method of the http request line. + // @param requestUri request ressource from the http request line. + // @return true when method can be handled. + bool canHandle(HTTPMethod requestMethod, const String UNUSED& _uri) override { + return ((requestMethod == HTTP_POST) || (requestMethod == HTTP_DELETE)); + } // canHandle() + + bool canUpload(const String& uri) override { + // only allow upload on root fs level. + return (uri == "/"); + } // canUpload() + + bool handle(ESP8266WebServer& server, HTTPMethod requestMethod, const String& requestUri) override { + // ensure that filename starts with '/' + String fName = requestUri; + if (!fName.startsWith("/")) { + fName = "/" + fName; + } + if (requestMethod == HTTP_POST) { + // all done in upload. no other forms. - bool handle(ESP8266WebServer &server, HTTPMethod requestMethod, const String &requestUri) override { - // ensure that filename starts with '/' - String fName = requestUri; - if (!fName.startsWith("/")) { - fName = "/" + fName; + } else if (requestMethod == HTTP_DELETE) { + if (LittleFS.exists(fName)) { + LittleFS.remove(fName); } + } // if + + server.send(200); // all done. + return (true); + } // handle() + + // uploading process + void upload(ESP8266WebServer UNUSED& server, const String UNUSED& _requestUri, HTTPUpload& upload) override { + // ensure that filename starts with '/' + String fName = upload.filename; + if (!fName.startsWith("/")) { + fName = "/" + fName; + } - if (requestMethod == HTTP_POST) { - // all done in upload. no other forms. - - } else if (requestMethod == HTTP_DELETE) { - if (LittleFS.exists(fName)) { - LittleFS.remove(fName); - } + if (upload.status == UPLOAD_FILE_START) { + // Open the file + if (LittleFS.exists(fName)) { + LittleFS.remove(fName); } // if + _fsUploadFile = LittleFS.open(fName, "w"); - server.send(200); // all done. - return (true); - } // handle() - - - // uploading process - void upload(ESP8266WebServer UNUSED &server, const String UNUSED &_requestUri, HTTPUpload &upload) override { - // ensure that filename starts with '/' - String fName = upload.filename; - if (!fName.startsWith("/")) { - fName = "/" + fName; + } else if (upload.status == UPLOAD_FILE_WRITE) { + // Write received bytes + if (_fsUploadFile) { + _fsUploadFile.write(upload.buf, upload.currentSize); } - if (upload.status == UPLOAD_FILE_START) { - // Open the file - if (LittleFS.exists(fName)) { - LittleFS.remove(fName); - } // if - _fsUploadFile = LittleFS.open(fName, "w"); - - } else if (upload.status == UPLOAD_FILE_WRITE) { - // Write received bytes - if (_fsUploadFile) { - _fsUploadFile.write(upload.buf, upload.currentSize); - } - - } else if (upload.status == UPLOAD_FILE_END) { - // Close the file - if (_fsUploadFile) { - _fsUploadFile.close(); - } - } // if - } // upload() + } else if (upload.status == UPLOAD_FILE_END) { + // Close the file + if (_fsUploadFile) { + _fsUploadFile.close(); + } + } // if + } // upload() protected: - File _fsUploadFile; + File _fsUploadFile; }; - // Setup everything to make the webserver work. void setup(void) { delay(3000); // wait for serial monitor to start completely. @@ -252,7 +243,6 @@ void setup(void) { TRACE("hostname=%s\n", WiFi.getHostname()); } // setup - // run the server... void loop(void) { server.handleClient(); diff --git a/libraries/ESP8266WebServer/examples/WebUpdate/WebUpdate.ino b/libraries/ESP8266WebServer/examples/WebUpdate/WebUpdate.ino index 17646fd172..4dff271390 100644 --- a/libraries/ESP8266WebServer/examples/WebUpdate/WebUpdate.ino +++ b/libraries/ESP8266WebServer/examples/WebUpdate/WebUpdate.ino @@ -9,7 +9,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* host = "esp8266-webupdate"; @@ -31,11 +31,11 @@ void setup(void) { server.sendHeader("Connection", "close"); server.send(200, "text/html", serverIndex); }); - server.on("/update", HTTP_POST, []() { + server.on( + "/update", HTTP_POST, []() { server.sendHeader("Connection", "close"); server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK"); - ESP.restart(); - }, []() { + ESP.restart(); }, []() { HTTPUpload& upload = server.upload(); if (upload.status == UPLOAD_FILE_START) { Serial.setDebugOutput(true); @@ -57,8 +57,7 @@ void setup(void) { } Serial.setDebugOutput(false); } - yield(); - }); + yield(); }); server.begin(); MDNS.addService("http", "tcp", 80); diff --git a/libraries/ESP8266WiFi/examples/BearSSL_CertStore/BearSSL_CertStore.ino b/libraries/ESP8266WiFi/examples/BearSSL_CertStore/BearSSL_CertStore.ino index a599a0395a..7b5ccc9ba1 100644 --- a/libraries/ESP8266WiFi/examples/BearSSL_CertStore/BearSSL_CertStore.ino +++ b/libraries/ESP8266WiFi/examples/BearSSL_CertStore/BearSSL_CertStore.ino @@ -41,11 +41,11 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char *ssid = STASSID; -const char *pass = STAPSK; +const char* ssid = STASSID; +const char* pass = STAPSK; // A single, global CertStore which can be used by all // connections. Needs to stay live the entire time any of @@ -71,7 +71,7 @@ void setClock() { } // Try and connect using a WiFiClientBearSSL to specified host:port and dump URL -void fetchURL(BearSSL::WiFiClientSecure *client, const char *host, const uint16_t port, const char *path) { +void fetchURL(BearSSL::WiFiClientSecure* client, const char* host, const uint16_t port, const char* path) { if (!path) { path = "/"; } @@ -100,7 +100,7 @@ void fetchURL(BearSSL::WiFiClientSecure *client, const char *host, const uint16_ break; } // Only print out first line up to \r, then abort connection - char *nl = strchr(tmp, '\r'); + char* nl = strchr(tmp, '\r'); if (nl) { *nl = 0; Serial.print(tmp); @@ -145,7 +145,7 @@ void setup() { return; // Can't connect to anything w/o certs! } - BearSSL::WiFiClientSecure *bear = new BearSSL::WiFiClientSecure(); + BearSSL::WiFiClientSecure* bear = new BearSSL::WiFiClientSecure(); // Integrate the cert store with this connection bear->setCertStore(&certStore); Serial.printf("Attempting to fetch https://github.com/...\n"); @@ -164,10 +164,9 @@ void loop() { site.replace(String("\n"), emptyString); Serial.printf("https://%s/\n", site.c_str()); - BearSSL::WiFiClientSecure *bear = new BearSSL::WiFiClientSecure(); + BearSSL::WiFiClientSecure* bear = new BearSSL::WiFiClientSecure(); // Integrate the cert store with this connection bear->setCertStore(&certStore); fetchURL(bear, site.c_str(), 443, "/"); delete bear; } - diff --git a/libraries/ESP8266WiFi/examples/BearSSL_MaxFragmentLength/BearSSL_MaxFragmentLength.ino b/libraries/ESP8266WiFi/examples/BearSSL_MaxFragmentLength/BearSSL_MaxFragmentLength.ino index 708d906eb1..b58177712c 100644 --- a/libraries/ESP8266WiFi/examples/BearSSL_MaxFragmentLength/BearSSL_MaxFragmentLength.ino +++ b/libraries/ESP8266WiFi/examples/BearSSL_MaxFragmentLength/BearSSL_MaxFragmentLength.ino @@ -9,13 +9,13 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char *ssid = STASSID; -const char *pass = STAPSK; +const char* ssid = STASSID; +const char* pass = STAPSK; -void fetch(BearSSL::WiFiClientSecure *client) { +void fetch(BearSSL::WiFiClientSecure* client) { client->write("GET / HTTP/1.0\r\nHost: tls.mbed.org\r\nUser-Agent: ESP8266\r\n\r\n"); client->flush(); using oneShot = esp8266::polledTimeout::oneShot; diff --git a/libraries/ESP8266WiFi/examples/BearSSL_Server/BearSSL_Server.ino b/libraries/ESP8266WiFi/examples/BearSSL_Server/BearSSL_Server.ino index 160b6a981e..9677178521 100644 --- a/libraries/ESP8266WiFi/examples/BearSSL_Server/BearSSL_Server.ino +++ b/libraries/ESP8266WiFi/examples/BearSSL_Server/BearSSL_Server.ino @@ -39,11 +39,11 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char *ssid = STASSID; -const char *pass = STAPSK; +const char* ssid = STASSID; +const char* pass = STAPSK; // The HTTPS server BearSSL::WiFiServerSecure server(443); @@ -139,10 +139,10 @@ GBEnkz4KpKv7TkHoW+j7F5EMcLcSrUIpyw== #endif #define CACHE_SIZE 5 // Number of sessions to cache. -#define USE_CACHE // Enable SSL session caching. - // Caching SSL sessions shortens the length of the SSL handshake. - // You can see the performance improvement by looking at the - // Network tab of the developer tools of your browser. +#define USE_CACHE // Enable SSL session caching. \ + // Caching SSL sessions shortens the length of the SSL handshake. \ + // You can see the performance improvement by looking at the \ + // Network tab of the developer tools of your browser. //#define DYNAMIC_CACHE // Whether to dynamically allocate the cache. #if defined(USE_CACHE) && defined(DYNAMIC_CACHE) @@ -176,12 +176,12 @@ void setup() { Serial.println(WiFi.localIP()); // Attach the server private cert/key combo - BearSSL::X509List *serverCertList = new BearSSL::X509List(server_cert); - BearSSL::PrivateKey *serverPrivKey = new BearSSL::PrivateKey(server_private_key); + BearSSL::X509List* serverCertList = new BearSSL::X509List(server_cert); + BearSSL::PrivateKey* serverPrivKey = new BearSSL::PrivateKey(server_private_key); #ifndef USE_EC server.setRSACert(serverCertList, serverPrivKey); #else - server.setECCert(serverCertList, BR_KEYTYPE_KEYX|BR_KEYTYPE_SIGN, serverPrivKey); + server.setECCert(serverCertList, BR_KEYTYPE_KEYX | BR_KEYTYPE_SIGN, serverPrivKey); #endif // Set the server's cache @@ -193,17 +193,16 @@ void setup() { server.begin(); } -static const char *HTTP_RES = - "HTTP/1.0 200 OK\r\n" - "Connection: close\r\n" - "Content-Length: 62\r\n" - "Content-Type: text/html; charset=iso-8859-1\r\n" - "\r\n" - "\r\n" - "\r\n" - "

    Hello from ESP8266!

    \r\n" - "\r\n" - "\r\n"; +static const char* HTTP_RES = "HTTP/1.0 200 OK\r\n" + "Connection: close\r\n" + "Content-Length: 62\r\n" + "Content-Type: text/html; charset=iso-8859-1\r\n" + "\r\n" + "\r\n" + "\r\n" + "

    Hello from ESP8266!

    \r\n" + "\r\n" + "\r\n"; void loop() { static int cnt; @@ -211,13 +210,13 @@ void loop() { if (!incoming) { return; } - Serial.printf("Incoming connection...%d\n",cnt++); - + Serial.printf("Incoming connection...%d\n", cnt++); + // Ugly way to wait for \r\n (i.e. end of HTTP request which we don't actually parse here) - uint32_t timeout=millis() + 1000; + uint32_t timeout = millis() + 1000; int lcwn = 0; for (;;) { - unsigned char x=0; + unsigned char x = 0; if ((millis() > timeout) || (incoming.available() && incoming.read(&x, 1) < 0)) { incoming.stop(); Serial.printf("Connection error, closed\n"); diff --git a/libraries/ESP8266WiFi/examples/BearSSL_ServerClientCert/BearSSL_ServerClientCert.ino b/libraries/ESP8266WiFi/examples/BearSSL_ServerClientCert/BearSSL_ServerClientCert.ino index 3e88019cf4..58687f9041 100644 --- a/libraries/ESP8266WiFi/examples/BearSSL_ServerClientCert/BearSSL_ServerClientCert.ino +++ b/libraries/ESP8266WiFi/examples/BearSSL_ServerClientCert/BearSSL_ServerClientCert.ino @@ -67,11 +67,11 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char *ssid = STASSID; -const char *pass = STAPSK; +const char* ssid = STASSID; +const char* pass = STAPSK; // The server which will require a client cert signed by the trusted CA BearSSL::WiFiServerSecure server(443); @@ -160,8 +160,7 @@ seoK24dHmt6tWmn/sbxX7Aa6TL/4mVlFoOgcaTJyVaY/BrY= // head of the app. // Set time via NTP, as required for x.509 validation -void setClock() -{ +void setClock() { configTime(3 * 3600, 0, "pool.ntp.org", "time.nist.gov"); Serial.print("Waiting for NTP time sync: "); @@ -202,29 +201,28 @@ void setup() { setClock(); // Required for X.509 validation // Attach the server private cert/key combo - BearSSL::X509List *serverCertList = new BearSSL::X509List(server_cert); - BearSSL::PrivateKey *serverPrivKey = new BearSSL::PrivateKey(server_private_key); + BearSSL::X509List* serverCertList = new BearSSL::X509List(server_cert); + BearSSL::PrivateKey* serverPrivKey = new BearSSL::PrivateKey(server_private_key); server.setRSACert(serverCertList, serverPrivKey); // Require a certificate validated by the trusted CA - BearSSL::X509List *serverTrustedCA = new BearSSL::X509List(ca_cert); + BearSSL::X509List* serverTrustedCA = new BearSSL::X509List(ca_cert); server.setClientTrustAnchor(serverTrustedCA); // Actually start accepting connections server.begin(); } -static const char *HTTP_RES = - "HTTP/1.0 200 OK\r\n" - "Connection: close\r\n" - "Content-Length: 59\r\n" - "Content-Type: text/html; charset=iso-8859-1\r\n" - "\r\n" - "\r\n" - "\r\n" - "

    Hello my friend!

    \r\n" - "\r\n" - "\r\n"; +static const char* HTTP_RES = "HTTP/1.0 200 OK\r\n" + "Connection: close\r\n" + "Content-Length: 59\r\n" + "Content-Type: text/html; charset=iso-8859-1\r\n" + "\r\n" + "\r\n" + "\r\n" + "

    Hello my friend!

    \r\n" + "\r\n" + "\r\n"; void loop() { BearSSL::WiFiClientSecure incoming = server.accept(); @@ -232,12 +230,12 @@ void loop() { return; } Serial.println("Incoming connection...\n"); - + // Ugly way to wait for \r\n (i.e. end of HTTP request which we don't actually parse here) - uint32_t timeout=millis() + 1000; + uint32_t timeout = millis() + 1000; int lcwn = 0; for (;;) { - unsigned char x=0; + unsigned char x = 0; if ((millis() > timeout) || (incoming.available() && incoming.read(&x, 1) < 0)) { incoming.stop(); Serial.printf("Connection error, closed\n"); diff --git a/libraries/ESP8266WiFi/examples/BearSSL_Sessions/BearSSL_Sessions.ino b/libraries/ESP8266WiFi/examples/BearSSL_Sessions/BearSSL_Sessions.ino index fa03c7fa38..5229f1c095 100644 --- a/libraries/ESP8266WiFi/examples/BearSSL_Sessions/BearSSL_Sessions.ino +++ b/libraries/ESP8266WiFi/examples/BearSSL_Sessions/BearSSL_Sessions.ino @@ -9,13 +9,13 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char *ssid = STASSID; -const char *pass = STAPSK; +const char* ssid = STASSID; +const char* pass = STAPSK; -const char * path = "/"; +const char* path = "/"; void setup() { Serial.begin(115200); @@ -52,7 +52,7 @@ void setup() { } // Try and connect using a WiFiClientBearSSL to specified host:port and dump HTTP response -void fetchURL(BearSSL::WiFiClientSecure *client, const char *host, const uint16_t port, const char *path) { +void fetchURL(BearSSL::WiFiClientSecure* client, const char* host, const uint16_t port, const char* path) { if (!path) { path = "/"; } @@ -81,7 +81,7 @@ void fetchURL(BearSSL::WiFiClientSecure *client, const char *host, const uint16_ break; } // Only print out first line up to \r, then abort connection - char *nl = strchr(tmp, '\r'); + char* nl = strchr(tmp, '\r'); if (nl) { *nl = 0; Serial.print(tmp); @@ -94,7 +94,6 @@ void fetchURL(BearSSL::WiFiClientSecure *client, const char *host, const uint16_ Serial.printf("\n-------\n\n"); } - void loop() { uint32_t start, finish; BearSSL::WiFiClientSecure client; @@ -132,4 +131,3 @@ void loop() { delay(10000); // Avoid DDOSing github } - diff --git a/libraries/ESP8266WiFi/examples/BearSSL_Validation/BearSSL_Validation.ino b/libraries/ESP8266WiFi/examples/BearSSL_Validation/BearSSL_Validation.ino index b91570da11..5968283bd6 100644 --- a/libraries/ESP8266WiFi/examples/BearSSL_Validation/BearSSL_Validation.ino +++ b/libraries/ESP8266WiFi/examples/BearSSL_Validation/BearSSL_Validation.ino @@ -12,13 +12,13 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char *ssid = STASSID; -const char *pass = STAPSK; +const char* ssid = STASSID; +const char* pass = STAPSK; -const char * path = "/"; +const char* path = "/"; // Set time via NTP, as required for x.509 validation void setClock() { @@ -39,7 +39,7 @@ void setClock() { } // Try and connect using a WiFiClientBearSSL to specified host:port and dump HTTP response -void fetchURL(BearSSL::WiFiClientSecure *client, const char *host, const uint16_t port, const char *path) { +void fetchURL(BearSSL::WiFiClientSecure* client, const char* host, const uint16_t port, const char* path) { if (!path) { path = "/"; } @@ -70,7 +70,7 @@ void fetchURL(BearSSL::WiFiClientSecure *client, const char *host, const uint16_ break; } // Only print out first line up to \r, then abort connection - char *nl = strchr(tmp, '\r'); + char* nl = strchr(tmp, '\r'); if (nl) { *nl = 0; Serial.print(tmp); @@ -223,7 +223,6 @@ void setup() { fetchFaster(); } - void loop() { // Nothing to do here } diff --git a/libraries/ESP8266WiFi/examples/HTTPSRequest/HTTPSRequest.ino b/libraries/ESP8266WiFi/examples/HTTPSRequest/HTTPSRequest.ino index 9ccf3b6b37..0493192afb 100644 --- a/libraries/ESP8266WiFi/examples/HTTPSRequest/HTTPSRequest.ino +++ b/libraries/ESP8266WiFi/examples/HTTPSRequest/HTTPSRequest.ino @@ -17,7 +17,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* ssid = STASSID; @@ -74,10 +74,7 @@ void setup() { Serial.print("Requesting URL: "); Serial.println(url); - client.print(String("GET ") + url + " HTTP/1.1\r\n" + - "Host: " + github_host + "\r\n" + - "User-Agent: BuildFailureDetectorESP8266\r\n" + - "Connection: close\r\n\r\n"); + client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + github_host + "\r\n" + "User-Agent: BuildFailureDetectorESP8266\r\n" + "Connection: close\r\n\r\n"); Serial.println("Request sent"); while (client.connected()) { diff --git a/libraries/ESP8266WiFi/examples/IPv6/IPv6.ino b/libraries/ESP8266WiFi/examples/IPv6/IPv6.ino index 560d9bfe46..6087b688b1 100644 --- a/libraries/ESP8266WiFi/examples/IPv6/IPv6.ino +++ b/libraries/ESP8266WiFi/examples/IPv6/IPv6.ino @@ -23,11 +23,11 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -#define FQDN F("www.google.com") // with both IPv4 & IPv6 addresses -#define FQDN2 F("www.yahoo.com") // with both IPv4 & IPv6 addresses +#define FQDN F("www.google.com") // with both IPv4 & IPv6 addresses +#define FQDN2 F("www.yahoo.com") // with both IPv4 & IPv6 addresses #define FQDN6 F("ipv6.google.com") // does not resolve in IPv4 #define STATUSDELAY_MS 10000 #define TCP_PORT 23 @@ -80,20 +80,19 @@ void status(Print& out) { out.println(F("(with 'telnet or 'nc -u 23')")); for (auto a : addrList) { out.printf("IF='%s' IPv6=%d local=%d hostname='%s' addr= %s", - a.ifname().c_str(), - a.isV6(), - a.isLocal(), - a.ifhostname(), - a.toString().c_str()); + a.ifname().c_str(), + a.isV6(), + a.isLocal(), + a.ifhostname(), + a.toString().c_str()); if (a.isLegacy()) { out.printf(" / mask:%s / gw:%s", - a.netmask().toString().c_str(), - a.gw().toString().c_str()); + a.netmask().toString().c_str(), + a.gw().toString().c_str()); } out.println(); - } // lwIP's dns client will ask for IPv4 first (by default) @@ -101,7 +100,7 @@ void status(Print& out) { fqdn(out, FQDN); fqdn(out, FQDN6); #if LWIP_IPV4 && LWIP_IPV6 - fqdn_rt(out, FQDN, DNSResolveType::DNS_AddrType_IPv4_IPv6); // IPv4 before IPv6 + fqdn_rt(out, FQDN, DNSResolveType::DNS_AddrType_IPv4_IPv6); // IPv4 before IPv6 fqdn_rt(out, FQDN2, DNSResolveType::DNS_AddrType_IPv6_IPv4); // IPv6 before IPv4 #endif out.println(F("------------------------------")); @@ -146,9 +145,9 @@ void setup() { for (bool configured = false; !configured;) { for (auto addr : addrList) if ((configured = !addr.isLocal() - // && addr.isV6() // uncomment when IPv6 is mandatory - // && addr.ifnumber() == STATION_IF - )) { + // && addr.isV6() // uncomment when IPv6 is mandatory + // && addr.ifnumber() == STATION_IF + )) { break; } Serial.print('.'); @@ -188,7 +187,7 @@ void loop() { udp.remoteIP().printTo(Serial); Serial.print(F(" :")); Serial.println(udp.remotePort()); - int c; + int c; while ((c = udp.read()) >= 0) { Serial.write(c); } @@ -199,9 +198,7 @@ void loop() { udp.endPacket(); } - if (showStatusOnSerialNow) { status(Serial); } - } diff --git a/libraries/ESP8266WiFi/examples/NTPClient/NTPClient.ino b/libraries/ESP8266WiFi/examples/NTPClient/NTPClient.ino index 927e78fee9..780bb71485 100644 --- a/libraries/ESP8266WiFi/examples/NTPClient/NTPClient.ino +++ b/libraries/ESP8266WiFi/examples/NTPClient/NTPClient.ino @@ -23,14 +23,13 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char * ssid = STASSID; // your network SSID (name) -const char * pass = STAPSK; // your network password +const char* ssid = STASSID; // your network SSID (name) +const char* pass = STAPSK; // your network password - -unsigned int localPort = 2390; // local port to listen for UDP packets +unsigned int localPort = 2390; // local port to listen for UDP packets /* Don't hardwire the IP address or we won't get the benefits of the pool. Lookup the IP address for the host name instead */ @@ -40,7 +39,7 @@ const char* ntpServerName = "time.nist.gov"; const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message -byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets +byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets // A UDP instance to let us send and receive packets over UDP WiFiUDP udp; @@ -109,16 +108,15 @@ void loop() { // print Unix time: Serial.println(epoch); - // print the hour, minute and second: - Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT) - Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day) + Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT) + Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day) Serial.print(':'); if (((epoch % 3600) / 60) < 10) { // In the first 10 minutes of each hour, we'll want a leading '0' Serial.print('0'); } - Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute) + Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute) Serial.print(':'); if ((epoch % 60) < 10) { // In the first 10 seconds of each minute, we'll want a leading '0' @@ -137,15 +135,15 @@ void sendNTPpacket(IPAddress& address) { memset(packetBuffer, 0, NTP_PACKET_SIZE); // Initialize values needed to form NTP request // (see URL above for details on the packets) - packetBuffer[0] = 0b11100011; // LI, Version, Mode - packetBuffer[1] = 0; // Stratum, or type of clock - packetBuffer[2] = 6; // Polling Interval - packetBuffer[3] = 0xEC; // Peer Clock Precision + packetBuffer[0] = 0b11100011; // LI, Version, Mode + packetBuffer[1] = 0; // Stratum, or type of clock + packetBuffer[2] = 6; // Polling Interval + packetBuffer[3] = 0xEC; // Peer Clock Precision // 8 bytes of zero for Root Delay & Root Dispersion - packetBuffer[12] = 49; - packetBuffer[13] = 0x4E; - packetBuffer[14] = 49; - packetBuffer[15] = 52; + packetBuffer[12] = 49; + packetBuffer[13] = 0x4E; + packetBuffer[14] = 49; + packetBuffer[15] = 52; // all NTP fields have been given values, now // you can send a packet requesting a timestamp: diff --git a/libraries/ESP8266WiFi/examples/PagerServer/PagerServer.ino b/libraries/ESP8266WiFi/examples/PagerServer/PagerServer.ino index 43f8fe981c..198cae34b0 100644 --- a/libraries/ESP8266WiFi/examples/PagerServer/PagerServer.ino +++ b/libraries/ESP8266WiFi/examples/PagerServer/PagerServer.ino @@ -25,10 +25,10 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char* ssid = STASSID; +const char* ssid = STASSID; const char* password = STAPSK; ArduinoWiFiServer server(2323); diff --git a/libraries/ESP8266WiFi/examples/RangeExtender-NAPT/RangeExtender-NAPT.ino b/libraries/ESP8266WiFi/examples/RangeExtender-NAPT/RangeExtender-NAPT.ino index a98e894873..a908495150 100644 --- a/libraries/ESP8266WiFi/examples/RangeExtender-NAPT/RangeExtender-NAPT.ino +++ b/libraries/ESP8266WiFi/examples/RangeExtender-NAPT/RangeExtender-NAPT.ino @@ -7,7 +7,7 @@ #ifndef STASSID #define STASSID "mynetwork" -#define STAPSK "mynetworkpassword" +#define STAPSK "mynetworkpassword" #endif #include @@ -52,18 +52,18 @@ void setup() { delay(500); } Serial.printf("\nSTA: %s (dns: %s / %s)\n", - WiFi.localIP().toString().c_str(), - WiFi.dnsIP(0).toString().c_str(), - WiFi.dnsIP(1).toString().c_str()); + WiFi.localIP().toString().c_str(), + WiFi.dnsIP(0).toString().c_str(), + WiFi.dnsIP(1).toString().c_str()); // give DNS servers to AP side dhcpSoftAP.dhcps_set_dns(0, WiFi.dnsIP(0)); dhcpSoftAP.dhcps_set_dns(1, WiFi.dnsIP(1)); - WiFi.softAPConfig( // enable AP, with android-compatible google domain - IPAddress(172, 217, 28, 254), - IPAddress(172, 217, 28, 254), - IPAddress(255, 255, 255, 0)); + WiFi.softAPConfig( // enable AP, with android-compatible google domain + IPAddress(172, 217, 28, 254), + IPAddress(172, 217, 28, 254), + IPAddress(255, 255, 255, 0)); WiFi.softAP(STASSID "extender", STAPSK); Serial.printf("AP: %s\n", WiFi.softAPIP().toString().c_str()); @@ -94,4 +94,3 @@ void setup() { void loop() { } - diff --git a/libraries/ESP8266WiFi/examples/StaticLease/StaticLease.ino b/libraries/ESP8266WiFi/examples/StaticLease/StaticLease.ino index e4520c4720..ada965fc16 100644 --- a/libraries/ESP8266WiFi/examples/StaticLease/StaticLease.ino +++ b/libraries/ESP8266WiFi/examples/StaticLease/StaticLease.ino @@ -7,8 +7,8 @@ #include /* Set these to your desired credentials. */ -const char *ssid = "ESPap"; -const char *password = "thereisnospoon"; +const char* ssid = "ESPap"; +const char* password = "thereisnospoon"; ESP8266WebServer server(80); @@ -20,7 +20,7 @@ void handleRoot() { String result; char wifiClientMac[18]; unsigned char number_client; - struct station_info *stat_info; + struct station_info* stat_info; int i = 1; @@ -76,8 +76,8 @@ void setup() { ... any client not listed will use next IP address available from the range (here 192.168.0.102 and more) */ - dhcpSoftAP.add_dhcps_lease(mac_CAM); // always 192.168.0.100 - dhcpSoftAP.add_dhcps_lease(mac_PC); // always 192.168.0.101 + dhcpSoftAP.add_dhcps_lease(mac_CAM); // always 192.168.0.100 + dhcpSoftAP.add_dhcps_lease(mac_PC); // always 192.168.0.101 /* Start Access Point. You can remove the password parameter if you want the AP to be open. */ WiFi.softAP(ssid, password); Serial.print("AP IP address: "); diff --git a/libraries/ESP8266WiFi/examples/Udp/Udp.ino b/libraries/ESP8266WiFi/examples/Udp/Udp.ino index 7ec287b392..d9ff61bfcf 100644 --- a/libraries/ESP8266WiFi/examples/Udp/Udp.ino +++ b/libraries/ESP8266WiFi/examples/Udp/Udp.ino @@ -14,20 +14,19 @@ adapted from Ethernet library examples */ - #include #include #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -unsigned int localPort = 8888; // local port to listen on +unsigned int localPort = 8888; // local port to listen on // buffers for receiving and sending data char packetBuffer[UDP_TX_PACKET_MAX_SIZE + 1]; //buffer to hold incoming packet, -char ReplyBuffer[] = "acknowledged\r\n"; // a string to send back +char ReplyBuffer[] = "acknowledged\r\n"; // a string to send back WiFiUDP Udp; @@ -50,10 +49,10 @@ void loop() { int packetSize = Udp.parsePacket(); if (packetSize) { Serial.printf("Received packet of size %d from %s:%d\n (to %s:%d, free heap = %d B)\n", - packetSize, - Udp.remoteIP().toString().c_str(), Udp.remotePort(), - Udp.destinationIP().toString().c_str(), Udp.localPort(), - ESP.getFreeHeap()); + packetSize, + Udp.remoteIP().toString().c_str(), Udp.remotePort(), + Udp.destinationIP().toString().c_str(), Udp.localPort(), + ESP.getFreeHeap()); // read the packet into packetBufffer int n = Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE); @@ -66,7 +65,6 @@ void loop() { Udp.write(ReplyBuffer); Udp.endPacket(); } - } /* diff --git a/libraries/ESP8266WiFi/examples/WiFiAccessPoint/WiFiAccessPoint.ino b/libraries/ESP8266WiFi/examples/WiFiAccessPoint/WiFiAccessPoint.ino index 6fea68f590..e32666a74b 100644 --- a/libraries/ESP8266WiFi/examples/WiFiAccessPoint/WiFiAccessPoint.ino +++ b/libraries/ESP8266WiFi/examples/WiFiAccessPoint/WiFiAccessPoint.ino @@ -36,12 +36,12 @@ #ifndef APSSID #define APSSID "ESPap" -#define APPSK "thereisnospoon" +#define APPSK "thereisnospoon" #endif /* Set these to your desired credentials. */ -const char *ssid = APSSID; -const char *password = APPSK; +const char* ssid = APSSID; +const char* password = APPSK; ESP8266WebServer server(80); diff --git a/libraries/ESP8266WiFi/examples/WiFiClient/WiFiClient.ino b/libraries/ESP8266WiFi/examples/WiFiClient/WiFiClient.ino index ef9016063b..5299765f62 100644 --- a/libraries/ESP8266WiFi/examples/WiFiClient/WiFiClient.ino +++ b/libraries/ESP8266WiFi/examples/WiFiClient/WiFiClient.ino @@ -7,10 +7,10 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char* ssid = STASSID; +const char* ssid = STASSID; const char* password = STAPSK; const char* host = "djxmmx.net"; diff --git a/libraries/ESP8266WiFi/examples/WiFiClientBasic/WiFiClientBasic.ino b/libraries/ESP8266WiFi/examples/WiFiClientBasic/WiFiClientBasic.ino index e442282e37..8723e7e8cd 100644 --- a/libraries/ESP8266WiFi/examples/WiFiClientBasic/WiFiClientBasic.ino +++ b/libraries/ESP8266WiFi/examples/WiFiClientBasic/WiFiClientBasic.ino @@ -9,10 +9,10 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char* ssid = STASSID; +const char* ssid = STASSID; const char* password = STAPSK; const char* host = "192.168.1.1"; @@ -44,7 +44,6 @@ void setup() { delay(500); } - void loop() { Serial.print("connecting to "); Serial.print(host); @@ -75,4 +74,3 @@ void loop() { Serial.println("wait 5 sec..."); delay(5000); } - diff --git a/libraries/ESP8266WiFi/examples/WiFiEcho/WiFiEcho.ino b/libraries/ESP8266WiFi/examples/WiFiEcho/WiFiEcho.ino index f902e019a9..b4761b46d2 100644 --- a/libraries/ESP8266WiFi/examples/WiFiEcho/WiFiEcho.ino +++ b/libraries/ESP8266WiFi/examples/WiFiEcho/WiFiEcho.ino @@ -11,7 +11,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif constexpr int port = 23; @@ -19,7 +19,7 @@ constexpr int port = 23; WiFiServer server(port); WiFiClient client; -constexpr size_t sizes [] = { 0, 512, 384, 256, 128, 64, 16, 8, 4 }; +constexpr size_t sizes[] = { 0, 512, 384, 256, 128, 64, 16, 8, 4 }; constexpr uint32_t breathMs = 200; esp8266::polledTimeout::oneShotFastMs enoughMs(breathMs); esp8266::polledTimeout::periodicFastMs test(2000); @@ -51,10 +51,9 @@ void setup() { "- Use 'telnet/nc echo23.local %d' to try echo\n\n" "- Use 'python3 echo-client.py' bandwidth meter to compare transfer APIs\n\n" " and try typing 1, 1, 1, 2, 2, 2, 3, 3, 3 on console during transfers\n\n", - port); + port); } - void loop() { MDNS.update(); @@ -84,10 +83,28 @@ void loop() { if (Serial.available()) { s = (s + 1) % (sizeof(sizes) / sizeof(sizes[0])); switch (Serial.read()) { - case '1': if (t != 1) s = 0; t = 1; Serial.println("byte-by-byte (watch then press 2, 3 or 4)"); break; - case '2': if (t != 2) s = 1; t = 2; Serial.printf("through buffer (watch then press 2 again, or 1, 3 or 4)\n"); break; - case '3': if (t != 3) s = 0; t = 3; Serial.printf("direct access (sendAvailable - watch then press 3 again, or 1, 2 or 4)\n"); break; - case '4': t = 4; Serial.printf("direct access (sendAll - close peer to stop, then press 1, 2 or 3 before restarting peer)\n"); break; + case '1': + if (t != 1) + s = 0; + t = 1; + Serial.println("byte-by-byte (watch then press 2, 3 or 4)"); + break; + case '2': + if (t != 2) + s = 1; + t = 2; + Serial.printf("through buffer (watch then press 2 again, or 1, 3 or 4)\n"); + break; + case '3': + if (t != 3) + s = 0; + t = 3; + Serial.printf("direct access (sendAvailable - watch then press 3 again, or 1, 2 or 4)\n"); + break; + case '4': + t = 4; + Serial.printf("direct access (sendAll - close peer to stop, then press 1, 2 or 3 before restarting peer)\n"); + break; } tot = cnt = 0; ESP.resetFreeContStack(); @@ -131,11 +148,20 @@ void loop() { cnt++; switch (client.getLastSendReport()) { - case Stream::Report::Success: break; - case Stream::Report::TimedOut: Serial.println("Stream::send: timeout"); break; - case Stream::Report::ReadError: Serial.println("Stream::send: read error"); break; - case Stream::Report::WriteError: Serial.println("Stream::send: write error"); break; - case Stream::Report::ShortOperation: Serial.println("Stream::send: short transfer"); break; + case Stream::Report::Success: + break; + case Stream::Report::TimedOut: + Serial.println("Stream::send: timeout"); + break; + case Stream::Report::ReadError: + Serial.println("Stream::send: read error"); + break; + case Stream::Report::WriteError: + Serial.println("Stream::send: write error"); + break; + case Stream::Report::ShortOperation: + Serial.println("Stream::send: short transfer"); + break; } } @@ -145,12 +171,20 @@ void loop() { cnt++; switch (client.getLastSendReport()) { - case Stream::Report::Success: break; - case Stream::Report::TimedOut: Serial.println("Stream::send: timeout"); break; - case Stream::Report::ReadError: Serial.println("Stream::send: read error"); break; - case Stream::Report::WriteError: Serial.println("Stream::send: write error"); break; - case Stream::Report::ShortOperation: Serial.println("Stream::send: short transfer"); break; + case Stream::Report::Success: + break; + case Stream::Report::TimedOut: + Serial.println("Stream::send: timeout"); + break; + case Stream::Report::ReadError: + Serial.println("Stream::send: read error"); + break; + case Stream::Report::WriteError: + Serial.println("Stream::send: write error"); + break; + case Stream::Report::ShortOperation: + Serial.println("Stream::send: short transfer"); + break; } } - } diff --git a/libraries/ESP8266WiFi/examples/WiFiEvents/WiFiEvents.ino b/libraries/ESP8266WiFi/examples/WiFiEvents/WiFiEvents.ino index d72985a9c1..70f8d06317 100644 --- a/libraries/ESP8266WiFi/examples/WiFiEvents/WiFiEvents.ino +++ b/libraries/ESP8266WiFi/examples/WiFiEvents/WiFiEvents.ino @@ -18,10 +18,10 @@ #ifndef APSSID #define APSSID "esp8266" -#define APPSK "esp8266" +#define APPSK "esp8266" #endif -const char* ssid = APSSID; +const char* ssid = APSSID; const char* password = APPSK; WiFiEventHandler stationConnectedHandler; @@ -99,6 +99,6 @@ void loop() { String macToString(const unsigned char* mac) { char buf[20]; snprintf(buf, sizeof(buf), "%02x:%02x:%02x:%02x:%02x:%02x", - mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); + mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); return String(buf); } diff --git a/libraries/ESP8266WiFi/examples/WiFiManualWebServer/WiFiManualWebServer.ino b/libraries/ESP8266WiFi/examples/WiFiManualWebServer/WiFiManualWebServer.ino index 56c04a3a53..e6b3160e18 100644 --- a/libraries/ESP8266WiFi/examples/WiFiManualWebServer/WiFiManualWebServer.ino +++ b/libraries/ESP8266WiFi/examples/WiFiManualWebServer/WiFiManualWebServer.ino @@ -11,7 +11,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* ssid = STASSID; diff --git a/libraries/ESP8266WiFi/examples/WiFiScan/WiFiScan.ino b/libraries/ESP8266WiFi/examples/WiFiScan/WiFiScan.ino index b546df4a7d..d7036e08c5 100644 --- a/libraries/ESP8266WiFi/examples/WiFiScan/WiFiScan.ino +++ b/libraries/ESP8266WiFi/examples/WiFiScan/WiFiScan.ino @@ -41,14 +41,14 @@ void loop() { WiFi.getNetworkInfo(i, ssid, encryptionType, rssi, bssid, channel, hidden); Serial.printf(PSTR(" %02d: [CH %02d] [%02X:%02X:%02X:%02X:%02X:%02X] %ddBm %c %c %s\n"), - i, - channel, - bssid[0], bssid[1], bssid[2], - bssid[3], bssid[4], bssid[5], - rssi, - (encryptionType == ENC_TYPE_NONE) ? ' ' : '*', - hidden ? 'H' : 'V', - ssid.c_str()); + i, + channel, + bssid[0], bssid[1], bssid[2], + bssid[3], bssid[4], bssid[5], + rssi, + (encryptionType == ENC_TYPE_NONE) ? ' ' : '*', + hidden ? 'H' : 'V', + ssid.c_str()); yield(); } } else { diff --git a/libraries/ESP8266WiFi/examples/WiFiShutdown/WiFiShutdown.ino b/libraries/ESP8266WiFi/examples/WiFiShutdown/WiFiShutdown.ino index b03357c143..31fc10d757 100644 --- a/libraries/ESP8266WiFi/examples/WiFiShutdown/WiFiShutdown.ino +++ b/libraries/ESP8266WiFi/examples/WiFiShutdown/WiFiShutdown.ino @@ -36,7 +36,7 @@ void setup() { // Here you can do whatever you need to do that doesn't need a WiFi connection. // --- - ESP.rtcUserMemoryRead(RTC_USER_DATA_SLOT_WIFI_STATE, reinterpret_cast(&state), sizeof(state)); + ESP.rtcUserMemoryRead(RTC_USER_DATA_SLOT_WIFI_STATE, reinterpret_cast(&state), sizeof(state)); unsigned long start = millis(); if (!WiFi.resumeFromShutdown(state) @@ -64,7 +64,7 @@ void setup() { // --- WiFi.shutdown(state); - ESP.rtcUserMemoryWrite(RTC_USER_DATA_SLOT_WIFI_STATE, reinterpret_cast(&state), sizeof(state)); + ESP.rtcUserMemoryWrite(RTC_USER_DATA_SLOT_WIFI_STATE, reinterpret_cast(&state), sizeof(state)); // --- // Here you can do whatever you need to do that doesn't need a WiFi connection anymore. diff --git a/libraries/ESP8266WiFi/examples/WiFiTelnetToSerial/WiFiTelnetToSerial.ino b/libraries/ESP8266WiFi/examples/WiFiTelnetToSerial/WiFiTelnetToSerial.ino index 7ddcdd6d07..b5ae8b2b10 100644 --- a/libraries/ESP8266WiFi/examples/WiFiTelnetToSerial/WiFiTelnetToSerial.ino +++ b/libraries/ESP8266WiFi/examples/WiFiTelnetToSerial/WiFiTelnetToSerial.ino @@ -24,7 +24,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif /* @@ -64,7 +64,7 @@ SoftwareSerial* logger = nullptr; #define logger (&Serial1) #endif -#define STACK_PROTECTOR 512 // bytes +#define STACK_PROTECTOR 512 // bytes //how many clients should be able to telnet to this ESP8266 #define MAX_SRV_CLIENTS 2 diff --git a/libraries/ESP8266WiFiMesh/examples/HelloEspnow/HelloEspnow.ino b/libraries/ESP8266WiFiMesh/examples/HelloEspnow/HelloEspnow.ino index 443d52e2bb..d8f1ece88d 100644 --- a/libraries/ESP8266WiFiMesh/examples/HelloEspnow/HelloEspnow.ino +++ b/libraries/ESP8266WiFiMesh/examples/HelloEspnow/HelloEspnow.ino @@ -25,25 +25,22 @@ constexpr char exampleWiFiPassword[] PROGMEM = "ChangeThisWiFiPassword_TODO"; // // A custom encryption key is required when using encrypted ESP-NOW transmissions. There is always a default Kok set, but it can be replaced if desired. // All ESP-NOW keys below must match in an encrypted connection pair for encrypted communication to be possible. // Note that it is also possible to use Strings as key seeds instead of arrays. -uint8_t espnowEncryptedConnectionKey[16] = {0x33, 0x44, 0x33, 0x44, 0x33, 0x44, 0x33, 0x44, // This is the key for encrypting transmissions of encrypted connections. - 0x33, 0x44, 0x33, 0x44, 0x33, 0x44, 0x32, 0x11 - }; -uint8_t espnowEncryptionKok[16] = {0x22, 0x44, 0x33, 0x44, 0x33, 0x44, 0x33, 0x44, // This is the key for encrypting the encrypted connection key. - 0x33, 0x44, 0x33, 0x44, 0x33, 0x44, 0x32, 0x33 - }; -uint8_t espnowHashKey[16] = {0xEF, 0x44, 0x33, 0x0C, 0x33, 0x44, 0xFE, 0x44, // This is the secret key used for HMAC during encrypted connection requests. - 0x33, 0x44, 0x33, 0xB0, 0x33, 0x44, 0x32, 0xAD - }; +uint8_t espnowEncryptedConnectionKey[16] = { 0x33, 0x44, 0x33, 0x44, 0x33, 0x44, 0x33, 0x44, // This is the key for encrypting transmissions of encrypted connections. + 0x33, 0x44, 0x33, 0x44, 0x33, 0x44, 0x32, 0x11 }; +uint8_t espnowEncryptionKok[16] = { 0x22, 0x44, 0x33, 0x44, 0x33, 0x44, 0x33, 0x44, // This is the key for encrypting the encrypted connection key. + 0x33, 0x44, 0x33, 0x44, 0x33, 0x44, 0x32, 0x33 }; +uint8_t espnowHashKey[16] = { 0xEF, 0x44, 0x33, 0x0C, 0x33, 0x44, 0xFE, 0x44, // This is the secret key used for HMAC during encrypted connection requests. + 0x33, 0x44, 0x33, 0xB0, 0x33, 0x44, 0x32, 0xAD }; unsigned int requestNumber = 0; unsigned int responseNumber = 0; const char broadcastMetadataDelimiter = 23; // 23 = End-of-Transmission-Block (ETB) control character in ASCII -String manageRequest(const String &request, MeshBackendBase &meshInstance); -TransmissionStatusType manageResponse(const String &response, MeshBackendBase &meshInstance); -void networkFilter(int numberOfNetworks, MeshBackendBase &meshInstance); -bool broadcastFilter(String &firstTransmission, EspnowMeshBackend &meshInstance); +String manageRequest(const String& request, MeshBackendBase& meshInstance); +TransmissionStatusType manageResponse(const String& response, MeshBackendBase& meshInstance); +void networkFilter(int numberOfNetworks, MeshBackendBase& meshInstance); +bool broadcastFilter(String& firstTransmission, EspnowMeshBackend& meshInstance); /* Create the mesh node object */ EspnowMeshBackend espnowNode = EspnowMeshBackend(manageRequest, manageResponse, networkFilter, broadcastFilter, FPSTR(exampleWiFiPassword), espnowEncryptedConnectionKey, espnowHashKey, FPSTR(exampleMeshName), TypeCast::uint64ToString(ESP.getChipId()), true); @@ -55,12 +52,12 @@ EspnowMeshBackend espnowNode = EspnowMeshBackend(manageRequest, manageResponse, @param meshInstance The MeshBackendBase instance that called the function. @return The string to send back to the other node. For ESP-NOW, return an empty string ("") if no response should be sent. */ -String manageRequest(const String &request, MeshBackendBase &meshInstance) { +String manageRequest(const String& request, MeshBackendBase& meshInstance) { // To get the actual class of the polymorphic meshInstance, do as follows (meshBackendCast replaces dynamic_cast since RTTI is disabled) - if (EspnowMeshBackend *espnowInstance = TypeCast::meshBackendCast(&meshInstance)) { + if (EspnowMeshBackend* espnowInstance = TypeCast::meshBackendCast(&meshInstance)) { String transmissionEncrypted = espnowInstance->receivedEncryptedTransmission() ? F(", Encrypted transmission") : F(", Unencrypted transmission"); Serial.print(String(F("ESP-NOW (")) + espnowInstance->getSenderMac() + transmissionEncrypted + F("): ")); - } else if (TcpIpMeshBackend *tcpIpInstance = TypeCast::meshBackendCast(&meshInstance)) { + } else if (TcpIpMeshBackend* tcpIpInstance = TypeCast::meshBackendCast(&meshInstance)) { (void)tcpIpInstance; // This is useful to remove a "unused parameter" compiler warning. Does nothing else. Serial.print(F("TCP/IP: ")); } else { @@ -74,7 +71,7 @@ String manageRequest(const String &request, MeshBackendBase &meshInstance) { Serial.print(F("Request received: ")); if (request.charAt(0) == 0) { - Serial.println(request); // substring will not work for multiStrings. + Serial.println(request); // substring will not work for multiStrings. } else { Serial.println(request.substring(0, 100)); } @@ -90,14 +87,14 @@ String manageRequest(const String &request, MeshBackendBase &meshInstance) { @param meshInstance The MeshBackendBase instance that called the function. @return The status code resulting from the response, as an int */ -TransmissionStatusType manageResponse(const String &response, MeshBackendBase &meshInstance) { +TransmissionStatusType manageResponse(const String& response, MeshBackendBase& meshInstance) { TransmissionStatusType statusCode = TransmissionStatusType::TRANSMISSION_COMPLETE; // To get the actual class of the polymorphic meshInstance, do as follows (meshBackendCast replaces dynamic_cast since RTTI is disabled) - if (EspnowMeshBackend *espnowInstance = TypeCast::meshBackendCast(&meshInstance)) { + if (EspnowMeshBackend* espnowInstance = TypeCast::meshBackendCast(&meshInstance)) { String transmissionEncrypted = espnowInstance->receivedEncryptedTransmission() ? F(", Encrypted transmission") : F(", Unencrypted transmission"); Serial.print(String(F("ESP-NOW (")) + espnowInstance->getSenderMac() + transmissionEncrypted + F("): ")); - } else if (TcpIpMeshBackend *tcpIpInstance = TypeCast::meshBackendCast(&meshInstance)) { + } else if (TcpIpMeshBackend* tcpIpInstance = TypeCast::meshBackendCast(&meshInstance)) { Serial.print(F("TCP/IP: ")); // Getting the sent message like this will work as long as ONLY(!) TCP/IP is used. @@ -126,7 +123,7 @@ TransmissionStatusType manageResponse(const String &response, MeshBackendBase &m @param numberOfNetworks The number of networks found in the WiFi scan. @param meshInstance The MeshBackendBase instance that called the function. */ -void networkFilter(int numberOfNetworks, MeshBackendBase &meshInstance) { +void networkFilter(int numberOfNetworks, MeshBackendBase& meshInstance) { // Note that the network index of a given node may change whenever a new scan is done. for (int networkIndex = 0; networkIndex < numberOfNetworks; ++networkIndex) { String currentSSID = WiFi.SSID(networkIndex); @@ -137,9 +134,9 @@ void networkFilter(int numberOfNetworks, MeshBackendBase &meshInstance) { uint64_t targetNodeID = TypeCast::stringToUint64(currentSSID.substring(meshNameIndex + meshInstance.getMeshName().length())); if (targetNodeID < TypeCast::stringToUint64(meshInstance.getNodeID())) { - if (EspnowMeshBackend *espnowInstance = TypeCast::meshBackendCast(&meshInstance)) { + if (EspnowMeshBackend* espnowInstance = TypeCast::meshBackendCast(&meshInstance)) { espnowInstance->connectionQueue().emplace_back(networkIndex); - } else if (TcpIpMeshBackend *tcpIpInstance = TypeCast::meshBackendCast(&meshInstance)) { + } else if (TcpIpMeshBackend* tcpIpInstance = TypeCast::meshBackendCast(&meshInstance)) { tcpIpInstance->connectionQueue().emplace_back(networkIndex); } else { Serial.println(F("Invalid mesh backend!")); @@ -161,14 +158,14 @@ void networkFilter(int numberOfNetworks, MeshBackendBase &meshInstance) { @return True if the broadcast should be accepted. False otherwise. */ -bool broadcastFilter(String &firstTransmission, EspnowMeshBackend &meshInstance) { +bool broadcastFilter(String& firstTransmission, EspnowMeshBackend& meshInstance) { // This example broadcastFilter will accept a transmission if it contains the broadcastMetadataDelimiter // and as metaData either no targetMeshName or a targetMeshName that matches the MeshName of meshInstance. int32_t metadataEndIndex = firstTransmission.indexOf(broadcastMetadataDelimiter); if (metadataEndIndex == -1) { - return false; // broadcastMetadataDelimiter not found + return false; // broadcastMetadataDelimiter not found } String targetMeshName = firstTransmission.substring(0, metadataEndIndex); @@ -195,7 +192,7 @@ bool broadcastFilter(String &firstTransmission, EspnowMeshBackend &meshInstance) @return True if attemptTransmission should continue with the next entry in the connectionQueue. False if attemptTransmission should stop. */ -bool exampleTransmissionOutcomesUpdateHook(MeshBackendBase &meshInstance) { +bool exampleTransmissionOutcomesUpdateHook(MeshBackendBase& meshInstance) { // Currently this is exactly the same as the default hook, but you can modify it to alter the behaviour of attemptTransmission. (void)meshInstance; // This is useful to remove a "unused parameter" compiler warning. Does nothing else. @@ -218,7 +215,7 @@ bool exampleTransmissionOutcomesUpdateHook(MeshBackendBase &meshInstance) { @return True if the response transmission process should continue with the next response in the waiting list. False if the response transmission process should stop once processing of the just sent response is complete. */ -bool exampleResponseTransmittedHook(bool transmissionSuccessful, const String &response, const uint8_t *recipientMac, uint32_t responseIndex, EspnowMeshBackend &meshInstance) { +bool exampleResponseTransmittedHook(bool transmissionSuccessful, const String& response, const uint8_t* recipientMac, uint32_t responseIndex, EspnowMeshBackend& meshInstance) { // Currently this is exactly the same as the default hook, but you can modify it to alter the behaviour of sendEspnowResponses. (void)transmissionSuccessful; // This is useful to remove a "unused parameter" compiler warning. Does nothing else. @@ -318,7 +315,7 @@ void loop() { if (espnowNode.latestTransmissionOutcomes().empty()) { Serial.println(F("No mesh AP found.")); } else { - for (TransmissionOutcome &transmissionOutcome : espnowNode.latestTransmissionOutcomes()) { + for (TransmissionOutcome& transmissionOutcome : espnowNode.latestTransmissionOutcomes()) { if (transmissionOutcome.transmissionStatus() == TransmissionStatusType::TRANSMISSION_FAILED) { Serial.println(String(F("Transmission failed to mesh AP ")) + transmissionOutcome.SSID()); } else if (transmissionOutcome.transmissionStatus() == TransmissionStatusType::CONNECTION_FAILED) { @@ -348,7 +345,7 @@ void loop() { // If you have a data array containing null values it is possible to transmit the raw data by making the array into a multiString as shown below. // You can use String::c_str() or String::begin() to retrieve the data array later. // Note that certain String methods such as String::substring use null values to determine String length, which means they will not work as normal with multiStrings. - uint8_t dataArray[] = {0, '\'', 0, '\'', ' ', '(', 'n', 'u', 'l', 'l', ')', ' ', 'v', 'a', 'l', 'u', 'e'}; + uint8_t dataArray[] = { 0, '\'', 0, '\'', ' ', '(', 'n', 'u', 'l', 'l', ')', ' ', 'v', 'a', 'l', 'u', 'e' }; String espnowMessage = TypeCast::uint8ArrayToMultiString(dataArray, sizeof dataArray) + F(" from ") + espnowNode.getMeshName() + espnowNode.getNodeID() + String('.'); Serial.println(String(F("\nTransmitting: ")) + espnowMessage); espnowNode.attemptTransmission(espnowMessage, false); @@ -356,7 +353,7 @@ void loop() { Serial.println(F("\nPerforming encrypted ESP-NOW transmissions.")); - uint8_t targetBSSID[6] {0}; + uint8_t targetBSSID[6] { 0 }; // We can create encrypted connections to individual nodes so that all ESP-NOW communication with the node will be encrypted. if (espnowNode.constConnectionQueue()[0].getBSSID(targetBSSID) && espnowNode.requestEncryptedConnection(targetBSSID) == EncryptedConnectionStatus::CONNECTION_ESTABLISHED) { @@ -434,7 +431,7 @@ void loop() { espnowNode.attemptAutoEncryptingTransmission(espnowMessage); espnowDelay(100); // Wait for response. } else { - Serial.println(String(F("Ooops! Encrypted connection removal failed. Status: ")) + String(static_cast(removalOutcome))); + Serial.println(String(F("Ooops! Encrypted connection removal failed. Status: ")) + String(static_cast(removalOutcome))); } // Finally, should you ever want to stop other parties from sending unencrypted messages to the node @@ -446,7 +443,7 @@ void loop() { // Our last request was sent to all nodes found, so time to create a new request. espnowNode.setMessage(String(F("Hello world request #")) + String(++requestNumber) + F(" from ") - + espnowNode.getMeshName() + espnowNode.getNodeID() + String('.')); + + espnowNode.getMeshName() + espnowNode.getNodeID() + String('.')); } Serial.println(); diff --git a/libraries/ESP8266WiFiMesh/examples/HelloMesh/HelloMesh.ino b/libraries/ESP8266WiFiMesh/examples/HelloMesh/HelloMesh.ino index 3ae8567e16..b70b41b8c4 100644 --- a/libraries/ESP8266WiFiMesh/examples/HelloMesh/HelloMesh.ino +++ b/libraries/ESP8266WiFiMesh/examples/HelloMesh/HelloMesh.ino @@ -34,14 +34,12 @@ constexpr char exampleWiFiPassword[] PROGMEM = "ChangeThisWiFiPassword_TODO"; // // A custom encryption key is required when using encrypted ESP-NOW transmissions. There is always a default Kok set, but it can be replaced if desired. // All ESP-NOW keys below must match in an encrypted connection pair for encrypted communication to be possible. // Note that it is also possible to use Strings as key seeds instead of arrays. -uint8_t espnowEncryptedConnectionKey[16] = {0x33, 0x44, 0x33, 0x44, 0x33, 0x44, 0x33, 0x44, // This is the key for encrypting transmissions of encrypted connections. - 0x33, 0x44, 0x33, 0x44, 0x33, 0x44, 0x32, 0x11 - }; -uint8_t espnowHashKey[16] = {0xEF, 0x44, 0x33, 0x0C, 0x33, 0x44, 0xFE, 0x44, // This is the secret key used for HMAC during encrypted connection requests. - 0x33, 0x44, 0x33, 0xB0, 0x33, 0x44, 0x32, 0xAD - }; +uint8_t espnowEncryptedConnectionKey[16] = { 0x33, 0x44, 0x33, 0x44, 0x33, 0x44, 0x33, 0x44, // This is the key for encrypting transmissions of encrypted connections. + 0x33, 0x44, 0x33, 0x44, 0x33, 0x44, 0x32, 0x11 }; +uint8_t espnowHashKey[16] = { 0xEF, 0x44, 0x33, 0x0C, 0x33, 0x44, 0xFE, 0x44, // This is the secret key used for HMAC during encrypted connection requests. + 0x33, 0x44, 0x33, 0xB0, 0x33, 0x44, 0x32, 0xAD }; -bool meshMessageHandler(String &message, FloodingMesh &meshInstance); +bool meshMessageHandler(String& message, FloodingMesh& meshInstance); /* Create the mesh node object */ FloodingMesh floodingMesh = FloodingMesh(meshMessageHandler, FPSTR(exampleWiFiPassword), espnowEncryptedConnectionKey, espnowHashKey, FPSTR(exampleMeshName), TypeCast::uint64ToString(ESP.getChipId()), true); @@ -62,7 +60,7 @@ bool useLED = false; // Change this to true if you wish the onboard LED to mark @param meshInstance The FloodingMesh instance that received the message. @return True if this node should forward the received message to other nodes. False otherwise. */ -bool meshMessageHandler(String &message, FloodingMesh &meshInstance) { +bool meshMessageHandler(String& message, FloodingMesh& meshInstance) { int32_t delimiterIndex = message.indexOf(meshInstance.metadataDelimiter()); if (delimiterIndex == 0) { Serial.print(String(F("Message received from STA MAC ")) + meshInstance.getEspnowMeshBackend().getSenderMac() + F(": ")); @@ -138,7 +136,7 @@ void setup() { floodingMesh.begin(); floodingMesh.activateAP(); // Required to receive messages - uint8_t apMacArray[6] {0}; + uint8_t apMacArray[6] { 0 }; theOneMac = TypeCast::macToString(WiFi.softAPmacAddress(apMacArray)); if (useLED) { diff --git a/libraries/ESP8266WiFiMesh/examples/HelloTcpIp/HelloTcpIp.ino b/libraries/ESP8266WiFiMesh/examples/HelloTcpIp/HelloTcpIp.ino index f68b81f181..f8c3b6a9f8 100644 --- a/libraries/ESP8266WiFiMesh/examples/HelloTcpIp/HelloTcpIp.ino +++ b/libraries/ESP8266WiFiMesh/examples/HelloTcpIp/HelloTcpIp.ino @@ -25,9 +25,9 @@ constexpr char exampleWiFiPassword[] PROGMEM = "ChangeThisWiFiPassword_TODO"; // unsigned int requestNumber = 0; unsigned int responseNumber = 0; -String manageRequest(const String &request, MeshBackendBase &meshInstance); -TransmissionStatusType manageResponse(const String &response, MeshBackendBase &meshInstance); -void networkFilter(int numberOfNetworks, MeshBackendBase &meshInstance); +String manageRequest(const String& request, MeshBackendBase& meshInstance); +TransmissionStatusType manageResponse(const String& response, MeshBackendBase& meshInstance); +void networkFilter(int numberOfNetworks, MeshBackendBase& meshInstance); /* Create the mesh node object */ TcpIpMeshBackend tcpIpNode = TcpIpMeshBackend(manageRequest, manageResponse, networkFilter, FPSTR(exampleWiFiPassword), FPSTR(exampleMeshName), TypeCast::uint64ToString(ESP.getChipId()), true); @@ -39,12 +39,12 @@ TcpIpMeshBackend tcpIpNode = TcpIpMeshBackend(manageRequest, manageResponse, net @param meshInstance The MeshBackendBase instance that called the function. @return The string to send back to the other node. For ESP-NOW, return an empty string ("") if no response should be sent. */ -String manageRequest(const String &request, MeshBackendBase &meshInstance) { +String manageRequest(const String& request, MeshBackendBase& meshInstance) { // To get the actual class of the polymorphic meshInstance, do as follows (meshBackendCast replaces dynamic_cast since RTTI is disabled) - if (EspnowMeshBackend *espnowInstance = TypeCast::meshBackendCast(&meshInstance)) { + if (EspnowMeshBackend* espnowInstance = TypeCast::meshBackendCast(&meshInstance)) { String transmissionEncrypted = espnowInstance->receivedEncryptedTransmission() ? F(", Encrypted transmission") : F(", Unencrypted transmission"); Serial.print(String(F("ESP-NOW (")) + espnowInstance->getSenderMac() + transmissionEncrypted + F("): ")); - } else if (TcpIpMeshBackend *tcpIpInstance = TypeCast::meshBackendCast(&meshInstance)) { + } else if (TcpIpMeshBackend* tcpIpInstance = TypeCast::meshBackendCast(&meshInstance)) { (void)tcpIpInstance; // This is useful to remove a "unused parameter" compiler warning. Does nothing else. Serial.print(F("TCP/IP: ")); } else { @@ -69,14 +69,14 @@ String manageRequest(const String &request, MeshBackendBase &meshInstance) { @param meshInstance The MeshBackendBase instance that called the function. @return The status code resulting from the response, as an int */ -TransmissionStatusType manageResponse(const String &response, MeshBackendBase &meshInstance) { +TransmissionStatusType manageResponse(const String& response, MeshBackendBase& meshInstance) { TransmissionStatusType statusCode = TransmissionStatusType::TRANSMISSION_COMPLETE; // To get the actual class of the polymorphic meshInstance, do as follows (meshBackendCast replaces dynamic_cast since RTTI is disabled) - if (EspnowMeshBackend *espnowInstance = TypeCast::meshBackendCast(&meshInstance)) { + if (EspnowMeshBackend* espnowInstance = TypeCast::meshBackendCast(&meshInstance)) { String transmissionEncrypted = espnowInstance->receivedEncryptedTransmission() ? F(", Encrypted transmission") : F(", Unencrypted transmission"); Serial.print(String(F("ESP-NOW (")) + espnowInstance->getSenderMac() + transmissionEncrypted + F("): ")); - } else if (TcpIpMeshBackend *tcpIpInstance = TypeCast::meshBackendCast(&meshInstance)) { + } else if (TcpIpMeshBackend* tcpIpInstance = TypeCast::meshBackendCast(&meshInstance)) { Serial.print(F("TCP/IP: ")); // Getting the sent message like this will work as long as ONLY(!) TCP/IP is used. @@ -105,7 +105,7 @@ TransmissionStatusType manageResponse(const String &response, MeshBackendBase &m @param numberOfNetworks The number of networks found in the WiFi scan. @param meshInstance The MeshBackendBase instance that called the function. */ -void networkFilter(int numberOfNetworks, MeshBackendBase &meshInstance) { +void networkFilter(int numberOfNetworks, MeshBackendBase& meshInstance) { // Note that the network index of a given node may change whenever a new scan is done. for (int networkIndex = 0; networkIndex < numberOfNetworks; ++networkIndex) { String currentSSID = WiFi.SSID(networkIndex); @@ -116,9 +116,9 @@ void networkFilter(int numberOfNetworks, MeshBackendBase &meshInstance) { uint64_t targetNodeID = TypeCast::stringToUint64(currentSSID.substring(meshNameIndex + meshInstance.getMeshName().length())); if (targetNodeID < TypeCast::stringToUint64(meshInstance.getNodeID())) { - if (EspnowMeshBackend *espnowInstance = TypeCast::meshBackendCast(&meshInstance)) { + if (EspnowMeshBackend* espnowInstance = TypeCast::meshBackendCast(&meshInstance)) { espnowInstance->connectionQueue().emplace_back(networkIndex); - } else if (TcpIpMeshBackend *tcpIpInstance = TypeCast::meshBackendCast(&meshInstance)) { + } else if (TcpIpMeshBackend* tcpIpInstance = TypeCast::meshBackendCast(&meshInstance)) { tcpIpInstance->connectionQueue().emplace_back(networkIndex); } else { Serial.println(F("Invalid mesh backend!")); @@ -139,14 +139,14 @@ void networkFilter(int numberOfNetworks, MeshBackendBase &meshInstance) { @return True if attemptTransmission should continue with the next entry in the connectionQueue. False if attemptTransmission should stop. */ -bool exampleTransmissionOutcomesUpdateHook(MeshBackendBase &meshInstance) { +bool exampleTransmissionOutcomesUpdateHook(MeshBackendBase& meshInstance) { // The default hook only returns true and does nothing else. - if (TcpIpMeshBackend *tcpIpInstance = TypeCast::meshBackendCast(&meshInstance)) { + if (TcpIpMeshBackend* tcpIpInstance = TypeCast::meshBackendCast(&meshInstance)) { if (tcpIpInstance->latestTransmissionOutcomes().back().transmissionStatus() == TransmissionStatusType::TRANSMISSION_COMPLETE) { // Our last request got a response, so time to create a new request. meshInstance.setMessage(String(F("Hello world request #")) + String(++requestNumber) + F(" from ") - + meshInstance.getMeshName() + meshInstance.getNodeID() + String('.')); + + meshInstance.getMeshName() + meshInstance.getNodeID() + String('.')); } } else { Serial.println(F("Invalid mesh backend!")); @@ -202,7 +202,7 @@ void loop() { if (tcpIpNode.latestTransmissionOutcomes().empty()) { Serial.println(F("No mesh AP found.")); } else { - for (TransmissionOutcome &transmissionOutcome : tcpIpNode.latestTransmissionOutcomes()) { + for (TransmissionOutcome& transmissionOutcome : tcpIpNode.latestTransmissionOutcomes()) { if (transmissionOutcome.transmissionStatus() == TransmissionStatusType::TRANSMISSION_FAILED) { Serial.println(String(F("Transmission failed to mesh AP ")) + transmissionOutcome.SSID()); } else if (transmissionOutcome.transmissionStatus() == TransmissionStatusType::CONNECTION_FAILED) { diff --git a/libraries/ESP8266httpUpdate/examples/httpUpdate/httpUpdate.ino b/libraries/ESP8266httpUpdate/examples/httpUpdate/httpUpdate.ino index 19c555a235..6f8e93dec4 100644 --- a/libraries/ESP8266httpUpdate/examples/httpUpdate/httpUpdate.ino +++ b/libraries/ESP8266httpUpdate/examples/httpUpdate/httpUpdate.ino @@ -15,7 +15,7 @@ #ifndef APSSID #define APSSID "APSSID" -#define APPSK "APPSK" +#define APPSK "APPSK" #endif ESP8266WiFiMulti WiFiMulti; @@ -37,8 +37,6 @@ void setup() { WiFi.mode(WIFI_STA); WiFiMulti.addAP(APSSID, APPSK); - - } void update_started() { @@ -57,7 +55,6 @@ void update_error(int err) { Serial.printf("CALLBACK: HTTP update fatal error code %d\n", err); } - void loop() { // wait for WiFi connection if ((WiFiMulti.run() == WL_CONNECTED)) { @@ -97,4 +94,3 @@ void loop() { } } } - diff --git a/libraries/ESP8266httpUpdate/examples/httpUpdateLittleFS/httpUpdateLittleFS.ino b/libraries/ESP8266httpUpdate/examples/httpUpdateLittleFS/httpUpdateLittleFS.ino index 6541d047fd..22f6e65260 100644 --- a/libraries/ESP8266httpUpdate/examples/httpUpdateLittleFS/httpUpdateLittleFS.ino +++ b/libraries/ESP8266httpUpdate/examples/httpUpdateLittleFS/httpUpdateLittleFS.ino @@ -17,7 +17,7 @@ ESP8266WiFiMulti WiFiMulti; #ifndef APSSID #define APSSID "APSSID" -#define APPSK "APPSK" +#define APPSK "APPSK" #endif void setup() { @@ -37,7 +37,6 @@ void setup() { WiFi.mode(WIFI_STA); WiFiMulti.addAP(APSSID, APPSK); - } void loop() { @@ -77,4 +76,3 @@ void loop() { } } } - diff --git a/libraries/ESP8266httpUpdate/examples/httpUpdateSecure/httpUpdateSecure.ino b/libraries/ESP8266httpUpdate/examples/httpUpdateSecure/httpUpdateSecure.ino index beb613897c..0353126ef2 100644 --- a/libraries/ESP8266httpUpdate/examples/httpUpdateSecure/httpUpdateSecure.ino +++ b/libraries/ESP8266httpUpdate/examples/httpUpdateSecure/httpUpdateSecure.ino @@ -18,7 +18,7 @@ #ifndef APSSID #define APSSID "APSSID" -#define APPSK "APPSK" +#define APPSK "APPSK" #endif ESP8266WiFiMulti WiFiMulti; @@ -31,7 +31,7 @@ BearSSL::CertStore certStore; // Set time via NTP, as required for x.509 validation void setClock() { - configTime(0, 0, "pool.ntp.org", "time.nist.gov"); // UTC + configTime(0, 0, "pool.ntp.org", "time.nist.gov"); // UTC Serial.print(F("Waiting for NTP time sync: ")); time_t now = time(nullptr); @@ -85,7 +85,7 @@ void loop() { setClock(); BearSSL::WiFiClientSecure client; - bool mfln = client.probeMaxFragmentLength("server", 443, 1024); // server must be the same as in ESPhttpUpdate.update() + bool mfln = client.probeMaxFragmentLength("server", 443, 1024); // server must be the same as in ESPhttpUpdate.update() Serial.printf("MFLN supported: %s\n", mfln ? "yes" : "no"); if (mfln) { client.setBufferSizes(1024, 1024); @@ -104,7 +104,6 @@ void loop() { // Or: //t_httpUpdate_return ret = ESPhttpUpdate.update(client, "server", 443, "file.bin"); - switch (ret) { case HTTP_UPDATE_FAILED: Serial.printf("HTTP_UPDATE_FAILED Error (%d): %s\n", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str()); diff --git a/libraries/ESP8266httpUpdate/examples/httpUpdateSigned/httpUpdateSigned.ino b/libraries/ESP8266httpUpdate/examples/httpUpdateSigned/httpUpdateSigned.ino index e196ef6419..c7580950a6 100644 --- a/libraries/ESP8266httpUpdate/examples/httpUpdateSigned/httpUpdateSigned.ino +++ b/libraries/ESP8266httpUpdate/examples/httpUpdateSigned/httpUpdateSigned.ino @@ -23,7 +23,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif ESP8266WiFiMulti WiFiMulti; @@ -50,9 +50,9 @@ TQIDAQAB -----END PUBLIC KEY----- )EOF"; #if MANUAL_SIGNING -BearSSL::PublicKey *signPubKey = nullptr; -BearSSL::HashSHA256 *hash; -BearSSL::SigningVerifier *sign; +BearSSL::PublicKey* signPubKey = nullptr; +BearSSL::HashSHA256* hash; +BearSSL::SigningVerifier* sign; #endif void setup() { @@ -73,24 +73,23 @@ void setup() { WiFi.mode(WIFI_STA); WiFiMulti.addAP(STASSID, STAPSK); - #if MANUAL_SIGNING +#if MANUAL_SIGNING signPubKey = new BearSSL::PublicKey(pubkey); hash = new BearSSL::HashSHA256(); sign = new BearSSL::SigningVerifier(signPubKey); - #endif +#endif } - void loop() { // wait for WiFi connection if ((WiFiMulti.run() == WL_CONNECTED)) { WiFiClient client; - #if MANUAL_SIGNING +#if MANUAL_SIGNING // Ensure all updates are signed appropriately. W/o this call, all will be accepted. Update.installSignature(hash, sign); - #endif +#endif // If the key files are present in the build directory, signing will be // enabled using them automatically @@ -114,4 +113,3 @@ void loop() { } delay(10000); } - diff --git a/libraries/ESP8266mDNS/examples/LEAmDNS/mDNS_Clock/mDNS_Clock.ino b/libraries/ESP8266mDNS/examples/LEAmDNS/mDNS_Clock/mDNS_Clock.ino index f0a9de1225..b5748bf331 100644 --- a/libraries/ESP8266mDNS/examples/LEAmDNS/mDNS_Clock/mDNS_Clock.ino +++ b/libraries/ESP8266mDNS/examples/LEAmDNS/mDNS_Clock/mDNS_Clock.ino @@ -31,7 +31,6 @@ */ - #include #include #include @@ -43,44 +42,42 @@ Global defines and vars */ -#define TIMEZONE_OFFSET 1 // CET -#define DST_OFFSET 1 // CEST -#define UPDATE_CYCLE (1 * 1000) // every second +#define TIMEZONE_OFFSET 1 // CET +#define DST_OFFSET 1 // CEST +#define UPDATE_CYCLE (1 * 1000) // every second -#define SERVICE_PORT 80 // HTTP port +#define SERVICE_PORT 80 // HTTP port #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char* ssid = STASSID; -const char* password = STAPSK; +const char* ssid = STASSID; +const char* password = STAPSK; -char* pcHostDomain = 0; // Negotiated host domain -bool bHostDomainConfirmed = false; // Flags the confirmation of the host domain -MDNSResponder::hMDNSService hMDNSService = 0; // The handle of the clock service in the MDNS responder +char* pcHostDomain = 0; // Negotiated host domain +bool bHostDomainConfirmed = false; // Flags the confirmation of the host domain +MDNSResponder::hMDNSService hMDNSService = 0; // The handle of the clock service in the MDNS responder // HTTP server at port 'SERVICE_PORT' will respond to HTTP requests -ESP8266WebServer server(SERVICE_PORT); +ESP8266WebServer server(SERVICE_PORT); /* getTimeString */ const char* getTimeString(void) { - static char acTimeString[32]; + static char acTimeString[32]; time_t now = time(nullptr); ctime_r(&now, acTimeString); - size_t stLength; - while (((stLength = strlen(acTimeString))) && - ('\n' == acTimeString[stLength - 1])) { + size_t stLength; + while (((stLength = strlen(acTimeString))) && ('\n' == acTimeString[stLength - 1])) { acTimeString[stLength - 1] = 0; // Remove trailing line break... } return acTimeString; } - /* setClock @@ -90,8 +87,8 @@ void setClock(void) { configTime((TIMEZONE_OFFSET * 3600), (DST_OFFSET * 3600), "pool.ntp.org", "time.nist.gov", "time.windows.com"); Serial.print("Waiting for NTP time sync: "); - time_t now = time(nullptr); // Secs since 01.01.1970 (when uninitialized starts with (8 * 3600 = 28800) - while (now < 8 * 3600 * 2) { // Wait for realistic value + time_t now = time(nullptr); // Secs since 01.01.1970 (when uninitialized starts with (8 * 3600 = 28800) + while (now < 8 * 3600 * 2) { // Wait for realistic value delay(500); Serial.print("."); now = time(nullptr); @@ -100,7 +97,6 @@ void setClock(void) { Serial.printf("Current time: %s\n", getTimeString()); } - /* setStationHostname */ @@ -113,7 +109,6 @@ bool setStationHostname(const char* p_pcHostname) { return true; } - /* MDNSDynamicServiceTxtCallback @@ -132,7 +127,6 @@ void MDNSDynamicServiceTxtCallback(const MDNSResponder::hMDNSService p_hService) } } - /* MDNSProbeResultCallback @@ -176,7 +170,6 @@ void hostProbeResult(String p_pcDomainName, bool p_bProbeResult) { } } - /* handleHTTPClient */ @@ -186,7 +179,8 @@ void handleHTTPRequest() { Serial.println("HTTP Request"); // Get current time - time_t now = time(nullptr);; + time_t now = time(nullptr); + ; struct tm timeinfo; gmtime_r(&now, &timeinfo); @@ -231,8 +225,7 @@ void setup(void) { // Setup MDNS responder MDNS.setHostProbeResultCallback(hostProbeResult); // Init the (currently empty) host domain string with 'esp8266' - if ((!MDNSResponder::indexDomain(pcHostDomain, 0, "esp8266")) || - (!MDNS.begin(pcHostDomain))) { + if ((!MDNSResponder::indexDomain(pcHostDomain, 0, "esp8266")) || (!MDNS.begin(pcHostDomain))) { Serial.println("Error setting up MDNS responder!"); while (1) { // STOP delay(1000); diff --git a/libraries/ESP8266mDNS/examples/LEAmDNS/mDNS_ServiceMonitor/mDNS_ServiceMonitor.ino b/libraries/ESP8266mDNS/examples/LEAmDNS/mDNS_ServiceMonitor/mDNS_ServiceMonitor.ino index 17b29ec57c..4724762b4d 100644 --- a/libraries/ESP8266mDNS/examples/LEAmDNS/mDNS_ServiceMonitor/mDNS_ServiceMonitor.ino +++ b/libraries/ESP8266mDNS/examples/LEAmDNS/mDNS_ServiceMonitor/mDNS_ServiceMonitor.ino @@ -29,7 +29,6 @@ */ - #include #include #include @@ -39,27 +38,26 @@ Global defines and vars */ -#define SERVICE_PORT 80 // HTTP port +#define SERVICE_PORT 80 // HTTP port #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char* ssid = STASSID; -const char* password = STAPSK; +const char* ssid = STASSID; +const char* password = STAPSK; -char* pcHostDomain = 0; // Negotiated host domain -bool bHostDomainConfirmed = false; // Flags the confirmation of the host domain -MDNSResponder::hMDNSService hMDNSService = 0; // The handle of the http service in the MDNS responder -MDNSResponder::hMDNSServiceQuery hMDNSServiceQuery = 0; // The handle of the 'http.tcp' service query in the MDNS responder +char* pcHostDomain = 0; // Negotiated host domain +bool bHostDomainConfirmed = false; // Flags the confirmation of the host domain +MDNSResponder::hMDNSService hMDNSService = 0; // The handle of the http service in the MDNS responder +MDNSResponder::hMDNSServiceQuery hMDNSServiceQuery = 0; // The handle of the 'http.tcp' service query in the MDNS responder -const String cstrNoHTTPServices = "Currently no 'http.tcp' services in the local network!
    "; -String strHTTPServices = cstrNoHTTPServices; +const String cstrNoHTTPServices = "Currently no 'http.tcp' services in the local network!
    "; +String strHTTPServices = cstrNoHTTPServices; // HTTP server at port 'SERVICE_PORT' will respond to HTTP requests -ESP8266WebServer server(SERVICE_PORT); - +ESP8266WebServer server(SERVICE_PORT); /* setStationHostname @@ -80,25 +78,25 @@ bool setStationHostname(const char* p_pcHostname) { void MDNSServiceQueryCallback(MDNSResponder::MDNSServiceInfo serviceInfo, MDNSResponder::AnswerType answerType, bool p_bSetContent) { String answerInfo; switch (answerType) { - case MDNSResponder::AnswerType::ServiceDomain : + case MDNSResponder::AnswerType::ServiceDomain: answerInfo = "ServiceDomain " + String(serviceInfo.serviceDomain()); break; - case MDNSResponder::AnswerType::HostDomainAndPort : + case MDNSResponder::AnswerType::HostDomainAndPort: answerInfo = "HostDomainAndPort " + String(serviceInfo.hostDomain()) + ":" + String(serviceInfo.hostPort()); break; - case MDNSResponder::AnswerType::IP4Address : + case MDNSResponder::AnswerType::IP4Address: answerInfo = "IP4Address "; for (IPAddress ip : serviceInfo.IP4Adresses()) { answerInfo += "- " + ip.toString(); }; break; - case MDNSResponder::AnswerType::Txt : + case MDNSResponder::AnswerType::Txt: answerInfo = "TXT " + String(serviceInfo.strKeyValue()); for (auto kv : serviceInfo.keyValues()) { answerInfo += "\nkv : " + String(kv.first) + " : " + String(kv.second); } break; - default : + default: answerInfo = "Unknown Answertype"; } Serial.printf("Answer %s %s\n", answerInfo.c_str(), p_bSetContent ? "Modified" : "Deleted"); @@ -110,9 +108,9 @@ void MDNSServiceQueryCallback(MDNSResponder::MDNSServiceInfo serviceInfo, MDNSRe */ void serviceProbeResult(String p_pcServiceName, - const MDNSResponder::hMDNSService p_hMDNSService, - bool p_bProbeResult) { - (void) p_hMDNSService; + const MDNSResponder::hMDNSService p_hMDNSService, + bool p_bProbeResult) { + (void)p_hMDNSService; Serial.printf("MDNSServiceProbeResultCallback: Service %s probe %s\n", p_pcServiceName.c_str(), (p_bProbeResult ? "succeeded." : "failed!")); } @@ -186,7 +184,7 @@ void handleHTTPRequest() { s += WiFi.hostname() + ".local at " + WiFi.localIP().toString() + ""; s += "

    Local HTTP services are :

    "; s += "
      "; - for (auto info : MDNS.answerInfo(hMDNSServiceQuery)) { + for (auto info : MDNS.answerInfo(hMDNSServiceQuery)) { s += "
    1. "; s += info.serviceDomain(); if (info.hostDomainAvailable()) { @@ -245,8 +243,7 @@ void setup(void) { MDNS.setHostProbeResultCallback(hostProbeResult); // Init the (currently empty) host domain string with 'esp8266' - if ((!MDNSResponder::indexDomain(pcHostDomain, 0, "esp8266")) || - (!MDNS.begin(pcHostDomain))) { + if ((!MDNSResponder::indexDomain(pcHostDomain, 0, "esp8266")) || (!MDNS.begin(pcHostDomain))) { Serial.println(" Error setting up MDNS responder!"); while (1) { // STOP delay(1000); @@ -265,6 +262,3 @@ void loop(void) { // Allow MDNS processing MDNS.update(); } - - - diff --git a/libraries/ESP8266mDNS/examples/OTA-mDNS-LittleFS/OTA-mDNS-LittleFS.ino b/libraries/ESP8266mDNS/examples/OTA-mDNS-LittleFS/OTA-mDNS-LittleFS.ino index 87d03900f3..97364eb729 100644 --- a/libraries/ESP8266mDNS/examples/OTA-mDNS-LittleFS/OTA-mDNS-LittleFS.ino +++ b/libraries/ESP8266mDNS/examples/OTA-mDNS-LittleFS/OTA-mDNS-LittleFS.ino @@ -14,12 +14,12 @@ #ifndef APSSID #define APSSID "your-apssid" -#define APPSK "your-password" +#define APPSK "your-password" #endif #ifndef STASSID #define STASSID "your-sta" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif // includes @@ -30,7 +30,6 @@ #include #include - /** @brief mDNS and OTA Constants @{ @@ -59,7 +58,7 @@ const char* ap_default_psk = APPSK; ///< Default PSK. and the WiFi PSK in the second line. Line separator can be \r\n (CR LF) \r or \n. */ -bool loadConfig(String *ssid, String *pass) { +bool loadConfig(String* ssid, String* pass) { // open file for reading. File configFile = LittleFS.open("/cl_conf.txt", "r"); if (!configFile) { @@ -112,14 +111,13 @@ bool loadConfig(String *ssid, String *pass) { return true; } // loadConfig - /** @brief Save WiFi SSID and PSK to configuration file. @param ssid SSID as string pointer. @param pass PSK as string pointer, @return True or False. */ -bool saveConfig(String *ssid, String *pass) { +bool saveConfig(String* ssid, String* pass) { // Open config file for writing. File configFile = LittleFS.open("/cl_conf.txt", "w"); if (!configFile) { @@ -137,7 +135,6 @@ bool saveConfig(String *ssid, String *pass) { return true; } // saveConfig - /** @brief Arduino setup function. */ @@ -162,7 +159,6 @@ void setup() { Serial.println("Hostname: " + hostname); //Serial.println(WiFi.hostname()); - // Initialize file system. if (!LittleFS.begin()) { Serial.println("Failed to mount file system"); @@ -170,7 +166,7 @@ void setup() { } // Load wifi connection information. - if (! loadConfig(&station_ssid, &station_psk)) { + if (!loadConfig(&station_ssid, &station_psk)) { station_ssid = STASSID; station_psk = STAPSK; @@ -233,11 +229,10 @@ void setup() { } // Start OTA server. - ArduinoOTA.setHostname((const char *)hostname.c_str()); + ArduinoOTA.setHostname((const char*)hostname.c_str()); ArduinoOTA.begin(); } - /** @brief Arduino loop function. */ @@ -245,4 +240,3 @@ void loop() { // Handle OTA server. ArduinoOTA.handle(); } - diff --git a/libraries/ESP8266mDNS/examples/mDNS-SD_Extended/mDNS-SD_Extended.ino b/libraries/ESP8266mDNS/examples/mDNS-SD_Extended/mDNS-SD_Extended.ino index fda2fe6562..0a43ca3e85 100644 --- a/libraries/ESP8266mDNS/examples/mDNS-SD_Extended/mDNS-SD_Extended.ino +++ b/libraries/ESP8266mDNS/examples/mDNS-SD_Extended/mDNS-SD_Extended.ino @@ -14,12 +14,12 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char* ssid = STASSID; +const char* ssid = STASSID; const char* password = STAPSK; -char hostString[16] = {0}; +char hostString[16] = { 0 }; void setup() { Serial.begin(115200); diff --git a/libraries/ESP8266mDNS/examples/mDNS_Web_Server/mDNS_Web_Server.ino b/libraries/ESP8266mDNS/examples/mDNS_Web_Server/mDNS_Web_Server.ino index e85714d821..3f65e361de 100644 --- a/libraries/ESP8266mDNS/examples/mDNS_Web_Server/mDNS_Web_Server.ino +++ b/libraries/ESP8266mDNS/examples/mDNS_Web_Server/mDNS_Web_Server.ino @@ -15,14 +15,13 @@ */ - #include #include #include #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* ssid = STASSID; @@ -121,4 +120,3 @@ void loop(void) { Serial.println("Done with client"); } - diff --git a/libraries/ESP8266mDNS/src/LEAmDNS.cpp b/libraries/ESP8266mDNS/src/LEAmDNS.cpp index 611c3dfc38..910884ae5d 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS.cpp +++ b/libraries/ESP8266mDNS/src/LEAmDNS.cpp @@ -48,35 +48,35 @@ namespace MDNSImplementation #define STRINGIZE_VALUE_OF(x) STRINGIZE(x) #endif -/** + /** INTERFACE */ -/** + /** MDNSResponder::MDNSResponder */ -MDNSResponder::MDNSResponder(void) - : m_pServices(0), - m_pUDPContext(0), - m_pcHostname(0), - m_pServiceQueries(0), - m_fnServiceTxtCallback(0) -{ -} + MDNSResponder::MDNSResponder(void) + : m_pServices(0) + , m_pUDPContext(0) + , m_pcHostname(0) + , m_pServiceQueries(0) + , m_fnServiceTxtCallback(0) + { + } -/* + /* MDNSResponder::~MDNSResponder */ -MDNSResponder::~MDNSResponder(void) -{ - _resetProbeStatus(false); - _releaseServiceQueries(); - _releaseHostname(); - _releaseUDPContext(); - _releaseServices(); -} + MDNSResponder::~MDNSResponder(void) + { + _resetProbeStatus(false); + _releaseServiceQueries(); + _releaseHostname(); + _releaseUDPContext(); + _releaseServices(); + } -/* + /* MDNSResponder::begin Set the host domain (for probing) and install WiFi event handlers for @@ -85,60 +85,60 @@ MDNSResponder::~MDNSResponder(void) Finally the responder is (re)started */ -bool MDNSResponder::begin(const char* p_pcHostname, const IPAddress& /*p_IPAddress*/, uint32_t /*p_u32TTL*/) -{ - bool bResult = false; - - if (_setHostname(p_pcHostname)) + bool MDNSResponder::begin(const char* p_pcHostname, const IPAddress& /*p_IPAddress*/, uint32_t /*p_u32TTL*/) { - bResult = _restart(); - } + bool bResult = false; - LwipIntf::stateUpCB( - [this](netif* intf) + if (_setHostname(p_pcHostname)) { - (void)intf; - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] new Interface '%c%c' is UP! restarting\n"), intf->name[0], intf->name[1])); - _restart(); - }); - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] begin: FAILED for '%s'!\n"), (p_pcHostname ?: "-")); - }); - - return bResult; -} + bResult = _restart(); + } -/* + LwipIntf::stateUpCB( + [this](netif* intf) + { + (void)intf; + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] new Interface '%c%c' is UP! restarting\n"), intf->name[0], intf->name[1])); + _restart(); + }); + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] begin: FAILED for '%s'!\n"), (p_pcHostname ?: "-")); + }); + + return bResult; + } + + /* MDNSResponder::close Ends the MDNS responder. Announced services are unannounced (by multicasting a goodbye message) */ -bool MDNSResponder::close(void) -{ - bool bResult = false; - - if (0 != m_pUDPContext) + bool MDNSResponder::close(void) { - _announce(false, true); - _resetProbeStatus(false); // Stop probing - _releaseServiceQueries(); - _releaseServices(); - _releaseUDPContext(); - _releaseHostname(); + bool bResult = false; - bResult = true; - } - else - { - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] close: Ignoring call to close!\n"));); + if (0 != m_pUDPContext) + { + _announce(false, true); + _resetProbeStatus(false); // Stop probing + _releaseServiceQueries(); + _releaseServices(); + _releaseUDPContext(); + _releaseHostname(); + + bResult = true; + } + else + { + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] close: Ignoring call to close!\n"));); + } + return bResult; } - return bResult; -} -/* + /* MDNSResponder::end Ends the MDNS responder. @@ -146,12 +146,12 @@ bool MDNSResponder::close(void) */ -bool MDNSResponder::end(void) -{ - return close(); -} + bool MDNSResponder::end(void) + { + return close(); + } -/* + /* MDNSResponder::setHostname Replaces the current hostname and restarts probing. @@ -159,45 +159,45 @@ bool MDNSResponder::end(void) name), the instance names are replaced also (and the probing is restarted). */ -bool MDNSResponder::setHostname(const char* p_pcHostname) -{ - bool bResult = false; - - if (_setHostname(p_pcHostname)) + bool MDNSResponder::setHostname(const char* p_pcHostname) { - m_HostProbeInformation.m_ProbingStatus = ProbingStatus_ReadyToStart; + bool bResult = false; - // Replace 'auto-set' service names - bResult = true; - for (stcMDNSService* pService = m_pServices; ((bResult) && (pService)); pService = pService->m_pNext) + if (_setHostname(p_pcHostname)) { - if (pService->m_bAutoName) + m_HostProbeInformation.m_ProbingStatus = ProbingStatus_ReadyToStart; + + // Replace 'auto-set' service names + bResult = true; + for (stcMDNSService* pService = m_pServices; ((bResult) && (pService)); pService = pService->m_pNext) { - bResult = pService->setName(p_pcHostname); - pService->m_ProbeInformation.m_ProbingStatus = ProbingStatus_ReadyToStart; + if (pService->m_bAutoName) + { + bResult = pService->setName(p_pcHostname); + pService->m_ProbeInformation.m_ProbingStatus = ProbingStatus_ReadyToStart; + } } } + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] setHostname: FAILED for '%s'!\n"), (p_pcHostname ?: "-")); + }); + return bResult; } - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] setHostname: FAILED for '%s'!\n"), (p_pcHostname ?: "-")); - }); - return bResult; -} -/* + /* MDNSResponder::setHostname (LEGACY) */ -bool MDNSResponder::setHostname(const String& p_strHostname) -{ - return setHostname(p_strHostname.c_str()); -} + bool MDNSResponder::setHostname(const String& p_strHostname) + { + return setHostname(p_strHostname.c_str()); + } -/* + /* SERVICES */ -/* + /* MDNSResponder::addService Add service; using hostname if no name is explicitly provided for the service @@ -205,456 +205,447 @@ bool MDNSResponder::setHostname(const String& p_strHostname) may be given. If not, it is added automatically. */ -MDNSResponder::hMDNSService MDNSResponder::addService(const char* p_pcName, - const char* p_pcService, - const char* p_pcProtocol, - uint16_t p_u16Port) -{ - hMDNSService hResult = 0; - - if (((!p_pcName) || // NO name OR - (MDNS_DOMAIN_LABEL_MAXLENGTH >= os_strlen(p_pcName))) && // Fitting name - (p_pcService) && - (MDNS_SERVICE_NAME_LENGTH >= os_strlen(p_pcService)) && - (p_pcProtocol) && - ((MDNS_SERVICE_PROTOCOL_LENGTH - 1) != os_strlen(p_pcProtocol)) && - (p_u16Port)) + MDNSResponder::hMDNSService MDNSResponder::addService(const char* p_pcName, + const char* p_pcService, + const char* p_pcProtocol, + uint16_t p_u16Port) { - if (!_findService((p_pcName ?: m_pcHostname), p_pcService, p_pcProtocol)) // Not already used + hMDNSService hResult = 0; + + if (((!p_pcName) || // NO name OR + (MDNS_DOMAIN_LABEL_MAXLENGTH >= os_strlen(p_pcName))) + && // Fitting name + (p_pcService) && (MDNS_SERVICE_NAME_LENGTH >= os_strlen(p_pcService)) && (p_pcProtocol) && ((MDNS_SERVICE_PROTOCOL_LENGTH - 1) != os_strlen(p_pcProtocol)) && (p_u16Port)) { - if (0 != (hResult = (hMDNSService)_allocService(p_pcName, p_pcService, p_pcProtocol, p_u16Port))) + if (!_findService((p_pcName ?: m_pcHostname), p_pcService, p_pcProtocol)) // Not already used { - // Start probing - ((stcMDNSService*)hResult)->m_ProbeInformation.m_ProbingStatus = ProbingStatus_ReadyToStart; + if (0 != (hResult = (hMDNSService)_allocService(p_pcName, p_pcService, p_pcProtocol, p_u16Port))) + { + // Start probing + ((stcMDNSService*)hResult)->m_ProbeInformation.m_ProbingStatus = ProbingStatus_ReadyToStart; + } } - } - } // else: bad arguments - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] addService: %s to add '%s.%s.%s'!\n"), (hResult ? "Succeeded" : "FAILED"), (p_pcName ?: "-"), p_pcService, p_pcProtocol);); - DEBUG_EX_ERR(if (!hResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] addService: FAILED to add '%s.%s.%s'!\n"), (p_pcName ?: "-"), p_pcService, p_pcProtocol); - }); - return hResult; -} + } // else: bad arguments + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] addService: %s to add '%s.%s.%s'!\n"), (hResult ? "Succeeded" : "FAILED"), (p_pcName ?: "-"), p_pcService, p_pcProtocol);); + DEBUG_EX_ERR(if (!hResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] addService: FAILED to add '%s.%s.%s'!\n"), (p_pcName ?: "-"), p_pcService, p_pcProtocol); + }); + return hResult; + } -/* + /* MDNSResponder::removeService Unanounce a service (by sending a goodbye message) and remove it from the MDNS responder */ -bool MDNSResponder::removeService(const MDNSResponder::hMDNSService p_hService) -{ - stcMDNSService* pService = 0; - bool bResult = (((pService = _findService(p_hService))) && - (_announceService(*pService, false)) && - (_releaseService(pService))); - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] removeService: FAILED!\n")); - }); - return bResult; -} + bool MDNSResponder::removeService(const MDNSResponder::hMDNSService p_hService) + { + stcMDNSService* pService = 0; + bool bResult = (((pService = _findService(p_hService))) && (_announceService(*pService, false)) && (_releaseService(pService))); + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] removeService: FAILED!\n")); + }); + return bResult; + } -/* + /* MDNSResponder::removeService */ -bool MDNSResponder::removeService(const char* p_pcName, - const char* p_pcService, - const char* p_pcProtocol) -{ - return removeService((hMDNSService)_findService((p_pcName ?: m_pcHostname), p_pcService, p_pcProtocol)); -} + bool MDNSResponder::removeService(const char* p_pcName, + const char* p_pcService, + const char* p_pcProtocol) + { + return removeService((hMDNSService)_findService((p_pcName ?: m_pcHostname), p_pcService, p_pcProtocol)); + } -/* + /* MDNSResponder::addService (LEGACY) */ -bool MDNSResponder::addService(const String& p_strService, - const String& p_strProtocol, - uint16_t p_u16Port) -{ - return (0 != addService(m_pcHostname, p_strService.c_str(), p_strProtocol.c_str(), p_u16Port)); -} + bool MDNSResponder::addService(const String& p_strService, + const String& p_strProtocol, + uint16_t p_u16Port) + { + return (0 != addService(m_pcHostname, p_strService.c_str(), p_strProtocol.c_str(), p_u16Port)); + } -/* + /* MDNSResponder::setServiceName */ -bool MDNSResponder::setServiceName(const MDNSResponder::hMDNSService p_hService, - const char* p_pcInstanceName) -{ - stcMDNSService* pService = 0; - bool bResult = (((!p_pcInstanceName) || - (MDNS_DOMAIN_LABEL_MAXLENGTH >= os_strlen(p_pcInstanceName))) && - ((pService = _findService(p_hService))) && - (pService->setName(p_pcInstanceName)) && - ((pService->m_ProbeInformation.m_ProbingStatus = ProbingStatus_ReadyToStart))); - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] setServiceName: FAILED for '%s'!\n"), (p_pcInstanceName ?: "-")); - }); - return bResult; -} + bool MDNSResponder::setServiceName(const MDNSResponder::hMDNSService p_hService, + const char* p_pcInstanceName) + { + stcMDNSService* pService = 0; + bool bResult = (((!p_pcInstanceName) || (MDNS_DOMAIN_LABEL_MAXLENGTH >= os_strlen(p_pcInstanceName))) && ((pService = _findService(p_hService))) && (pService->setName(p_pcInstanceName)) && ((pService->m_ProbeInformation.m_ProbingStatus = ProbingStatus_ReadyToStart))); + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] setServiceName: FAILED for '%s'!\n"), (p_pcInstanceName ?: "-")); + }); + return bResult; + } -/* + /* SERVICE TXT */ -/* + /* MDNSResponder::addServiceTxt Add a static service TXT item ('Key'='Value') to a service. */ -MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - const char* p_pcValue) -{ - hMDNSTxt hTxt = 0; - stcMDNSService* pService = _findService(p_hService); - if (pService) + MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSService p_hService, + const char* p_pcKey, + const char* p_pcValue) { - hTxt = (hMDNSTxt)_addServiceTxt(pService, p_pcKey, p_pcValue, false); + hMDNSTxt hTxt = 0; + stcMDNSService* pService = _findService(p_hService); + if (pService) + { + hTxt = (hMDNSTxt)_addServiceTxt(pService, p_pcKey, p_pcValue, false); + } + DEBUG_EX_ERR(if (!hTxt) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] addServiceTxt: FAILED for '%s=%s'!\n"), (p_pcKey ?: "-"), (p_pcValue ?: "-")); + }); + return hTxt; } - DEBUG_EX_ERR(if (!hTxt) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] addServiceTxt: FAILED for '%s=%s'!\n"), (p_pcKey ?: "-"), (p_pcValue ?: "-")); - }); - return hTxt; -} -/* + /* MDNSResponder::addServiceTxt (uint32_t) Formats: http://www.cplusplus.com/reference/cstdio/printf/ */ -MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - uint32_t p_u32Value) -{ - char acBuffer[32]; - *acBuffer = 0; - sprintf(acBuffer, "%u", p_u32Value); + MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSService p_hService, + const char* p_pcKey, + uint32_t p_u32Value) + { + char acBuffer[32]; + *acBuffer = 0; + sprintf(acBuffer, "%u", p_u32Value); - return addServiceTxt(p_hService, p_pcKey, acBuffer); -} + return addServiceTxt(p_hService, p_pcKey, acBuffer); + } -/* + /* MDNSResponder::addServiceTxt (uint16_t) */ -MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - uint16_t p_u16Value) -{ - char acBuffer[16]; - *acBuffer = 0; - sprintf(acBuffer, "%hu", p_u16Value); + MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSService p_hService, + const char* p_pcKey, + uint16_t p_u16Value) + { + char acBuffer[16]; + *acBuffer = 0; + sprintf(acBuffer, "%hu", p_u16Value); - return addServiceTxt(p_hService, p_pcKey, acBuffer); -} + return addServiceTxt(p_hService, p_pcKey, acBuffer); + } -/* + /* MDNSResponder::addServiceTxt (uint8_t) */ -MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - uint8_t p_u8Value) -{ - char acBuffer[8]; - *acBuffer = 0; - sprintf(acBuffer, "%hhu", p_u8Value); + MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSService p_hService, + const char* p_pcKey, + uint8_t p_u8Value) + { + char acBuffer[8]; + *acBuffer = 0; + sprintf(acBuffer, "%hhu", p_u8Value); - return addServiceTxt(p_hService, p_pcKey, acBuffer); -} + return addServiceTxt(p_hService, p_pcKey, acBuffer); + } -/* + /* MDNSResponder::addServiceTxt (int32_t) */ -MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - int32_t p_i32Value) -{ - char acBuffer[32]; - *acBuffer = 0; - sprintf(acBuffer, "%i", p_i32Value); + MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSService p_hService, + const char* p_pcKey, + int32_t p_i32Value) + { + char acBuffer[32]; + *acBuffer = 0; + sprintf(acBuffer, "%i", p_i32Value); - return addServiceTxt(p_hService, p_pcKey, acBuffer); -} + return addServiceTxt(p_hService, p_pcKey, acBuffer); + } -/* + /* MDNSResponder::addServiceTxt (int16_t) */ -MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - int16_t p_i16Value) -{ - char acBuffer[16]; - *acBuffer = 0; - sprintf(acBuffer, "%hi", p_i16Value); + MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSService p_hService, + const char* p_pcKey, + int16_t p_i16Value) + { + char acBuffer[16]; + *acBuffer = 0; + sprintf(acBuffer, "%hi", p_i16Value); - return addServiceTxt(p_hService, p_pcKey, acBuffer); -} + return addServiceTxt(p_hService, p_pcKey, acBuffer); + } -/* + /* MDNSResponder::addServiceTxt (int8_t) */ -MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - int8_t p_i8Value) -{ - char acBuffer[8]; - *acBuffer = 0; - sprintf(acBuffer, "%hhi", p_i8Value); + MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSService p_hService, + const char* p_pcKey, + int8_t p_i8Value) + { + char acBuffer[8]; + *acBuffer = 0; + sprintf(acBuffer, "%hhi", p_i8Value); - return addServiceTxt(p_hService, p_pcKey, acBuffer); -} + return addServiceTxt(p_hService, p_pcKey, acBuffer); + } -/* + /* MDNSResponder::removeServiceTxt Remove a static service TXT item from a service. */ -bool MDNSResponder::removeServiceTxt(const MDNSResponder::hMDNSService p_hService, - const MDNSResponder::hMDNSTxt p_hTxt) -{ - bool bResult = false; - - stcMDNSService* pService = _findService(p_hService); - if (pService) + bool MDNSResponder::removeServiceTxt(const MDNSResponder::hMDNSService p_hService, + const MDNSResponder::hMDNSTxt p_hTxt) { - stcMDNSServiceTxt* pTxt = _findServiceTxt(pService, p_hTxt); - if (pTxt) + bool bResult = false; + + stcMDNSService* pService = _findService(p_hService); + if (pService) { - bResult = _releaseServiceTxt(pService, pTxt); + stcMDNSServiceTxt* pTxt = _findServiceTxt(pService, p_hTxt); + if (pTxt) + { + bResult = _releaseServiceTxt(pService, pTxt); + } } + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] removeServiceTxt: FAILED!\n")); + }); + return bResult; } - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] removeServiceTxt: FAILED!\n")); - }); - return bResult; -} -/* + /* MDNSResponder::removeServiceTxt */ -bool MDNSResponder::removeServiceTxt(const MDNSResponder::hMDNSService p_hService, - const char* p_pcKey) -{ - bool bResult = false; - - stcMDNSService* pService = _findService(p_hService); - if (pService) + bool MDNSResponder::removeServiceTxt(const MDNSResponder::hMDNSService p_hService, + const char* p_pcKey) { - stcMDNSServiceTxt* pTxt = _findServiceTxt(pService, p_pcKey); - if (pTxt) + bool bResult = false; + + stcMDNSService* pService = _findService(p_hService); + if (pService) { - bResult = _releaseServiceTxt(pService, pTxt); + stcMDNSServiceTxt* pTxt = _findServiceTxt(pService, p_pcKey); + if (pTxt) + { + bResult = _releaseServiceTxt(pService, pTxt); + } } + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] removeServiceTxt: FAILED for '%s'!\n"), (p_pcKey ?: "-")); + }); + return bResult; } - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] removeServiceTxt: FAILED for '%s'!\n"), (p_pcKey ?: "-")); - }); - return bResult; -} -/* + /* MDNSResponder::removeServiceTxt */ -bool MDNSResponder::removeServiceTxt(const char* p_pcName, - const char* p_pcService, - const char* p_pcProtocol, - const char* p_pcKey) -{ - bool bResult = false; - - stcMDNSService* pService = _findService((p_pcName ?: m_pcHostname), p_pcService, p_pcProtocol); - if (pService) + bool MDNSResponder::removeServiceTxt(const char* p_pcName, + const char* p_pcService, + const char* p_pcProtocol, + const char* p_pcKey) { - stcMDNSServiceTxt* pTxt = _findServiceTxt(pService, p_pcKey); - if (pTxt) + bool bResult = false; + + stcMDNSService* pService = _findService((p_pcName ?: m_pcHostname), p_pcService, p_pcProtocol); + if (pService) { - bResult = _releaseServiceTxt(pService, pTxt); + stcMDNSServiceTxt* pTxt = _findServiceTxt(pService, p_pcKey); + if (pTxt) + { + bResult = _releaseServiceTxt(pService, pTxt); + } } + return bResult; } - return bResult; -} -/* + /* MDNSResponder::addServiceTxt (LEGACY) */ -bool MDNSResponder::addServiceTxt(const char* p_pcService, - const char* p_pcProtocol, - const char* p_pcKey, - const char* p_pcValue) -{ - return (0 != _addServiceTxt(_findService(m_pcHostname, p_pcService, p_pcProtocol), p_pcKey, p_pcValue, false)); -} + bool MDNSResponder::addServiceTxt(const char* p_pcService, + const char* p_pcProtocol, + const char* p_pcKey, + const char* p_pcValue) + { + return (0 != _addServiceTxt(_findService(m_pcHostname, p_pcService, p_pcProtocol), p_pcKey, p_pcValue, false)); + } -/* + /* MDNSResponder::addServiceTxt (LEGACY) */ -bool MDNSResponder::addServiceTxt(const String& p_strService, - const String& p_strProtocol, - const String& p_strKey, - const String& p_strValue) -{ - return (0 != _addServiceTxt(_findService(m_pcHostname, p_strService.c_str(), p_strProtocol.c_str()), p_strKey.c_str(), p_strValue.c_str(), false)); -} + bool MDNSResponder::addServiceTxt(const String& p_strService, + const String& p_strProtocol, + const String& p_strKey, + const String& p_strValue) + { + return (0 != _addServiceTxt(_findService(m_pcHostname, p_strService.c_str(), p_strProtocol.c_str()), p_strKey.c_str(), p_strValue.c_str(), false)); + } -/* + /* MDNSResponder::setDynamicServiceTxtCallback (global) Set a global callback for dynamic service TXT items. The callback is called, whenever service TXT items are needed. */ -bool MDNSResponder::setDynamicServiceTxtCallback(MDNSResponder::MDNSDynamicServiceTxtCallbackFunc p_fnCallback) -{ - m_fnServiceTxtCallback = p_fnCallback; + bool MDNSResponder::setDynamicServiceTxtCallback(MDNSResponder::MDNSDynamicServiceTxtCallbackFunc p_fnCallback) + { + m_fnServiceTxtCallback = p_fnCallback; - return true; -} + return true; + } -/* + /* MDNSResponder::setDynamicServiceTxtCallback (service specific) Set a service specific callback for dynamic service TXT items. The callback is called, whenever service TXT items are needed for the given service. */ -bool MDNSResponder::setDynamicServiceTxtCallback(MDNSResponder::hMDNSService p_hService, - MDNSResponder::MDNSDynamicServiceTxtCallbackFunc p_fnCallback) -{ - bool bResult = false; - - stcMDNSService* pService = _findService(p_hService); - if (pService) + bool MDNSResponder::setDynamicServiceTxtCallback(MDNSResponder::hMDNSService p_hService, + MDNSResponder::MDNSDynamicServiceTxtCallbackFunc p_fnCallback) { - pService->m_fnTxtCallback = p_fnCallback; + bool bResult = false; + + stcMDNSService* pService = _findService(p_hService); + if (pService) + { + pService->m_fnTxtCallback = p_fnCallback; - bResult = true; + bResult = true; + } + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] setDynamicServiceTxtCallback: FAILED!\n")); + }); + return bResult; } - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] setDynamicServiceTxtCallback: FAILED!\n")); - }); - return bResult; -} -/* + /* MDNSResponder::addDynamicServiceTxt */ -MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - const char* p_pcValue) -{ - //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] addDynamicServiceTxt (%s=%s)\n"), p_pcKey, p_pcValue);); + MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, + const char* p_pcKey, + const char* p_pcValue) + { + //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] addDynamicServiceTxt (%s=%s)\n"), p_pcKey, p_pcValue);); - hMDNSTxt hTxt = 0; + hMDNSTxt hTxt = 0; - stcMDNSService* pService = _findService(p_hService); - if (pService) - { - hTxt = _addServiceTxt(pService, p_pcKey, p_pcValue, true); + stcMDNSService* pService = _findService(p_hService); + if (pService) + { + hTxt = _addServiceTxt(pService, p_pcKey, p_pcValue, true); + } + DEBUG_EX_ERR(if (!hTxt) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] addDynamicServiceTxt: FAILED for '%s=%s'!\n"), (p_pcKey ?: "-"), (p_pcValue ?: "-")); + }); + return hTxt; } - DEBUG_EX_ERR(if (!hTxt) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] addDynamicServiceTxt: FAILED for '%s=%s'!\n"), (p_pcKey ?: "-"), (p_pcValue ?: "-")); - }); - return hTxt; -} -/* + /* MDNSResponder::addDynamicServiceTxt (uint32_t) */ -MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - uint32_t p_u32Value) -{ - char acBuffer[32]; - *acBuffer = 0; - sprintf(acBuffer, "%u", p_u32Value); + MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, + const char* p_pcKey, + uint32_t p_u32Value) + { + char acBuffer[32]; + *acBuffer = 0; + sprintf(acBuffer, "%u", p_u32Value); - return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); -} + return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); + } -/* + /* MDNSResponder::addDynamicServiceTxt (uint16_t) */ -MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - uint16_t p_u16Value) -{ - char acBuffer[16]; - *acBuffer = 0; - sprintf(acBuffer, "%hu", p_u16Value); + MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, + const char* p_pcKey, + uint16_t p_u16Value) + { + char acBuffer[16]; + *acBuffer = 0; + sprintf(acBuffer, "%hu", p_u16Value); - return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); -} + return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); + } -/* + /* MDNSResponder::addDynamicServiceTxt (uint8_t) */ -MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - uint8_t p_u8Value) -{ - char acBuffer[8]; - *acBuffer = 0; - sprintf(acBuffer, "%hhu", p_u8Value); + MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, + const char* p_pcKey, + uint8_t p_u8Value) + { + char acBuffer[8]; + *acBuffer = 0; + sprintf(acBuffer, "%hhu", p_u8Value); - return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); -} + return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); + } -/* + /* MDNSResponder::addDynamicServiceTxt (int32_t) */ -MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - int32_t p_i32Value) -{ - char acBuffer[32]; - *acBuffer = 0; - sprintf(acBuffer, "%i", p_i32Value); + MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, + const char* p_pcKey, + int32_t p_i32Value) + { + char acBuffer[32]; + *acBuffer = 0; + sprintf(acBuffer, "%i", p_i32Value); - return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); -} + return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); + } -/* + /* MDNSResponder::addDynamicServiceTxt (int16_t) */ -MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - int16_t p_i16Value) -{ - char acBuffer[16]; - *acBuffer = 0; - sprintf(acBuffer, "%hi", p_i16Value); + MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, + const char* p_pcKey, + int16_t p_i16Value) + { + char acBuffer[16]; + *acBuffer = 0; + sprintf(acBuffer, "%hi", p_i16Value); - return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); -} + return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); + } -/* + /* MDNSResponder::addDynamicServiceTxt (int8_t) */ -MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - int8_t p_i8Value) -{ - char acBuffer[8]; - *acBuffer = 0; - sprintf(acBuffer, "%hhi", p_i8Value); + MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, + const char* p_pcKey, + int8_t p_i8Value) + { + char acBuffer[8]; + *acBuffer = 0; + sprintf(acBuffer, "%hhi", p_i8Value); - return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); -} + return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); + } -/** + /** STATIC SERVICE QUERY (LEGACY) */ -/* + /* MDNSResponder::queryService Perform a (blocking) static service query. @@ -664,160 +655,151 @@ MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNS - answerPort (or 'port') */ -uint32_t MDNSResponder::queryService(const char* p_pcService, - const char* p_pcProtocol, - const uint16_t p_u16Timeout /*= MDNS_QUERYSERVICES_WAIT_TIME*/) -{ - if (0 == m_pUDPContext) + uint32_t MDNSResponder::queryService(const char* p_pcService, + const char* p_pcProtocol, + const uint16_t p_u16Timeout /*= MDNS_QUERYSERVICES_WAIT_TIME*/) { - // safeguard against misuse - return 0; - } - - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] queryService '%s.%s'\n"), p_pcService, p_pcProtocol);); + if (0 == m_pUDPContext) + { + // safeguard against misuse + return 0; + } - uint32_t u32Result = 0; + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] queryService '%s.%s'\n"), p_pcService, p_pcProtocol);); - stcMDNSServiceQuery* pServiceQuery = 0; - if ((p_pcService) && - (os_strlen(p_pcService)) && - (p_pcProtocol) && - (os_strlen(p_pcProtocol)) && - (p_u16Timeout) && - (_removeLegacyServiceQuery()) && - ((pServiceQuery = _allocServiceQuery())) && - (_buildDomainForService(p_pcService, p_pcProtocol, pServiceQuery->m_ServiceTypeDomain))) - { - pServiceQuery->m_bLegacyQuery = true; + uint32_t u32Result = 0; - if (_sendMDNSServiceQuery(*pServiceQuery)) + stcMDNSServiceQuery* pServiceQuery = 0; + if ((p_pcService) && (os_strlen(p_pcService)) && (p_pcProtocol) && (os_strlen(p_pcProtocol)) && (p_u16Timeout) && (_removeLegacyServiceQuery()) && ((pServiceQuery = _allocServiceQuery())) && (_buildDomainForService(p_pcService, p_pcProtocol, pServiceQuery->m_ServiceTypeDomain))) { - // Wait for answers to arrive - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] queryService: Waiting %u ms for answers...\n"), p_u16Timeout);); - delay(p_u16Timeout); + pServiceQuery->m_bLegacyQuery = true; + + if (_sendMDNSServiceQuery(*pServiceQuery)) + { + // Wait for answers to arrive + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] queryService: Waiting %u ms for answers...\n"), p_u16Timeout);); + delay(p_u16Timeout); - // All answers should have arrived by now -> stop adding new answers - pServiceQuery->m_bAwaitingAnswers = false; - u32Result = pServiceQuery->answerCount(); + // All answers should have arrived by now -> stop adding new answers + pServiceQuery->m_bAwaitingAnswers = false; + u32Result = pServiceQuery->answerCount(); + } + else // FAILED to send query + { + _removeServiceQuery(pServiceQuery); + } } - else // FAILED to send query + else { - _removeServiceQuery(pServiceQuery); + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] queryService: INVALID input data!\n"));); } + return u32Result; } - else - { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] queryService: INVALID input data!\n"));); - } - return u32Result; -} -/* + /* MDNSResponder::removeQuery Remove the last static service query (and all answers). */ -bool MDNSResponder::removeQuery(void) -{ - return _removeLegacyServiceQuery(); -} + bool MDNSResponder::removeQuery(void) + { + return _removeLegacyServiceQuery(); + } -/* + /* MDNSResponder::queryService (LEGACY) */ -uint32_t MDNSResponder::queryService(const String& p_strService, - const String& p_strProtocol) -{ - return queryService(p_strService.c_str(), p_strProtocol.c_str()); -} + uint32_t MDNSResponder::queryService(const String& p_strService, + const String& p_strProtocol) + { + return queryService(p_strService.c_str(), p_strProtocol.c_str()); + } -/* + /* MDNSResponder::answerHostname */ -const char* MDNSResponder::answerHostname(const uint32_t p_u32AnswerIndex) -{ - stcMDNSServiceQuery* pServiceQuery = _findLegacyServiceQuery(); - stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - - if ((pSQAnswer) && - (pSQAnswer->m_HostDomain.m_u16NameLength) && - (!pSQAnswer->m_pcHostDomain)) + const char* MDNSResponder::answerHostname(const uint32_t p_u32AnswerIndex) { - char* pcHostDomain = pSQAnswer->allocHostDomain(pSQAnswer->m_HostDomain.c_strLength()); - if (pcHostDomain) + stcMDNSServiceQuery* pServiceQuery = _findLegacyServiceQuery(); + stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); + + if ((pSQAnswer) && (pSQAnswer->m_HostDomain.m_u16NameLength) && (!pSQAnswer->m_pcHostDomain)) { - pSQAnswer->m_HostDomain.c_str(pcHostDomain); + char* pcHostDomain = pSQAnswer->allocHostDomain(pSQAnswer->m_HostDomain.c_strLength()); + if (pcHostDomain) + { + pSQAnswer->m_HostDomain.c_str(pcHostDomain); + } } + return (pSQAnswer ? pSQAnswer->m_pcHostDomain : 0); } - return (pSQAnswer ? pSQAnswer->m_pcHostDomain : 0); -} #ifdef MDNS_IP4_SUPPORT -/* + /* MDNSResponder::answerIP */ -IPAddress MDNSResponder::answerIP(const uint32_t p_u32AnswerIndex) -{ - const stcMDNSServiceQuery* pServiceQuery = _findLegacyServiceQuery(); - const stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - const stcMDNSServiceQuery::stcAnswer::stcIP4Address* pIP4Address = (((pSQAnswer) && (pSQAnswer->m_pIP4Addresses)) ? pSQAnswer->IP4AddressAtIndex(0) : 0); - return (pIP4Address ? pIP4Address->m_IPAddress : IPAddress()); -} + IPAddress MDNSResponder::answerIP(const uint32_t p_u32AnswerIndex) + { + const stcMDNSServiceQuery* pServiceQuery = _findLegacyServiceQuery(); + const stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); + const stcMDNSServiceQuery::stcAnswer::stcIP4Address* pIP4Address = (((pSQAnswer) && (pSQAnswer->m_pIP4Addresses)) ? pSQAnswer->IP4AddressAtIndex(0) : 0); + return (pIP4Address ? pIP4Address->m_IPAddress : IPAddress()); + } #endif #ifdef MDNS_IP6_SUPPORT -/* + /* MDNSResponder::answerIP6 */ -IPAddress MDNSResponder::answerIP6(const uint32_t p_u32AnswerIndex) -{ - const stcMDNSServiceQuery* pServiceQuery = _findLegacyServiceQuery(); - const stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - const stcMDNSServiceQuery::stcAnswer::stcIP6Address* pIP6Address = (((pSQAnswer) && (pSQAnswer->m_pIP6Addresses)) ? pSQAnswer->IP6AddressAtIndex(0) : 0); - return (pIP6Address ? pIP6Address->m_IPAddress : IP6Address()); -} + IPAddress MDNSResponder::answerIP6(const uint32_t p_u32AnswerIndex) + { + const stcMDNSServiceQuery* pServiceQuery = _findLegacyServiceQuery(); + const stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); + const stcMDNSServiceQuery::stcAnswer::stcIP6Address* pIP6Address = (((pSQAnswer) && (pSQAnswer->m_pIP6Addresses)) ? pSQAnswer->IP6AddressAtIndex(0) : 0); + return (pIP6Address ? pIP6Address->m_IPAddress : IP6Address()); + } #endif -/* + /* MDNSResponder::answerPort */ -uint16_t MDNSResponder::answerPort(const uint32_t p_u32AnswerIndex) -{ - const stcMDNSServiceQuery* pServiceQuery = _findLegacyServiceQuery(); - const stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - return (pSQAnswer ? pSQAnswer->m_u16Port : 0); -} + uint16_t MDNSResponder::answerPort(const uint32_t p_u32AnswerIndex) + { + const stcMDNSServiceQuery* pServiceQuery = _findLegacyServiceQuery(); + const stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); + return (pSQAnswer ? pSQAnswer->m_u16Port : 0); + } -/* + /* MDNSResponder::hostname (LEGACY) */ -String MDNSResponder::hostname(const uint32_t p_u32AnswerIndex) -{ - return String(answerHostname(p_u32AnswerIndex)); -} + String MDNSResponder::hostname(const uint32_t p_u32AnswerIndex) + { + return String(answerHostname(p_u32AnswerIndex)); + } -/* + /* MDNSResponder::IP (LEGACY) */ -IPAddress MDNSResponder::IP(const uint32_t p_u32AnswerIndex) -{ - return answerIP(p_u32AnswerIndex); -} + IPAddress MDNSResponder::IP(const uint32_t p_u32AnswerIndex) + { + return answerIP(p_u32AnswerIndex); + } -/* + /* MDNSResponder::port (LEGACY) */ -uint16_t MDNSResponder::port(const uint32_t p_u32AnswerIndex) -{ - return answerPort(p_u32AnswerIndex); -} + uint16_t MDNSResponder::port(const uint32_t p_u32AnswerIndex) + { + return answerPort(p_u32AnswerIndex); + } -/** + /** DYNAMIC SERVICE QUERY */ -/* + /* MDNSResponder::installServiceQuery Add a dynamic service query and a corresponding callback to the MDNS responder. @@ -830,287 +812,269 @@ uint16_t MDNSResponder::port(const uint32_t p_u32AnswerIndex) - answerTxts */ -MDNSResponder::hMDNSServiceQuery MDNSResponder::installServiceQuery(const char* p_pcService, - const char* p_pcProtocol, - MDNSResponder::MDNSServiceQueryCallbackFunc p_fnCallback) -{ - hMDNSServiceQuery hResult = 0; - - stcMDNSServiceQuery* pServiceQuery = 0; - if ((p_pcService) && - (os_strlen(p_pcService)) && - (p_pcProtocol) && - (os_strlen(p_pcProtocol)) && - (p_fnCallback) && - ((pServiceQuery = _allocServiceQuery())) && - (_buildDomainForService(p_pcService, p_pcProtocol, pServiceQuery->m_ServiceTypeDomain))) + MDNSResponder::hMDNSServiceQuery MDNSResponder::installServiceQuery(const char* p_pcService, + const char* p_pcProtocol, + MDNSResponder::MDNSServiceQueryCallbackFunc p_fnCallback) { - pServiceQuery->m_fnCallback = p_fnCallback; - pServiceQuery->m_bLegacyQuery = false; + hMDNSServiceQuery hResult = 0; - if (_sendMDNSServiceQuery(*pServiceQuery)) + stcMDNSServiceQuery* pServiceQuery = 0; + if ((p_pcService) && (os_strlen(p_pcService)) && (p_pcProtocol) && (os_strlen(p_pcProtocol)) && (p_fnCallback) && ((pServiceQuery = _allocServiceQuery())) && (_buildDomainForService(p_pcService, p_pcProtocol, pServiceQuery->m_ServiceTypeDomain))) { - pServiceQuery->m_u8SentCount = 1; - pServiceQuery->m_ResendTimeout.reset(MDNS_DYNAMIC_QUERY_RESEND_DELAY); + pServiceQuery->m_fnCallback = p_fnCallback; + pServiceQuery->m_bLegacyQuery = false; - hResult = (hMDNSServiceQuery)pServiceQuery; - } - else - { - _removeServiceQuery(pServiceQuery); + if (_sendMDNSServiceQuery(*pServiceQuery)) + { + pServiceQuery->m_u8SentCount = 1; + pServiceQuery->m_ResendTimeout.reset(MDNS_DYNAMIC_QUERY_RESEND_DELAY); + + hResult = (hMDNSServiceQuery)pServiceQuery; + } + else + { + _removeServiceQuery(pServiceQuery); + } } + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] installServiceQuery: %s for '%s.%s'!\n\n"), (hResult ? "Succeeded" : "FAILED"), (p_pcService ?: "-"), (p_pcProtocol ?: "-"));); + DEBUG_EX_ERR(if (!hResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] installServiceQuery: FAILED for '%s.%s'!\n\n"), (p_pcService ?: "-"), (p_pcProtocol ?: "-")); + }); + return hResult; } - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] installServiceQuery: %s for '%s.%s'!\n\n"), (hResult ? "Succeeded" : "FAILED"), (p_pcService ?: "-"), (p_pcProtocol ?: "-"));); - DEBUG_EX_ERR(if (!hResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] installServiceQuery: FAILED for '%s.%s'!\n\n"), (p_pcService ?: "-"), (p_pcProtocol ?: "-")); - }); - return hResult; -} -/* + /* MDNSResponder::removeServiceQuery Remove a dynamic service query (and all collected answers) from the MDNS responder */ -bool MDNSResponder::removeServiceQuery(MDNSResponder::hMDNSServiceQuery p_hServiceQuery) -{ - stcMDNSServiceQuery* pServiceQuery = 0; - bool bResult = (((pServiceQuery = _findServiceQuery(p_hServiceQuery))) && - (_removeServiceQuery(pServiceQuery))); - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] removeServiceQuery: FAILED!\n")); - }); - return bResult; -} + bool MDNSResponder::removeServiceQuery(MDNSResponder::hMDNSServiceQuery p_hServiceQuery) + { + stcMDNSServiceQuery* pServiceQuery = 0; + bool bResult = (((pServiceQuery = _findServiceQuery(p_hServiceQuery))) && (_removeServiceQuery(pServiceQuery))); + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] removeServiceQuery: FAILED!\n")); + }); + return bResult; + } -/* + /* MDNSResponder::answerCount */ -uint32_t MDNSResponder::answerCount(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery) -{ - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); - return (pServiceQuery ? pServiceQuery->answerCount() : 0); -} + uint32_t MDNSResponder::answerCount(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery) + { + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + return (pServiceQuery ? pServiceQuery->answerCount() : 0); + } -std::vector MDNSResponder::answerInfo(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery) -{ - std::vector tempVector; - for (uint32_t i = 0; i < answerCount(p_hServiceQuery); i++) + std::vector MDNSResponder::answerInfo(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery) { - tempVector.emplace_back(*this, p_hServiceQuery, i); + std::vector tempVector; + for (uint32_t i = 0; i < answerCount(p_hServiceQuery); i++) + { + tempVector.emplace_back(*this, p_hServiceQuery, i); + } + return tempVector; } - return tempVector; -} -/* + /* MDNSResponder::answerServiceDomain Returns the domain for the given service. If not already existing, the string is allocated, filled and attached to the answer. */ -const char* MDNSResponder::answerServiceDomain(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) -{ - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); - stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - // Fill m_pcServiceDomain (if not already done) - if ((pSQAnswer) && - (pSQAnswer->m_ServiceDomain.m_u16NameLength) && - (!pSQAnswer->m_pcServiceDomain)) - { - pSQAnswer->m_pcServiceDomain = pSQAnswer->allocServiceDomain(pSQAnswer->m_ServiceDomain.c_strLength()); - if (pSQAnswer->m_pcServiceDomain) + const char* MDNSResponder::answerServiceDomain(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex) + { + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); + // Fill m_pcServiceDomain (if not already done) + if ((pSQAnswer) && (pSQAnswer->m_ServiceDomain.m_u16NameLength) && (!pSQAnswer->m_pcServiceDomain)) { - pSQAnswer->m_ServiceDomain.c_str(pSQAnswer->m_pcServiceDomain); + pSQAnswer->m_pcServiceDomain = pSQAnswer->allocServiceDomain(pSQAnswer->m_ServiceDomain.c_strLength()); + if (pSQAnswer->m_pcServiceDomain) + { + pSQAnswer->m_ServiceDomain.c_str(pSQAnswer->m_pcServiceDomain); + } } + return (pSQAnswer ? pSQAnswer->m_pcServiceDomain : 0); } - return (pSQAnswer ? pSQAnswer->m_pcServiceDomain : 0); -} -/* + /* MDNSResponder::hasAnswerHostDomain */ -bool MDNSResponder::hasAnswerHostDomain(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) -{ - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); - stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - return ((pSQAnswer) && - (pSQAnswer->m_u32ContentFlags & ServiceQueryAnswerType_HostDomainAndPort)); -} + bool MDNSResponder::hasAnswerHostDomain(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex) + { + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); + return ((pSQAnswer) && (pSQAnswer->m_u32ContentFlags & ServiceQueryAnswerType_HostDomainAndPort)); + } -/* + /* MDNSResponder::answerHostDomain Returns the host domain for the given service. If not already existing, the string is allocated, filled and attached to the answer. */ -const char* MDNSResponder::answerHostDomain(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) -{ - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); - stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - // Fill m_pcHostDomain (if not already done) - if ((pSQAnswer) && - (pSQAnswer->m_HostDomain.m_u16NameLength) && - (!pSQAnswer->m_pcHostDomain)) - { - pSQAnswer->m_pcHostDomain = pSQAnswer->allocHostDomain(pSQAnswer->m_HostDomain.c_strLength()); - if (pSQAnswer->m_pcHostDomain) + const char* MDNSResponder::answerHostDomain(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex) + { + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); + // Fill m_pcHostDomain (if not already done) + if ((pSQAnswer) && (pSQAnswer->m_HostDomain.m_u16NameLength) && (!pSQAnswer->m_pcHostDomain)) { - pSQAnswer->m_HostDomain.c_str(pSQAnswer->m_pcHostDomain); + pSQAnswer->m_pcHostDomain = pSQAnswer->allocHostDomain(pSQAnswer->m_HostDomain.c_strLength()); + if (pSQAnswer->m_pcHostDomain) + { + pSQAnswer->m_HostDomain.c_str(pSQAnswer->m_pcHostDomain); + } } + return (pSQAnswer ? pSQAnswer->m_pcHostDomain : 0); } - return (pSQAnswer ? pSQAnswer->m_pcHostDomain : 0); -} #ifdef MDNS_IP4_SUPPORT -/* + /* MDNSResponder::hasAnswerIP4Address */ -bool MDNSResponder::hasAnswerIP4Address(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) -{ - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); - stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - return ((pSQAnswer) && - (pSQAnswer->m_u32ContentFlags & ServiceQueryAnswerType_IP4Address)); -} + bool MDNSResponder::hasAnswerIP4Address(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex) + { + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); + return ((pSQAnswer) && (pSQAnswer->m_u32ContentFlags & ServiceQueryAnswerType_IP4Address)); + } -/* + /* MDNSResponder::answerIP4AddressCount */ -uint32_t MDNSResponder::answerIP4AddressCount(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) -{ - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); - stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - return (pSQAnswer ? pSQAnswer->IP4AddressCount() : 0); -} + uint32_t MDNSResponder::answerIP4AddressCount(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex) + { + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); + return (pSQAnswer ? pSQAnswer->IP4AddressCount() : 0); + } -/* + /* MDNSResponder::answerIP4Address */ -IPAddress MDNSResponder::answerIP4Address(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex, - const uint32_t p_u32AddressIndex) -{ - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); - stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - stcMDNSServiceQuery::stcAnswer::stcIP4Address* pIP4Address = (pSQAnswer ? pSQAnswer->IP4AddressAtIndex(p_u32AddressIndex) : 0); - return (pIP4Address ? pIP4Address->m_IPAddress : IPAddress()); -} + IPAddress MDNSResponder::answerIP4Address(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex, + const uint32_t p_u32AddressIndex) + { + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); + stcMDNSServiceQuery::stcAnswer::stcIP4Address* pIP4Address = (pSQAnswer ? pSQAnswer->IP4AddressAtIndex(p_u32AddressIndex) : 0); + return (pIP4Address ? pIP4Address->m_IPAddress : IPAddress()); + } #endif #ifdef MDNS_IP6_SUPPORT -/* + /* MDNSResponder::hasAnswerIP6Address */ -bool MDNSResponder::hasAnswerIP6Address(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) -{ - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); - stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - return ((pSQAnswer) && - (pSQAnswer->m_u32ContentFlags & ServiceQueryAnswerType_HostIP6Address)); -} + bool MDNSResponder::hasAnswerIP6Address(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex) + { + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); + return ((pSQAnswer) && (pSQAnswer->m_u32ContentFlags & ServiceQueryAnswerType_HostIP6Address)); + } -/* + /* MDNSResponder::answerIP6AddressCount */ -uint32_t MDNSResponder::answerIP6AddressCount(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) -{ - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); - stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - return (pSQAnswer ? pSQAnswer->IP6AddressCount() : 0); -} + uint32_t MDNSResponder::answerIP6AddressCount(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex) + { + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); + return (pSQAnswer ? pSQAnswer->IP6AddressCount() : 0); + } -/* + /* MDNSResponder::answerIP6Address */ -IPAddress MDNSResponder::answerIP6Address(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex, - const uint32_t p_u32AddressIndex) -{ - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); - stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - stcMDNSServiceQuery::stcAnswer::stcIP6Address* pIP6Address = (pSQAnswer ? pSQAnswer->IP6AddressAtIndex(p_u32AddressIndex) : 0); - return (pIP6Address ? pIP6Address->m_IPAddress : IPAddress()); -} + IPAddress MDNSResponder::answerIP6Address(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex, + const uint32_t p_u32AddressIndex) + { + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); + stcMDNSServiceQuery::stcAnswer::stcIP6Address* pIP6Address = (pSQAnswer ? pSQAnswer->IP6AddressAtIndex(p_u32AddressIndex) : 0); + return (pIP6Address ? pIP6Address->m_IPAddress : IPAddress()); + } #endif -/* + /* MDNSResponder::hasAnswerPort */ -bool MDNSResponder::hasAnswerPort(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) -{ - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); - stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - return ((pSQAnswer) && - (pSQAnswer->m_u32ContentFlags & ServiceQueryAnswerType_HostDomainAndPort)); -} + bool MDNSResponder::hasAnswerPort(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex) + { + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); + return ((pSQAnswer) && (pSQAnswer->m_u32ContentFlags & ServiceQueryAnswerType_HostDomainAndPort)); + } -/* + /* MDNSResponder::answerPort */ -uint16_t MDNSResponder::answerPort(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) -{ - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); - stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - return (pSQAnswer ? pSQAnswer->m_u16Port : 0); -} + uint16_t MDNSResponder::answerPort(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex) + { + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); + return (pSQAnswer ? pSQAnswer->m_u16Port : 0); + } -/* + /* MDNSResponder::hasAnswerTxts */ -bool MDNSResponder::hasAnswerTxts(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) -{ - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); - stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - return ((pSQAnswer) && - (pSQAnswer->m_u32ContentFlags & ServiceQueryAnswerType_Txts)); -} + bool MDNSResponder::hasAnswerTxts(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex) + { + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); + return ((pSQAnswer) && (pSQAnswer->m_u32ContentFlags & ServiceQueryAnswerType_Txts)); + } -/* + /* MDNSResponder::answerTxts Returns all TXT items for the given service as a ';'-separated string. If not already existing; the string is allocated, filled and attached to the answer. */ -const char* MDNSResponder::answerTxts(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) -{ - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); - stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - // Fill m_pcTxts (if not already done) - if ((pSQAnswer) && - (pSQAnswer->m_Txts.m_pTxts) && - (!pSQAnswer->m_pcTxts)) - { - pSQAnswer->m_pcTxts = pSQAnswer->allocTxts(pSQAnswer->m_Txts.c_strLength()); - if (pSQAnswer->m_pcTxts) + const char* MDNSResponder::answerTxts(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex) + { + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); + // Fill m_pcTxts (if not already done) + if ((pSQAnswer) && (pSQAnswer->m_Txts.m_pTxts) && (!pSQAnswer->m_pcTxts)) { - pSQAnswer->m_Txts.c_str(pSQAnswer->m_pcTxts); + pSQAnswer->m_pcTxts = pSQAnswer->allocTxts(pSQAnswer->m_Txts.c_strLength()); + if (pSQAnswer->m_pcTxts) + { + pSQAnswer->m_Txts.c_str(pSQAnswer->m_pcTxts); + } } + return (pSQAnswer ? pSQAnswer->m_pcTxts : 0); } - return (pSQAnswer ? pSQAnswer->m_pcTxts : 0); -} -/* + /* PROBING */ -/* + /* MDNSResponder::setProbeResultCallback Set a global callback for probe results. The callback is called, when probing @@ -1120,21 +1084,21 @@ const char* MDNSResponder::answerTxts(const MDNSResponder::hMDNSServiceQuery p_h When succeeded, the host or service domain will be announced by the MDNS responder. */ -bool MDNSResponder::setHostProbeResultCallback(MDNSResponder::MDNSHostProbeFn p_fnCallback) -{ - m_HostProbeInformation.m_fnHostProbeResultCallback = p_fnCallback; + bool MDNSResponder::setHostProbeResultCallback(MDNSResponder::MDNSHostProbeFn p_fnCallback) + { + m_HostProbeInformation.m_fnHostProbeResultCallback = p_fnCallback; - return true; -} + return true; + } -bool MDNSResponder::setHostProbeResultCallback(MDNSHostProbeFn1 pfn) -{ - using namespace std::placeholders; - return setHostProbeResultCallback([this, pfn](const char* p_pcDomainName, bool p_bProbeResult) - { pfn(*this, p_pcDomainName, p_bProbeResult); }); -} + bool MDNSResponder::setHostProbeResultCallback(MDNSHostProbeFn1 pfn) + { + using namespace std::placeholders; + return setHostProbeResultCallback([this, pfn](const char* p_pcDomainName, bool p_bProbeResult) + { pfn(*this, p_pcDomainName, p_bProbeResult); }); + } -/* + /* MDNSResponder::setServiceProbeResultCallback Set a service specific callback for probe results. The callback is called, when probing @@ -1143,176 +1107,171 @@ bool MDNSResponder::setHostProbeResultCallback(MDNSHostProbeFn1 pfn) When succeeded, the service domain will be announced by the MDNS responder. */ -bool MDNSResponder::setServiceProbeResultCallback(const MDNSResponder::hMDNSService p_hService, - MDNSResponder::MDNSServiceProbeFn p_fnCallback) -{ - bool bResult = false; - - stcMDNSService* pService = _findService(p_hService); - if (pService) + bool MDNSResponder::setServiceProbeResultCallback(const MDNSResponder::hMDNSService p_hService, + MDNSResponder::MDNSServiceProbeFn p_fnCallback) { - pService->m_ProbeInformation.m_fnServiceProbeResultCallback = p_fnCallback; + bool bResult = false; + + stcMDNSService* pService = _findService(p_hService); + if (pService) + { + pService->m_ProbeInformation.m_fnServiceProbeResultCallback = p_fnCallback; - bResult = true; + bResult = true; + } + return bResult; } - return bResult; -} -bool MDNSResponder::setServiceProbeResultCallback(const MDNSResponder::hMDNSService p_hService, - MDNSResponder::MDNSServiceProbeFn1 p_fnCallback) -{ - using namespace std::placeholders; - return setServiceProbeResultCallback(p_hService, [this, p_fnCallback](const char* p_pcServiceName, const hMDNSService p_hMDNSService, bool p_bProbeResult) - { p_fnCallback(*this, p_pcServiceName, p_hMDNSService, p_bProbeResult); }); -} + bool MDNSResponder::setServiceProbeResultCallback(const MDNSResponder::hMDNSService p_hService, + MDNSResponder::MDNSServiceProbeFn1 p_fnCallback) + { + using namespace std::placeholders; + return setServiceProbeResultCallback(p_hService, [this, p_fnCallback](const char* p_pcServiceName, const hMDNSService p_hMDNSService, bool p_bProbeResult) + { p_fnCallback(*this, p_pcServiceName, p_hMDNSService, p_bProbeResult); }); + } -/* + /* MISC */ -/* + /* MDNSResponder::notifyAPChange Should be called, whenever the AP for the MDNS responder changes. A bit of this is caught by the event callbacks installed in the constructor. */ -bool MDNSResponder::notifyAPChange(void) -{ - return _restart(); -} + bool MDNSResponder::notifyAPChange(void) + { + return _restart(); + } -/* + /* MDNSResponder::update Should be called in every 'loop'. */ -bool MDNSResponder::update(void) -{ - return _process(true); -} + bool MDNSResponder::update(void) + { + return _process(true); + } -/* + /* MDNSResponder::announce Should be called, if the 'configuration' changes. Mainly this will be changes in the TXT items... */ -bool MDNSResponder::announce(void) -{ - return (_announce(true, true)); -} + bool MDNSResponder::announce(void) + { + return (_announce(true, true)); + } -/* + /* MDNSResponder::enableArduino Enable the OTA update service. */ -MDNSResponder::hMDNSService MDNSResponder::enableArduino(uint16_t p_u16Port, - bool p_bAuthUpload /*= false*/) -{ - hMDNSService hService = addService(0, "arduino", "tcp", p_u16Port); - if (hService) + MDNSResponder::hMDNSService MDNSResponder::enableArduino(uint16_t p_u16Port, + bool p_bAuthUpload /*= false*/) { - if ((!addServiceTxt(hService, "tcp_check", "no")) || - (!addServiceTxt(hService, "ssh_upload", "no")) || - (!addServiceTxt(hService, "board", STRINGIZE_VALUE_OF(ARDUINO_BOARD))) || - (!addServiceTxt(hService, "auth_upload", (p_bAuthUpload) ? "yes" : "no"))) + hMDNSService hService = addService(0, "arduino", "tcp", p_u16Port); + if (hService) { - removeService(hService); - hService = 0; + if ((!addServiceTxt(hService, "tcp_check", "no")) || (!addServiceTxt(hService, "ssh_upload", "no")) || (!addServiceTxt(hService, "board", STRINGIZE_VALUE_OF(ARDUINO_BOARD))) || (!addServiceTxt(hService, "auth_upload", (p_bAuthUpload) ? "yes" : "no"))) + { + removeService(hService); + hService = 0; + } } + return hService; } - return hService; -} -/* + /* MULTICAST GROUPS */ -/* + /* MDNSResponder::_joinMulticastGroups */ -bool MDNSResponder::_joinMulticastGroups(void) -{ - bool bResult = false; - - // Join multicast group(s) - for (netif* pNetIf = netif_list; pNetIf; pNetIf = pNetIf->next) + bool MDNSResponder::_joinMulticastGroups(void) { - if (netif_is_up(pNetIf)) + bool bResult = false; + + // Join multicast group(s) + for (netif* pNetIf = netif_list; pNetIf; pNetIf = pNetIf->next) { -#ifdef MDNS_IP4_SUPPORT - ip_addr_t multicast_addr_V4 = DNS_MQUERY_IPV4_GROUP_INIT; - if (!(pNetIf->flags & NETIF_FLAG_IGMP)) + if (netif_is_up(pNetIf)) { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _createHost: Setting flag: flags & NETIF_FLAG_IGMP\n"));); - pNetIf->flags |= NETIF_FLAG_IGMP; - - if (ERR_OK != igmp_start(pNetIf)) +#ifdef MDNS_IP4_SUPPORT + ip_addr_t multicast_addr_V4 = DNS_MQUERY_IPV4_GROUP_INIT; + if (!(pNetIf->flags & NETIF_FLAG_IGMP)) { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _createHost: igmp_start FAILED!\n"));); + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _createHost: Setting flag: flags & NETIF_FLAG_IGMP\n"));); + pNetIf->flags |= NETIF_FLAG_IGMP; + + if (ERR_OK != igmp_start(pNetIf)) + { + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _createHost: igmp_start FAILED!\n"));); + } } - } - if ((ERR_OK == igmp_joingroup_netif(pNetIf, ip_2_ip4(&multicast_addr_V4)))) - { - bResult = true; - } - else - { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _createHost: igmp_joingroup_netif(" NETIFID_STR ": %s) FAILED!\n"), - NETIFID_VAL(pNetIf), IPAddress(multicast_addr_V4).toString().c_str());); - } + if ((ERR_OK == igmp_joingroup_netif(pNetIf, ip_2_ip4(&multicast_addr_V4)))) + { + bResult = true; + } + else + { + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _createHost: igmp_joingroup_netif(" NETIFID_STR ": %s) FAILED!\n"), + NETIFID_VAL(pNetIf), IPAddress(multicast_addr_V4).toString().c_str());); + } #endif #ifdef MDNS_IPV6_SUPPORT - ip_addr_t multicast_addr_V6 = DNS_MQUERY_IPV6_GROUP_INIT; - bResult = ((bResult) && - (ERR_OK == mld6_joingroup_netif(pNetIf, ip_2_ip6(&multicast_addr_V6)))); - DEBUG_EX_ERR_IF(!bResult, DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _createHost: mld6_joingroup_netif (" NETIFID_STR ") FAILED!\n"), - NETIFID_VAL(pNetIf))); + ip_addr_t multicast_addr_V6 = DNS_MQUERY_IPV6_GROUP_INIT; + bResult = ((bResult) && (ERR_OK == mld6_joingroup_netif(pNetIf, ip_2_ip6(&multicast_addr_V6)))); + DEBUG_EX_ERR_IF(!bResult, DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _createHost: mld6_joingroup_netif (" NETIFID_STR ") FAILED!\n"), NETIFID_VAL(pNetIf))); #endif + } } + return bResult; } - return bResult; -} -/* + /* clsLEAmDNS2_Host::_leaveMulticastGroups */ -bool MDNSResponder::_leaveMulticastGroups() -{ - bool bResult = false; - - for (netif* pNetIf = netif_list; pNetIf; pNetIf = pNetIf->next) + bool MDNSResponder::_leaveMulticastGroups() { - if (netif_is_up(pNetIf)) + bool bResult = false; + + for (netif* pNetIf = netif_list; pNetIf; pNetIf = pNetIf->next) { - bResult = true; + if (netif_is_up(pNetIf)) + { + bResult = true; - // Leave multicast group(s) + // Leave multicast group(s) #ifdef MDNS_IP4_SUPPORT - ip_addr_t multicast_addr_V4 = DNS_MQUERY_IPV4_GROUP_INIT; - if (ERR_OK != igmp_leavegroup_netif(pNetIf, ip_2_ip4(&multicast_addr_V4))) - { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("\n"));); - } + ip_addr_t multicast_addr_V4 = DNS_MQUERY_IPV4_GROUP_INIT; + if (ERR_OK != igmp_leavegroup_netif(pNetIf, ip_2_ip4(&multicast_addr_V4))) + { + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("\n"));); + } #endif #ifdef MDNS_IPV6_SUPPORT - ip_addr_t multicast_addr_V6 = DNS_MQUERY_IPV6_GROUP_INIT; - if (ERR_OK != mld6_leavegroup_netif(pNetIf, ip_2_ip6(&multicast_addr_V6) /*&(multicast_addr_V6.u_addr.ip6)*/)) - { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("\n"));); - } + ip_addr_t multicast_addr_V6 = DNS_MQUERY_IPV6_GROUP_INIT; + if (ERR_OK != mld6_leavegroup_netif(pNetIf, ip_2_ip6(&multicast_addr_V6) /*&(multicast_addr_V6.u_addr.ip6)*/)) + { + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("\n"));); + } #endif + } } + return bResult; } - return bResult; -} } //namespace MDNSImplementation diff --git a/libraries/ESP8266mDNS/src/LEAmDNS.h b/libraries/ESP8266mDNS/src/LEAmDNS.h index 48ceab3b09..24a561080f 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS.h +++ b/libraries/ESP8266mDNS/src/LEAmDNS.h @@ -166,1291 +166,1290 @@ namespace MDNSImplementation */ #define MDNS_UDPCONTEXT_TIMEOUT 50 -/** + /** MDNSResponder */ -class MDNSResponder -{ - public: - /* INTERFACE */ - - MDNSResponder(void); - virtual ~MDNSResponder(void); - - // Start the MDNS responder by setting the default hostname - // Later call MDNS::update() in every 'loop' to run the process loop - // (probing, announcing, responding, ...) - // if interfaceAddress is not specified, default interface is STA, or AP when STA is not set - bool begin(const char* p_pcHostname, const IPAddress& p_IPAddress = INADDR_ANY, uint32_t p_u32TTL = 120 /*ignored*/); - bool begin(const String& p_strHostname, const IPAddress& p_IPAddress = INADDR_ANY, uint32_t p_u32TTL = 120 /*ignored*/) - { - return begin(p_strHostname.c_str(), p_IPAddress, p_u32TTL); - } - bool _joinMulticastGroups(void); - bool _leaveMulticastGroups(void); - - // Finish MDNS processing - bool close(void); - // for esp32 compatibility - bool end(void); - // Change hostname (probing is restarted) - bool setHostname(const char* p_pcHostname); - // for compatibility... - bool setHostname(const String& p_strHostname); - - bool isRunning(void) + class MDNSResponder { - return (m_pUDPContext != 0); - } + public: + /* INTERFACE */ + + MDNSResponder(void); + virtual ~MDNSResponder(void); + + // Start the MDNS responder by setting the default hostname + // Later call MDNS::update() in every 'loop' to run the process loop + // (probing, announcing, responding, ...) + // if interfaceAddress is not specified, default interface is STA, or AP when STA is not set + bool begin(const char* p_pcHostname, const IPAddress& p_IPAddress = INADDR_ANY, uint32_t p_u32TTL = 120 /*ignored*/); + bool begin(const String& p_strHostname, const IPAddress& p_IPAddress = INADDR_ANY, uint32_t p_u32TTL = 120 /*ignored*/) + { + return begin(p_strHostname.c_str(), p_IPAddress, p_u32TTL); + } + bool _joinMulticastGroups(void); + bool _leaveMulticastGroups(void); + + // Finish MDNS processing + bool close(void); + // for esp32 compatibility + bool end(void); + // Change hostname (probing is restarted) + bool setHostname(const char* p_pcHostname); + // for compatibility... + bool setHostname(const String& p_strHostname); + + bool isRunning(void) + { + return (m_pUDPContext != 0); + } - /** + /** hMDNSService (opaque handle to access the service) */ - typedef const void* hMDNSService; - - // Add a new service to the MDNS responder. If no name (instance name) is given (p_pcName = 0) - // the current hostname is used. If the hostname is changed later, the instance names for - // these 'auto-named' services are changed to the new name also (and probing is restarted). - // The usual '_' before p_pcService (eg. http) and protocol (eg. tcp) may be given. - hMDNSService addService(const char* p_pcName, - const char* p_pcService, - const char* p_pcProtocol, - uint16_t p_u16Port); - // Removes a service from the MDNS responder - bool removeService(const hMDNSService p_hService); - bool removeService(const char* p_pcInstanceName, - const char* p_pcServiceName, - const char* p_pcProtocol); - // for compatibility... - bool addService(const String& p_strServiceName, - const String& p_strProtocol, - uint16_t p_u16Port); - - // Change the services instance name (and restart probing). - bool setServiceName(const hMDNSService p_hService, - const char* p_pcInstanceName); - //for compatibility - //Warning: this has the side effect of changing the hostname. - //TODO: implement instancename different from hostname - void setInstanceName(const char* p_pcHostname) - { - setHostname(p_pcHostname); - } - // for esp32 compatibility - void setInstanceName(const String& s_pcHostname) - { - setInstanceName(s_pcHostname.c_str()); - } + typedef const void* hMDNSService; + + // Add a new service to the MDNS responder. If no name (instance name) is given (p_pcName = 0) + // the current hostname is used. If the hostname is changed later, the instance names for + // these 'auto-named' services are changed to the new name also (and probing is restarted). + // The usual '_' before p_pcService (eg. http) and protocol (eg. tcp) may be given. + hMDNSService addService(const char* p_pcName, + const char* p_pcService, + const char* p_pcProtocol, + uint16_t p_u16Port); + // Removes a service from the MDNS responder + bool removeService(const hMDNSService p_hService); + bool removeService(const char* p_pcInstanceName, + const char* p_pcServiceName, + const char* p_pcProtocol); + // for compatibility... + bool addService(const String& p_strServiceName, + const String& p_strProtocol, + uint16_t p_u16Port); + + // Change the services instance name (and restart probing). + bool setServiceName(const hMDNSService p_hService, + const char* p_pcInstanceName); + //for compatibility + //Warning: this has the side effect of changing the hostname. + //TODO: implement instancename different from hostname + void setInstanceName(const char* p_pcHostname) + { + setHostname(p_pcHostname); + } + // for esp32 compatibility + void setInstanceName(const String& s_pcHostname) + { + setInstanceName(s_pcHostname.c_str()); + } - /** + /** hMDNSTxt (opaque handle to access the TXT items) */ - typedef void* hMDNSTxt; - - // Add a (static) MDNS TXT item ('key' = 'value') to the service - hMDNSTxt addServiceTxt(const hMDNSService p_hService, - const char* p_pcKey, - const char* p_pcValue); - hMDNSTxt addServiceTxt(const hMDNSService p_hService, - const char* p_pcKey, - uint32_t p_u32Value); - hMDNSTxt addServiceTxt(const hMDNSService p_hService, - const char* p_pcKey, - uint16_t p_u16Value); - hMDNSTxt addServiceTxt(const hMDNSService p_hService, - const char* p_pcKey, - uint8_t p_u8Value); - hMDNSTxt addServiceTxt(const hMDNSService p_hService, - const char* p_pcKey, - int32_t p_i32Value); - hMDNSTxt addServiceTxt(const hMDNSService p_hService, - const char* p_pcKey, - int16_t p_i16Value); - hMDNSTxt addServiceTxt(const hMDNSService p_hService, - const char* p_pcKey, - int8_t p_i8Value); - - // Remove an existing (static) MDNS TXT item from the service - bool removeServiceTxt(const hMDNSService p_hService, - const hMDNSTxt p_hTxt); - bool removeServiceTxt(const hMDNSService p_hService, - const char* p_pcKey); - bool removeServiceTxt(const char* p_pcinstanceName, - const char* p_pcServiceName, - const char* p_pcProtocol, - const char* p_pcKey); - // for compatibility... - bool addServiceTxt(const char* p_pcService, - const char* p_pcProtocol, - const char* p_pcKey, - const char* p_pcValue); - bool addServiceTxt(const String& p_strService, - const String& p_strProtocol, - const String& p_strKey, - const String& p_strValue); + typedef void* hMDNSTxt; + + // Add a (static) MDNS TXT item ('key' = 'value') to the service + hMDNSTxt addServiceTxt(const hMDNSService p_hService, + const char* p_pcKey, + const char* p_pcValue); + hMDNSTxt addServiceTxt(const hMDNSService p_hService, + const char* p_pcKey, + uint32_t p_u32Value); + hMDNSTxt addServiceTxt(const hMDNSService p_hService, + const char* p_pcKey, + uint16_t p_u16Value); + hMDNSTxt addServiceTxt(const hMDNSService p_hService, + const char* p_pcKey, + uint8_t p_u8Value); + hMDNSTxt addServiceTxt(const hMDNSService p_hService, + const char* p_pcKey, + int32_t p_i32Value); + hMDNSTxt addServiceTxt(const hMDNSService p_hService, + const char* p_pcKey, + int16_t p_i16Value); + hMDNSTxt addServiceTxt(const hMDNSService p_hService, + const char* p_pcKey, + int8_t p_i8Value); + + // Remove an existing (static) MDNS TXT item from the service + bool removeServiceTxt(const hMDNSService p_hService, + const hMDNSTxt p_hTxt); + bool removeServiceTxt(const hMDNSService p_hService, + const char* p_pcKey); + bool removeServiceTxt(const char* p_pcinstanceName, + const char* p_pcServiceName, + const char* p_pcProtocol, + const char* p_pcKey); + // for compatibility... + bool addServiceTxt(const char* p_pcService, + const char* p_pcProtocol, + const char* p_pcKey, + const char* p_pcValue); + bool addServiceTxt(const String& p_strService, + const String& p_strProtocol, + const String& p_strKey, + const String& p_strValue); - /** + /** MDNSDynamicServiceTxtCallbackFn Callback function for dynamic MDNS TXT items */ - typedef std::function MDNSDynamicServiceTxtCallbackFunc; - - // Set a global callback for dynamic MDNS TXT items. The callback function is called - // every time, a TXT item is needed for one of the installed services. - bool setDynamicServiceTxtCallback(MDNSDynamicServiceTxtCallbackFunc p_fnCallback); - // Set a service specific callback for dynamic MDNS TXT items. The callback function - // is called every time, a TXT item is needed for the given service. - bool setDynamicServiceTxtCallback(const hMDNSService p_hService, - MDNSDynamicServiceTxtCallbackFunc p_fnCallback); - - // Add a (dynamic) MDNS TXT item ('key' = 'value') to the service - // Dynamic TXT items are removed right after one-time use. So they need to be added - // every time the value s needed (via callback). - hMDNSTxt addDynamicServiceTxt(hMDNSService p_hService, - const char* p_pcKey, - const char* p_pcValue); - hMDNSTxt addDynamicServiceTxt(hMDNSService p_hService, - const char* p_pcKey, - uint32_t p_u32Value); - hMDNSTxt addDynamicServiceTxt(hMDNSService p_hService, - const char* p_pcKey, - uint16_t p_u16Value); - hMDNSTxt addDynamicServiceTxt(hMDNSService p_hService, - const char* p_pcKey, - uint8_t p_u8Value); - hMDNSTxt addDynamicServiceTxt(hMDNSService p_hService, - const char* p_pcKey, - int32_t p_i32Value); - hMDNSTxt addDynamicServiceTxt(hMDNSService p_hService, - const char* p_pcKey, - int16_t p_i16Value); - hMDNSTxt addDynamicServiceTxt(hMDNSService p_hService, - const char* p_pcKey, - int8_t p_i8Value); - - // Perform a (static) service query. The function returns after p_u16Timeout milliseconds - // The answers (the number of received answers is returned) can be retrieved by calling - // - answerHostname (or hostname) - // - answerIP (or IP) - // - answerPort (or port) - uint32_t queryService(const char* p_pcService, - const char* p_pcProtocol, - const uint16_t p_u16Timeout = MDNS_QUERYSERVICES_WAIT_TIME); - bool removeQuery(void); - // for compatibility... - uint32_t queryService(const String& p_strService, - const String& p_strProtocol); - - const char* answerHostname(const uint32_t p_u32AnswerIndex); - IPAddress answerIP(const uint32_t p_u32AnswerIndex); - uint16_t answerPort(const uint32_t p_u32AnswerIndex); - // for compatibility... - String hostname(const uint32_t p_u32AnswerIndex); - IPAddress IP(const uint32_t p_u32AnswerIndex); - uint16_t port(const uint32_t p_u32AnswerIndex); + typedef std::function MDNSDynamicServiceTxtCallbackFunc; + + // Set a global callback for dynamic MDNS TXT items. The callback function is called + // every time, a TXT item is needed for one of the installed services. + bool setDynamicServiceTxtCallback(MDNSDynamicServiceTxtCallbackFunc p_fnCallback); + // Set a service specific callback for dynamic MDNS TXT items. The callback function + // is called every time, a TXT item is needed for the given service. + bool setDynamicServiceTxtCallback(const hMDNSService p_hService, + MDNSDynamicServiceTxtCallbackFunc p_fnCallback); + + // Add a (dynamic) MDNS TXT item ('key' = 'value') to the service + // Dynamic TXT items are removed right after one-time use. So they need to be added + // every time the value s needed (via callback). + hMDNSTxt addDynamicServiceTxt(hMDNSService p_hService, + const char* p_pcKey, + const char* p_pcValue); + hMDNSTxt addDynamicServiceTxt(hMDNSService p_hService, + const char* p_pcKey, + uint32_t p_u32Value); + hMDNSTxt addDynamicServiceTxt(hMDNSService p_hService, + const char* p_pcKey, + uint16_t p_u16Value); + hMDNSTxt addDynamicServiceTxt(hMDNSService p_hService, + const char* p_pcKey, + uint8_t p_u8Value); + hMDNSTxt addDynamicServiceTxt(hMDNSService p_hService, + const char* p_pcKey, + int32_t p_i32Value); + hMDNSTxt addDynamicServiceTxt(hMDNSService p_hService, + const char* p_pcKey, + int16_t p_i16Value); + hMDNSTxt addDynamicServiceTxt(hMDNSService p_hService, + const char* p_pcKey, + int8_t p_i8Value); + + // Perform a (static) service query. The function returns after p_u16Timeout milliseconds + // The answers (the number of received answers is returned) can be retrieved by calling + // - answerHostname (or hostname) + // - answerIP (or IP) + // - answerPort (or port) + uint32_t queryService(const char* p_pcService, + const char* p_pcProtocol, + const uint16_t p_u16Timeout = MDNS_QUERYSERVICES_WAIT_TIME); + bool removeQuery(void); + // for compatibility... + uint32_t queryService(const String& p_strService, + const String& p_strProtocol); + + const char* answerHostname(const uint32_t p_u32AnswerIndex); + IPAddress answerIP(const uint32_t p_u32AnswerIndex); + uint16_t answerPort(const uint32_t p_u32AnswerIndex); + // for compatibility... + String hostname(const uint32_t p_u32AnswerIndex); + IPAddress IP(const uint32_t p_u32AnswerIndex); + uint16_t port(const uint32_t p_u32AnswerIndex); - /** + /** hMDNSServiceQuery (opaque handle to access dynamic service queries) */ - typedef const void* hMDNSServiceQuery; + typedef const void* hMDNSServiceQuery; - /** + /** enuServiceQueryAnswerType */ - typedef enum _enuServiceQueryAnswerType - { - ServiceQueryAnswerType_ServiceDomain = (1 << 0), // Service instance name - ServiceQueryAnswerType_HostDomainAndPort = (1 << 1), // Host domain and service port - ServiceQueryAnswerType_Txts = (1 << 2), // TXT items + typedef enum _enuServiceQueryAnswerType + { + ServiceQueryAnswerType_ServiceDomain = (1 << 0), // Service instance name + ServiceQueryAnswerType_HostDomainAndPort = (1 << 1), // Host domain and service port + ServiceQueryAnswerType_Txts = (1 << 2), // TXT items #ifdef MDNS_IP4_SUPPORT - ServiceQueryAnswerType_IP4Address = (1 << 3), // IP4 address + ServiceQueryAnswerType_IP4Address = (1 << 3), // IP4 address #endif #ifdef MDNS_IP6_SUPPORT - ServiceQueryAnswerType_IP6Address = (1 << 4), // IP6 address + ServiceQueryAnswerType_IP6Address = (1 << 4), // IP6 address #endif - } enuServiceQueryAnswerType; + } enuServiceQueryAnswerType; - enum class AnswerType : uint32_t - { - Unknown = 0, - ServiceDomain = ServiceQueryAnswerType_ServiceDomain, - HostDomainAndPort = ServiceQueryAnswerType_HostDomainAndPort, - Txt = ServiceQueryAnswerType_Txts, + enum class AnswerType : uint32_t + { + Unknown = 0, + ServiceDomain = ServiceQueryAnswerType_ServiceDomain, + HostDomainAndPort = ServiceQueryAnswerType_HostDomainAndPort, + Txt = ServiceQueryAnswerType_Txts, #ifdef MDNS_IP4_SUPPORT - IP4Address = ServiceQueryAnswerType_IP4Address, + IP4Address = ServiceQueryAnswerType_IP4Address, #endif #ifdef MDNS_IP6_SUPPORT - IP6Address = ServiceQueryAnswerType_IP6Address, + IP6Address = ServiceQueryAnswerType_IP6Address, #endif - }; + }; - /** + /** MDNSServiceQueryCallbackFn Callback function for received answers for dynamic service queries */ - struct MDNSServiceInfo; // forward declaration - typedef std::function - MDNSServiceQueryCallbackFunc; - - // Install a dynamic service query. For every received answer (part) the given callback - // function is called. The query will be updated every time, the TTL for an answer - // has timed-out. - // The answers can also be retrieved by calling - // - answerCount - // - answerServiceDomain - // - hasAnswerHostDomain/answerHostDomain - // - hasAnswerIP4Address/answerIP4Address - // - hasAnswerIP6Address/answerIP6Address - // - hasAnswerPort/answerPort - // - hasAnswerTxts/answerTxts - hMDNSServiceQuery installServiceQuery(const char* p_pcService, - const char* p_pcProtocol, - MDNSServiceQueryCallbackFunc p_fnCallback); - // Remove a dynamic service query - bool removeServiceQuery(hMDNSServiceQuery p_hServiceQuery); - - uint32_t answerCount(const hMDNSServiceQuery p_hServiceQuery); - std::vector answerInfo(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery); - - const char* answerServiceDomain(const hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex); - bool hasAnswerHostDomain(const hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex); - const char* answerHostDomain(const hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex); + struct MDNSServiceInfo; // forward declaration + typedef std::function + MDNSServiceQueryCallbackFunc; + + // Install a dynamic service query. For every received answer (part) the given callback + // function is called. The query will be updated every time, the TTL for an answer + // has timed-out. + // The answers can also be retrieved by calling + // - answerCount + // - answerServiceDomain + // - hasAnswerHostDomain/answerHostDomain + // - hasAnswerIP4Address/answerIP4Address + // - hasAnswerIP6Address/answerIP6Address + // - hasAnswerPort/answerPort + // - hasAnswerTxts/answerTxts + hMDNSServiceQuery installServiceQuery(const char* p_pcService, + const char* p_pcProtocol, + MDNSServiceQueryCallbackFunc p_fnCallback); + // Remove a dynamic service query + bool removeServiceQuery(hMDNSServiceQuery p_hServiceQuery); + + uint32_t answerCount(const hMDNSServiceQuery p_hServiceQuery); + std::vector answerInfo(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery); + + const char* answerServiceDomain(const hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex); + bool hasAnswerHostDomain(const hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex); + const char* answerHostDomain(const hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex); #ifdef MDNS_IP4_SUPPORT - bool hasAnswerIP4Address(const hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex); - uint32_t answerIP4AddressCount(const hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex); - IPAddress answerIP4Address(const hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex, - const uint32_t p_u32AddressIndex); + bool hasAnswerIP4Address(const hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex); + uint32_t answerIP4AddressCount(const hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex); + IPAddress answerIP4Address(const hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex, + const uint32_t p_u32AddressIndex); #endif #ifdef MDNS_IP6_SUPPORT - bool hasAnswerIP6Address(const hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex); - uint32_t answerIP6AddressCount(const hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex); - IPAddress answerIP6Address(const hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex, - const uint32_t p_u32AddressIndex); + bool hasAnswerIP6Address(const hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex); + uint32_t answerIP6AddressCount(const hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex); + IPAddress answerIP6Address(const hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex, + const uint32_t p_u32AddressIndex); #endif - bool hasAnswerPort(const hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex); - uint16_t answerPort(const hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex); - bool hasAnswerTxts(const hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex); - // Get the TXT items as a ';'-separated string - const char* answerTxts(const hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex); + bool hasAnswerPort(const hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex); + uint16_t answerPort(const hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex); + bool hasAnswerTxts(const hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex); + // Get the TXT items as a ';'-separated string + const char* answerTxts(const hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex); - /** + /** MDNSProbeResultCallbackFn Callback function for (host and service domain) probe results */ - typedef std::function - MDNSHostProbeFn; - - typedef std::function - MDNSHostProbeFn1; - - typedef std::function - MDNSServiceProbeFn; - - typedef std::function - MDNSServiceProbeFn1; - - // Set a global callback function for host and service probe results - // The callback function is called, when the probing for the host domain - // (or a service domain, which hasn't got a service specific callback) - // Succeeds or fails. - // In case of failure, the failed domain name should be changed. - bool setHostProbeResultCallback(MDNSHostProbeFn p_fnCallback); - bool setHostProbeResultCallback(MDNSHostProbeFn1 p_fnCallback); - - // Set a service specific probe result callback - bool setServiceProbeResultCallback(const MDNSResponder::hMDNSService p_hService, - MDNSServiceProbeFn p_fnCallback); - bool setServiceProbeResultCallback(const MDNSResponder::hMDNSService p_hService, - MDNSServiceProbeFn1 p_fnCallback); - - // Application should call this whenever AP is configured/disabled - bool notifyAPChange(void); - - // 'update' should be called in every 'loop' to run the MDNS processing - bool update(void); - - // 'announce' can be called every time, the configuration of some service - // changes. Mainly, this would be changed content of TXT items. - bool announce(void); - - // Enable OTA update - hMDNSService enableArduino(uint16_t p_u16Port, - bool p_bAuthUpload = false); - - // Domain name helper - static bool indexDomain(char*& p_rpcDomain, - const char* p_pcDivider = "-", - const char* p_pcDefaultDomain = 0); - - /** STRUCTS **/ - - public: - /** + typedef std::function + MDNSHostProbeFn; + + typedef std::function + MDNSHostProbeFn1; + + typedef std::function + MDNSServiceProbeFn; + + typedef std::function + MDNSServiceProbeFn1; + + // Set a global callback function for host and service probe results + // The callback function is called, when the probing for the host domain + // (or a service domain, which hasn't got a service specific callback) + // Succeeds or fails. + // In case of failure, the failed domain name should be changed. + bool setHostProbeResultCallback(MDNSHostProbeFn p_fnCallback); + bool setHostProbeResultCallback(MDNSHostProbeFn1 p_fnCallback); + + // Set a service specific probe result callback + bool setServiceProbeResultCallback(const MDNSResponder::hMDNSService p_hService, + MDNSServiceProbeFn p_fnCallback); + bool setServiceProbeResultCallback(const MDNSResponder::hMDNSService p_hService, + MDNSServiceProbeFn1 p_fnCallback); + + // Application should call this whenever AP is configured/disabled + bool notifyAPChange(void); + + // 'update' should be called in every 'loop' to run the MDNS processing + bool update(void); + + // 'announce' can be called every time, the configuration of some service + // changes. Mainly, this would be changed content of TXT items. + bool announce(void); + + // Enable OTA update + hMDNSService enableArduino(uint16_t p_u16Port, + bool p_bAuthUpload = false); + + // Domain name helper + static bool indexDomain(char*& p_rpcDomain, + const char* p_pcDivider = "-", + const char* p_pcDefaultDomain = 0); + + /** STRUCTS **/ + + public: + /** MDNSServiceInfo, used in application callbacks */ - struct MDNSServiceInfo - { - MDNSServiceInfo(MDNSResponder& p_pM, MDNSResponder::hMDNSServiceQuery p_hS, uint32_t p_u32A) - : p_pMDNSResponder(p_pM), - p_hServiceQuery(p_hS), - p_u32AnswerIndex(p_u32A){}; - struct CompareKey + struct MDNSServiceInfo { - bool operator()(char const* a, char const* b) const + MDNSServiceInfo(MDNSResponder& p_pM, MDNSResponder::hMDNSServiceQuery p_hS, uint32_t p_u32A) + : p_pMDNSResponder(p_pM) + , p_hServiceQuery(p_hS) + , p_u32AnswerIndex(p_u32A) {}; + struct CompareKey { - return strcmp(a, b) < 0; - } - }; - using KeyValueMap = std::map; + bool operator()(char const* a, char const* b) const + { + return strcmp(a, b) < 0; + } + }; + using KeyValueMap = std::map; - protected: - MDNSResponder& p_pMDNSResponder; - MDNSResponder::hMDNSServiceQuery p_hServiceQuery; - uint32_t p_u32AnswerIndex; - KeyValueMap keyValueMap; + protected: + MDNSResponder& p_pMDNSResponder; + MDNSResponder::hMDNSServiceQuery p_hServiceQuery; + uint32_t p_u32AnswerIndex; + KeyValueMap keyValueMap; - public: - const char* serviceDomain() - { - return p_pMDNSResponder.answerServiceDomain(p_hServiceQuery, p_u32AnswerIndex); - }; - bool hostDomainAvailable() - { - return (p_pMDNSResponder.hasAnswerHostDomain(p_hServiceQuery, p_u32AnswerIndex)); - } - const char* hostDomain() - { - return (hostDomainAvailable()) ? p_pMDNSResponder.answerHostDomain(p_hServiceQuery, p_u32AnswerIndex) : nullptr; - }; - bool hostPortAvailable() - { - return (p_pMDNSResponder.hasAnswerPort(p_hServiceQuery, p_u32AnswerIndex)); - } - uint16_t hostPort() - { - return (hostPortAvailable()) ? p_pMDNSResponder.answerPort(p_hServiceQuery, p_u32AnswerIndex) : 0; - }; - bool IP4AddressAvailable() - { - return (p_pMDNSResponder.hasAnswerIP4Address(p_hServiceQuery, p_u32AnswerIndex)); - } - std::vector IP4Adresses() - { - std::vector internalIP; - if (IP4AddressAvailable()) + public: + const char* serviceDomain() + { + return p_pMDNSResponder.answerServiceDomain(p_hServiceQuery, p_u32AnswerIndex); + }; + bool hostDomainAvailable() + { + return (p_pMDNSResponder.hasAnswerHostDomain(p_hServiceQuery, p_u32AnswerIndex)); + } + const char* hostDomain() + { + return (hostDomainAvailable()) ? p_pMDNSResponder.answerHostDomain(p_hServiceQuery, p_u32AnswerIndex) : nullptr; + }; + bool hostPortAvailable() + { + return (p_pMDNSResponder.hasAnswerPort(p_hServiceQuery, p_u32AnswerIndex)); + } + uint16_t hostPort() + { + return (hostPortAvailable()) ? p_pMDNSResponder.answerPort(p_hServiceQuery, p_u32AnswerIndex) : 0; + }; + bool IP4AddressAvailable() + { + return (p_pMDNSResponder.hasAnswerIP4Address(p_hServiceQuery, p_u32AnswerIndex)); + } + std::vector IP4Adresses() { - uint16_t cntIP4Adress = p_pMDNSResponder.answerIP4AddressCount(p_hServiceQuery, p_u32AnswerIndex); - for (uint32_t u2 = 0; u2 < cntIP4Adress; ++u2) + std::vector internalIP; + if (IP4AddressAvailable()) { - internalIP.emplace_back(p_pMDNSResponder.answerIP4Address(p_hServiceQuery, p_u32AnswerIndex, u2)); + uint16_t cntIP4Adress = p_pMDNSResponder.answerIP4AddressCount(p_hServiceQuery, p_u32AnswerIndex); + for (uint32_t u2 = 0; u2 < cntIP4Adress; ++u2) + { + internalIP.emplace_back(p_pMDNSResponder.answerIP4Address(p_hServiceQuery, p_u32AnswerIndex, u2)); + } } + return internalIP; + }; + bool txtAvailable() + { + return (p_pMDNSResponder.hasAnswerTxts(p_hServiceQuery, p_u32AnswerIndex)); } - return internalIP; - }; - bool txtAvailable() - { - return (p_pMDNSResponder.hasAnswerTxts(p_hServiceQuery, p_u32AnswerIndex)); - } - const char* strKeyValue() - { - return (txtAvailable()) ? p_pMDNSResponder.answerTxts(p_hServiceQuery, p_u32AnswerIndex) : nullptr; - }; - const KeyValueMap& keyValues() - { - if (txtAvailable() && keyValueMap.size() == 0) + const char* strKeyValue() + { + return (txtAvailable()) ? p_pMDNSResponder.answerTxts(p_hServiceQuery, p_u32AnswerIndex) : nullptr; + }; + const KeyValueMap& keyValues() { - for (auto kv = p_pMDNSResponder._answerKeyValue(p_hServiceQuery, p_u32AnswerIndex); kv != nullptr; kv = kv->m_pNext) + if (txtAvailable() && keyValueMap.size() == 0) { - keyValueMap.emplace(std::pair(kv->m_pcKey, kv->m_pcValue)); + for (auto kv = p_pMDNSResponder._answerKeyValue(p_hServiceQuery, p_u32AnswerIndex); kv != nullptr; kv = kv->m_pNext) + { + keyValueMap.emplace(std::pair(kv->m_pcKey, kv->m_pcValue)); + } } + return keyValueMap; } - return keyValueMap; - } - const char* value(const char* key) - { - char* result = nullptr; - - for (stcMDNSServiceTxt* pTxt = p_pMDNSResponder._answerKeyValue(p_hServiceQuery, p_u32AnswerIndex); pTxt; pTxt = pTxt->m_pNext) + const char* value(const char* key) { - if ((key) && - (0 == strcmp(pTxt->m_pcKey, key))) + char* result = nullptr; + + for (stcMDNSServiceTxt* pTxt = p_pMDNSResponder._answerKeyValue(p_hServiceQuery, p_u32AnswerIndex); pTxt; pTxt = pTxt->m_pNext) { - result = pTxt->m_pcValue; - break; + if ((key) && (0 == strcmp(pTxt->m_pcKey, key))) + { + result = pTxt->m_pcValue; + break; + } } + return result; } - return result; - } - }; + }; - protected: - /** + protected: + /** stcMDNSServiceTxt */ - struct stcMDNSServiceTxt - { - stcMDNSServiceTxt* m_pNext; - char* m_pcKey; - char* m_pcValue; - bool m_bTemp; - - stcMDNSServiceTxt(const char* p_pcKey = 0, - const char* p_pcValue = 0, - bool p_bTemp = false); - stcMDNSServiceTxt(const stcMDNSServiceTxt& p_Other); - ~stcMDNSServiceTxt(void); - - stcMDNSServiceTxt& operator=(const stcMDNSServiceTxt& p_Other); - bool clear(void); - - char* allocKey(size_t p_stLength); - bool setKey(const char* p_pcKey, - size_t p_stLength); - bool setKey(const char* p_pcKey); - bool releaseKey(void); - - char* allocValue(size_t p_stLength); - bool setValue(const char* p_pcValue, - size_t p_stLength); - bool setValue(const char* p_pcValue); - bool releaseValue(void); - - bool set(const char* p_pcKey, - const char* p_pcValue, - bool p_bTemp = false); - - bool update(const char* p_pcValue); - - size_t length(void) const; - }; + struct stcMDNSServiceTxt + { + stcMDNSServiceTxt* m_pNext; + char* m_pcKey; + char* m_pcValue; + bool m_bTemp; + + stcMDNSServiceTxt(const char* p_pcKey = 0, + const char* p_pcValue = 0, + bool p_bTemp = false); + stcMDNSServiceTxt(const stcMDNSServiceTxt& p_Other); + ~stcMDNSServiceTxt(void); + + stcMDNSServiceTxt& operator=(const stcMDNSServiceTxt& p_Other); + bool clear(void); - /** + char* allocKey(size_t p_stLength); + bool setKey(const char* p_pcKey, + size_t p_stLength); + bool setKey(const char* p_pcKey); + bool releaseKey(void); + + char* allocValue(size_t p_stLength); + bool setValue(const char* p_pcValue, + size_t p_stLength); + bool setValue(const char* p_pcValue); + bool releaseValue(void); + + bool set(const char* p_pcKey, + const char* p_pcValue, + bool p_bTemp = false); + + bool update(const char* p_pcValue); + + size_t length(void) const; + }; + + /** stcMDNSTxts */ - struct stcMDNSServiceTxts - { - stcMDNSServiceTxt* m_pTxts; + struct stcMDNSServiceTxts + { + stcMDNSServiceTxt* m_pTxts; - stcMDNSServiceTxts(void); - stcMDNSServiceTxts(const stcMDNSServiceTxts& p_Other); - ~stcMDNSServiceTxts(void); + stcMDNSServiceTxts(void); + stcMDNSServiceTxts(const stcMDNSServiceTxts& p_Other); + ~stcMDNSServiceTxts(void); - stcMDNSServiceTxts& operator=(const stcMDNSServiceTxts& p_Other); + stcMDNSServiceTxts& operator=(const stcMDNSServiceTxts& p_Other); - bool clear(void); + bool clear(void); - bool add(stcMDNSServiceTxt* p_pTxt); - bool remove(stcMDNSServiceTxt* p_pTxt); + bool add(stcMDNSServiceTxt* p_pTxt); + bool remove(stcMDNSServiceTxt* p_pTxt); - bool removeTempTxts(void); + bool removeTempTxts(void); - stcMDNSServiceTxt* find(const char* p_pcKey); - const stcMDNSServiceTxt* find(const char* p_pcKey) const; - stcMDNSServiceTxt* find(const stcMDNSServiceTxt* p_pTxt); + stcMDNSServiceTxt* find(const char* p_pcKey); + const stcMDNSServiceTxt* find(const char* p_pcKey) const; + stcMDNSServiceTxt* find(const stcMDNSServiceTxt* p_pTxt); - uint16_t length(void) const; + uint16_t length(void) const; - size_t c_strLength(void) const; - bool c_str(char* p_pcBuffer); + size_t c_strLength(void) const; + bool c_str(char* p_pcBuffer); - size_t bufferLength(void) const; - bool buffer(char* p_pcBuffer); + size_t bufferLength(void) const; + bool buffer(char* p_pcBuffer); - bool compare(const stcMDNSServiceTxts& p_Other) const; - bool operator==(const stcMDNSServiceTxts& p_Other) const; - bool operator!=(const stcMDNSServiceTxts& p_Other) const; - }; + bool compare(const stcMDNSServiceTxts& p_Other) const; + bool operator==(const stcMDNSServiceTxts& p_Other) const; + bool operator!=(const stcMDNSServiceTxts& p_Other) const; + }; - /** + /** enuContentFlags */ - typedef enum _enuContentFlags - { - // Host - ContentFlag_A = 0x01, - ContentFlag_PTR_IP4 = 0x02, - ContentFlag_PTR_IP6 = 0x04, - ContentFlag_AAAA = 0x08, - // Service - ContentFlag_PTR_TYPE = 0x10, - ContentFlag_PTR_NAME = 0x20, - ContentFlag_TXT = 0x40, - ContentFlag_SRV = 0x80, - } enuContentFlags; + typedef enum _enuContentFlags + { + // Host + ContentFlag_A = 0x01, + ContentFlag_PTR_IP4 = 0x02, + ContentFlag_PTR_IP6 = 0x04, + ContentFlag_AAAA = 0x08, + // Service + ContentFlag_PTR_TYPE = 0x10, + ContentFlag_PTR_NAME = 0x20, + ContentFlag_TXT = 0x40, + ContentFlag_SRV = 0x80, + } enuContentFlags; - /** + /** stcMDNS_MsgHeader */ - struct stcMDNS_MsgHeader - { - uint16_t m_u16ID; // Identifier - bool m_1bQR : 1; // Query/Response flag - unsigned char m_4bOpcode : 4; // Operation code - bool m_1bAA : 1; // Authoritative Answer flag - bool m_1bTC : 1; // Truncation flag - bool m_1bRD : 1; // Recursion desired - bool m_1bRA : 1; // Recursion available - unsigned char m_3bZ : 3; // Zero - unsigned char m_4bRCode : 4; // Response code - uint16_t m_u16QDCount; // Question count - uint16_t m_u16ANCount; // Answer count - uint16_t m_u16NSCount; // Authority Record count - uint16_t m_u16ARCount; // Additional Record count - - stcMDNS_MsgHeader(uint16_t p_u16ID = 0, - bool p_bQR = false, - unsigned char p_ucOpcode = 0, - bool p_bAA = false, - bool p_bTC = false, - bool p_bRD = false, - bool p_bRA = false, - unsigned char p_ucRCode = 0, - uint16_t p_u16QDCount = 0, - uint16_t p_u16ANCount = 0, - uint16_t p_u16NSCount = 0, - uint16_t p_u16ARCount = 0); - }; + struct stcMDNS_MsgHeader + { + uint16_t m_u16ID; // Identifier + bool m_1bQR : 1; // Query/Response flag + unsigned char m_4bOpcode : 4; // Operation code + bool m_1bAA : 1; // Authoritative Answer flag + bool m_1bTC : 1; // Truncation flag + bool m_1bRD : 1; // Recursion desired + bool m_1bRA : 1; // Recursion available + unsigned char m_3bZ : 3; // Zero + unsigned char m_4bRCode : 4; // Response code + uint16_t m_u16QDCount; // Question count + uint16_t m_u16ANCount; // Answer count + uint16_t m_u16NSCount; // Authority Record count + uint16_t m_u16ARCount; // Additional Record count + + stcMDNS_MsgHeader(uint16_t p_u16ID = 0, + bool p_bQR = false, + unsigned char p_ucOpcode = 0, + bool p_bAA = false, + bool p_bTC = false, + bool p_bRD = false, + bool p_bRA = false, + unsigned char p_ucRCode = 0, + uint16_t p_u16QDCount = 0, + uint16_t p_u16ANCount = 0, + uint16_t p_u16NSCount = 0, + uint16_t p_u16ARCount = 0); + }; - /** + /** stcMDNS_RRDomain */ - struct stcMDNS_RRDomain - { - char m_acName[MDNS_DOMAIN_MAXLENGTH]; // Encoded domain name - uint16_t m_u16NameLength; // Length (incl. '\0') + struct stcMDNS_RRDomain + { + char m_acName[MDNS_DOMAIN_MAXLENGTH]; // Encoded domain name + uint16_t m_u16NameLength; // Length (incl. '\0') - stcMDNS_RRDomain(void); - stcMDNS_RRDomain(const stcMDNS_RRDomain& p_Other); + stcMDNS_RRDomain(void); + stcMDNS_RRDomain(const stcMDNS_RRDomain& p_Other); - stcMDNS_RRDomain& operator=(const stcMDNS_RRDomain& p_Other); + stcMDNS_RRDomain& operator=(const stcMDNS_RRDomain& p_Other); - bool clear(void); + bool clear(void); - bool addLabel(const char* p_pcLabel, - bool p_bPrependUnderline = false); + bool addLabel(const char* p_pcLabel, + bool p_bPrependUnderline = false); - bool compare(const stcMDNS_RRDomain& p_Other) const; - bool operator==(const stcMDNS_RRDomain& p_Other) const; - bool operator!=(const stcMDNS_RRDomain& p_Other) const; - bool operator>(const stcMDNS_RRDomain& p_Other) const; + bool compare(const stcMDNS_RRDomain& p_Other) const; + bool operator==(const stcMDNS_RRDomain& p_Other) const; + bool operator!=(const stcMDNS_RRDomain& p_Other) const; + bool operator>(const stcMDNS_RRDomain& p_Other) const; - size_t c_strLength(void) const; - bool c_str(char* p_pcBuffer); - }; + size_t c_strLength(void) const; + bool c_str(char* p_pcBuffer); + }; - /** + /** stcMDNS_RRAttributes */ - struct stcMDNS_RRAttributes - { - uint16_t m_u16Type; // Type - uint16_t m_u16Class; // Class, nearly always 'IN' + struct stcMDNS_RRAttributes + { + uint16_t m_u16Type; // Type + uint16_t m_u16Class; // Class, nearly always 'IN' - stcMDNS_RRAttributes(uint16_t p_u16Type = 0, - uint16_t p_u16Class = 1 /*DNS_RRCLASS_IN Internet*/); - stcMDNS_RRAttributes(const stcMDNS_RRAttributes& p_Other); + stcMDNS_RRAttributes(uint16_t p_u16Type = 0, + uint16_t p_u16Class = 1 /*DNS_RRCLASS_IN Internet*/); + stcMDNS_RRAttributes(const stcMDNS_RRAttributes& p_Other); - stcMDNS_RRAttributes& operator=(const stcMDNS_RRAttributes& p_Other); - }; + stcMDNS_RRAttributes& operator=(const stcMDNS_RRAttributes& p_Other); + }; - /** + /** stcMDNS_RRHeader */ - struct stcMDNS_RRHeader - { - stcMDNS_RRDomain m_Domain; - stcMDNS_RRAttributes m_Attributes; + struct stcMDNS_RRHeader + { + stcMDNS_RRDomain m_Domain; + stcMDNS_RRAttributes m_Attributes; - stcMDNS_RRHeader(void); - stcMDNS_RRHeader(const stcMDNS_RRHeader& p_Other); + stcMDNS_RRHeader(void); + stcMDNS_RRHeader(const stcMDNS_RRHeader& p_Other); - stcMDNS_RRHeader& operator=(const stcMDNS_RRHeader& p_Other); + stcMDNS_RRHeader& operator=(const stcMDNS_RRHeader& p_Other); - bool clear(void); - }; + bool clear(void); + }; - /** + /** stcMDNS_RRQuestion */ - struct stcMDNS_RRQuestion - { - stcMDNS_RRQuestion* m_pNext; - stcMDNS_RRHeader m_Header; - bool m_bUnicast; // Unicast reply requested + struct stcMDNS_RRQuestion + { + stcMDNS_RRQuestion* m_pNext; + stcMDNS_RRHeader m_Header; + bool m_bUnicast; // Unicast reply requested - stcMDNS_RRQuestion(void); - }; + stcMDNS_RRQuestion(void); + }; - /** + /** enuAnswerType */ - typedef enum _enuAnswerType - { - AnswerType_A, - AnswerType_PTR, - AnswerType_TXT, - AnswerType_AAAA, - AnswerType_SRV, - AnswerType_Generic - } enuAnswerType; + typedef enum _enuAnswerType + { + AnswerType_A, + AnswerType_PTR, + AnswerType_TXT, + AnswerType_AAAA, + AnswerType_SRV, + AnswerType_Generic + } enuAnswerType; - /** + /** stcMDNS_RRAnswer */ - struct stcMDNS_RRAnswer - { - stcMDNS_RRAnswer* m_pNext; - const enuAnswerType m_AnswerType; - stcMDNS_RRHeader m_Header; - bool m_bCacheFlush; // Cache flush command bit - uint32_t m_u32TTL; // Validity time in seconds + struct stcMDNS_RRAnswer + { + stcMDNS_RRAnswer* m_pNext; + const enuAnswerType m_AnswerType; + stcMDNS_RRHeader m_Header; + bool m_bCacheFlush; // Cache flush command bit + uint32_t m_u32TTL; // Validity time in seconds - virtual ~stcMDNS_RRAnswer(void); + virtual ~stcMDNS_RRAnswer(void); - enuAnswerType answerType(void) const; + enuAnswerType answerType(void) const; - bool clear(void); + bool clear(void); - protected: - stcMDNS_RRAnswer(enuAnswerType p_AnswerType, - const stcMDNS_RRHeader& p_Header, - uint32_t p_u32TTL); - }; + protected: + stcMDNS_RRAnswer(enuAnswerType p_AnswerType, + const stcMDNS_RRHeader& p_Header, + uint32_t p_u32TTL); + }; #ifdef MDNS_IP4_SUPPORT - /** + /** stcMDNS_RRAnswerA */ - struct stcMDNS_RRAnswerA : public stcMDNS_RRAnswer - { - IPAddress m_IPAddress; + struct stcMDNS_RRAnswerA : public stcMDNS_RRAnswer + { + IPAddress m_IPAddress; - stcMDNS_RRAnswerA(const stcMDNS_RRHeader& p_Header, - uint32_t p_u32TTL); - ~stcMDNS_RRAnswerA(void); + stcMDNS_RRAnswerA(const stcMDNS_RRHeader& p_Header, + uint32_t p_u32TTL); + ~stcMDNS_RRAnswerA(void); - bool clear(void); - }; + bool clear(void); + }; #endif - /** + /** stcMDNS_RRAnswerPTR */ - struct stcMDNS_RRAnswerPTR : public stcMDNS_RRAnswer - { - stcMDNS_RRDomain m_PTRDomain; + struct stcMDNS_RRAnswerPTR : public stcMDNS_RRAnswer + { + stcMDNS_RRDomain m_PTRDomain; - stcMDNS_RRAnswerPTR(const stcMDNS_RRHeader& p_Header, - uint32_t p_u32TTL); - ~stcMDNS_RRAnswerPTR(void); + stcMDNS_RRAnswerPTR(const stcMDNS_RRHeader& p_Header, + uint32_t p_u32TTL); + ~stcMDNS_RRAnswerPTR(void); - bool clear(void); - }; + bool clear(void); + }; - /** + /** stcMDNS_RRAnswerTXT */ - struct stcMDNS_RRAnswerTXT : public stcMDNS_RRAnswer - { - stcMDNSServiceTxts m_Txts; + struct stcMDNS_RRAnswerTXT : public stcMDNS_RRAnswer + { + stcMDNSServiceTxts m_Txts; - stcMDNS_RRAnswerTXT(const stcMDNS_RRHeader& p_Header, - uint32_t p_u32TTL); - ~stcMDNS_RRAnswerTXT(void); + stcMDNS_RRAnswerTXT(const stcMDNS_RRHeader& p_Header, + uint32_t p_u32TTL); + ~stcMDNS_RRAnswerTXT(void); - bool clear(void); - }; + bool clear(void); + }; #ifdef MDNS_IP6_SUPPORT - /** + /** stcMDNS_RRAnswerAAAA */ - struct stcMDNS_RRAnswerAAAA : public stcMDNS_RRAnswer - { - //TODO: IP6Address m_IPAddress; + struct stcMDNS_RRAnswerAAAA : public stcMDNS_RRAnswer + { + //TODO: IP6Address m_IPAddress; - stcMDNS_RRAnswerAAAA(const stcMDNS_RRHeader& p_Header, - uint32_t p_u32TTL); - ~stcMDNS_RRAnswerAAAA(void); + stcMDNS_RRAnswerAAAA(const stcMDNS_RRHeader& p_Header, + uint32_t p_u32TTL); + ~stcMDNS_RRAnswerAAAA(void); - bool clear(void); - }; + bool clear(void); + }; #endif - /** + /** stcMDNS_RRAnswerSRV */ - struct stcMDNS_RRAnswerSRV : public stcMDNS_RRAnswer - { - uint16_t m_u16Priority; - uint16_t m_u16Weight; - uint16_t m_u16Port; - stcMDNS_RRDomain m_SRVDomain; + struct stcMDNS_RRAnswerSRV : public stcMDNS_RRAnswer + { + uint16_t m_u16Priority; + uint16_t m_u16Weight; + uint16_t m_u16Port; + stcMDNS_RRDomain m_SRVDomain; - stcMDNS_RRAnswerSRV(const stcMDNS_RRHeader& p_Header, - uint32_t p_u32TTL); - ~stcMDNS_RRAnswerSRV(void); + stcMDNS_RRAnswerSRV(const stcMDNS_RRHeader& p_Header, + uint32_t p_u32TTL); + ~stcMDNS_RRAnswerSRV(void); - bool clear(void); - }; + bool clear(void); + }; - /** + /** stcMDNS_RRAnswerGeneric */ - struct stcMDNS_RRAnswerGeneric : public stcMDNS_RRAnswer - { - uint16_t m_u16RDLength; // Length of variable answer - uint8_t* m_pu8RDData; // Offset of start of variable answer in packet + struct stcMDNS_RRAnswerGeneric : public stcMDNS_RRAnswer + { + uint16_t m_u16RDLength; // Length of variable answer + uint8_t* m_pu8RDData; // Offset of start of variable answer in packet - stcMDNS_RRAnswerGeneric(const stcMDNS_RRHeader& p_Header, - uint32_t p_u32TTL); - ~stcMDNS_RRAnswerGeneric(void); + stcMDNS_RRAnswerGeneric(const stcMDNS_RRHeader& p_Header, + uint32_t p_u32TTL); + ~stcMDNS_RRAnswerGeneric(void); - bool clear(void); - }; + bool clear(void); + }; - /** + /** enuProbingStatus */ - typedef enum _enuProbingStatus - { - ProbingStatus_WaitingForData, - ProbingStatus_ReadyToStart, - ProbingStatus_InProgress, - ProbingStatus_Done - } enuProbingStatus; + typedef enum _enuProbingStatus + { + ProbingStatus_WaitingForData, + ProbingStatus_ReadyToStart, + ProbingStatus_InProgress, + ProbingStatus_Done + } enuProbingStatus; - /** + /** stcProbeInformation */ - struct stcProbeInformation - { - enuProbingStatus m_ProbingStatus; - uint8_t m_u8SentCount; // Used for probes and announcements - esp8266::polledTimeout::oneShotMs m_Timeout; // Used for probes and announcements - //clsMDNSTimeFlag m_TimeFlag; // Used for probes and announcements - bool m_bConflict; - bool m_bTiebreakNeeded; - MDNSHostProbeFn m_fnHostProbeResultCallback; - MDNSServiceProbeFn m_fnServiceProbeResultCallback; - - stcProbeInformation(void); - - bool clear(bool p_bClearUserdata = false); - }; + struct stcProbeInformation + { + enuProbingStatus m_ProbingStatus; + uint8_t m_u8SentCount; // Used for probes and announcements + esp8266::polledTimeout::oneShotMs m_Timeout; // Used for probes and announcements + //clsMDNSTimeFlag m_TimeFlag; // Used for probes and announcements + bool m_bConflict; + bool m_bTiebreakNeeded; + MDNSHostProbeFn m_fnHostProbeResultCallback; + MDNSServiceProbeFn m_fnServiceProbeResultCallback; + + stcProbeInformation(void); + + bool clear(bool p_bClearUserdata = false); + }; - /** + /** stcMDNSService */ - struct stcMDNSService - { - stcMDNSService* m_pNext; - char* m_pcName; - bool m_bAutoName; // Name was set automatically to hostname (if no name was supplied) - char* m_pcService; - char* m_pcProtocol; - uint16_t m_u16Port; - uint8_t m_u8ReplyMask; - stcMDNSServiceTxts m_Txts; - MDNSDynamicServiceTxtCallbackFunc m_fnTxtCallback; - stcProbeInformation m_ProbeInformation; - - stcMDNSService(const char* p_pcName = 0, - const char* p_pcService = 0, - const char* p_pcProtocol = 0); - ~stcMDNSService(void); - - bool setName(const char* p_pcName); - bool releaseName(void); - - bool setService(const char* p_pcService); - bool releaseService(void); - - bool setProtocol(const char* p_pcProtocol); - bool releaseProtocol(void); - }; + struct stcMDNSService + { + stcMDNSService* m_pNext; + char* m_pcName; + bool m_bAutoName; // Name was set automatically to hostname (if no name was supplied) + char* m_pcService; + char* m_pcProtocol; + uint16_t m_u16Port; + uint8_t m_u8ReplyMask; + stcMDNSServiceTxts m_Txts; + MDNSDynamicServiceTxtCallbackFunc m_fnTxtCallback; + stcProbeInformation m_ProbeInformation; + + stcMDNSService(const char* p_pcName = 0, + const char* p_pcService = 0, + const char* p_pcProtocol = 0); + ~stcMDNSService(void); + + bool setName(const char* p_pcName); + bool releaseName(void); + + bool setService(const char* p_pcService); + bool releaseService(void); + + bool setProtocol(const char* p_pcProtocol); + bool releaseProtocol(void); + }; - /** + /** stcMDNSServiceQuery */ - struct stcMDNSServiceQuery - { - /** - stcAnswer - */ - struct stcAnswer + struct stcMDNSServiceQuery { /** - stcTTL - */ - struct stcTTL + stcAnswer + */ + struct stcAnswer { /** + stcTTL + */ + struct stcTTL + { + /** timeoutLevel_t */ - typedef uint8_t timeoutLevel_t; - /** + typedef uint8_t timeoutLevel_t; + /** TIMEOUTLEVELs */ - const timeoutLevel_t TIMEOUTLEVEL_UNSET = 0; - const timeoutLevel_t TIMEOUTLEVEL_BASE = 80; - const timeoutLevel_t TIMEOUTLEVEL_INTERVAL = 5; - const timeoutLevel_t TIMEOUTLEVEL_FINAL = 100; + const timeoutLevel_t TIMEOUTLEVEL_UNSET = 0; + const timeoutLevel_t TIMEOUTLEVEL_BASE = 80; + const timeoutLevel_t TIMEOUTLEVEL_INTERVAL = 5; + const timeoutLevel_t TIMEOUTLEVEL_FINAL = 100; - uint32_t m_u32TTL; - esp8266::polledTimeout::oneShotMs m_TTLTimeout; - timeoutLevel_t m_timeoutLevel; + uint32_t m_u32TTL; + esp8266::polledTimeout::oneShotMs m_TTLTimeout; + timeoutLevel_t m_timeoutLevel; - using timeoutBase = decltype(m_TTLTimeout); + using timeoutBase = decltype(m_TTLTimeout); - stcTTL(void); - bool set(uint32_t p_u32TTL); + stcTTL(void); + bool set(uint32_t p_u32TTL); - bool flagged(void); - bool restart(void); + bool flagged(void); + bool restart(void); - bool prepareDeletion(void); - bool finalTimeoutLevel(void) const; + bool prepareDeletion(void); + bool finalTimeoutLevel(void) const; - timeoutBase::timeType timeout(void) const; - }; + timeoutBase::timeType timeout(void) const; + }; #ifdef MDNS_IP4_SUPPORT - /** + /** stcIP4Address */ - struct stcIP4Address - { - stcIP4Address* m_pNext; - IPAddress m_IPAddress; - stcTTL m_TTL; + struct stcIP4Address + { + stcIP4Address* m_pNext; + IPAddress m_IPAddress; + stcTTL m_TTL; - stcIP4Address(IPAddress p_IPAddress, - uint32_t p_u32TTL = 0); - }; + stcIP4Address(IPAddress p_IPAddress, + uint32_t p_u32TTL = 0); + }; #endif #ifdef MDNS_IP6_SUPPORT - /** + /** stcIP6Address */ - struct stcIP6Address - { - stcIP6Address* m_pNext; - IP6Address m_IPAddress; - stcTTL m_TTL; + struct stcIP6Address + { + stcIP6Address* m_pNext; + IP6Address m_IPAddress; + stcTTL m_TTL; - stcIP6Address(IPAddress p_IPAddress, - uint32_t p_u32TTL = 0); - }; + stcIP6Address(IPAddress p_IPAddress, + uint32_t p_u32TTL = 0); + }; #endif - stcAnswer* m_pNext; - // The service domain is the first 'answer' (from PTR answer, using service and protocol) to be set - // Defines the key for additional answer, like host domain, etc. - stcMDNS_RRDomain m_ServiceDomain; // 1. level answer (PTR), eg. MyESP._http._tcp.local - char* m_pcServiceDomain; - stcTTL m_TTLServiceDomain; - stcMDNS_RRDomain m_HostDomain; // 2. level answer (SRV, using service domain), eg. esp8266.local - char* m_pcHostDomain; - uint16_t m_u16Port; // 2. level answer (SRV, using service domain), eg. 5000 - stcTTL m_TTLHostDomainAndPort; - stcMDNSServiceTxts m_Txts; // 2. level answer (TXT, using service domain), eg. c#=1 - char* m_pcTxts; - stcTTL m_TTLTxts; + stcAnswer* m_pNext; + // The service domain is the first 'answer' (from PTR answer, using service and protocol) to be set + // Defines the key for additional answer, like host domain, etc. + stcMDNS_RRDomain m_ServiceDomain; // 1. level answer (PTR), eg. MyESP._http._tcp.local + char* m_pcServiceDomain; + stcTTL m_TTLServiceDomain; + stcMDNS_RRDomain m_HostDomain; // 2. level answer (SRV, using service domain), eg. esp8266.local + char* m_pcHostDomain; + uint16_t m_u16Port; // 2. level answer (SRV, using service domain), eg. 5000 + stcTTL m_TTLHostDomainAndPort; + stcMDNSServiceTxts m_Txts; // 2. level answer (TXT, using service domain), eg. c#=1 + char* m_pcTxts; + stcTTL m_TTLTxts; #ifdef MDNS_IP4_SUPPORT - stcIP4Address* m_pIP4Addresses; // 3. level answer (A, using host domain), eg. 123.456.789.012 + stcIP4Address* m_pIP4Addresses; // 3. level answer (A, using host domain), eg. 123.456.789.012 #endif #ifdef MDNS_IP6_SUPPORT - stcIP6Address* m_pIP6Addresses; // 3. level answer (AAAA, using host domain), eg. 1234::09 + stcIP6Address* m_pIP6Addresses; // 3. level answer (AAAA, using host domain), eg. 1234::09 #endif - uint32_t m_u32ContentFlags; + uint32_t m_u32ContentFlags; - stcAnswer(void); - ~stcAnswer(void); + stcAnswer(void); + ~stcAnswer(void); - bool clear(void); + bool clear(void); - char* allocServiceDomain(size_t p_stLength); - bool releaseServiceDomain(void); + char* allocServiceDomain(size_t p_stLength); + bool releaseServiceDomain(void); - char* allocHostDomain(size_t p_stLength); - bool releaseHostDomain(void); + char* allocHostDomain(size_t p_stLength); + bool releaseHostDomain(void); - char* allocTxts(size_t p_stLength); - bool releaseTxts(void); + char* allocTxts(size_t p_stLength); + bool releaseTxts(void); #ifdef MDNS_IP4_SUPPORT - bool releaseIP4Addresses(void); - bool addIP4Address(stcIP4Address* p_pIP4Address); - bool removeIP4Address(stcIP4Address* p_pIP4Address); - const stcIP4Address* findIP4Address(const IPAddress& p_IPAddress) const; - stcIP4Address* findIP4Address(const IPAddress& p_IPAddress); - uint32_t IP4AddressCount(void) const; - const stcIP4Address* IP4AddressAtIndex(uint32_t p_u32Index) const; - stcIP4Address* IP4AddressAtIndex(uint32_t p_u32Index); + bool releaseIP4Addresses(void); + bool addIP4Address(stcIP4Address* p_pIP4Address); + bool removeIP4Address(stcIP4Address* p_pIP4Address); + const stcIP4Address* findIP4Address(const IPAddress& p_IPAddress) const; + stcIP4Address* findIP4Address(const IPAddress& p_IPAddress); + uint32_t IP4AddressCount(void) const; + const stcIP4Address* IP4AddressAtIndex(uint32_t p_u32Index) const; + stcIP4Address* IP4AddressAtIndex(uint32_t p_u32Index); #endif #ifdef MDNS_IP6_SUPPORT - bool releaseIP6Addresses(void); - bool addIP6Address(stcIP6Address* p_pIP6Address); - bool removeIP6Address(stcIP6Address* p_pIP6Address); - const stcIP6Address* findIP6Address(const IPAddress& p_IPAddress) const; - stcIP6Address* findIP6Address(const IPAddress& p_IPAddress); - uint32_t IP6AddressCount(void) const; - const stcIP6Address* IP6AddressAtIndex(uint32_t p_u32Index) const; - stcIP6Address* IP6AddressAtIndex(uint32_t p_u32Index); + bool releaseIP6Addresses(void); + bool addIP6Address(stcIP6Address* p_pIP6Address); + bool removeIP6Address(stcIP6Address* p_pIP6Address); + const stcIP6Address* findIP6Address(const IPAddress& p_IPAddress) const; + stcIP6Address* findIP6Address(const IPAddress& p_IPAddress); + uint32_t IP6AddressCount(void) const; + const stcIP6Address* IP6AddressAtIndex(uint32_t p_u32Index) const; + stcIP6Address* IP6AddressAtIndex(uint32_t p_u32Index); #endif - }; + }; - stcMDNSServiceQuery* m_pNext; - stcMDNS_RRDomain m_ServiceTypeDomain; // eg. _http._tcp.local - MDNSServiceQueryCallbackFunc m_fnCallback; - bool m_bLegacyQuery; - uint8_t m_u8SentCount; - esp8266::polledTimeout::oneShotMs m_ResendTimeout; - bool m_bAwaitingAnswers; - stcAnswer* m_pAnswers; + stcMDNSServiceQuery* m_pNext; + stcMDNS_RRDomain m_ServiceTypeDomain; // eg. _http._tcp.local + MDNSServiceQueryCallbackFunc m_fnCallback; + bool m_bLegacyQuery; + uint8_t m_u8SentCount; + esp8266::polledTimeout::oneShotMs m_ResendTimeout; + bool m_bAwaitingAnswers; + stcAnswer* m_pAnswers; - stcMDNSServiceQuery(void); - ~stcMDNSServiceQuery(void); + stcMDNSServiceQuery(void); + ~stcMDNSServiceQuery(void); - bool clear(void); + bool clear(void); - uint32_t answerCount(void) const; - const stcAnswer* answerAtIndex(uint32_t p_u32Index) const; - stcAnswer* answerAtIndex(uint32_t p_u32Index); - uint32_t indexOfAnswer(const stcAnswer* p_pAnswer) const; + uint32_t answerCount(void) const; + const stcAnswer* answerAtIndex(uint32_t p_u32Index) const; + stcAnswer* answerAtIndex(uint32_t p_u32Index); + uint32_t indexOfAnswer(const stcAnswer* p_pAnswer) const; - bool addAnswer(stcAnswer* p_pAnswer); - bool removeAnswer(stcAnswer* p_pAnswer); + bool addAnswer(stcAnswer* p_pAnswer); + bool removeAnswer(stcAnswer* p_pAnswer); - stcAnswer* findAnswerForServiceDomain(const stcMDNS_RRDomain& p_ServiceDomain); - stcAnswer* findAnswerForHostDomain(const stcMDNS_RRDomain& p_HostDomain); - }; + stcAnswer* findAnswerForServiceDomain(const stcMDNS_RRDomain& p_ServiceDomain); + stcAnswer* findAnswerForHostDomain(const stcMDNS_RRDomain& p_HostDomain); + }; - /** + /** stcMDNSSendParameter */ - struct stcMDNSSendParameter - { - protected: - /** + struct stcMDNSSendParameter + { + protected: + /** stcDomainCacheItem */ - struct stcDomainCacheItem - { - stcDomainCacheItem* m_pNext; - const void* m_pHostnameOrService; // Opaque id for host or service domain (pointer) - bool m_bAdditionalData; // Opaque flag for special info (service domain included) - uint16_t m_u16Offset; // Offset in UDP output buffer - - stcDomainCacheItem(const void* p_pHostnameOrService, - bool p_bAdditionalData, - uint32_t p_u16Offset); - }; + struct stcDomainCacheItem + { + stcDomainCacheItem* m_pNext; + const void* m_pHostnameOrService; // Opaque id for host or service domain (pointer) + bool m_bAdditionalData; // Opaque flag for special info (service domain included) + uint16_t m_u16Offset; // Offset in UDP output buffer + + stcDomainCacheItem(const void* p_pHostnameOrService, + bool p_bAdditionalData, + uint32_t p_u16Offset); + }; - public: - uint16_t m_u16ID; // Query ID (used only in lagacy queries) - stcMDNS_RRQuestion* m_pQuestions; // A list of queries - uint8_t m_u8HostReplyMask; // Flags for reply components/answers - bool m_bLegacyQuery; // Flag: Legacy query - bool m_bResponse; // Flag: Response to a query - bool m_bAuthorative; // Flag: Authoritative (owner) response - bool m_bCacheFlush; // Flag: Clients should flush their caches - bool m_bUnicast; // Flag: Unicast response - bool m_bUnannounce; // Flag: Unannounce service - uint16_t m_u16Offset; // Current offset in UDP write buffer (mainly for domain cache) - stcDomainCacheItem* m_pDomainCacheItems; // Cached host and service domains - - stcMDNSSendParameter(void); - ~stcMDNSSendParameter(void); - - bool clear(void); - bool clearCachedNames(void); - - bool shiftOffset(uint16_t p_u16Shift); - - bool addDomainCacheItem(const void* p_pHostnameOrService, - bool p_bAdditionalData, - uint16_t p_u16Offset); - uint16_t findCachedDomainOffset(const void* p_pHostnameOrService, - bool p_bAdditionalData) const; - }; + public: + uint16_t m_u16ID; // Query ID (used only in lagacy queries) + stcMDNS_RRQuestion* m_pQuestions; // A list of queries + uint8_t m_u8HostReplyMask; // Flags for reply components/answers + bool m_bLegacyQuery; // Flag: Legacy query + bool m_bResponse; // Flag: Response to a query + bool m_bAuthorative; // Flag: Authoritative (owner) response + bool m_bCacheFlush; // Flag: Clients should flush their caches + bool m_bUnicast; // Flag: Unicast response + bool m_bUnannounce; // Flag: Unannounce service + uint16_t m_u16Offset; // Current offset in UDP write buffer (mainly for domain cache) + stcDomainCacheItem* m_pDomainCacheItems; // Cached host and service domains + + stcMDNSSendParameter(void); + ~stcMDNSSendParameter(void); + + bool clear(void); + bool clearCachedNames(void); - // Instance variables - stcMDNSService* m_pServices; - UdpContext* m_pUDPContext; - char* m_pcHostname; - stcMDNSServiceQuery* m_pServiceQueries; - MDNSDynamicServiceTxtCallbackFunc m_fnServiceTxtCallback; - stcProbeInformation m_HostProbeInformation; - - /** CONTROL **/ - /* MAINTENANCE */ - bool _process(bool p_bUserContext); - bool _restart(void); - - /* RECEIVING */ - bool _parseMessage(void); - bool _parseQuery(const stcMDNS_MsgHeader& p_Header); - - bool _parseResponse(const stcMDNS_MsgHeader& p_Header); - bool _processAnswers(const stcMDNS_RRAnswer* p_pPTRAnswers); - bool _processPTRAnswer(const stcMDNS_RRAnswerPTR* p_pPTRAnswer, - bool& p_rbFoundNewKeyAnswer); - bool _processSRVAnswer(const stcMDNS_RRAnswerSRV* p_pSRVAnswer, - bool& p_rbFoundNewKeyAnswer); - bool _processTXTAnswer(const stcMDNS_RRAnswerTXT* p_pTXTAnswer); + bool shiftOffset(uint16_t p_u16Shift); + + bool addDomainCacheItem(const void* p_pHostnameOrService, + bool p_bAdditionalData, + uint16_t p_u16Offset); + uint16_t findCachedDomainOffset(const void* p_pHostnameOrService, + bool p_bAdditionalData) const; + }; + + // Instance variables + stcMDNSService* m_pServices; + UdpContext* m_pUDPContext; + char* m_pcHostname; + stcMDNSServiceQuery* m_pServiceQueries; + MDNSDynamicServiceTxtCallbackFunc m_fnServiceTxtCallback; + stcProbeInformation m_HostProbeInformation; + + /** CONTROL **/ + /* MAINTENANCE */ + bool _process(bool p_bUserContext); + bool _restart(void); + + /* RECEIVING */ + bool _parseMessage(void); + bool _parseQuery(const stcMDNS_MsgHeader& p_Header); + + bool _parseResponse(const stcMDNS_MsgHeader& p_Header); + bool _processAnswers(const stcMDNS_RRAnswer* p_pPTRAnswers); + bool _processPTRAnswer(const stcMDNS_RRAnswerPTR* p_pPTRAnswer, + bool& p_rbFoundNewKeyAnswer); + bool _processSRVAnswer(const stcMDNS_RRAnswerSRV* p_pSRVAnswer, + bool& p_rbFoundNewKeyAnswer); + bool _processTXTAnswer(const stcMDNS_RRAnswerTXT* p_pTXTAnswer); #ifdef MDNS_IP4_SUPPORT - bool _processAAnswer(const stcMDNS_RRAnswerA* p_pAAnswer); + bool _processAAnswer(const stcMDNS_RRAnswerA* p_pAAnswer); #endif #ifdef MDNS_IP6_SUPPORT - bool _processAAAAAnswer(const stcMDNS_RRAnswerAAAA* p_pAAAAAnswer); + bool _processAAAAAnswer(const stcMDNS_RRAnswerAAAA* p_pAAAAAnswer); #endif - /* PROBING */ - bool _updateProbeStatus(void); - bool _resetProbeStatus(bool p_bRestart = true); - bool _hasProbesWaitingForAnswers(void) const; - bool _sendHostProbe(void); - bool _sendServiceProbe(stcMDNSService& p_rService); - bool _cancelProbingForHost(void); - bool _cancelProbingForService(stcMDNSService& p_rService); - - /* ANNOUNCE */ - bool _announce(bool p_bAnnounce, - bool p_bIncludeServices); - bool _announceService(stcMDNSService& p_rService, - bool p_bAnnounce = true); - - /* SERVICE QUERY CACHE */ - bool _hasServiceQueriesWaitingForAnswers(void) const; - bool _checkServiceQueryCache(void); - - /** TRANSFER **/ - /* SENDING */ - bool _sendMDNSMessage(stcMDNSSendParameter& p_SendParameter); - bool _sendMDNSMessage_Multicast(MDNSResponder::stcMDNSSendParameter& p_rSendParameter); - bool _prepareMDNSMessage(stcMDNSSendParameter& p_SendParameter, - IPAddress p_IPAddress); - bool _sendMDNSServiceQuery(const stcMDNSServiceQuery& p_ServiceQuery); - bool _sendMDNSQuery(const stcMDNS_RRDomain& p_QueryDomain, - uint16_t p_u16QueryType, - stcMDNSServiceQuery::stcAnswer* p_pKnownAnswers = 0); - - uint8_t _replyMaskForHost(const stcMDNS_RRHeader& p_RRHeader, - bool* p_pbFullNameMatch = 0) const; - uint8_t _replyMaskForService(const stcMDNS_RRHeader& p_RRHeader, - const stcMDNSService& p_Service, - bool* p_pbFullNameMatch = 0) const; - - /* RESOURCE RECORD */ - bool _readRRQuestion(stcMDNS_RRQuestion& p_rQuestion); - bool _readRRAnswer(stcMDNS_RRAnswer*& p_rpAnswer); + /* PROBING */ + bool _updateProbeStatus(void); + bool _resetProbeStatus(bool p_bRestart = true); + bool _hasProbesWaitingForAnswers(void) const; + bool _sendHostProbe(void); + bool _sendServiceProbe(stcMDNSService& p_rService); + bool _cancelProbingForHost(void); + bool _cancelProbingForService(stcMDNSService& p_rService); + + /* ANNOUNCE */ + bool _announce(bool p_bAnnounce, + bool p_bIncludeServices); + bool _announceService(stcMDNSService& p_rService, + bool p_bAnnounce = true); + + /* SERVICE QUERY CACHE */ + bool _hasServiceQueriesWaitingForAnswers(void) const; + bool _checkServiceQueryCache(void); + + /** TRANSFER **/ + /* SENDING */ + bool _sendMDNSMessage(stcMDNSSendParameter& p_SendParameter); + bool _sendMDNSMessage_Multicast(MDNSResponder::stcMDNSSendParameter& p_rSendParameter); + bool _prepareMDNSMessage(stcMDNSSendParameter& p_SendParameter, + IPAddress p_IPAddress); + bool _sendMDNSServiceQuery(const stcMDNSServiceQuery& p_ServiceQuery); + bool _sendMDNSQuery(const stcMDNS_RRDomain& p_QueryDomain, + uint16_t p_u16QueryType, + stcMDNSServiceQuery::stcAnswer* p_pKnownAnswers = 0); + + uint8_t _replyMaskForHost(const stcMDNS_RRHeader& p_RRHeader, + bool* p_pbFullNameMatch = 0) const; + uint8_t _replyMaskForService(const stcMDNS_RRHeader& p_RRHeader, + const stcMDNSService& p_Service, + bool* p_pbFullNameMatch = 0) const; + + /* RESOURCE RECORD */ + bool _readRRQuestion(stcMDNS_RRQuestion& p_rQuestion); + bool _readRRAnswer(stcMDNS_RRAnswer*& p_rpAnswer); #ifdef MDNS_IP4_SUPPORT - bool _readRRAnswerA(stcMDNS_RRAnswerA& p_rRRAnswerA, - uint16_t p_u16RDLength); + bool _readRRAnswerA(stcMDNS_RRAnswerA& p_rRRAnswerA, + uint16_t p_u16RDLength); #endif - bool _readRRAnswerPTR(stcMDNS_RRAnswerPTR& p_rRRAnswerPTR, - uint16_t p_u16RDLength); - bool _readRRAnswerTXT(stcMDNS_RRAnswerTXT& p_rRRAnswerTXT, - uint16_t p_u16RDLength); + bool _readRRAnswerPTR(stcMDNS_RRAnswerPTR& p_rRRAnswerPTR, + uint16_t p_u16RDLength); + bool _readRRAnswerTXT(stcMDNS_RRAnswerTXT& p_rRRAnswerTXT, + uint16_t p_u16RDLength); #ifdef MDNS_IP6_SUPPORT - bool _readRRAnswerAAAA(stcMDNS_RRAnswerAAAA& p_rRRAnswerAAAA, - uint16_t p_u16RDLength); + bool _readRRAnswerAAAA(stcMDNS_RRAnswerAAAA& p_rRRAnswerAAAA, + uint16_t p_u16RDLength); #endif - bool _readRRAnswerSRV(stcMDNS_RRAnswerSRV& p_rRRAnswerSRV, - uint16_t p_u16RDLength); - bool _readRRAnswerGeneric(stcMDNS_RRAnswerGeneric& p_rRRAnswerGeneric, - uint16_t p_u16RDLength); - - bool _readRRHeader(stcMDNS_RRHeader& p_rHeader); - bool _readRRDomain(stcMDNS_RRDomain& p_rRRDomain); - bool _readRRDomain_Loop(stcMDNS_RRDomain& p_rRRDomain, - uint8_t p_u8Depth); - bool _readRRAttributes(stcMDNS_RRAttributes& p_rAttributes); - - /* DOMAIN NAMES */ - bool _buildDomainForHost(const char* p_pcHostname, - stcMDNS_RRDomain& p_rHostDomain) const; - bool _buildDomainForDNSSD(stcMDNS_RRDomain& p_rDNSSDDomain) const; - bool _buildDomainForService(const stcMDNSService& p_Service, - bool p_bIncludeName, - stcMDNS_RRDomain& p_rServiceDomain) const; - bool _buildDomainForService(const char* p_pcService, - const char* p_pcProtocol, - stcMDNS_RRDomain& p_rServiceDomain) const; + bool _readRRAnswerSRV(stcMDNS_RRAnswerSRV& p_rRRAnswerSRV, + uint16_t p_u16RDLength); + bool _readRRAnswerGeneric(stcMDNS_RRAnswerGeneric& p_rRRAnswerGeneric, + uint16_t p_u16RDLength); + + bool _readRRHeader(stcMDNS_RRHeader& p_rHeader); + bool _readRRDomain(stcMDNS_RRDomain& p_rRRDomain); + bool _readRRDomain_Loop(stcMDNS_RRDomain& p_rRRDomain, + uint8_t p_u8Depth); + bool _readRRAttributes(stcMDNS_RRAttributes& p_rAttributes); + + /* DOMAIN NAMES */ + bool _buildDomainForHost(const char* p_pcHostname, + stcMDNS_RRDomain& p_rHostDomain) const; + bool _buildDomainForDNSSD(stcMDNS_RRDomain& p_rDNSSDDomain) const; + bool _buildDomainForService(const stcMDNSService& p_Service, + bool p_bIncludeName, + stcMDNS_RRDomain& p_rServiceDomain) const; + bool _buildDomainForService(const char* p_pcService, + const char* p_pcProtocol, + stcMDNS_RRDomain& p_rServiceDomain) const; #ifdef MDNS_IP4_SUPPORT - bool _buildDomainForReverseIP4(IPAddress p_IP4Address, - stcMDNS_RRDomain& p_rReverseIP4Domain) const; + bool _buildDomainForReverseIP4(IPAddress p_IP4Address, + stcMDNS_RRDomain& p_rReverseIP4Domain) const; #endif #ifdef MDNS_IP6_SUPPORT - bool _buildDomainForReverseIP6(IPAddress p_IP4Address, - stcMDNS_RRDomain& p_rReverseIP6Domain) const; + bool _buildDomainForReverseIP6(IPAddress p_IP4Address, + stcMDNS_RRDomain& p_rReverseIP6Domain) const; #endif - /* UDP */ - bool _udpReadBuffer(unsigned char* p_pBuffer, - size_t p_stLength); - bool _udpRead8(uint8_t& p_ru8Value); - bool _udpRead16(uint16_t& p_ru16Value); - bool _udpRead32(uint32_t& p_ru32Value); + /* UDP */ + bool _udpReadBuffer(unsigned char* p_pBuffer, + size_t p_stLength); + bool _udpRead8(uint8_t& p_ru8Value); + bool _udpRead16(uint16_t& p_ru16Value); + bool _udpRead32(uint32_t& p_ru32Value); - bool _udpAppendBuffer(const unsigned char* p_pcBuffer, - size_t p_stLength); - bool _udpAppend8(uint8_t p_u8Value); - bool _udpAppend16(uint16_t p_u16Value); - bool _udpAppend32(uint32_t p_u32Value); + bool _udpAppendBuffer(const unsigned char* p_pcBuffer, + size_t p_stLength); + bool _udpAppend8(uint8_t p_u8Value); + bool _udpAppend16(uint16_t p_u16Value); + bool _udpAppend32(uint32_t p_u32Value); #if not defined ESP_8266_MDNS_INCLUDE || defined DEBUG_ESP_MDNS_RESPONDER - bool _udpDump(bool p_bMovePointer = false); - bool _udpDump(unsigned p_uOffset, - unsigned p_uLength); + bool _udpDump(bool p_bMovePointer = false); + bool _udpDump(unsigned p_uOffset, + unsigned p_uLength); #endif - /* READ/WRITE MDNS STRUCTS */ - bool _readMDNSMsgHeader(stcMDNS_MsgHeader& p_rMsgHeader); - - bool _write8(uint8_t p_u8Value, - stcMDNSSendParameter& p_rSendParameter); - bool _write16(uint16_t p_u16Value, - stcMDNSSendParameter& p_rSendParameter); - bool _write32(uint32_t p_u32Value, - stcMDNSSendParameter& p_rSendParameter); - - bool _writeMDNSMsgHeader(const stcMDNS_MsgHeader& p_MsgHeader, - stcMDNSSendParameter& p_rSendParameter); - bool _writeMDNSRRAttributes(const stcMDNS_RRAttributes& p_Attributes, - stcMDNSSendParameter& p_rSendParameter); - bool _writeMDNSRRDomain(const stcMDNS_RRDomain& p_Domain, - stcMDNSSendParameter& p_rSendParameter); - bool _writeMDNSHostDomain(const char* m_pcHostname, - bool p_bPrependRDLength, - stcMDNSSendParameter& p_rSendParameter); - bool _writeMDNSServiceDomain(const stcMDNSService& p_Service, - bool p_bIncludeName, - bool p_bPrependRDLength, - stcMDNSSendParameter& p_rSendParameter); - - bool _writeMDNSQuestion(stcMDNS_RRQuestion& p_Question, - stcMDNSSendParameter& p_rSendParameter); + /* READ/WRITE MDNS STRUCTS */ + bool _readMDNSMsgHeader(stcMDNS_MsgHeader& p_rMsgHeader); + + bool _write8(uint8_t p_u8Value, + stcMDNSSendParameter& p_rSendParameter); + bool _write16(uint16_t p_u16Value, + stcMDNSSendParameter& p_rSendParameter); + bool _write32(uint32_t p_u32Value, + stcMDNSSendParameter& p_rSendParameter); + + bool _writeMDNSMsgHeader(const stcMDNS_MsgHeader& p_MsgHeader, + stcMDNSSendParameter& p_rSendParameter); + bool _writeMDNSRRAttributes(const stcMDNS_RRAttributes& p_Attributes, + stcMDNSSendParameter& p_rSendParameter); + bool _writeMDNSRRDomain(const stcMDNS_RRDomain& p_Domain, + stcMDNSSendParameter& p_rSendParameter); + bool _writeMDNSHostDomain(const char* m_pcHostname, + bool p_bPrependRDLength, + stcMDNSSendParameter& p_rSendParameter); + bool _writeMDNSServiceDomain(const stcMDNSService& p_Service, + bool p_bIncludeName, + bool p_bPrependRDLength, + stcMDNSSendParameter& p_rSendParameter); + + bool _writeMDNSQuestion(stcMDNS_RRQuestion& p_Question, + stcMDNSSendParameter& p_rSendParameter); #ifdef MDNS_IP4_SUPPORT - bool _writeMDNSAnswer_A(IPAddress p_IPAddress, - stcMDNSSendParameter& p_rSendParameter); - bool _writeMDNSAnswer_PTR_IP4(IPAddress p_IPAddress, - stcMDNSSendParameter& p_rSendParameter); + bool _writeMDNSAnswer_A(IPAddress p_IPAddress, + stcMDNSSendParameter& p_rSendParameter); + bool _writeMDNSAnswer_PTR_IP4(IPAddress p_IPAddress, + stcMDNSSendParameter& p_rSendParameter); #endif - bool _writeMDNSAnswer_PTR_TYPE(stcMDNSService& p_rService, - stcMDNSSendParameter& p_rSendParameter); - bool _writeMDNSAnswer_PTR_NAME(stcMDNSService& p_rService, - stcMDNSSendParameter& p_rSendParameter); - bool _writeMDNSAnswer_TXT(stcMDNSService& p_rService, - stcMDNSSendParameter& p_rSendParameter); + bool _writeMDNSAnswer_PTR_TYPE(stcMDNSService& p_rService, + stcMDNSSendParameter& p_rSendParameter); + bool _writeMDNSAnswer_PTR_NAME(stcMDNSService& p_rService, + stcMDNSSendParameter& p_rSendParameter); + bool _writeMDNSAnswer_TXT(stcMDNSService& p_rService, + stcMDNSSendParameter& p_rSendParameter); #ifdef MDNS_IP6_SUPPORT - bool _writeMDNSAnswer_AAAA(IPAddress p_IPAddress, - stcMDNSSendParameter& p_rSendParameter); - bool _writeMDNSAnswer_PTR_IP6(IPAddress p_IPAddress, - stcMDNSSendParameter& p_rSendParameter); + bool _writeMDNSAnswer_AAAA(IPAddress p_IPAddress, + stcMDNSSendParameter& p_rSendParameter); + bool _writeMDNSAnswer_PTR_IP6(IPAddress p_IPAddress, + stcMDNSSendParameter& p_rSendParameter); #endif - bool _writeMDNSAnswer_SRV(stcMDNSService& p_rService, - stcMDNSSendParameter& p_rSendParameter); - - /** HELPERS **/ - /* UDP CONTEXT */ - bool _callProcess(void); - bool _allocUDPContext(void); - bool _releaseUDPContext(void); - - /* SERVICE QUERY */ - stcMDNSServiceQuery* _allocServiceQuery(void); - bool _removeServiceQuery(stcMDNSServiceQuery* p_pServiceQuery); - bool _removeLegacyServiceQuery(void); - stcMDNSServiceQuery* _findServiceQuery(hMDNSServiceQuery p_hServiceQuery); - stcMDNSServiceQuery* _findLegacyServiceQuery(void); - bool _releaseServiceQueries(void); - stcMDNSServiceQuery* _findNextServiceQueryByServiceType(const stcMDNS_RRDomain& p_ServiceDomain, - const stcMDNSServiceQuery* p_pPrevServiceQuery); - - /* HOSTNAME */ - bool _setHostname(const char* p_pcHostname); - bool _releaseHostname(void); - - /* SERVICE */ - stcMDNSService* _allocService(const char* p_pcName, - const char* p_pcService, - const char* p_pcProtocol, - uint16_t p_u16Port); - bool _releaseService(stcMDNSService* p_pService); - bool _releaseServices(void); - - stcMDNSService* _findService(const char* p_pcName, - const char* p_pcService, - const char* p_pcProtocol); - stcMDNSService* _findService(const hMDNSService p_hService); - - size_t _countServices(void) const; - - /* SERVICE TXT */ - stcMDNSServiceTxt* _allocServiceTxt(stcMDNSService* p_pService, - const char* p_pcKey, - const char* p_pcValue, - bool p_bTemp); - bool _releaseServiceTxt(stcMDNSService* p_pService, - stcMDNSServiceTxt* p_pTxt); - stcMDNSServiceTxt* _updateServiceTxt(stcMDNSService* p_pService, - stcMDNSServiceTxt* p_pTxt, - const char* p_pcValue, - bool p_bTemp); - - stcMDNSServiceTxt* _findServiceTxt(stcMDNSService* p_pService, - const char* p_pcKey); - stcMDNSServiceTxt* _findServiceTxt(stcMDNSService* p_pService, - const hMDNSTxt p_hTxt); - - stcMDNSServiceTxt* _addServiceTxt(stcMDNSService* p_pService, - const char* p_pcKey, - const char* p_pcValue, - bool p_bTemp); - - stcMDNSServiceTxt* _answerKeyValue(const hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex); - - bool _collectServiceTxts(stcMDNSService& p_rService); - bool _releaseTempServiceTxts(stcMDNSService& p_rService); - const stcMDNSServiceTxt* _serviceTxts(const char* p_pcName, - const char* p_pcService, - const char* p_pcProtocol); - - /* MISC */ + bool _writeMDNSAnswer_SRV(stcMDNSService& p_rService, + stcMDNSSendParameter& p_rSendParameter); + + /** HELPERS **/ + /* UDP CONTEXT */ + bool _callProcess(void); + bool _allocUDPContext(void); + bool _releaseUDPContext(void); + + /* SERVICE QUERY */ + stcMDNSServiceQuery* _allocServiceQuery(void); + bool _removeServiceQuery(stcMDNSServiceQuery* p_pServiceQuery); + bool _removeLegacyServiceQuery(void); + stcMDNSServiceQuery* _findServiceQuery(hMDNSServiceQuery p_hServiceQuery); + stcMDNSServiceQuery* _findLegacyServiceQuery(void); + bool _releaseServiceQueries(void); + stcMDNSServiceQuery* _findNextServiceQueryByServiceType(const stcMDNS_RRDomain& p_ServiceDomain, + const stcMDNSServiceQuery* p_pPrevServiceQuery); + + /* HOSTNAME */ + bool _setHostname(const char* p_pcHostname); + bool _releaseHostname(void); + + /* SERVICE */ + stcMDNSService* _allocService(const char* p_pcName, + const char* p_pcService, + const char* p_pcProtocol, + uint16_t p_u16Port); + bool _releaseService(stcMDNSService* p_pService); + bool _releaseServices(void); + + stcMDNSService* _findService(const char* p_pcName, + const char* p_pcService, + const char* p_pcProtocol); + stcMDNSService* _findService(const hMDNSService p_hService); + + size_t _countServices(void) const; + + /* SERVICE TXT */ + stcMDNSServiceTxt* _allocServiceTxt(stcMDNSService* p_pService, + const char* p_pcKey, + const char* p_pcValue, + bool p_bTemp); + bool _releaseServiceTxt(stcMDNSService* p_pService, + stcMDNSServiceTxt* p_pTxt); + stcMDNSServiceTxt* _updateServiceTxt(stcMDNSService* p_pService, + stcMDNSServiceTxt* p_pTxt, + const char* p_pcValue, + bool p_bTemp); + + stcMDNSServiceTxt* _findServiceTxt(stcMDNSService* p_pService, + const char* p_pcKey); + stcMDNSServiceTxt* _findServiceTxt(stcMDNSService* p_pService, + const hMDNSTxt p_hTxt); + + stcMDNSServiceTxt* _addServiceTxt(stcMDNSService* p_pService, + const char* p_pcKey, + const char* p_pcValue, + bool p_bTemp); + + stcMDNSServiceTxt* _answerKeyValue(const hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex); + + bool _collectServiceTxts(stcMDNSService& p_rService); + bool _releaseTempServiceTxts(stcMDNSService& p_rService); + const stcMDNSServiceTxt* _serviceTxts(const char* p_pcName, + const char* p_pcService, + const char* p_pcProtocol); + + /* MISC */ #if not defined ESP_8266_MDNS_INCLUDE || defined DEBUG_ESP_MDNS_RESPONDER - bool _printRRDomain(const stcMDNS_RRDomain& p_rRRDomain) const; - bool _printRRAnswer(const MDNSResponder::stcMDNS_RRAnswer& p_RRAnswer) const; + bool _printRRDomain(const stcMDNS_RRDomain& p_rRRDomain) const; + bool _printRRAnswer(const MDNSResponder::stcMDNS_RRAnswer& p_RRAnswer) const; #endif -}; + }; } // namespace MDNSImplementation diff --git a/libraries/ESP8266mDNS/src/LEAmDNS_Control.cpp b/libraries/ESP8266mDNS/src/LEAmDNS_Control.cpp index 7b66d086af..4c3be2b063 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS_Control.cpp +++ b/libraries/ESP8266mDNS/src/LEAmDNS_Control.cpp @@ -49,15 +49,15 @@ namespace esp8266 */ namespace MDNSImplementation { -/** + /** CONTROL */ -/** + /** MAINTENANCE */ -/* + /* MDNSResponder::_process Run the MDNS process. @@ -65,90 +65,90 @@ namespace MDNSImplementation should be called in every 'loop' by calling 'MDNS::update()'. */ -bool MDNSResponder::_process(bool p_bUserContext) -{ - bool bResult = true; - - if (!p_bUserContext) + bool MDNSResponder::_process(bool p_bUserContext) { - if ((m_pUDPContext) && // UDPContext available AND - (m_pUDPContext->next())) // has content + bool bResult = true; + + if (!p_bUserContext) { - //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _update: Calling _parseMessage\n"));); - bResult = _parseMessage(); - //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parsePacket %s\n"), (bResult ? "succeeded" : "FAILED"));); + if ((m_pUDPContext) && // UDPContext available AND + (m_pUDPContext->next())) // has content + { + //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _update: Calling _parseMessage\n"));); + bResult = _parseMessage(); + //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parsePacket %s\n"), (bResult ? "succeeded" : "FAILED"));); + } } + else + { + bResult = _updateProbeStatus() && // Probing + _checkServiceQueryCache(); // Service query cache check + } + return bResult; } - else - { - bResult = _updateProbeStatus() && // Probing - _checkServiceQueryCache(); // Service query cache check - } - return bResult; -} -/* + /* MDNSResponder::_restart */ -bool MDNSResponder::_restart(void) -{ - return ((_resetProbeStatus(true /*restart*/)) && // Stop and restart probing - (_allocUDPContext())); // Restart UDP -} + bool MDNSResponder::_restart(void) + { + return ((_resetProbeStatus(true /*restart*/)) && // Stop and restart probing + (_allocUDPContext())); // Restart UDP + } -/** + /** RECEIVING */ -/* + /* MDNSResponder::_parseMessage */ -bool MDNSResponder::_parseMessage(void) -{ - DEBUG_EX_INFO( - unsigned long ulStartTime = millis(); - unsigned uStartMemory = ESP.getFreeHeap(); - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseMessage (Time: %lu ms, heap: %u bytes, from %s(%u), to %s(%u))\n"), ulStartTime, uStartMemory, - IPAddress(m_pUDPContext->getRemoteAddress()).toString().c_str(), m_pUDPContext->getRemotePort(), - IPAddress(m_pUDPContext->getDestAddress()).toString().c_str(), m_pUDPContext->getLocalPort());); - //DEBUG_EX_INFO(_udpDump();); - - bool bResult = false; - - stcMDNS_MsgHeader header; - if (_readMDNSMsgHeader(header)) + bool MDNSResponder::_parseMessage(void) { - if (0 == header.m_4bOpcode) // A standard query + DEBUG_EX_INFO( + unsigned long ulStartTime = millis(); + unsigned uStartMemory = ESP.getFreeHeap(); + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseMessage (Time: %lu ms, heap: %u bytes, from %s(%u), to %s(%u))\n"), ulStartTime, uStartMemory, + IPAddress(m_pUDPContext->getRemoteAddress()).toString().c_str(), m_pUDPContext->getRemotePort(), + IPAddress(m_pUDPContext->getDestAddress()).toString().c_str(), m_pUDPContext->getLocalPort());); + //DEBUG_EX_INFO(_udpDump();); + + bool bResult = false; + + stcMDNS_MsgHeader header; + if (_readMDNSMsgHeader(header)) { - if (header.m_1bQR) // Received a response -> answers to a query + if (0 == header.m_4bOpcode) // A standard query { - //DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseMessage: Reading answers: ID:%u, Q:%u, A:%u, NS:%u, AR:%u\n"), header.m_u16ID, header.m_u16QDCount, header.m_u16ANCount, header.m_u16NSCount, header.m_u16ARCount);); - bResult = _parseResponse(header); + if (header.m_1bQR) // Received a response -> answers to a query + { + //DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseMessage: Reading answers: ID:%u, Q:%u, A:%u, NS:%u, AR:%u\n"), header.m_u16ID, header.m_u16QDCount, header.m_u16ANCount, header.m_u16NSCount, header.m_u16ARCount);); + bResult = _parseResponse(header); + } + else // Received a query (Questions) + { + //DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseMessage: Reading query: ID:%u, Q:%u, A:%u, NS:%u, AR:%u\n"), header.m_u16ID, header.m_u16QDCount, header.m_u16ANCount, header.m_u16NSCount, header.m_u16ARCount);); + bResult = _parseQuery(header); + } } - else // Received a query (Questions) + else { - //DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseMessage: Reading query: ID:%u, Q:%u, A:%u, NS:%u, AR:%u\n"), header.m_u16ID, header.m_u16QDCount, header.m_u16ANCount, header.m_u16NSCount, header.m_u16ARCount);); - bResult = _parseQuery(header); + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseMessage: Received UNEXPECTED opcode:%u. Ignoring message!\n"), header.m_4bOpcode);); + m_pUDPContext->flush(); } } else { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseMessage: Received UNEXPECTED opcode:%u. Ignoring message!\n"), header.m_4bOpcode);); + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseMessage: FAILED to read header\n"));); m_pUDPContext->flush(); } + DEBUG_EX_INFO( + unsigned uFreeHeap = ESP.getFreeHeap(); + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseMessage: Done (%s after %lu ms, ate %i bytes, remaining %u)\n\n"), (bResult ? "Succeeded" : "FAILED"), (millis() - ulStartTime), (uStartMemory - uFreeHeap), uFreeHeap);); + return bResult; } - else - { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseMessage: FAILED to read header\n"));); - m_pUDPContext->flush(); - } - DEBUG_EX_INFO( - unsigned uFreeHeap = ESP.getFreeHeap(); - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseMessage: Done (%s after %lu ms, ate %i bytes, remaining %u)\n\n"), (bResult ? "Succeeded" : "FAILED"), (millis() - ulStartTime), (uStartMemory - uFreeHeap), uFreeHeap);); - return bResult; -} -/* + /* MDNSResponder::_parseQuery Queries are of interest in two cases: @@ -165,412 +165,393 @@ bool MDNSResponder::_parseMessage(void) 1. */ -bool MDNSResponder::_parseQuery(const MDNSResponder::stcMDNS_MsgHeader& p_MsgHeader) -{ - bool bResult = true; - - stcMDNSSendParameter sendParameter; - uint8_t u8HostOrServiceReplies = 0; - for (uint16_t qd = 0; ((bResult) && (qd < p_MsgHeader.m_u16QDCount)); ++qd) + bool MDNSResponder::_parseQuery(const MDNSResponder::stcMDNS_MsgHeader& p_MsgHeader) { - stcMDNS_RRQuestion questionRR; - if ((bResult = _readRRQuestion(questionRR))) + bool bResult = true; + + stcMDNSSendParameter sendParameter; + uint8_t u8HostOrServiceReplies = 0; + for (uint16_t qd = 0; ((bResult) && (qd < p_MsgHeader.m_u16QDCount)); ++qd) { - // Define host replies, BUT only answer queries after probing is done - u8HostOrServiceReplies = - sendParameter.m_u8HostReplyMask |= (((ProbingStatus_Done == m_HostProbeInformation.m_ProbingStatus)) - ? _replyMaskForHost(questionRR.m_Header, 0) - : 0); - DEBUG_EX_INFO(if (u8HostOrServiceReplies) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Host reply needed 0x%X\n"), u8HostOrServiceReplies); - }); - - // Check tiebreak need for host domain - if (ProbingStatus_InProgress == m_HostProbeInformation.m_ProbingStatus) + stcMDNS_RRQuestion questionRR; + if ((bResult = _readRRQuestion(questionRR))) { - bool bFullNameMatch = false; - if ((_replyMaskForHost(questionRR.m_Header, &bFullNameMatch)) && - (bFullNameMatch)) - { - // We're in 'probing' state and someone is asking for our host domain: this might be - // a race-condition: Two host with the same domain names try simutanously to probe their domains - // See: RFC 6762, 8.2 (Tiebraking) - // However, we're using a max. reduced approach for tiebreaking here: The higher IP-address wins! - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Possible race-condition for host domain detected while probing.\n"));); - - m_HostProbeInformation.m_bTiebreakNeeded = true; - } - } + // Define host replies, BUT only answer queries after probing is done + u8HostOrServiceReplies = sendParameter.m_u8HostReplyMask |= (((ProbingStatus_Done == m_HostProbeInformation.m_ProbingStatus)) + ? _replyMaskForHost(questionRR.m_Header, 0) + : 0); + DEBUG_EX_INFO(if (u8HostOrServiceReplies) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Host reply needed 0x%X\n"), u8HostOrServiceReplies); + }); - // Define service replies - for (stcMDNSService* pService = m_pServices; pService; pService = pService->m_pNext) - { - // Define service replies, BUT only answer queries after probing is done - uint8_t u8ReplyMaskForQuestion = (((ProbingStatus_Done == pService->m_ProbeInformation.m_ProbingStatus)) - ? _replyMaskForService(questionRR.m_Header, *pService, 0) - : 0); - u8HostOrServiceReplies |= (pService->m_u8ReplyMask |= u8ReplyMaskForQuestion); - DEBUG_EX_INFO(if (u8ReplyMaskForQuestion) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Service reply needed for (%s.%s.%s): 0x%X (%s)\n"), (pService->m_pcName ?: m_pcHostname), pService->m_pcService, pService->m_pcProtocol, u8ReplyMaskForQuestion, IPAddress(m_pUDPContext->getRemoteAddress()).toString().c_str()); - }); - - // Check tiebreak need for service domain - if (ProbingStatus_InProgress == pService->m_ProbeInformation.m_ProbingStatus) + // Check tiebreak need for host domain + if (ProbingStatus_InProgress == m_HostProbeInformation.m_ProbingStatus) { bool bFullNameMatch = false; - if ((_replyMaskForService(questionRR.m_Header, *pService, &bFullNameMatch)) && - (bFullNameMatch)) + if ((_replyMaskForHost(questionRR.m_Header, &bFullNameMatch)) && (bFullNameMatch)) { - // We're in 'probing' state and someone is asking for this service domain: this might be - // a race-condition: Two services with the same domain names try simutanously to probe their domains + // We're in 'probing' state and someone is asking for our host domain: this might be + // a race-condition: Two host with the same domain names try simutanously to probe their domains // See: RFC 6762, 8.2 (Tiebraking) - // However, we're using a max. reduced approach for tiebreaking here: The 'higher' SRV host wins! - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Possible race-condition for service domain %s.%s.%s detected while probing.\n"), (pService->m_pcName ?: m_pcHostname), pService->m_pcService, pService->m_pcProtocol);); + // However, we're using a max. reduced approach for tiebreaking here: The higher IP-address wins! + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Possible race-condition for host domain detected while probing.\n"));); - pService->m_ProbeInformation.m_bTiebreakNeeded = true; + m_HostProbeInformation.m_bTiebreakNeeded = true; } } - } - // Handle unicast and legacy specialities - // If only one question asks for unicast reply, the whole reply packet is send unicast - if (((DNS_MQUERY_PORT != m_pUDPContext->getRemotePort()) || // Unicast (maybe legacy) query OR - (questionRR.m_bUnicast)) && // Expressivly unicast query - (!sendParameter.m_bUnicast)) - { - sendParameter.m_bUnicast = true; - sendParameter.m_bCacheFlush = false; - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Unicast response for %s!\n"), IPAddress(m_pUDPContext->getRemoteAddress()).toString().c_str());); - - if ((DNS_MQUERY_PORT != m_pUDPContext->getRemotePort()) && // Unicast (maybe legacy) query AND - (1 == p_MsgHeader.m_u16QDCount) && // Only one question AND - ((sendParameter.m_u8HostReplyMask) || // Host replies OR - (u8HostOrServiceReplies))) // Host or service replies available + // Define service replies + for (stcMDNSService* pService = m_pServices; pService; pService = pService->m_pNext) { - // We're a match for this legacy query, BUT - // make sure, that the query comes from a local host - ip_info IPInfo_Local; - ip_info IPInfo_Remote; - if (((IPInfo_Remote.ip.addr = m_pUDPContext->getRemoteAddress())) && - (((wifi_get_ip_info(SOFTAP_IF, &IPInfo_Local)) && - (ip4_addr_netcmp(&IPInfo_Remote.ip, &IPInfo_Local.ip, &IPInfo_Local.netmask))) || // Remote IP in SOFTAP's subnet OR - ((wifi_get_ip_info(STATION_IF, &IPInfo_Local)) && - (ip4_addr_netcmp(&IPInfo_Remote.ip, &IPInfo_Local.ip, &IPInfo_Local.netmask))))) // Remote IP in STATION's subnet + // Define service replies, BUT only answer queries after probing is done + uint8_t u8ReplyMaskForQuestion = (((ProbingStatus_Done == pService->m_ProbeInformation.m_ProbingStatus)) + ? _replyMaskForService(questionRR.m_Header, *pService, 0) + : 0); + u8HostOrServiceReplies |= (pService->m_u8ReplyMask |= u8ReplyMaskForQuestion); + DEBUG_EX_INFO(if (u8ReplyMaskForQuestion) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Service reply needed for (%s.%s.%s): 0x%X (%s)\n"), (pService->m_pcName ?: m_pcHostname), pService->m_pcService, pService->m_pcProtocol, u8ReplyMaskForQuestion, IPAddress(m_pUDPContext->getRemoteAddress()).toString().c_str()); + }); + + // Check tiebreak need for service domain + if (ProbingStatus_InProgress == pService->m_ProbeInformation.m_ProbingStatus) { - DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Legacy query from local host %s, id %u!\n"), IPAddress(m_pUDPContext->getRemoteAddress()).toString().c_str(), p_MsgHeader.m_u16ID);); + bool bFullNameMatch = false; + if ((_replyMaskForService(questionRR.m_Header, *pService, &bFullNameMatch)) && (bFullNameMatch)) + { + // We're in 'probing' state and someone is asking for this service domain: this might be + // a race-condition: Two services with the same domain names try simutanously to probe their domains + // See: RFC 6762, 8.2 (Tiebraking) + // However, we're using a max. reduced approach for tiebreaking here: The 'higher' SRV host wins! + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Possible race-condition for service domain %s.%s.%s detected while probing.\n"), (pService->m_pcName ?: m_pcHostname), pService->m_pcService, pService->m_pcProtocol);); + + pService->m_ProbeInformation.m_bTiebreakNeeded = true; + } + } + } - sendParameter.m_u16ID = p_MsgHeader.m_u16ID; - sendParameter.m_bLegacyQuery = true; - sendParameter.m_pQuestions = new stcMDNS_RRQuestion; - if ((bResult = (0 != sendParameter.m_pQuestions))) + // Handle unicast and legacy specialities + // If only one question asks for unicast reply, the whole reply packet is send unicast + if (((DNS_MQUERY_PORT != m_pUDPContext->getRemotePort()) || // Unicast (maybe legacy) query OR + (questionRR.m_bUnicast)) + && // Expressivly unicast query + (!sendParameter.m_bUnicast)) + { + sendParameter.m_bUnicast = true; + sendParameter.m_bCacheFlush = false; + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Unicast response for %s!\n"), IPAddress(m_pUDPContext->getRemoteAddress()).toString().c_str());); + + if ((DNS_MQUERY_PORT != m_pUDPContext->getRemotePort()) && // Unicast (maybe legacy) query AND + (1 == p_MsgHeader.m_u16QDCount) && // Only one question AND + ((sendParameter.m_u8HostReplyMask) || // Host replies OR + (u8HostOrServiceReplies))) // Host or service replies available + { + // We're a match for this legacy query, BUT + // make sure, that the query comes from a local host + ip_info IPInfo_Local; + ip_info IPInfo_Remote; + if (((IPInfo_Remote.ip.addr = m_pUDPContext->getRemoteAddress())) && (((wifi_get_ip_info(SOFTAP_IF, &IPInfo_Local)) && (ip4_addr_netcmp(&IPInfo_Remote.ip, &IPInfo_Local.ip, &IPInfo_Local.netmask))) || // Remote IP in SOFTAP's subnet OR + ((wifi_get_ip_info(STATION_IF, &IPInfo_Local)) && (ip4_addr_netcmp(&IPInfo_Remote.ip, &IPInfo_Local.ip, &IPInfo_Local.netmask))))) // Remote IP in STATION's subnet { - sendParameter.m_pQuestions->m_Header.m_Domain = questionRR.m_Header.m_Domain; - sendParameter.m_pQuestions->m_Header.m_Attributes.m_u16Type = questionRR.m_Header.m_Attributes.m_u16Type; - sendParameter.m_pQuestions->m_Header.m_Attributes.m_u16Class = questionRR.m_Header.m_Attributes.m_u16Class; + DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Legacy query from local host %s, id %u!\n"), IPAddress(m_pUDPContext->getRemoteAddress()).toString().c_str(), p_MsgHeader.m_u16ID);); + + sendParameter.m_u16ID = p_MsgHeader.m_u16ID; + sendParameter.m_bLegacyQuery = true; + sendParameter.m_pQuestions = new stcMDNS_RRQuestion; + if ((bResult = (0 != sendParameter.m_pQuestions))) + { + sendParameter.m_pQuestions->m_Header.m_Domain = questionRR.m_Header.m_Domain; + sendParameter.m_pQuestions->m_Header.m_Attributes.m_u16Type = questionRR.m_Header.m_Attributes.m_u16Type; + sendParameter.m_pQuestions->m_Header.m_Attributes.m_u16Class = questionRR.m_Header.m_Attributes.m_u16Class; + } + else + { + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: FAILED to add legacy question!\n"));); + } } else { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: FAILED to add legacy question!\n"));); + DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Legacy query from NON-LOCAL host!\n"));); + bResult = false; } } - else - { - DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Legacy query from NON-LOCAL host!\n"));); - bResult = false; - } } } - } - else - { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: FAILED to read question!\n"));); - } - } // for questions + else + { + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: FAILED to read question!\n"));); + } + } // for questions - //DEBUG_EX_INFO(if (u8HostOrServiceReplies) { DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Reply needed: %u (%s: %s->%s)\n"), u8HostOrServiceReplies, clsTimeSyncer::timestr(), IPAddress(m_pUDPContext->getRemoteAddress()).toString().c_str(), IPAddress(m_pUDPContext->getDestAddress()).toString().c_str()); } ); + //DEBUG_EX_INFO(if (u8HostOrServiceReplies) { DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Reply needed: %u (%s: %s->%s)\n"), u8HostOrServiceReplies, clsTimeSyncer::timestr(), IPAddress(m_pUDPContext->getRemoteAddress()).toString().c_str(), IPAddress(m_pUDPContext->getDestAddress()).toString().c_str()); } ); - // Handle known answers - uint32_t u32Answers = (p_MsgHeader.m_u16ANCount + p_MsgHeader.m_u16NSCount + p_MsgHeader.m_u16ARCount); - DEBUG_EX_INFO(if ((u8HostOrServiceReplies) && (u32Answers)) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Known answers(%u):\n"), u32Answers); - }); + // Handle known answers + uint32_t u32Answers = (p_MsgHeader.m_u16ANCount + p_MsgHeader.m_u16NSCount + p_MsgHeader.m_u16ARCount); + DEBUG_EX_INFO(if ((u8HostOrServiceReplies) && (u32Answers)) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Known answers(%u):\n"), u32Answers); + }); - for (uint32_t an = 0; ((bResult) && (an < u32Answers)); ++an) - { - stcMDNS_RRAnswer* pKnownRRAnswer = 0; - if (((bResult = _readRRAnswer(pKnownRRAnswer))) && - (pKnownRRAnswer)) + for (uint32_t an = 0; ((bResult) && (an < u32Answers)); ++an) { - if ((DNS_RRTYPE_ANY != pKnownRRAnswer->m_Header.m_Attributes.m_u16Type) && // No ANY type answer - (DNS_RRCLASS_ANY != pKnownRRAnswer->m_Header.m_Attributes.m_u16Class)) // No ANY class answer + stcMDNS_RRAnswer* pKnownRRAnswer = 0; + if (((bResult = _readRRAnswer(pKnownRRAnswer))) && (pKnownRRAnswer)) { - // Find match between planned answer (sendParameter.m_u8HostReplyMask) and this 'known answer' - uint8_t u8HostMatchMask = (sendParameter.m_u8HostReplyMask & _replyMaskForHost(pKnownRRAnswer->m_Header)); - if ((u8HostMatchMask) && // The RR in the known answer matches an RR we are planning to send, AND - ((MDNS_HOST_TTL / 2) <= pKnownRRAnswer->m_u32TTL)) // The TTL of the known answer is longer than half of the new host TTL (120s) + if ((DNS_RRTYPE_ANY != pKnownRRAnswer->m_Header.m_Attributes.m_u16Type) && // No ANY type answer + (DNS_RRCLASS_ANY != pKnownRRAnswer->m_Header.m_Attributes.m_u16Class)) // No ANY class answer { - // Compare contents - if (AnswerType_PTR == pKnownRRAnswer->answerType()) + // Find match between planned answer (sendParameter.m_u8HostReplyMask) and this 'known answer' + uint8_t u8HostMatchMask = (sendParameter.m_u8HostReplyMask & _replyMaskForHost(pKnownRRAnswer->m_Header)); + if ((u8HostMatchMask) && // The RR in the known answer matches an RR we are planning to send, AND + ((MDNS_HOST_TTL / 2) <= pKnownRRAnswer->m_u32TTL)) // The TTL of the known answer is longer than half of the new host TTL (120s) { - stcMDNS_RRDomain hostDomain; - if ((_buildDomainForHost(m_pcHostname, hostDomain)) && - (((stcMDNS_RRAnswerPTR*)pKnownRRAnswer)->m_PTRDomain == hostDomain)) + // Compare contents + if (AnswerType_PTR == pKnownRRAnswer->answerType()) { - // Host domain match -#ifdef MDNS_IP4_SUPPORT - if (u8HostMatchMask & ContentFlag_PTR_IP4) + stcMDNS_RRDomain hostDomain; + if ((_buildDomainForHost(m_pcHostname, hostDomain)) && (((stcMDNS_RRAnswerPTR*)pKnownRRAnswer)->m_PTRDomain == hostDomain)) { - // IP4 PTR was asked for, but is already known -> skipping - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: IP4 PTR already known... skipping!\n"));); - sendParameter.m_u8HostReplyMask &= ~ContentFlag_PTR_IP4; - } + // Host domain match +#ifdef MDNS_IP4_SUPPORT + if (u8HostMatchMask & ContentFlag_PTR_IP4) + { + // IP4 PTR was asked for, but is already known -> skipping + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: IP4 PTR already known... skipping!\n"));); + sendParameter.m_u8HostReplyMask &= ~ContentFlag_PTR_IP4; + } #endif #ifdef MDNS_IP6_SUPPORT - if (u8HostMatchMask & ContentFlag_PTR_IP6) - { - // IP6 PTR was asked for, but is already known -> skipping - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: IP6 PTR already known... skipping!\n"));); - sendParameter.m_u8HostReplyMask &= ~ContentFlag_PTR_IP6; - } + if (u8HostMatchMask & ContentFlag_PTR_IP6) + { + // IP6 PTR was asked for, but is already known -> skipping + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: IP6 PTR already known... skipping!\n"));); + sendParameter.m_u8HostReplyMask &= ~ContentFlag_PTR_IP6; + } #endif + } } - } - else if (u8HostMatchMask & ContentFlag_A) - { - // IP4 address was asked for -#ifdef MDNS_IP4_SUPPORT - if ((AnswerType_A == pKnownRRAnswer->answerType()) && - (((stcMDNS_RRAnswerA*)pKnownRRAnswer)->m_IPAddress == m_pUDPContext->getInputNetif()->ip_addr)) + else if (u8HostMatchMask & ContentFlag_A) { - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: IP4 address already known... skipping!\n"));); - sendParameter.m_u8HostReplyMask &= ~ContentFlag_A; - } // else: RData NOT IP4 length !! + // IP4 address was asked for +#ifdef MDNS_IP4_SUPPORT + if ((AnswerType_A == pKnownRRAnswer->answerType()) && (((stcMDNS_RRAnswerA*)pKnownRRAnswer)->m_IPAddress == m_pUDPContext->getInputNetif()->ip_addr)) + { + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: IP4 address already known... skipping!\n"));); + sendParameter.m_u8HostReplyMask &= ~ContentFlag_A; + } // else: RData NOT IP4 length !! #endif - } - else if (u8HostMatchMask & ContentFlag_AAAA) - { - // IP6 address was asked for -#ifdef MDNS_IP6_SUPPORT - if ((AnswerType_AAAA == pAnswerRR->answerType()) && - (((stcMDNS_RRAnswerAAAA*)pAnswerRR)->m_IPAddress == _getResponseMulticastInterface())) + } + else if (u8HostMatchMask & ContentFlag_AAAA) { - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: IP6 address already known... skipping!\n"));); - sendParameter.m_u8HostReplyMask &= ~ContentFlag_AAAA; - } // else: RData NOT IP6 length !! + // IP6 address was asked for +#ifdef MDNS_IP6_SUPPORT + if ((AnswerType_AAAA == pAnswerRR->answerType()) && (((stcMDNS_RRAnswerAAAA*)pAnswerRR)->m_IPAddress == _getResponseMulticastInterface())) + { + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: IP6 address already known... skipping!\n"));); + sendParameter.m_u8HostReplyMask &= ~ContentFlag_AAAA; + } // else: RData NOT IP6 length !! #endif - } - } // Host match /*and TTL*/ + } + } // Host match /*and TTL*/ - // - // Check host tiebreak possibility - if (m_HostProbeInformation.m_bTiebreakNeeded) - { - stcMDNS_RRDomain hostDomain; - if ((_buildDomainForHost(m_pcHostname, hostDomain)) && - (pKnownRRAnswer->m_Header.m_Domain == hostDomain)) + // + // Check host tiebreak possibility + if (m_HostProbeInformation.m_bTiebreakNeeded) { - // Host domain match -#ifdef MDNS_IP4_SUPPORT - if (AnswerType_A == pKnownRRAnswer->answerType()) + stcMDNS_RRDomain hostDomain; + if ((_buildDomainForHost(m_pcHostname, hostDomain)) && (pKnownRRAnswer->m_Header.m_Domain == hostDomain)) { - IPAddress localIPAddress(m_pUDPContext->getInputNetif()->ip_addr); - if (((stcMDNS_RRAnswerA*)pKnownRRAnswer)->m_IPAddress == localIPAddress) - { - // SAME IP address -> We've received an old message from ourselves (same IP) - DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Tiebreak (IP4) WON (was an old message)!\n"));); - m_HostProbeInformation.m_bTiebreakNeeded = false; - } - else + // Host domain match +#ifdef MDNS_IP4_SUPPORT + if (AnswerType_A == pKnownRRAnswer->answerType()) { - if ((uint32_t)(((stcMDNS_RRAnswerA*)pKnownRRAnswer)->m_IPAddress) > (uint32_t)localIPAddress) // The OTHER IP is 'higher' -> LOST + IPAddress localIPAddress(m_pUDPContext->getInputNetif()->ip_addr); + if (((stcMDNS_RRAnswerA*)pKnownRRAnswer)->m_IPAddress == localIPAddress) { - // LOST tiebreak - DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Tiebreak (IP4) LOST (lower)!\n"));); - _cancelProbingForHost(); + // SAME IP address -> We've received an old message from ourselves (same IP) + DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Tiebreak (IP4) WON (was an old message)!\n"));); m_HostProbeInformation.m_bTiebreakNeeded = false; } - else // WON tiebreak + else { - //TiebreakState = TiebreakState_Won; // We received an 'old' message from ourselves -> Just ignore - DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Tiebreak (IP4) WON (higher IP)!\n"));); - m_HostProbeInformation.m_bTiebreakNeeded = false; + if ((uint32_t)(((stcMDNS_RRAnswerA*)pKnownRRAnswer)->m_IPAddress) > (uint32_t)localIPAddress) // The OTHER IP is 'higher' -> LOST + { + // LOST tiebreak + DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Tiebreak (IP4) LOST (lower)!\n"));); + _cancelProbingForHost(); + m_HostProbeInformation.m_bTiebreakNeeded = false; + } + else // WON tiebreak + { + //TiebreakState = TiebreakState_Won; // We received an 'old' message from ourselves -> Just ignore + DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Tiebreak (IP4) WON (higher IP)!\n"));); + m_HostProbeInformation.m_bTiebreakNeeded = false; + } } } - } #endif #ifdef MDNS_IP6_SUPPORT - if (AnswerType_AAAA == pAnswerRR->answerType()) - { - // TODO - } + if (AnswerType_AAAA == pAnswerRR->answerType()) + { + // TODO + } #endif - } - } // Host tiebreak possibility - - // Check service answers - for (stcMDNSService* pService = m_pServices; pService; pService = pService->m_pNext) - { - uint8_t u8ServiceMatchMask = (pService->m_u8ReplyMask & _replyMaskForService(pKnownRRAnswer->m_Header, *pService)); + } + } // Host tiebreak possibility - if ((u8ServiceMatchMask) && // The RR in the known answer matches an RR we are planning to send, AND - ((MDNS_SERVICE_TTL / 2) <= pKnownRRAnswer->m_u32TTL)) // The TTL of the known answer is longer than half of the new service TTL (4500s) + // Check service answers + for (stcMDNSService* pService = m_pServices; pService; pService = pService->m_pNext) { - if (AnswerType_PTR == pKnownRRAnswer->answerType()) + uint8_t u8ServiceMatchMask = (pService->m_u8ReplyMask & _replyMaskForService(pKnownRRAnswer->m_Header, *pService)); + + if ((u8ServiceMatchMask) && // The RR in the known answer matches an RR we are planning to send, AND + ((MDNS_SERVICE_TTL / 2) <= pKnownRRAnswer->m_u32TTL)) // The TTL of the known answer is longer than half of the new service TTL (4500s) { - stcMDNS_RRDomain serviceDomain; - if ((u8ServiceMatchMask & ContentFlag_PTR_TYPE) && - (_buildDomainForService(*pService, false, serviceDomain)) && - (serviceDomain == ((stcMDNS_RRAnswerPTR*)pKnownRRAnswer)->m_PTRDomain)) + if (AnswerType_PTR == pKnownRRAnswer->answerType()) { - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Service type PTR already known... skipping!\n"));); - pService->m_u8ReplyMask &= ~ContentFlag_PTR_TYPE; - } - if ((u8ServiceMatchMask & ContentFlag_PTR_NAME) && - (_buildDomainForService(*pService, true, serviceDomain)) && - (serviceDomain == ((stcMDNS_RRAnswerPTR*)pKnownRRAnswer)->m_PTRDomain)) - { - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Service name PTR already known... skipping!\n"));); - pService->m_u8ReplyMask &= ~ContentFlag_PTR_NAME; + stcMDNS_RRDomain serviceDomain; + if ((u8ServiceMatchMask & ContentFlag_PTR_TYPE) && (_buildDomainForService(*pService, false, serviceDomain)) && (serviceDomain == ((stcMDNS_RRAnswerPTR*)pKnownRRAnswer)->m_PTRDomain)) + { + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Service type PTR already known... skipping!\n"));); + pService->m_u8ReplyMask &= ~ContentFlag_PTR_TYPE; + } + if ((u8ServiceMatchMask & ContentFlag_PTR_NAME) && (_buildDomainForService(*pService, true, serviceDomain)) && (serviceDomain == ((stcMDNS_RRAnswerPTR*)pKnownRRAnswer)->m_PTRDomain)) + { + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Service name PTR already known... skipping!\n"));); + pService->m_u8ReplyMask &= ~ContentFlag_PTR_NAME; + } } - } - else if (u8ServiceMatchMask & ContentFlag_SRV) - { - DEBUG_EX_ERR(if (AnswerType_SRV != pKnownRRAnswer->answerType()) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: ERROR! INVALID answer type (SRV)!\n"));); - stcMDNS_RRDomain hostDomain; - if ((_buildDomainForHost(m_pcHostname, hostDomain)) && - (hostDomain == ((stcMDNS_RRAnswerSRV*)pKnownRRAnswer)->m_SRVDomain)) // Host domain match + else if (u8ServiceMatchMask & ContentFlag_SRV) { - if ((MDNS_SRV_PRIORITY == ((stcMDNS_RRAnswerSRV*)pKnownRRAnswer)->m_u16Priority) && - (MDNS_SRV_WEIGHT == ((stcMDNS_RRAnswerSRV*)pKnownRRAnswer)->m_u16Weight) && - (pService->m_u16Port == ((stcMDNS_RRAnswerSRV*)pKnownRRAnswer)->m_u16Port)) + DEBUG_EX_ERR(if (AnswerType_SRV != pKnownRRAnswer->answerType()) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: ERROR! INVALID answer type (SRV)!\n"));); + stcMDNS_RRDomain hostDomain; + if ((_buildDomainForHost(m_pcHostname, hostDomain)) && (hostDomain == ((stcMDNS_RRAnswerSRV*)pKnownRRAnswer)->m_SRVDomain)) // Host domain match { - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Service SRV answer already known... skipping!\n"));); - pService->m_u8ReplyMask &= ~ContentFlag_SRV; - } // else: Small differences -> send update message + if ((MDNS_SRV_PRIORITY == ((stcMDNS_RRAnswerSRV*)pKnownRRAnswer)->m_u16Priority) && (MDNS_SRV_WEIGHT == ((stcMDNS_RRAnswerSRV*)pKnownRRAnswer)->m_u16Weight) && (pService->m_u16Port == ((stcMDNS_RRAnswerSRV*)pKnownRRAnswer)->m_u16Port)) + { + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Service SRV answer already known... skipping!\n"));); + pService->m_u8ReplyMask &= ~ContentFlag_SRV; + } // else: Small differences -> send update message + } } - } - else if (u8ServiceMatchMask & ContentFlag_TXT) - { - DEBUG_EX_ERR(if (AnswerType_TXT != pKnownRRAnswer->answerType()) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: ERROR! INVALID answer type (TXT)!\n"));); - _collectServiceTxts(*pService); - if (pService->m_Txts == ((stcMDNS_RRAnswerTXT*)pKnownRRAnswer)->m_Txts) + else if (u8ServiceMatchMask & ContentFlag_TXT) { - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Service TXT answer already known... skipping!\n"));); - pService->m_u8ReplyMask &= ~ContentFlag_TXT; + DEBUG_EX_ERR(if (AnswerType_TXT != pKnownRRAnswer->answerType()) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: ERROR! INVALID answer type (TXT)!\n"));); + _collectServiceTxts(*pService); + if (pService->m_Txts == ((stcMDNS_RRAnswerTXT*)pKnownRRAnswer)->m_Txts) + { + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Service TXT answer already known... skipping!\n"));); + pService->m_u8ReplyMask &= ~ContentFlag_TXT; + } + _releaseTempServiceTxts(*pService); } - _releaseTempServiceTxts(*pService); - } - } // Service match and enough TTL + } // Service match and enough TTL - // - // Check service tiebreak possibility - if (pService->m_ProbeInformation.m_bTiebreakNeeded) - { - stcMDNS_RRDomain serviceDomain; - if ((_buildDomainForService(*pService, true, serviceDomain)) && - (pKnownRRAnswer->m_Header.m_Domain == serviceDomain)) + // + // Check service tiebreak possibility + if (pService->m_ProbeInformation.m_bTiebreakNeeded) { - // Service domain match - if (AnswerType_SRV == pKnownRRAnswer->answerType()) + stcMDNS_RRDomain serviceDomain; + if ((_buildDomainForService(*pService, true, serviceDomain)) && (pKnownRRAnswer->m_Header.m_Domain == serviceDomain)) { - stcMDNS_RRDomain hostDomain; - if ((_buildDomainForHost(m_pcHostname, hostDomain)) && - (hostDomain == ((stcMDNS_RRAnswerSRV*)pKnownRRAnswer)->m_SRVDomain)) // Host domain match - { - // We've received an old message from ourselves (same SRV) - DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Tiebreak (SRV) won (was an old message)!\n"));); - pService->m_ProbeInformation.m_bTiebreakNeeded = false; - } - else + // Service domain match + if (AnswerType_SRV == pKnownRRAnswer->answerType()) { - if (((stcMDNS_RRAnswerSRV*)pKnownRRAnswer)->m_SRVDomain > hostDomain) // The OTHER domain is 'higher' -> LOST + stcMDNS_RRDomain hostDomain; + if ((_buildDomainForHost(m_pcHostname, hostDomain)) && (hostDomain == ((stcMDNS_RRAnswerSRV*)pKnownRRAnswer)->m_SRVDomain)) // Host domain match { - // LOST tiebreak - DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Tiebreak (SRV) LOST (lower)!\n"));); - _cancelProbingForService(*pService); + // We've received an old message from ourselves (same SRV) + DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Tiebreak (SRV) won (was an old message)!\n"));); pService->m_ProbeInformation.m_bTiebreakNeeded = false; } - else // WON tiebreak + else { - //TiebreakState = TiebreakState_Won; // We received an 'old' message from ourselves -> Just ignore - DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Tiebreak (SRV) won (higher)!\n"));); - pService->m_ProbeInformation.m_bTiebreakNeeded = false; + if (((stcMDNS_RRAnswerSRV*)pKnownRRAnswer)->m_SRVDomain > hostDomain) // The OTHER domain is 'higher' -> LOST + { + // LOST tiebreak + DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Tiebreak (SRV) LOST (lower)!\n"));); + _cancelProbingForService(*pService); + pService->m_ProbeInformation.m_bTiebreakNeeded = false; + } + else // WON tiebreak + { + //TiebreakState = TiebreakState_Won; // We received an 'old' message from ourselves -> Just ignore + DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Tiebreak (SRV) won (higher)!\n"));); + pService->m_ProbeInformation.m_bTiebreakNeeded = false; + } } } } - } - } // service tiebreak possibility - } // for services - } // ANY answers + } // service tiebreak possibility + } // for services + } // ANY answers + } + else + { + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: FAILED to read known answer!\n"));); + } + + if (pKnownRRAnswer) + { + delete pKnownRRAnswer; + pKnownRRAnswer = 0; + } + } // for answers + + if (bResult) + { + // Check, if a reply is needed + uint8_t u8ReplyNeeded = sendParameter.m_u8HostReplyMask; + for (stcMDNSService* pService = m_pServices; pService; pService = pService->m_pNext) + { + u8ReplyNeeded |= pService->m_u8ReplyMask; + } + + if (u8ReplyNeeded) + { + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Sending answer(0x%X)...\n"), u8ReplyNeeded);); + + sendParameter.m_bResponse = true; + sendParameter.m_bAuthorative = true; + + bResult = _sendMDNSMessage(sendParameter); + } + DEBUG_EX_INFO( + else + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: No reply needed\n")); + }); } else { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: FAILED to read known answer!\n"));); + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Something FAILED!\n"));); + m_pUDPContext->flush(); } - if (pKnownRRAnswer) + // + // Check and reset tiebreak-states + if (m_HostProbeInformation.m_bTiebreakNeeded) { - delete pKnownRRAnswer; - pKnownRRAnswer = 0; + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: UNSOLVED tiebreak-need for host domain!\n"));); + m_HostProbeInformation.m_bTiebreakNeeded = false; } - } // for answers - - if (bResult) - { - // Check, if a reply is needed - uint8_t u8ReplyNeeded = sendParameter.m_u8HostReplyMask; for (stcMDNSService* pService = m_pServices; pService; pService = pService->m_pNext) { - u8ReplyNeeded |= pService->m_u8ReplyMask; - } - - if (u8ReplyNeeded) - { - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Sending answer(0x%X)...\n"), u8ReplyNeeded);); - - sendParameter.m_bResponse = true; - sendParameter.m_bAuthorative = true; - - bResult = _sendMDNSMessage(sendParameter); + if (pService->m_ProbeInformation.m_bTiebreakNeeded) + { + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: UNSOLVED tiebreak-need for service domain (%s.%s.%s)\n"), (pService->m_pcName ?: m_pcHostname), pService->m_pcService, pService->m_pcProtocol);); + pService->m_ProbeInformation.m_bTiebreakNeeded = false; + } } - DEBUG_EX_INFO( - else + DEBUG_EX_ERR(if (!bResult) { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: No reply needed\n")); + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: FAILED!\n")); }); + return bResult; } - else - { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Something FAILED!\n"));); - m_pUDPContext->flush(); - } - - // - // Check and reset tiebreak-states - if (m_HostProbeInformation.m_bTiebreakNeeded) - { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: UNSOLVED tiebreak-need for host domain!\n"));); - m_HostProbeInformation.m_bTiebreakNeeded = false; - } - for (stcMDNSService* pService = m_pServices; pService; pService = pService->m_pNext) - { - if (pService->m_ProbeInformation.m_bTiebreakNeeded) - { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: UNSOLVED tiebreak-need for service domain (%s.%s.%s)\n"), (pService->m_pcName ?: m_pcHostname), pService->m_pcService, pService->m_pcProtocol);); - pService->m_ProbeInformation.m_bTiebreakNeeded = false; - } - } - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: FAILED!\n")); - }); - return bResult; -} -/* + /* MDNSResponder::_parseResponse Responses are of interest in two cases: @@ -597,83 +578,81 @@ bool MDNSResponder::_parseQuery(const MDNSResponder::stcMDNS_MsgHeader& p_MsgHea TXT - links the instance name to services TXTs Level 3: A/AAAA - links the host domain to an IP address */ -bool MDNSResponder::_parseResponse(const MDNSResponder::stcMDNS_MsgHeader& p_MsgHeader) -{ - //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse\n"));); - //DEBUG_EX_INFO(_udpDump();); - - bool bResult = false; - - // A response should be the result of a query or a probe - if ((_hasServiceQueriesWaitingForAnswers()) || // Waiting for query answers OR - (_hasProbesWaitingForAnswers())) // Probe responses + bool MDNSResponder::_parseResponse(const MDNSResponder::stcMDNS_MsgHeader& p_MsgHeader) { - DEBUG_EX_INFO( - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse: Received a response\n")); - //_udpDump(); - ); + //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse\n"));); + //DEBUG_EX_INFO(_udpDump();); - bResult = true; - // - // Ignore questions here - stcMDNS_RRQuestion dummyRRQ; - for (uint16_t qd = 0; ((bResult) && (qd < p_MsgHeader.m_u16QDCount)); ++qd) - { - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse: Received a response containing a question... ignoring!\n"));); - bResult = _readRRQuestion(dummyRRQ); - } // for queries + bool bResult = false; - // - // Read and collect answers - stcMDNS_RRAnswer* pCollectedRRAnswers = 0; - uint32_t u32NumberOfAnswerRRs = (p_MsgHeader.m_u16ANCount + p_MsgHeader.m_u16NSCount + p_MsgHeader.m_u16ARCount); - for (uint32_t an = 0; ((bResult) && (an < u32NumberOfAnswerRRs)); ++an) + // A response should be the result of a query or a probe + if ((_hasServiceQueriesWaitingForAnswers()) || // Waiting for query answers OR + (_hasProbesWaitingForAnswers())) // Probe responses { - stcMDNS_RRAnswer* pRRAnswer = 0; - if (((bResult = _readRRAnswer(pRRAnswer))) && - (pRRAnswer)) + DEBUG_EX_INFO( + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse: Received a response\n")); + //_udpDump(); + ); + + bResult = true; + // + // Ignore questions here + stcMDNS_RRQuestion dummyRRQ; + for (uint16_t qd = 0; ((bResult) && (qd < p_MsgHeader.m_u16QDCount)); ++qd) { - //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse: ADDING answer!\n"));); - pRRAnswer->m_pNext = pCollectedRRAnswers; - pCollectedRRAnswers = pRRAnswer; - } - else + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse: Received a response containing a question... ignoring!\n"));); + bResult = _readRRQuestion(dummyRRQ); + } // for queries + + // + // Read and collect answers + stcMDNS_RRAnswer* pCollectedRRAnswers = 0; + uint32_t u32NumberOfAnswerRRs = (p_MsgHeader.m_u16ANCount + p_MsgHeader.m_u16NSCount + p_MsgHeader.m_u16ARCount); + for (uint32_t an = 0; ((bResult) && (an < u32NumberOfAnswerRRs)); ++an) { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse: FAILED to read answer!\n"));); - if (pRRAnswer) + stcMDNS_RRAnswer* pRRAnswer = 0; + if (((bResult = _readRRAnswer(pRRAnswer))) && (pRRAnswer)) + { + //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse: ADDING answer!\n"));); + pRRAnswer->m_pNext = pCollectedRRAnswers; + pCollectedRRAnswers = pRRAnswer; + } + else { - delete pRRAnswer; - pRRAnswer = 0; + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse: FAILED to read answer!\n"));); + if (pRRAnswer) + { + delete pRRAnswer; + pRRAnswer = 0; + } + bResult = false; } - bResult = false; + } // for answers + + // + // Process answers + if (bResult) + { + bResult = ((!pCollectedRRAnswers) || (_processAnswers(pCollectedRRAnswers))); + } + else // Some failure while reading answers + { + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse: FAILED to read answers!\n"));); + m_pUDPContext->flush(); } - } // for answers - // - // Process answers - if (bResult) - { - bResult = ((!pCollectedRRAnswers) || - (_processAnswers(pCollectedRRAnswers))); - } - else // Some failure while reading answers - { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse: FAILED to read answers!\n"));); - m_pUDPContext->flush(); + // Delete collected answers + while (pCollectedRRAnswers) + { + //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse: DELETING answer!\n"));); + stcMDNS_RRAnswer* pNextAnswer = pCollectedRRAnswers->m_pNext; + delete pCollectedRRAnswers; + pCollectedRRAnswers = pNextAnswer; + } } - - // Delete collected answers - while (pCollectedRRAnswers) + else // Received an unexpected response -> ignore { - //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse: DELETING answer!\n"));); - stcMDNS_RRAnswer* pNextAnswer = pCollectedRRAnswers->m_pNext; - delete pCollectedRRAnswers; - pCollectedRRAnswers = pNextAnswer; - } - } - else // Received an unexpected response -> ignore - { - /* DEBUG_EX_INFO( + /* DEBUG_EX_INFO( DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse: Received an unexpected response... ignoring!\nDUMP:\n")); bool bDumpResult = true; for (uint16_t qd=0; ((bDumpResult) && (qdflush(); - bResult = true; + m_pUDPContext->flush(); + bResult = true; + } + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse: FAILED!\n")); + }); + return bResult; } - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse: FAILED!\n")); - }); - return bResult; -} -/* + /* MDNSResponder::_processAnswers Host: A (0x01): eg. esp8266.local A OP TTL 123.456.789.012 @@ -717,438 +696,427 @@ bool MDNSResponder::_parseResponse(const MDNSResponder::stcMDNS_MsgHeader& p_Msg TXT (0x10): eg. MyESP._http._tcp.local TXT OP TTL c#=1 */ -bool MDNSResponder::_processAnswers(const MDNSResponder::stcMDNS_RRAnswer* p_pAnswers) -{ - bool bResult = false; - - if (p_pAnswers) + bool MDNSResponder::_processAnswers(const MDNSResponder::stcMDNS_RRAnswer* p_pAnswers) { - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAnswers: Processing answers...\n"));); - bResult = true; + bool bResult = false; - // Answers may arrive in an unexpected order. So we loop our answers as long, as we - // can connect new information to service queries - bool bFoundNewKeyAnswer; - do + if (p_pAnswers) { - bFoundNewKeyAnswer = false; + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAnswers: Processing answers...\n"));); + bResult = true; - const stcMDNS_RRAnswer* pRRAnswer = p_pAnswers; - while ((pRRAnswer) && - (bResult)) + // Answers may arrive in an unexpected order. So we loop our answers as long, as we + // can connect new information to service queries + bool bFoundNewKeyAnswer; + do { - // 1. level answer (PTR) - if (AnswerType_PTR == pRRAnswer->answerType()) - { - // eg. _http._tcp.local PTR xxxx xx MyESP._http._tcp.local - bResult = _processPTRAnswer((stcMDNS_RRAnswerPTR*)pRRAnswer, bFoundNewKeyAnswer); // May 'enable' new SRV or TXT answers to be linked to queries - } - // 2. level answers - // SRV -> host domain and port - else if (AnswerType_SRV == pRRAnswer->answerType()) - { - // eg. MyESP_http._tcp.local SRV xxxx xx yy zz 5000 esp8266.local - bResult = _processSRVAnswer((stcMDNS_RRAnswerSRV*)pRRAnswer, bFoundNewKeyAnswer); // May 'enable' new A/AAAA answers to be linked to queries - } - // TXT -> Txts - else if (AnswerType_TXT == pRRAnswer->answerType()) + bFoundNewKeyAnswer = false; + + const stcMDNS_RRAnswer* pRRAnswer = p_pAnswers; + while ((pRRAnswer) && (bResult)) { - // eg. MyESP_http._tcp.local TXT xxxx xx c#=1 - bResult = _processTXTAnswer((stcMDNS_RRAnswerTXT*)pRRAnswer); - } - // 3. level answers + // 1. level answer (PTR) + if (AnswerType_PTR == pRRAnswer->answerType()) + { + // eg. _http._tcp.local PTR xxxx xx MyESP._http._tcp.local + bResult = _processPTRAnswer((stcMDNS_RRAnswerPTR*)pRRAnswer, bFoundNewKeyAnswer); // May 'enable' new SRV or TXT answers to be linked to queries + } + // 2. level answers + // SRV -> host domain and port + else if (AnswerType_SRV == pRRAnswer->answerType()) + { + // eg. MyESP_http._tcp.local SRV xxxx xx yy zz 5000 esp8266.local + bResult = _processSRVAnswer((stcMDNS_RRAnswerSRV*)pRRAnswer, bFoundNewKeyAnswer); // May 'enable' new A/AAAA answers to be linked to queries + } + // TXT -> Txts + else if (AnswerType_TXT == pRRAnswer->answerType()) + { + // eg. MyESP_http._tcp.local TXT xxxx xx c#=1 + bResult = _processTXTAnswer((stcMDNS_RRAnswerTXT*)pRRAnswer); + } + // 3. level answers #ifdef MDNS_IP4_SUPPORT - // A -> IP4Address - else if (AnswerType_A == pRRAnswer->answerType()) - { - // eg. esp8266.local A xxxx xx 192.168.2.120 - bResult = _processAAnswer((stcMDNS_RRAnswerA*)pRRAnswer); - } + // A -> IP4Address + else if (AnswerType_A == pRRAnswer->answerType()) + { + // eg. esp8266.local A xxxx xx 192.168.2.120 + bResult = _processAAnswer((stcMDNS_RRAnswerA*)pRRAnswer); + } #endif #ifdef MDNS_IP6_SUPPORT - // AAAA -> IP6Address - else if (AnswerType_AAAA == pRRAnswer->answerType()) - { - // eg. esp8266.local AAAA xxxx xx 09cf::0c - bResult = _processAAAAAnswer((stcMDNS_RRAnswerAAAA*)pRRAnswer); - } + // AAAA -> IP6Address + else if (AnswerType_AAAA == pRRAnswer->answerType()) + { + // eg. esp8266.local AAAA xxxx xx 09cf::0c + bResult = _processAAAAAnswer((stcMDNS_RRAnswerAAAA*)pRRAnswer); + } #endif - // Finally check for probing conflicts - // Host domain - if ((ProbingStatus_InProgress == m_HostProbeInformation.m_ProbingStatus) && - ((AnswerType_A == pRRAnswer->answerType()) || - (AnswerType_AAAA == pRRAnswer->answerType()))) - { - stcMDNS_RRDomain hostDomain; - if ((_buildDomainForHost(m_pcHostname, hostDomain)) && - (pRRAnswer->m_Header.m_Domain == hostDomain)) + // Finally check for probing conflicts + // Host domain + if ((ProbingStatus_InProgress == m_HostProbeInformation.m_ProbingStatus) && ((AnswerType_A == pRRAnswer->answerType()) || (AnswerType_AAAA == pRRAnswer->answerType()))) { - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAnswers: Probing CONFLICT found with: %s.local\n"), m_pcHostname);); - _cancelProbingForHost(); + stcMDNS_RRDomain hostDomain; + if ((_buildDomainForHost(m_pcHostname, hostDomain)) && (pRRAnswer->m_Header.m_Domain == hostDomain)) + { + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAnswers: Probing CONFLICT found with: %s.local\n"), m_pcHostname);); + _cancelProbingForHost(); + } } - } - // Service domains - for (stcMDNSService* pService = m_pServices; pService; pService = pService->m_pNext) - { - if ((ProbingStatus_InProgress == pService->m_ProbeInformation.m_ProbingStatus) && - ((AnswerType_TXT == pRRAnswer->answerType()) || - (AnswerType_SRV == pRRAnswer->answerType()))) + // Service domains + for (stcMDNSService* pService = m_pServices; pService; pService = pService->m_pNext) { - stcMDNS_RRDomain serviceDomain; - if ((_buildDomainForService(*pService, true, serviceDomain)) && - (pRRAnswer->m_Header.m_Domain == serviceDomain)) + if ((ProbingStatus_InProgress == pService->m_ProbeInformation.m_ProbingStatus) && ((AnswerType_TXT == pRRAnswer->answerType()) || (AnswerType_SRV == pRRAnswer->answerType()))) { - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAnswers: Probing CONFLICT found with: %s.%s.%s\n"), (pService->m_pcName ?: m_pcHostname), pService->m_pcService, pService->m_pcProtocol);); - _cancelProbingForService(*pService); + stcMDNS_RRDomain serviceDomain; + if ((_buildDomainForService(*pService, true, serviceDomain)) && (pRRAnswer->m_Header.m_Domain == serviceDomain)) + { + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAnswers: Probing CONFLICT found with: %s.%s.%s\n"), (pService->m_pcName ?: m_pcHostname), pService->m_pcService, pService->m_pcProtocol);); + _cancelProbingForService(*pService); + } } } - } - pRRAnswer = pRRAnswer->m_pNext; // Next collected answer - } // while (answers) - } while ((bFoundNewKeyAnswer) && - (bResult)); - } // else: No answers provided - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAnswers: FAILED!\n")); - }); - return bResult; -} + pRRAnswer = pRRAnswer->m_pNext; // Next collected answer + } // while (answers) + } while ((bFoundNewKeyAnswer) && (bResult)); + } // else: No answers provided + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAnswers: FAILED!\n")); + }); + return bResult; + } -/* + /* MDNSResponder::_processPTRAnswer */ -bool MDNSResponder::_processPTRAnswer(const MDNSResponder::stcMDNS_RRAnswerPTR* p_pPTRAnswer, - bool& p_rbFoundNewKeyAnswer) -{ - bool bResult = false; - - if ((bResult = (0 != p_pPTRAnswer))) + bool MDNSResponder::_processPTRAnswer(const MDNSResponder::stcMDNS_RRAnswerPTR* p_pPTRAnswer, + bool& p_rbFoundNewKeyAnswer) { - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processPTRAnswer: Processing PTR answers...\n"));); - // eg. _http._tcp.local PTR xxxx xx MyESP._http._tcp.local - // Check pending service queries for eg. '_http._tcp' + bool bResult = false; - stcMDNSServiceQuery* pServiceQuery = _findNextServiceQueryByServiceType(p_pPTRAnswer->m_Header.m_Domain, 0); - while (pServiceQuery) + if ((bResult = (0 != p_pPTRAnswer))) { - if (pServiceQuery->m_bAwaitingAnswers) + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processPTRAnswer: Processing PTR answers...\n"));); + // eg. _http._tcp.local PTR xxxx xx MyESP._http._tcp.local + // Check pending service queries for eg. '_http._tcp' + + stcMDNSServiceQuery* pServiceQuery = _findNextServiceQueryByServiceType(p_pPTRAnswer->m_Header.m_Domain, 0); + while (pServiceQuery) { - // Find answer for service domain (eg. MyESP._http._tcp.local) - stcMDNSServiceQuery::stcAnswer* pSQAnswer = pServiceQuery->findAnswerForServiceDomain(p_pPTRAnswer->m_PTRDomain); - if (pSQAnswer) // existing answer + if (pServiceQuery->m_bAwaitingAnswers) { - if (p_pPTRAnswer->m_u32TTL) // Received update message - { - pSQAnswer->m_TTLServiceDomain.set(p_pPTRAnswer->m_u32TTL); // Update TTL tag - DEBUG_EX_INFO( - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processPTRAnswer: Updated TTL(%d) for "), (int)p_pPTRAnswer->m_u32TTL); - _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR("\n"));); - } - else // received goodbye-message + // Find answer for service domain (eg. MyESP._http._tcp.local) + stcMDNSServiceQuery::stcAnswer* pSQAnswer = pServiceQuery->findAnswerForServiceDomain(p_pPTRAnswer->m_PTRDomain); + if (pSQAnswer) // existing answer { - pSQAnswer->m_TTLServiceDomain.prepareDeletion(); // Prepare answer deletion according to RFC 6762, 10.1 - DEBUG_EX_INFO( - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processPTRAnswer: 'Goodbye' received for ")); - _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR("\n"));); + if (p_pPTRAnswer->m_u32TTL) // Received update message + { + pSQAnswer->m_TTLServiceDomain.set(p_pPTRAnswer->m_u32TTL); // Update TTL tag + DEBUG_EX_INFO( + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processPTRAnswer: Updated TTL(%d) for "), (int)p_pPTRAnswer->m_u32TTL); + _printRRDomain(pSQAnswer->m_ServiceDomain); + DEBUG_OUTPUT.printf_P(PSTR("\n"));); + } + else // received goodbye-message + { + pSQAnswer->m_TTLServiceDomain.prepareDeletion(); // Prepare answer deletion according to RFC 6762, 10.1 + DEBUG_EX_INFO( + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processPTRAnswer: 'Goodbye' received for ")); + _printRRDomain(pSQAnswer->m_ServiceDomain); + DEBUG_OUTPUT.printf_P(PSTR("\n"));); + } } - } - else if ((p_pPTRAnswer->m_u32TTL) && // Not just a goodbye-message - ((pSQAnswer = new stcMDNSServiceQuery::stcAnswer))) // Not yet included -> add answer - { - pSQAnswer->m_ServiceDomain = p_pPTRAnswer->m_PTRDomain; - pSQAnswer->m_u32ContentFlags |= ServiceQueryAnswerType_ServiceDomain; - pSQAnswer->m_TTLServiceDomain.set(p_pPTRAnswer->m_u32TTL); - pSQAnswer->releaseServiceDomain(); - - bResult = pServiceQuery->addAnswer(pSQAnswer); - p_rbFoundNewKeyAnswer = true; - if (pServiceQuery->m_fnCallback) + else if ((p_pPTRAnswer->m_u32TTL) && // Not just a goodbye-message + ((pSQAnswer = new stcMDNSServiceQuery::stcAnswer))) // Not yet included -> add answer { - MDNSServiceInfo serviceInfo(*this, (hMDNSServiceQuery)pServiceQuery, pServiceQuery->indexOfAnswer(pSQAnswer)); - pServiceQuery->m_fnCallback(serviceInfo, static_cast(ServiceQueryAnswerType_ServiceDomain), true); + pSQAnswer->m_ServiceDomain = p_pPTRAnswer->m_PTRDomain; + pSQAnswer->m_u32ContentFlags |= ServiceQueryAnswerType_ServiceDomain; + pSQAnswer->m_TTLServiceDomain.set(p_pPTRAnswer->m_u32TTL); + pSQAnswer->releaseServiceDomain(); + + bResult = pServiceQuery->addAnswer(pSQAnswer); + p_rbFoundNewKeyAnswer = true; + if (pServiceQuery->m_fnCallback) + { + MDNSServiceInfo serviceInfo(*this, (hMDNSServiceQuery)pServiceQuery, pServiceQuery->indexOfAnswer(pSQAnswer)); + pServiceQuery->m_fnCallback(serviceInfo, static_cast(ServiceQueryAnswerType_ServiceDomain), true); + } } } + pServiceQuery = _findNextServiceQueryByServiceType(p_pPTRAnswer->m_Header.m_Domain, pServiceQuery); } - pServiceQuery = _findNextServiceQueryByServiceType(p_pPTRAnswer->m_Header.m_Domain, pServiceQuery); - } - } // else: No p_pPTRAnswer - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processPTRAnswer: FAILED!\n")); - }); - return bResult; -} + } // else: No p_pPTRAnswer + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processPTRAnswer: FAILED!\n")); + }); + return bResult; + } -/* + /* MDNSResponder::_processSRVAnswer */ -bool MDNSResponder::_processSRVAnswer(const MDNSResponder::stcMDNS_RRAnswerSRV* p_pSRVAnswer, - bool& p_rbFoundNewKeyAnswer) -{ - bool bResult = false; - - if ((bResult = (0 != p_pSRVAnswer))) + bool MDNSResponder::_processSRVAnswer(const MDNSResponder::stcMDNS_RRAnswerSRV* p_pSRVAnswer, + bool& p_rbFoundNewKeyAnswer) { - // eg. MyESP._http._tcp.local SRV xxxx xx yy zz 5000 esp8266.local + bool bResult = false; - stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; - while (pServiceQuery) + if ((bResult = (0 != p_pSRVAnswer))) { - stcMDNSServiceQuery::stcAnswer* pSQAnswer = pServiceQuery->findAnswerForServiceDomain(p_pSRVAnswer->m_Header.m_Domain); - if (pSQAnswer) // Answer for this service domain (eg. MyESP._http._tcp.local) available + // eg. MyESP._http._tcp.local SRV xxxx xx yy zz 5000 esp8266.local + + stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; + while (pServiceQuery) { - if (p_pSRVAnswer->m_u32TTL) // First or update message (TTL != 0) + stcMDNSServiceQuery::stcAnswer* pSQAnswer = pServiceQuery->findAnswerForServiceDomain(p_pSRVAnswer->m_Header.m_Domain); + if (pSQAnswer) // Answer for this service domain (eg. MyESP._http._tcp.local) available { - pSQAnswer->m_TTLHostDomainAndPort.set(p_pSRVAnswer->m_u32TTL); // Update TTL tag - DEBUG_EX_INFO( - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processSRVAnswer: Updated TTL(%d) for "), (int)p_pSRVAnswer->m_u32TTL); - _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR(" host domain and port\n"));); - // Host domain & Port - if ((pSQAnswer->m_HostDomain != p_pSRVAnswer->m_SRVDomain) || - (pSQAnswer->m_u16Port != p_pSRVAnswer->m_u16Port)) + if (p_pSRVAnswer->m_u32TTL) // First or update message (TTL != 0) { - pSQAnswer->m_HostDomain = p_pSRVAnswer->m_SRVDomain; - pSQAnswer->releaseHostDomain(); - pSQAnswer->m_u16Port = p_pSRVAnswer->m_u16Port; - pSQAnswer->m_u32ContentFlags |= ServiceQueryAnswerType_HostDomainAndPort; - - p_rbFoundNewKeyAnswer = true; - if (pServiceQuery->m_fnCallback) + pSQAnswer->m_TTLHostDomainAndPort.set(p_pSRVAnswer->m_u32TTL); // Update TTL tag + DEBUG_EX_INFO( + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processSRVAnswer: Updated TTL(%d) for "), (int)p_pSRVAnswer->m_u32TTL); + _printRRDomain(pSQAnswer->m_ServiceDomain); + DEBUG_OUTPUT.printf_P(PSTR(" host domain and port\n"));); + // Host domain & Port + if ((pSQAnswer->m_HostDomain != p_pSRVAnswer->m_SRVDomain) || (pSQAnswer->m_u16Port != p_pSRVAnswer->m_u16Port)) { - MDNSServiceInfo serviceInfo(*this, (hMDNSServiceQuery)pServiceQuery, pServiceQuery->indexOfAnswer(pSQAnswer)); - pServiceQuery->m_fnCallback(serviceInfo, static_cast(ServiceQueryAnswerType_HostDomainAndPort), true); + pSQAnswer->m_HostDomain = p_pSRVAnswer->m_SRVDomain; + pSQAnswer->releaseHostDomain(); + pSQAnswer->m_u16Port = p_pSRVAnswer->m_u16Port; + pSQAnswer->m_u32ContentFlags |= ServiceQueryAnswerType_HostDomainAndPort; + + p_rbFoundNewKeyAnswer = true; + if (pServiceQuery->m_fnCallback) + { + MDNSServiceInfo serviceInfo(*this, (hMDNSServiceQuery)pServiceQuery, pServiceQuery->indexOfAnswer(pSQAnswer)); + pServiceQuery->m_fnCallback(serviceInfo, static_cast(ServiceQueryAnswerType_HostDomainAndPort), true); + } } } + else // Goodby message + { + pSQAnswer->m_TTLHostDomainAndPort.prepareDeletion(); // Prepare answer deletion according to RFC 6762, 10.1 + DEBUG_EX_INFO( + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processSRVAnswer: 'Goodbye' received for ")); + _printRRDomain(pSQAnswer->m_ServiceDomain); + DEBUG_OUTPUT.printf_P(PSTR(" host domain and port\n"));); + } } - else // Goodby message - { - pSQAnswer->m_TTLHostDomainAndPort.prepareDeletion(); // Prepare answer deletion according to RFC 6762, 10.1 - DEBUG_EX_INFO( - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processSRVAnswer: 'Goodbye' received for ")); - _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR(" host domain and port\n"));); - } - } - pServiceQuery = pServiceQuery->m_pNext; - } // while(service query) - } // else: No p_pSRVAnswer - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processSRVAnswer: FAILED!\n")); - }); - return bResult; -} + pServiceQuery = pServiceQuery->m_pNext; + } // while(service query) + } // else: No p_pSRVAnswer + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processSRVAnswer: FAILED!\n")); + }); + return bResult; + } -/* + /* MDNSResponder::_processTXTAnswer */ -bool MDNSResponder::_processTXTAnswer(const MDNSResponder::stcMDNS_RRAnswerTXT* p_pTXTAnswer) -{ - bool bResult = false; - - if ((bResult = (0 != p_pTXTAnswer))) + bool MDNSResponder::_processTXTAnswer(const MDNSResponder::stcMDNS_RRAnswerTXT* p_pTXTAnswer) { - // eg. MyESP._http._tcp.local TXT xxxx xx c#=1 + bool bResult = false; - stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; - while (pServiceQuery) + if ((bResult = (0 != p_pTXTAnswer))) { - stcMDNSServiceQuery::stcAnswer* pSQAnswer = pServiceQuery->findAnswerForServiceDomain(p_pTXTAnswer->m_Header.m_Domain); - if (pSQAnswer) // Answer for this service domain (eg. MyESP._http._tcp.local) available + // eg. MyESP._http._tcp.local TXT xxxx xx c#=1 + + stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; + while (pServiceQuery) { - if (p_pTXTAnswer->m_u32TTL) // First or update message + stcMDNSServiceQuery::stcAnswer* pSQAnswer = pServiceQuery->findAnswerForServiceDomain(p_pTXTAnswer->m_Header.m_Domain); + if (pSQAnswer) // Answer for this service domain (eg. MyESP._http._tcp.local) available { - pSQAnswer->m_TTLTxts.set(p_pTXTAnswer->m_u32TTL); // Update TTL tag - DEBUG_EX_INFO( - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processTXTAnswer: Updated TTL(%d) for "), (int)p_pTXTAnswer->m_u32TTL); - _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR(" TXTs\n"));); - if (!pSQAnswer->m_Txts.compare(p_pTXTAnswer->m_Txts)) + if (p_pTXTAnswer->m_u32TTL) // First or update message { - pSQAnswer->m_Txts = p_pTXTAnswer->m_Txts; - pSQAnswer->m_u32ContentFlags |= ServiceQueryAnswerType_Txts; - pSQAnswer->releaseTxts(); - - if (pServiceQuery->m_fnCallback) + pSQAnswer->m_TTLTxts.set(p_pTXTAnswer->m_u32TTL); // Update TTL tag + DEBUG_EX_INFO( + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processTXTAnswer: Updated TTL(%d) for "), (int)p_pTXTAnswer->m_u32TTL); + _printRRDomain(pSQAnswer->m_ServiceDomain); + DEBUG_OUTPUT.printf_P(PSTR(" TXTs\n"));); + if (!pSQAnswer->m_Txts.compare(p_pTXTAnswer->m_Txts)) { - MDNSServiceInfo serviceInfo(*this, (hMDNSServiceQuery)pServiceQuery, pServiceQuery->indexOfAnswer(pSQAnswer)); - pServiceQuery->m_fnCallback(serviceInfo, static_cast(ServiceQueryAnswerType_Txts), true); + pSQAnswer->m_Txts = p_pTXTAnswer->m_Txts; + pSQAnswer->m_u32ContentFlags |= ServiceQueryAnswerType_Txts; + pSQAnswer->releaseTxts(); + + if (pServiceQuery->m_fnCallback) + { + MDNSServiceInfo serviceInfo(*this, (hMDNSServiceQuery)pServiceQuery, pServiceQuery->indexOfAnswer(pSQAnswer)); + pServiceQuery->m_fnCallback(serviceInfo, static_cast(ServiceQueryAnswerType_Txts), true); + } } } + else // Goodby message + { + pSQAnswer->m_TTLTxts.prepareDeletion(); // Prepare answer deletion according to RFC 6762, 10.1 + DEBUG_EX_INFO( + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processTXTAnswer: 'Goodbye' received for ")); + _printRRDomain(pSQAnswer->m_ServiceDomain); + DEBUG_OUTPUT.printf_P(PSTR(" TXTs\n"));); + } } - else // Goodby message - { - pSQAnswer->m_TTLTxts.prepareDeletion(); // Prepare answer deletion according to RFC 6762, 10.1 - DEBUG_EX_INFO( - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processTXTAnswer: 'Goodbye' received for ")); - _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR(" TXTs\n"));); - } - } - pServiceQuery = pServiceQuery->m_pNext; - } // while(service query) - } // else: No p_pTXTAnswer - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processTXTAnswer: FAILED!\n")); - }); - return bResult; -} + pServiceQuery = pServiceQuery->m_pNext; + } // while(service query) + } // else: No p_pTXTAnswer + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processTXTAnswer: FAILED!\n")); + }); + return bResult; + } #ifdef MDNS_IP4_SUPPORT -/* + /* MDNSResponder::_processAAnswer */ -bool MDNSResponder::_processAAnswer(const MDNSResponder::stcMDNS_RRAnswerA* p_pAAnswer) -{ - bool bResult = false; - - if ((bResult = (0 != p_pAAnswer))) + bool MDNSResponder::_processAAnswer(const MDNSResponder::stcMDNS_RRAnswerA* p_pAAnswer) { - // eg. esp8266.local A xxxx xx 192.168.2.120 + bool bResult = false; - stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; - while (pServiceQuery) + if ((bResult = (0 != p_pAAnswer))) { - stcMDNSServiceQuery::stcAnswer* pSQAnswer = pServiceQuery->findAnswerForHostDomain(p_pAAnswer->m_Header.m_Domain); - if (pSQAnswer) // Answer for this host domain (eg. esp8266.local) available + // eg. esp8266.local A xxxx xx 192.168.2.120 + + stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; + while (pServiceQuery) { - stcMDNSServiceQuery::stcAnswer::stcIP4Address* pIP4Address = pSQAnswer->findIP4Address(p_pAAnswer->m_IPAddress); - if (pIP4Address) + stcMDNSServiceQuery::stcAnswer* pSQAnswer = pServiceQuery->findAnswerForHostDomain(p_pAAnswer->m_Header.m_Domain); + if (pSQAnswer) // Answer for this host domain (eg. esp8266.local) available { - // Already known IP4 address - if (p_pAAnswer->m_u32TTL) // Valid TTL -> Update answers TTL + stcMDNSServiceQuery::stcAnswer::stcIP4Address* pIP4Address = pSQAnswer->findIP4Address(p_pAAnswer->m_IPAddress); + if (pIP4Address) { - pIP4Address->m_TTL.set(p_pAAnswer->m_u32TTL); - DEBUG_EX_INFO( - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAAnswer: Updated TTL(%d) for "), (int)p_pAAnswer->m_u32TTL); - _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR(" IP4Address (%s)\n"), pIP4Address->m_IPAddress.toString().c_str());); - } - else // 'Goodbye' message for known IP4 address - { - pIP4Address->m_TTL.prepareDeletion(); // Prepare answer deletion according to RFC 6762, 10.1 - DEBUG_EX_INFO( - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAAnswer: 'Goodbye' received for ")); - _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR(" IP4 address (%s)\n"), pIP4Address->m_IPAddress.toString().c_str());); + // Already known IP4 address + if (p_pAAnswer->m_u32TTL) // Valid TTL -> Update answers TTL + { + pIP4Address->m_TTL.set(p_pAAnswer->m_u32TTL); + DEBUG_EX_INFO( + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAAnswer: Updated TTL(%d) for "), (int)p_pAAnswer->m_u32TTL); + _printRRDomain(pSQAnswer->m_ServiceDomain); + DEBUG_OUTPUT.printf_P(PSTR(" IP4Address (%s)\n"), pIP4Address->m_IPAddress.toString().c_str());); + } + else // 'Goodbye' message for known IP4 address + { + pIP4Address->m_TTL.prepareDeletion(); // Prepare answer deletion according to RFC 6762, 10.1 + DEBUG_EX_INFO( + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAAnswer: 'Goodbye' received for ")); + _printRRDomain(pSQAnswer->m_ServiceDomain); + DEBUG_OUTPUT.printf_P(PSTR(" IP4 address (%s)\n"), pIP4Address->m_IPAddress.toString().c_str());); + } } - } - else - { - // Until now unknown IP4 address -> Add (if the message isn't just a 'Goodbye' note) - if (p_pAAnswer->m_u32TTL) // NOT just a 'Goodbye' message + else { - pIP4Address = new stcMDNSServiceQuery::stcAnswer::stcIP4Address(p_pAAnswer->m_IPAddress, p_pAAnswer->m_u32TTL); - if ((pIP4Address) && - (pSQAnswer->addIP4Address(pIP4Address))) + // Until now unknown IP4 address -> Add (if the message isn't just a 'Goodbye' note) + if (p_pAAnswer->m_u32TTL) // NOT just a 'Goodbye' message { - pSQAnswer->m_u32ContentFlags |= ServiceQueryAnswerType_IP4Address; - if (pServiceQuery->m_fnCallback) + pIP4Address = new stcMDNSServiceQuery::stcAnswer::stcIP4Address(p_pAAnswer->m_IPAddress, p_pAAnswer->m_u32TTL); + if ((pIP4Address) && (pSQAnswer->addIP4Address(pIP4Address))) { - MDNSServiceInfo serviceInfo(*this, (hMDNSServiceQuery)pServiceQuery, pServiceQuery->indexOfAnswer(pSQAnswer)); - pServiceQuery->m_fnCallback(serviceInfo, static_cast(ServiceQueryAnswerType_IP4Address), true); + pSQAnswer->m_u32ContentFlags |= ServiceQueryAnswerType_IP4Address; + if (pServiceQuery->m_fnCallback) + { + MDNSServiceInfo serviceInfo(*this, (hMDNSServiceQuery)pServiceQuery, pServiceQuery->indexOfAnswer(pSQAnswer)); + pServiceQuery->m_fnCallback(serviceInfo, static_cast(ServiceQueryAnswerType_IP4Address), true); + } + } + else + { + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAAnswer: FAILED to add IP4 address (%s)!\n"), p_pAAnswer->m_IPAddress.toString().c_str());); } - } - else - { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAAnswer: FAILED to add IP4 address (%s)!\n"), p_pAAnswer->m_IPAddress.toString().c_str());); } } } - } - pServiceQuery = pServiceQuery->m_pNext; - } // while(service query) - } // else: No p_pAAnswer - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAAnswer: FAILED!\n")); - }); - return bResult; -} + pServiceQuery = pServiceQuery->m_pNext; + } // while(service query) + } // else: No p_pAAnswer + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAAnswer: FAILED!\n")); + }); + return bResult; + } #endif #ifdef MDNS_IP6_SUPPORT -/* + /* MDNSResponder::_processAAAAAnswer */ -bool MDNSResponder::_processAAAAAnswer(const MDNSResponder::stcMDNS_RRAnswerAAAA* p_pAAAAAnswer) -{ - bool bResult = false; - - if ((bResult = (0 != p_pAAAAAnswer))) + bool MDNSResponder::_processAAAAAnswer(const MDNSResponder::stcMDNS_RRAnswerAAAA* p_pAAAAAnswer) { - // eg. esp8266.local AAAA xxxx xx 0bf3::0c + bool bResult = false; - stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; - while (pServiceQuery) + if ((bResult = (0 != p_pAAAAAnswer))) { - stcMDNSServiceQuery::stcAnswer* pSQAnswer = pServiceQuery->findAnswerForHostDomain(p_pAAAAAnswer->m_Header.m_Domain); - if (pSQAnswer) // Answer for this host domain (eg. esp8266.local) available + // eg. esp8266.local AAAA xxxx xx 0bf3::0c + + stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; + while (pServiceQuery) { - stcIP6Address* pIP6Address = pSQAnswer->findIP6Address(p_pAAAAAnswer->m_IPAddress); - if (pIP6Address) + stcMDNSServiceQuery::stcAnswer* pSQAnswer = pServiceQuery->findAnswerForHostDomain(p_pAAAAAnswer->m_Header.m_Domain); + if (pSQAnswer) // Answer for this host domain (eg. esp8266.local) available { - // Already known IP6 address - if (p_pAAAAAnswer->m_u32TTL) // Valid TTL -> Update answers TTL - { - pIP6Address->m_TTL.set(p_pAAAAAnswer->m_u32TTL); - DEBUG_EX_INFO( - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAAnswer: Updated TTL(%lu) for "), p_pAAAAAnswer->m_u32TTL); - _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR(" IP6 address (%s)\n"), pIP6Address->m_IPAddress.toString().c_str());); - } - else // 'Goodbye' message for known IP6 address + stcIP6Address* pIP6Address = pSQAnswer->findIP6Address(p_pAAAAAnswer->m_IPAddress); + if (pIP6Address) { - pIP6Address->m_TTL.prepareDeletion(); // Prepare answer deletion according to RFC 6762, 10.1 - DEBUG_EX_INFO( - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAAnswer: 'Goodbye' received for ")); - _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR(" IP6 address (%s)\n"), pIP6Address->m_IPAddress.toString().c_str());); + // Already known IP6 address + if (p_pAAAAAnswer->m_u32TTL) // Valid TTL -> Update answers TTL + { + pIP6Address->m_TTL.set(p_pAAAAAnswer->m_u32TTL); + DEBUG_EX_INFO( + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAAnswer: Updated TTL(%lu) for "), p_pAAAAAnswer->m_u32TTL); + _printRRDomain(pSQAnswer->m_ServiceDomain); + DEBUG_OUTPUT.printf_P(PSTR(" IP6 address (%s)\n"), pIP6Address->m_IPAddress.toString().c_str());); + } + else // 'Goodbye' message for known IP6 address + { + pIP6Address->m_TTL.prepareDeletion(); // Prepare answer deletion according to RFC 6762, 10.1 + DEBUG_EX_INFO( + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAAnswer: 'Goodbye' received for ")); + _printRRDomain(pSQAnswer->m_ServiceDomain); + DEBUG_OUTPUT.printf_P(PSTR(" IP6 address (%s)\n"), pIP6Address->m_IPAddress.toString().c_str());); + } } - } - else - { - // Until now unknown IP6 address -> Add (if the message isn't just a 'Goodbye' note) - if (p_pAAAAAnswer->m_u32TTL) // NOT just a 'Goodbye' message + else { - pIP6Address = new stcIP6Address(p_pAAAAAnswer->m_IPAddress, p_pAAAAAnswer->m_u32TTL); - if ((pIP6Address) && - (pSQAnswer->addIP6Address(pIP6Address))) + // Until now unknown IP6 address -> Add (if the message isn't just a 'Goodbye' note) + if (p_pAAAAAnswer->m_u32TTL) // NOT just a 'Goodbye' message { - pSQAnswer->m_u32ContentFlags |= ServiceQueryAnswerType_IP6Address; + pIP6Address = new stcIP6Address(p_pAAAAAnswer->m_IPAddress, p_pAAAAAnswer->m_u32TTL); + if ((pIP6Address) && (pSQAnswer->addIP6Address(pIP6Address))) + { + pSQAnswer->m_u32ContentFlags |= ServiceQueryAnswerType_IP6Address; - if (pServiceQuery->m_fnCallback) + if (pServiceQuery->m_fnCallback) + { + pServiceQuery->m_fnCallback(this, (hMDNSServiceQuery)pServiceQuery, pServiceQuery->indexOfAnswer(pSQAnswer), ServiceQueryAnswerType_IP6Address, true, pServiceQuery->m_pUserdata); + } + } + else { - pServiceQuery->m_fnCallback(this, (hMDNSServiceQuery)pServiceQuery, pServiceQuery->indexOfAnswer(pSQAnswer), ServiceQueryAnswerType_IP6Address, true, pServiceQuery->m_pUserdata); + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAAnswer: FAILED to add IP6 address (%s)!\n"), p_pAAAAAnswer->m_IPAddress.toString().c_str());); } } - else - { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAAnswer: FAILED to add IP6 address (%s)!\n"), p_pAAAAAnswer->m_IPAddress.toString().c_str());); - } } } - } - pServiceQuery = pServiceQuery->m_pNext; - } // while(service query) - } // else: No p_pAAAAAnswer + pServiceQuery = pServiceQuery->m_pNext; + } // while(service query) + } // else: No p_pAAAAAnswer - return bResult; -} + return bResult; + } #endif -/* + /* PROBING */ -/* + /* MDNSResponder::_updateProbeStatus Manages the (outgoing) probing process. @@ -1160,132 +1128,130 @@ bool MDNSResponder::_processAAAAAnswer(const MDNSResponder::stcMDNS_RRAnswerAAAA Conflict management is handled in '_parseResponse ff.' Tiebraking is handled in 'parseQuery ff.' */ -bool MDNSResponder::_updateProbeStatus(void) -{ - bool bResult = true; - - // - // Probe host domain - if (ProbingStatus_ReadyToStart == m_HostProbeInformation.m_ProbingStatus) - { - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Starting host probing...\n"));); - - // First probe delay SHOULD be random 0-250 ms - m_HostProbeInformation.m_Timeout.reset(rand() % MDNS_PROBE_DELAY); - m_HostProbeInformation.m_ProbingStatus = ProbingStatus_InProgress; - } - else if ((ProbingStatus_InProgress == m_HostProbeInformation.m_ProbingStatus) && // Probing AND - (m_HostProbeInformation.m_Timeout.expired())) // Time for next probe + bool MDNSResponder::_updateProbeStatus(void) { - if (MDNS_PROBE_COUNT > m_HostProbeInformation.m_u8SentCount) // Send next probe - { - if ((bResult = _sendHostProbe())) - { - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Did sent host probe\n\n"));); - m_HostProbeInformation.m_Timeout.reset(MDNS_PROBE_DELAY); - ++m_HostProbeInformation.m_u8SentCount; - } - } - else // Probing finished - { - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Done host probing.\n"));); - m_HostProbeInformation.m_ProbingStatus = ProbingStatus_Done; - m_HostProbeInformation.m_Timeout.resetToNeverExpires(); - if (m_HostProbeInformation.m_fnHostProbeResultCallback) - { - m_HostProbeInformation.m_fnHostProbeResultCallback(m_pcHostname, true); - } + bool bResult = true; - // Prepare to announce host - m_HostProbeInformation.m_u8SentCount = 0; - m_HostProbeInformation.m_Timeout.reset(MDNS_ANNOUNCE_DELAY); - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Prepared host announcing.\n\n"));); - } - } // else: Probing already finished OR waiting for next time slot - else if ((ProbingStatus_Done == m_HostProbeInformation.m_ProbingStatus) && - (m_HostProbeInformation.m_Timeout.expired())) - { - if ((bResult = _announce(true, false))) // Don't announce services here + // + // Probe host domain + if (ProbingStatus_ReadyToStart == m_HostProbeInformation.m_ProbingStatus) { - ++m_HostProbeInformation.m_u8SentCount; - - if (MDNS_ANNOUNCE_COUNT > m_HostProbeInformation.m_u8SentCount) - { - m_HostProbeInformation.m_Timeout.reset(MDNS_ANNOUNCE_DELAY); - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Announcing host (%d).\n\n"), m_HostProbeInformation.m_u8SentCount);); - } - else - { - m_HostProbeInformation.m_Timeout.resetToNeverExpires(); - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Done host announcing.\n\n"));); - } - } - } + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Starting host probing...\n"));); - // - // Probe services - for (stcMDNSService* pService = m_pServices; ((bResult) && (pService)); pService = pService->m_pNext) - { - if (ProbingStatus_ReadyToStart == pService->m_ProbeInformation.m_ProbingStatus) // Ready to get started - { - pService->m_ProbeInformation.m_Timeout.reset(MDNS_PROBE_DELAY); // More or equal than first probe for host domain - pService->m_ProbeInformation.m_ProbingStatus = ProbingStatus_InProgress; + // First probe delay SHOULD be random 0-250 ms + m_HostProbeInformation.m_Timeout.reset(rand() % MDNS_PROBE_DELAY); + m_HostProbeInformation.m_ProbingStatus = ProbingStatus_InProgress; } - else if ((ProbingStatus_InProgress == pService->m_ProbeInformation.m_ProbingStatus) && // Probing AND - (pService->m_ProbeInformation.m_Timeout.expired())) // Time for next probe + else if ((ProbingStatus_InProgress == m_HostProbeInformation.m_ProbingStatus) && // Probing AND + (m_HostProbeInformation.m_Timeout.expired())) // Time for next probe { - if (MDNS_PROBE_COUNT > pService->m_ProbeInformation.m_u8SentCount) // Send next probe + if (MDNS_PROBE_COUNT > m_HostProbeInformation.m_u8SentCount) // Send next probe { - if ((bResult = _sendServiceProbe(*pService))) + if ((bResult = _sendHostProbe())) { - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Did sent service probe (%u)\n\n"), (pService->m_ProbeInformation.m_u8SentCount + 1));); - pService->m_ProbeInformation.m_Timeout.reset(MDNS_PROBE_DELAY); - ++pService->m_ProbeInformation.m_u8SentCount; + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Did sent host probe\n\n"));); + m_HostProbeInformation.m_Timeout.reset(MDNS_PROBE_DELAY); + ++m_HostProbeInformation.m_u8SentCount; } } else // Probing finished { - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Done service probing %s.%s.%s\n\n"), (pService->m_pcName ?: m_pcHostname), pService->m_pcService, pService->m_pcProtocol);); - pService->m_ProbeInformation.m_ProbingStatus = ProbingStatus_Done; - pService->m_ProbeInformation.m_Timeout.resetToNeverExpires(); - if (pService->m_ProbeInformation.m_fnServiceProbeResultCallback) + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Done host probing.\n"));); + m_HostProbeInformation.m_ProbingStatus = ProbingStatus_Done; + m_HostProbeInformation.m_Timeout.resetToNeverExpires(); + if (m_HostProbeInformation.m_fnHostProbeResultCallback) { - pService->m_ProbeInformation.m_fnServiceProbeResultCallback(pService->m_pcName, pService, true); + m_HostProbeInformation.m_fnHostProbeResultCallback(m_pcHostname, true); } - // Prepare to announce service - pService->m_ProbeInformation.m_u8SentCount = 0; - pService->m_ProbeInformation.m_Timeout.reset(MDNS_ANNOUNCE_DELAY); - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Prepared service announcing.\n\n"));); + + // Prepare to announce host + m_HostProbeInformation.m_u8SentCount = 0; + m_HostProbeInformation.m_Timeout.reset(MDNS_ANNOUNCE_DELAY); + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Prepared host announcing.\n\n"));); } } // else: Probing already finished OR waiting for next time slot - else if ((ProbingStatus_Done == pService->m_ProbeInformation.m_ProbingStatus) && - (pService->m_ProbeInformation.m_Timeout.expired())) + else if ((ProbingStatus_Done == m_HostProbeInformation.m_ProbingStatus) && (m_HostProbeInformation.m_Timeout.expired())) { - if ((bResult = _announceService(*pService))) // Announce service + if ((bResult = _announce(true, false))) // Don't announce services here { - ++pService->m_ProbeInformation.m_u8SentCount; + ++m_HostProbeInformation.m_u8SentCount; - if (MDNS_ANNOUNCE_COUNT > pService->m_ProbeInformation.m_u8SentCount) + if (MDNS_ANNOUNCE_COUNT > m_HostProbeInformation.m_u8SentCount) { - pService->m_ProbeInformation.m_Timeout.reset(MDNS_ANNOUNCE_DELAY); - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Announcing service %s.%s.%s (%d)\n\n"), (pService->m_pcName ?: m_pcHostname), pService->m_pcService, pService->m_pcProtocol, pService->m_ProbeInformation.m_u8SentCount);); + m_HostProbeInformation.m_Timeout.reset(MDNS_ANNOUNCE_DELAY); + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Announcing host (%d).\n\n"), m_HostProbeInformation.m_u8SentCount);); } else { + m_HostProbeInformation.m_Timeout.resetToNeverExpires(); + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Done host announcing.\n\n"));); + } + } + } + + // + // Probe services + for (stcMDNSService* pService = m_pServices; ((bResult) && (pService)); pService = pService->m_pNext) + { + if (ProbingStatus_ReadyToStart == pService->m_ProbeInformation.m_ProbingStatus) // Ready to get started + { + pService->m_ProbeInformation.m_Timeout.reset(MDNS_PROBE_DELAY); // More or equal than first probe for host domain + pService->m_ProbeInformation.m_ProbingStatus = ProbingStatus_InProgress; + } + else if ((ProbingStatus_InProgress == pService->m_ProbeInformation.m_ProbingStatus) && // Probing AND + (pService->m_ProbeInformation.m_Timeout.expired())) // Time for next probe + { + if (MDNS_PROBE_COUNT > pService->m_ProbeInformation.m_u8SentCount) // Send next probe + { + if ((bResult = _sendServiceProbe(*pService))) + { + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Did sent service probe (%u)\n\n"), (pService->m_ProbeInformation.m_u8SentCount + 1));); + pService->m_ProbeInformation.m_Timeout.reset(MDNS_PROBE_DELAY); + ++pService->m_ProbeInformation.m_u8SentCount; + } + } + else // Probing finished + { + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Done service probing %s.%s.%s\n\n"), (pService->m_pcName ?: m_pcHostname), pService->m_pcService, pService->m_pcProtocol);); + pService->m_ProbeInformation.m_ProbingStatus = ProbingStatus_Done; pService->m_ProbeInformation.m_Timeout.resetToNeverExpires(); - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Done service announcing for %s.%s.%s\n\n"), (pService->m_pcName ?: m_pcHostname), pService->m_pcService, pService->m_pcProtocol);); + if (pService->m_ProbeInformation.m_fnServiceProbeResultCallback) + { + pService->m_ProbeInformation.m_fnServiceProbeResultCallback(pService->m_pcName, pService, true); + } + // Prepare to announce service + pService->m_ProbeInformation.m_u8SentCount = 0; + pService->m_ProbeInformation.m_Timeout.reset(MDNS_ANNOUNCE_DELAY); + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Prepared service announcing.\n\n"));); + } + } // else: Probing already finished OR waiting for next time slot + else if ((ProbingStatus_Done == pService->m_ProbeInformation.m_ProbingStatus) && (pService->m_ProbeInformation.m_Timeout.expired())) + { + if ((bResult = _announceService(*pService))) // Announce service + { + ++pService->m_ProbeInformation.m_u8SentCount; + + if (MDNS_ANNOUNCE_COUNT > pService->m_ProbeInformation.m_u8SentCount) + { + pService->m_ProbeInformation.m_Timeout.reset(MDNS_ANNOUNCE_DELAY); + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Announcing service %s.%s.%s (%d)\n\n"), (pService->m_pcName ?: m_pcHostname), pService->m_pcService, pService->m_pcProtocol, pService->m_ProbeInformation.m_u8SentCount);); + } + else + { + pService->m_ProbeInformation.m_Timeout.resetToNeverExpires(); + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Done service announcing for %s.%s.%s\n\n"), (pService->m_pcName ?: m_pcHostname), pService->m_pcService, pService->m_pcProtocol);); + } } } } + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: FAILED!\n\n")); + }); + return bResult; } - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: FAILED!\n\n")); - }); - return bResult; -} -/* + /* MDNSResponder::_resetProbeStatus Resets the probe status. @@ -1293,36 +1259,36 @@ bool MDNSResponder::_updateProbeStatus(void) when running 'updateProbeStatus' (which is done in every '_update' loop), the probing process is restarted. */ -bool MDNSResponder::_resetProbeStatus(bool p_bRestart /*= true*/) -{ - m_HostProbeInformation.clear(false); - m_HostProbeInformation.m_ProbingStatus = (p_bRestart ? ProbingStatus_ReadyToStart : ProbingStatus_Done); - - for (stcMDNSService* pService = m_pServices; pService; pService = pService->m_pNext) + bool MDNSResponder::_resetProbeStatus(bool p_bRestart /*= true*/) { - pService->m_ProbeInformation.clear(false); - pService->m_ProbeInformation.m_ProbingStatus = (p_bRestart ? ProbingStatus_ReadyToStart : ProbingStatus_Done); + m_HostProbeInformation.clear(false); + m_HostProbeInformation.m_ProbingStatus = (p_bRestart ? ProbingStatus_ReadyToStart : ProbingStatus_Done); + + for (stcMDNSService* pService = m_pServices; pService; pService = pService->m_pNext) + { + pService->m_ProbeInformation.clear(false); + pService->m_ProbeInformation.m_ProbingStatus = (p_bRestart ? ProbingStatus_ReadyToStart : ProbingStatus_Done); + } + return true; } - return true; -} -/* + /* MDNSResponder::_hasProbesWaitingForAnswers */ -bool MDNSResponder::_hasProbesWaitingForAnswers(void) const -{ - bool bResult = ((ProbingStatus_InProgress == m_HostProbeInformation.m_ProbingStatus) && // Probing - (0 < m_HostProbeInformation.m_u8SentCount)); // And really probing - - for (stcMDNSService* pService = m_pServices; ((!bResult) && (pService)); pService = pService->m_pNext) + bool MDNSResponder::_hasProbesWaitingForAnswers(void) const { - bResult = ((ProbingStatus_InProgress == pService->m_ProbeInformation.m_ProbingStatus) && // Probing - (0 < pService->m_ProbeInformation.m_u8SentCount)); // And really probing + bool bResult = ((ProbingStatus_InProgress == m_HostProbeInformation.m_ProbingStatus) && // Probing + (0 < m_HostProbeInformation.m_u8SentCount)); // And really probing + + for (stcMDNSService* pService = m_pServices; ((!bResult) && (pService)); pService = pService->m_pNext) + { + bResult = ((ProbingStatus_InProgress == pService->m_ProbeInformation.m_ProbingStatus) && // Probing + (0 < pService->m_ProbeInformation.m_u8SentCount)); // And really probing + } + return bResult; } - return bResult; -} -/* + /* MDNSResponder::_sendHostProbe Asks (probes) in the local network for the planned host domain @@ -1333,50 +1299,48 @@ bool MDNSResponder::_hasProbesWaitingForAnswers(void) const Host domain: - A/AAAA (eg. esp8266.esp -> 192.168.2.120) */ -bool MDNSResponder::_sendHostProbe(void) -{ - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendHostProbe (%s, %lu)\n"), m_pcHostname, millis());); + bool MDNSResponder::_sendHostProbe(void) + { + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendHostProbe (%s, %lu)\n"), m_pcHostname, millis());); - bool bResult = true; + bool bResult = true; - // Requests for host domain - stcMDNSSendParameter sendParameter; - sendParameter.m_bCacheFlush = false; // RFC 6762 10.2 + // Requests for host domain + stcMDNSSendParameter sendParameter; + sendParameter.m_bCacheFlush = false; // RFC 6762 10.2 - sendParameter.m_pQuestions = new stcMDNS_RRQuestion; - if (((bResult = (0 != sendParameter.m_pQuestions))) && - ((bResult = _buildDomainForHost(m_pcHostname, sendParameter.m_pQuestions->m_Header.m_Domain)))) - { - //sendParameter.m_pQuestions->m_bUnicast = true; - sendParameter.m_pQuestions->m_Header.m_Attributes.m_u16Type = DNS_RRTYPE_ANY; - sendParameter.m_pQuestions->m_Header.m_Attributes.m_u16Class = (0x8000 | DNS_RRCLASS_IN); // Unicast & INternet + sendParameter.m_pQuestions = new stcMDNS_RRQuestion; + if (((bResult = (0 != sendParameter.m_pQuestions))) && ((bResult = _buildDomainForHost(m_pcHostname, sendParameter.m_pQuestions->m_Header.m_Domain)))) + { + //sendParameter.m_pQuestions->m_bUnicast = true; + sendParameter.m_pQuestions->m_Header.m_Attributes.m_u16Type = DNS_RRTYPE_ANY; + sendParameter.m_pQuestions->m_Header.m_Attributes.m_u16Class = (0x8000 | DNS_RRCLASS_IN); // Unicast & INternet - // Add known answers + // Add known answers #ifdef MDNS_IP4_SUPPORT - sendParameter.m_u8HostReplyMask |= ContentFlag_A; // Add A answer + sendParameter.m_u8HostReplyMask |= ContentFlag_A; // Add A answer #endif #ifdef MDNS_IP6_SUPPORT - sendParameter.m_u8HostReplyMask |= ContentFlag_AAAA; // Add AAAA answer + sendParameter.m_u8HostReplyMask |= ContentFlag_AAAA; // Add AAAA answer #endif - } - else - { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendHostProbe: FAILED to create host question!\n"));); - if (sendParameter.m_pQuestions) + } + else { - delete sendParameter.m_pQuestions; - sendParameter.m_pQuestions = 0; + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendHostProbe: FAILED to create host question!\n"));); + if (sendParameter.m_pQuestions) + { + delete sendParameter.m_pQuestions; + sendParameter.m_pQuestions = 0; + } } + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendHostProbe: FAILED!\n")); + }); + return ((bResult) && (_sendMDNSMessage(sendParameter))); } - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendHostProbe: FAILED!\n")); - }); - return ((bResult) && - (_sendMDNSMessage(sendParameter))); -} -/* + /* MDNSResponder::_sendServiceProbe Asks (probes) in the local network for the planned service instance domain @@ -1388,89 +1352,87 @@ bool MDNSResponder::_sendHostProbe(void) - SRV (eg. MyESP._http._tcp.local -> 5000 esp8266.local) - PTR NAME (eg. _http._tcp.local -> MyESP._http._tcp.local) (TODO: Check if needed, maybe TXT is better) */ -bool MDNSResponder::_sendServiceProbe(stcMDNSService& p_rService) -{ - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendServiceProbe (%s.%s.%s, %lu)\n"), (p_rService.m_pcName ?: m_pcHostname), p_rService.m_pcService, p_rService.m_pcProtocol, millis());); - - bool bResult = true; + bool MDNSResponder::_sendServiceProbe(stcMDNSService& p_rService) + { + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendServiceProbe (%s.%s.%s, %lu)\n"), (p_rService.m_pcName ?: m_pcHostname), p_rService.m_pcService, p_rService.m_pcProtocol, millis());); - // Requests for service instance domain - stcMDNSSendParameter sendParameter; - sendParameter.m_bCacheFlush = false; // RFC 6762 10.2 + bool bResult = true; - sendParameter.m_pQuestions = new stcMDNS_RRQuestion; - if (((bResult = (0 != sendParameter.m_pQuestions))) && - ((bResult = _buildDomainForService(p_rService, true, sendParameter.m_pQuestions->m_Header.m_Domain)))) - { - sendParameter.m_pQuestions->m_bUnicast = true; - sendParameter.m_pQuestions->m_Header.m_Attributes.m_u16Type = DNS_RRTYPE_ANY; - sendParameter.m_pQuestions->m_Header.m_Attributes.m_u16Class = (0x8000 | DNS_RRCLASS_IN); // Unicast & INternet + // Requests for service instance domain + stcMDNSSendParameter sendParameter; + sendParameter.m_bCacheFlush = false; // RFC 6762 10.2 - // Add known answers - p_rService.m_u8ReplyMask = (ContentFlag_SRV | ContentFlag_PTR_NAME); // Add SRV and PTR NAME answers - } - else - { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendServiceProbe: FAILED to create service question!\n"));); - if (sendParameter.m_pQuestions) + sendParameter.m_pQuestions = new stcMDNS_RRQuestion; + if (((bResult = (0 != sendParameter.m_pQuestions))) && ((bResult = _buildDomainForService(p_rService, true, sendParameter.m_pQuestions->m_Header.m_Domain)))) + { + sendParameter.m_pQuestions->m_bUnicast = true; + sendParameter.m_pQuestions->m_Header.m_Attributes.m_u16Type = DNS_RRTYPE_ANY; + sendParameter.m_pQuestions->m_Header.m_Attributes.m_u16Class = (0x8000 | DNS_RRCLASS_IN); // Unicast & INternet + + // Add known answers + p_rService.m_u8ReplyMask = (ContentFlag_SRV | ContentFlag_PTR_NAME); // Add SRV and PTR NAME answers + } + else { - delete sendParameter.m_pQuestions; - sendParameter.m_pQuestions = 0; + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendServiceProbe: FAILED to create service question!\n"));); + if (sendParameter.m_pQuestions) + { + delete sendParameter.m_pQuestions; + sendParameter.m_pQuestions = 0; + } } + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendServiceProbe: FAILED!\n")); + }); + return ((bResult) && (_sendMDNSMessage(sendParameter))); } - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendServiceProbe: FAILED!\n")); - }); - return ((bResult) && - (_sendMDNSMessage(sendParameter))); -} -/* + /* MDNSResponder::_cancelProbingForHost */ -bool MDNSResponder::_cancelProbingForHost(void) -{ - bool bResult = false; - - m_HostProbeInformation.clear(false); - // Send host notification - if (m_HostProbeInformation.m_fnHostProbeResultCallback) + bool MDNSResponder::_cancelProbingForHost(void) { - m_HostProbeInformation.m_fnHostProbeResultCallback(m_pcHostname, false); + bool bResult = false; - bResult = true; - } + m_HostProbeInformation.clear(false); + // Send host notification + if (m_HostProbeInformation.m_fnHostProbeResultCallback) + { + m_HostProbeInformation.m_fnHostProbeResultCallback(m_pcHostname, false); - for (stcMDNSService* pService = m_pServices; ((!bResult) && (pService)); pService = pService->m_pNext) - { - bResult = _cancelProbingForService(*pService); + bResult = true; + } + + for (stcMDNSService* pService = m_pServices; ((!bResult) && (pService)); pService = pService->m_pNext) + { + bResult = _cancelProbingForService(*pService); + } + return bResult; } - return bResult; -} -/* + /* MDNSResponder::_cancelProbingForService */ -bool MDNSResponder::_cancelProbingForService(stcMDNSService& p_rService) -{ - bool bResult = false; - - p_rService.m_ProbeInformation.clear(false); - // Send notification - if (p_rService.m_ProbeInformation.m_fnServiceProbeResultCallback) + bool MDNSResponder::_cancelProbingForService(stcMDNSService& p_rService) { - p_rService.m_ProbeInformation.m_fnServiceProbeResultCallback(p_rService.m_pcName, &p_rService, false); - bResult = true; + bool bResult = false; + + p_rService.m_ProbeInformation.clear(false); + // Send notification + if (p_rService.m_ProbeInformation.m_fnServiceProbeResultCallback) + { + p_rService.m_ProbeInformation.m_fnServiceProbeResultCallback(p_rService.m_pcName, &p_rService, false); + bResult = true; + } + return bResult; } - return bResult; -} -/** + /** ANNOUNCING */ -/* + /* MDNSResponder::_announce Announces the host domain: @@ -1487,110 +1449,108 @@ bool MDNSResponder::_cancelProbingForService(stcMDNSService& p_rService) Goodbye messages are created by setting the TTL for the answer to 0, this happens inside the '_writeXXXAnswer' procs via 'sendParameter.m_bUnannounce = true' */ -bool MDNSResponder::_announce(bool p_bAnnounce, - bool p_bIncludeServices) -{ - bool bResult = false; - - stcMDNSSendParameter sendParameter; - if (ProbingStatus_Done == m_HostProbeInformation.m_ProbingStatus) + bool MDNSResponder::_announce(bool p_bAnnounce, + bool p_bIncludeServices) { - bResult = true; + bool bResult = false; + + stcMDNSSendParameter sendParameter; + if (ProbingStatus_Done == m_HostProbeInformation.m_ProbingStatus) + { + bResult = true; - sendParameter.m_bResponse = true; // Announces are 'Unsolicited authoritative responses' - sendParameter.m_bAuthorative = true; - sendParameter.m_bUnannounce = !p_bAnnounce; // When unannouncing, the TTL is set to '0' while creating the answers + sendParameter.m_bResponse = true; // Announces are 'Unsolicited authoritative responses' + sendParameter.m_bAuthorative = true; + sendParameter.m_bUnannounce = !p_bAnnounce; // When unannouncing, the TTL is set to '0' while creating the answers - // Announce host - sendParameter.m_u8HostReplyMask = 0; + // Announce host + sendParameter.m_u8HostReplyMask = 0; #ifdef MDNS_IP4_SUPPORT - sendParameter.m_u8HostReplyMask |= ContentFlag_A; // A answer - sendParameter.m_u8HostReplyMask |= ContentFlag_PTR_IP4; // PTR_IP4 answer + sendParameter.m_u8HostReplyMask |= ContentFlag_A; // A answer + sendParameter.m_u8HostReplyMask |= ContentFlag_PTR_IP4; // PTR_IP4 answer #endif #ifdef MDNS_IP6_SUPPORT - sendParameter.m_u8HostReplyMask |= ContentFlag_AAAA; // AAAA answer - sendParameter.m_u8HostReplyMask |= ContentFlag_PTR_IP6; // PTR_IP6 answer + sendParameter.m_u8HostReplyMask |= ContentFlag_AAAA; // AAAA answer + sendParameter.m_u8HostReplyMask |= ContentFlag_PTR_IP6; // PTR_IP6 answer #endif - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _announce: Announcing host %s (content 0x%X)\n"), m_pcHostname, sendParameter.m_u8HostReplyMask);); + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _announce: Announcing host %s (content 0x%X)\n"), m_pcHostname, sendParameter.m_u8HostReplyMask);); - if (p_bIncludeServices) - { - // Announce services (service type, name, SRV (location) and TXTs) - for (stcMDNSService* pService = m_pServices; ((bResult) && (pService)); pService = pService->m_pNext) + if (p_bIncludeServices) { - if (ProbingStatus_Done == pService->m_ProbeInformation.m_ProbingStatus) + // Announce services (service type, name, SRV (location) and TXTs) + for (stcMDNSService* pService = m_pServices; ((bResult) && (pService)); pService = pService->m_pNext) { - pService->m_u8ReplyMask = (ContentFlag_PTR_TYPE | ContentFlag_PTR_NAME | ContentFlag_SRV | ContentFlag_TXT); + if (ProbingStatus_Done == pService->m_ProbeInformation.m_ProbingStatus) + { + pService->m_u8ReplyMask = (ContentFlag_PTR_TYPE | ContentFlag_PTR_NAME | ContentFlag_SRV | ContentFlag_TXT); - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _announce: Announcing service %s.%s.%s (content %u)\n"), (pService->m_pcName ?: m_pcHostname), pService->m_pcService, pService->m_pcProtocol, pService->m_u8ReplyMask);); + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _announce: Announcing service %s.%s.%s (content %u)\n"), (pService->m_pcName ?: m_pcHostname), pService->m_pcService, pService->m_pcProtocol, pService->m_u8ReplyMask);); + } } } } + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _announce: FAILED!\n")); + }); + return ((bResult) && (_sendMDNSMessage(sendParameter))); } - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _announce: FAILED!\n")); - }); - return ((bResult) && - (_sendMDNSMessage(sendParameter))); -} -/* + /* MDNSResponder::_announceService */ -bool MDNSResponder::_announceService(stcMDNSService& p_rService, - bool p_bAnnounce /*= true*/) -{ - bool bResult = false; - - stcMDNSSendParameter sendParameter; - if (ProbingStatus_Done == p_rService.m_ProbeInformation.m_ProbingStatus) + bool MDNSResponder::_announceService(stcMDNSService& p_rService, + bool p_bAnnounce /*= true*/) { - sendParameter.m_bResponse = true; // Announces are 'Unsolicited authoritative responses' - sendParameter.m_bAuthorative = true; - sendParameter.m_bUnannounce = !p_bAnnounce; // When unannouncing, the TTL is set to '0' while creating the answers + bool bResult = false; + + stcMDNSSendParameter sendParameter; + if (ProbingStatus_Done == p_rService.m_ProbeInformation.m_ProbingStatus) + { + sendParameter.m_bResponse = true; // Announces are 'Unsolicited authoritative responses' + sendParameter.m_bAuthorative = true; + sendParameter.m_bUnannounce = !p_bAnnounce; // When unannouncing, the TTL is set to '0' while creating the answers - // DON'T announce host - sendParameter.m_u8HostReplyMask = 0; + // DON'T announce host + sendParameter.m_u8HostReplyMask = 0; - // Announce services (service type, name, SRV (location) and TXTs) - p_rService.m_u8ReplyMask = (ContentFlag_PTR_TYPE | ContentFlag_PTR_NAME | ContentFlag_SRV | ContentFlag_TXT); - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _announceService: Announcing service %s.%s.%s (content 0x%X)\n"), (p_rService.m_pcName ?: m_pcHostname), p_rService.m_pcService, p_rService.m_pcProtocol, p_rService.m_u8ReplyMask);); + // Announce services (service type, name, SRV (location) and TXTs) + p_rService.m_u8ReplyMask = (ContentFlag_PTR_TYPE | ContentFlag_PTR_NAME | ContentFlag_SRV | ContentFlag_TXT); + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _announceService: Announcing service %s.%s.%s (content 0x%X)\n"), (p_rService.m_pcName ?: m_pcHostname), p_rService.m_pcService, p_rService.m_pcProtocol, p_rService.m_u8ReplyMask);); - bResult = true; + bResult = true; + } + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _announceService: FAILED!\n")); + }); + return ((bResult) && (_sendMDNSMessage(sendParameter))); } - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _announceService: FAILED!\n")); - }); - return ((bResult) && - (_sendMDNSMessage(sendParameter))); -} -/** + /** SERVICE QUERY CACHE */ -/* + /* MDNSResponder::_hasServiceQueriesWaitingForAnswers */ -bool MDNSResponder::_hasServiceQueriesWaitingForAnswers(void) const -{ - bool bOpenQueries = false; - - for (stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; pServiceQuery; pServiceQuery = pServiceQuery->m_pNext) + bool MDNSResponder::_hasServiceQueriesWaitingForAnswers(void) const { - if (pServiceQuery->m_bAwaitingAnswers) + bool bOpenQueries = false; + + for (stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; pServiceQuery; pServiceQuery = pServiceQuery->m_pNext) { - bOpenQueries = true; - break; + if (pServiceQuery->m_bAwaitingAnswers) + { + bOpenQueries = true; + break; + } } + return bOpenQueries; } - return bOpenQueries; -} -/* + /* MDNSResponder::_checkServiceQueryCache For any 'living' service query (m_bAwaitingAnswers == true) all available answers (their components) @@ -1599,281 +1559,268 @@ bool MDNSResponder::_hasServiceQueriesWaitingForAnswers(void) const When no update arrived (in time), the component is removed from the answer (cache). */ -bool MDNSResponder::_checkServiceQueryCache(void) -{ - bool bResult = true; - - DEBUG_EX_INFO( - bool printedInfo = false;); - for (stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; ((bResult) && (pServiceQuery)); pServiceQuery = pServiceQuery->m_pNext) + bool MDNSResponder::_checkServiceQueryCache(void) { - // - // Resend dynamic service queries, if not already done often enough - if ((!pServiceQuery->m_bLegacyQuery) && - (MDNS_DYNAMIC_QUERY_RESEND_COUNT > pServiceQuery->m_u8SentCount) && - (pServiceQuery->m_ResendTimeout.expired())) + bool bResult = true; + + DEBUG_EX_INFO( + bool printedInfo = false;); + for (stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; ((bResult) && (pServiceQuery)); pServiceQuery = pServiceQuery->m_pNext) { - if ((bResult = _sendMDNSServiceQuery(*pServiceQuery))) + // + // Resend dynamic service queries, if not already done often enough + if ((!pServiceQuery->m_bLegacyQuery) && (MDNS_DYNAMIC_QUERY_RESEND_COUNT > pServiceQuery->m_u8SentCount) && (pServiceQuery->m_ResendTimeout.expired())) { - ++pServiceQuery->m_u8SentCount; - pServiceQuery->m_ResendTimeout.reset((MDNS_DYNAMIC_QUERY_RESEND_COUNT > pServiceQuery->m_u8SentCount) - ? (MDNS_DYNAMIC_QUERY_RESEND_DELAY * (pServiceQuery->m_u8SentCount - 1)) - : esp8266::polledTimeout::oneShotMs::neverExpires); + if ((bResult = _sendMDNSServiceQuery(*pServiceQuery))) + { + ++pServiceQuery->m_u8SentCount; + pServiceQuery->m_ResendTimeout.reset((MDNS_DYNAMIC_QUERY_RESEND_COUNT > pServiceQuery->m_u8SentCount) + ? (MDNS_DYNAMIC_QUERY_RESEND_DELAY * (pServiceQuery->m_u8SentCount - 1)) + : esp8266::polledTimeout::oneShotMs::neverExpires); + } + DEBUG_EX_INFO( + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: %s to resend service query!"), (bResult ? "Succeeded" : "FAILED")); + printedInfo = true;); } - DEBUG_EX_INFO( - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: %s to resend service query!"), (bResult ? "Succeeded" : "FAILED")); - printedInfo = true;); - } - // - // Schedule updates for cached answers - if (pServiceQuery->m_bAwaitingAnswers) - { - stcMDNSServiceQuery::stcAnswer* pSQAnswer = pServiceQuery->m_pAnswers; - while ((bResult) && - (pSQAnswer)) + // + // Schedule updates for cached answers + if (pServiceQuery->m_bAwaitingAnswers) { - stcMDNSServiceQuery::stcAnswer* pNextSQAnswer = pSQAnswer->m_pNext; - - // 1. level answer - if ((bResult) && - (pSQAnswer->m_TTLServiceDomain.flagged())) + stcMDNSServiceQuery::stcAnswer* pSQAnswer = pServiceQuery->m_pAnswers; + while ((bResult) && (pSQAnswer)) { - if (!pSQAnswer->m_TTLServiceDomain.finalTimeoutLevel()) - { - bResult = ((_sendMDNSServiceQuery(*pServiceQuery)) && - (pSQAnswer->m_TTLServiceDomain.restart())); - DEBUG_EX_INFO( - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: PTR update scheduled for ")); - _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR(" %s\n"), (bResult ? "OK" : "FAILURE")); - printedInfo = true;); - } - else + stcMDNSServiceQuery::stcAnswer* pNextSQAnswer = pSQAnswer->m_pNext; + + // 1. level answer + if ((bResult) && (pSQAnswer->m_TTLServiceDomain.flagged())) { - // Timed out! -> Delete - if (pServiceQuery->m_fnCallback) + if (!pSQAnswer->m_TTLServiceDomain.finalTimeoutLevel()) { - MDNSServiceInfo serviceInfo(*this, (hMDNSServiceQuery)pServiceQuery, pServiceQuery->indexOfAnswer(pSQAnswer)); - pServiceQuery->m_fnCallback(serviceInfo, static_cast(ServiceQueryAnswerType_ServiceDomain), false); + bResult = ((_sendMDNSServiceQuery(*pServiceQuery)) && (pSQAnswer->m_TTLServiceDomain.restart())); + DEBUG_EX_INFO( + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: PTR update scheduled for ")); + _printRRDomain(pSQAnswer->m_ServiceDomain); + DEBUG_OUTPUT.printf_P(PSTR(" %s\n"), (bResult ? "OK" : "FAILURE")); + printedInfo = true;); } - DEBUG_EX_INFO( - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: Will remove PTR answer for ")); - _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR("\n")); - printedInfo = true;); + else + { + // Timed out! -> Delete + if (pServiceQuery->m_fnCallback) + { + MDNSServiceInfo serviceInfo(*this, (hMDNSServiceQuery)pServiceQuery, pServiceQuery->indexOfAnswer(pSQAnswer)); + pServiceQuery->m_fnCallback(serviceInfo, static_cast(ServiceQueryAnswerType_ServiceDomain), false); + } + DEBUG_EX_INFO( + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: Will remove PTR answer for ")); + _printRRDomain(pSQAnswer->m_ServiceDomain); + DEBUG_OUTPUT.printf_P(PSTR("\n")); + printedInfo = true;); - bResult = pServiceQuery->removeAnswer(pSQAnswer); - pSQAnswer = 0; - continue; // Don't use this answer anymore - } - } // ServiceDomain flagged + bResult = pServiceQuery->removeAnswer(pSQAnswer); + pSQAnswer = 0; + continue; // Don't use this answer anymore + } + } // ServiceDomain flagged - // 2. level answers - // HostDomain & Port (from SRV) - if ((bResult) && - (pSQAnswer->m_TTLHostDomainAndPort.flagged())) - { - if (!pSQAnswer->m_TTLHostDomainAndPort.finalTimeoutLevel()) - { - bResult = ((_sendMDNSQuery(pSQAnswer->m_ServiceDomain, DNS_RRTYPE_SRV)) && - (pSQAnswer->m_TTLHostDomainAndPort.restart())); - DEBUG_EX_INFO( - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: SRV update scheduled for ")); - _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR(" host domain and port %s\n"), (bResult ? "OK" : "FAILURE")); - printedInfo = true;); - } - else + // 2. level answers + // HostDomain & Port (from SRV) + if ((bResult) && (pSQAnswer->m_TTLHostDomainAndPort.flagged())) { - // Timed out! -> Delete - DEBUG_EX_INFO( - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: Will remove SRV answer for ")); - _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR(" host domain and port\n")); - printedInfo = true;); - // Delete - pSQAnswer->m_HostDomain.clear(); - pSQAnswer->releaseHostDomain(); - pSQAnswer->m_u16Port = 0; - pSQAnswer->m_TTLHostDomainAndPort.set(0); - uint32_t u32ContentFlags = ServiceQueryAnswerType_HostDomainAndPort; - // As the host domain is the base for the IP4- and IP6Address, remove these too + if (!pSQAnswer->m_TTLHostDomainAndPort.finalTimeoutLevel()) + { + bResult = ((_sendMDNSQuery(pSQAnswer->m_ServiceDomain, DNS_RRTYPE_SRV)) && (pSQAnswer->m_TTLHostDomainAndPort.restart())); + DEBUG_EX_INFO( + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: SRV update scheduled for ")); + _printRRDomain(pSQAnswer->m_ServiceDomain); + DEBUG_OUTPUT.printf_P(PSTR(" host domain and port %s\n"), (bResult ? "OK" : "FAILURE")); + printedInfo = true;); + } + else + { + // Timed out! -> Delete + DEBUG_EX_INFO( + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: Will remove SRV answer for ")); + _printRRDomain(pSQAnswer->m_ServiceDomain); + DEBUG_OUTPUT.printf_P(PSTR(" host domain and port\n")); + printedInfo = true;); + // Delete + pSQAnswer->m_HostDomain.clear(); + pSQAnswer->releaseHostDomain(); + pSQAnswer->m_u16Port = 0; + pSQAnswer->m_TTLHostDomainAndPort.set(0); + uint32_t u32ContentFlags = ServiceQueryAnswerType_HostDomainAndPort; + // As the host domain is the base for the IP4- and IP6Address, remove these too #ifdef MDNS_IP4_SUPPORT - pSQAnswer->releaseIP4Addresses(); - u32ContentFlags |= ServiceQueryAnswerType_IP4Address; + pSQAnswer->releaseIP4Addresses(); + u32ContentFlags |= ServiceQueryAnswerType_IP4Address; #endif #ifdef MDNS_IP6_SUPPORT - pSQAnswer->releaseIP6Addresses(); - u32ContentFlags |= ServiceQueryAnswerType_IP6Address; + pSQAnswer->releaseIP6Addresses(); + u32ContentFlags |= ServiceQueryAnswerType_IP6Address; #endif - // Remove content flags for deleted answer parts - pSQAnswer->m_u32ContentFlags &= ~u32ContentFlags; - if (pServiceQuery->m_fnCallback) - { - MDNSServiceInfo serviceInfo(*this, (hMDNSServiceQuery)pServiceQuery, pServiceQuery->indexOfAnswer(pSQAnswer)); - pServiceQuery->m_fnCallback(serviceInfo, static_cast(u32ContentFlags), false); - } - } - } // HostDomainAndPort flagged - - // Txts (from TXT) - if ((bResult) && - (pSQAnswer->m_TTLTxts.flagged())) - { - if (!pSQAnswer->m_TTLTxts.finalTimeoutLevel()) - { - bResult = ((_sendMDNSQuery(pSQAnswer->m_ServiceDomain, DNS_RRTYPE_TXT)) && - (pSQAnswer->m_TTLTxts.restart())); - DEBUG_EX_INFO( - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: TXT update scheduled for ")); - _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR(" TXTs %s\n"), (bResult ? "OK" : "FAILURE")); - printedInfo = true;); - } - else - { - // Timed out! -> Delete - DEBUG_EX_INFO( - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: Will remove TXT answer for ")); - _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR(" TXTs\n")); - printedInfo = true;); - // Delete - pSQAnswer->m_Txts.clear(); - pSQAnswer->m_TTLTxts.set(0); - - // Remove content flags for deleted answer parts - pSQAnswer->m_u32ContentFlags &= ~ServiceQueryAnswerType_Txts; - - if (pServiceQuery->m_fnCallback) - { - MDNSServiceInfo serviceInfo(*this, (hMDNSServiceQuery)pServiceQuery, pServiceQuery->indexOfAnswer(pSQAnswer)); - pServiceQuery->m_fnCallback(serviceInfo, static_cast(ServiceQueryAnswerType_Txts), false); + // Remove content flags for deleted answer parts + pSQAnswer->m_u32ContentFlags &= ~u32ContentFlags; + if (pServiceQuery->m_fnCallback) + { + MDNSServiceInfo serviceInfo(*this, (hMDNSServiceQuery)pServiceQuery, pServiceQuery->indexOfAnswer(pSQAnswer)); + pServiceQuery->m_fnCallback(serviceInfo, static_cast(u32ContentFlags), false); + } } - } - } // TXTs flagged - - // 3. level answers -#ifdef MDNS_IP4_SUPPORT - // IP4Address (from A) - stcMDNSServiceQuery::stcAnswer::stcIP4Address* pIP4Address = pSQAnswer->m_pIP4Addresses; - bool bAUpdateQuerySent = false; - while ((pIP4Address) && - (bResult)) - { - stcMDNSServiceQuery::stcAnswer::stcIP4Address* pNextIP4Address = pIP4Address->m_pNext; // Get 'next' early, as 'current' may be deleted at the end... + } // HostDomainAndPort flagged - if (pIP4Address->m_TTL.flagged()) + // Txts (from TXT) + if ((bResult) && (pSQAnswer->m_TTLTxts.flagged())) { - if (!pIP4Address->m_TTL.finalTimeoutLevel()) // Needs update + if (!pSQAnswer->m_TTLTxts.finalTimeoutLevel()) { - if ((bAUpdateQuerySent) || - ((bResult = _sendMDNSQuery(pSQAnswer->m_HostDomain, DNS_RRTYPE_A)))) - { - pIP4Address->m_TTL.restart(); - bAUpdateQuerySent = true; - - DEBUG_EX_INFO( - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: IP4 update scheduled for ")); - _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR(" IP4 address (%s)\n"), (pIP4Address->m_IPAddress.toString().c_str())); - printedInfo = true;); - } + bResult = ((_sendMDNSQuery(pSQAnswer->m_ServiceDomain, DNS_RRTYPE_TXT)) && (pSQAnswer->m_TTLTxts.restart())); + DEBUG_EX_INFO( + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: TXT update scheduled for ")); + _printRRDomain(pSQAnswer->m_ServiceDomain); + DEBUG_OUTPUT.printf_P(PSTR(" TXTs %s\n"), (bResult ? "OK" : "FAILURE")); + printedInfo = true;); } else { // Timed out! -> Delete DEBUG_EX_INFO( - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: Will remove IP4 answer for ")); + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: Will remove TXT answer for ")); _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR(" IP4 address\n")); + DEBUG_OUTPUT.printf_P(PSTR(" TXTs\n")); printedInfo = true;); - pSQAnswer->removeIP4Address(pIP4Address); - if (!pSQAnswer->m_pIP4Addresses) // NO IP4 address left -> remove content flag - { - pSQAnswer->m_u32ContentFlags &= ~ServiceQueryAnswerType_IP4Address; - } - // Notify client + // Delete + pSQAnswer->m_Txts.clear(); + pSQAnswer->m_TTLTxts.set(0); + + // Remove content flags for deleted answer parts + pSQAnswer->m_u32ContentFlags &= ~ServiceQueryAnswerType_Txts; + if (pServiceQuery->m_fnCallback) { MDNSServiceInfo serviceInfo(*this, (hMDNSServiceQuery)pServiceQuery, pServiceQuery->indexOfAnswer(pSQAnswer)); - pServiceQuery->m_fnCallback(serviceInfo, static_cast(ServiceQueryAnswerType_IP4Address), false); + pServiceQuery->m_fnCallback(serviceInfo, static_cast(ServiceQueryAnswerType_Txts), false); } } - } // IP4 flagged - - pIP4Address = pNextIP4Address; // Next - } // while -#endif -#ifdef MDNS_IP6_SUPPORT - // IP6Address (from AAAA) - stcMDNSServiceQuery::stcAnswer::stcIP6Address* pIP6Address = pSQAnswer->m_pIP6Addresses; - bool bAAAAUpdateQuerySent = false; - while ((pIP6Address) && - (bResult)) - { - stcMDNSServiceQuery::stcAnswer::stcIP6Address* pNextIP6Address = pIP6Address->m_pNext; // Get 'next' early, as 'current' may be deleted at the end... + } // TXTs flagged - if (pIP6Address->m_TTL.flagged()) + // 3. level answers +#ifdef MDNS_IP4_SUPPORT + // IP4Address (from A) + stcMDNSServiceQuery::stcAnswer::stcIP4Address* pIP4Address = pSQAnswer->m_pIP4Addresses; + bool bAUpdateQuerySent = false; + while ((pIP4Address) && (bResult)) { - if (!pIP6Address->m_TTL.finalTimeoutLevel()) // Needs update + stcMDNSServiceQuery::stcAnswer::stcIP4Address* pNextIP4Address = pIP4Address->m_pNext; // Get 'next' early, as 'current' may be deleted at the end... + + if (pIP4Address->m_TTL.flagged()) { - if ((bAAAAUpdateQuerySent) || - ((bResult = _sendMDNSQuery(pSQAnswer->m_HostDomain, DNS_RRTYPE_AAAA)))) + if (!pIP4Address->m_TTL.finalTimeoutLevel()) // Needs update { - pIP6Address->m_TTL.restart(); - bAAAAUpdateQuerySent = true; - + if ((bAUpdateQuerySent) || ((bResult = _sendMDNSQuery(pSQAnswer->m_HostDomain, DNS_RRTYPE_A)))) + { + pIP4Address->m_TTL.restart(); + bAUpdateQuerySent = true; + + DEBUG_EX_INFO( + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: IP4 update scheduled for ")); + _printRRDomain(pSQAnswer->m_ServiceDomain); + DEBUG_OUTPUT.printf_P(PSTR(" IP4 address (%s)\n"), (pIP4Address->m_IPAddress.toString().c_str())); + printedInfo = true;); + } + } + else + { + // Timed out! -> Delete DEBUG_EX_INFO( - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: IP6 update scheduled for ")); + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: Will remove IP4 answer for ")); _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR(" IP6 address (%s)\n"), (pIP6Address->m_IPAddress.toString().c_str())); + DEBUG_OUTPUT.printf_P(PSTR(" IP4 address\n")); printedInfo = true;); + pSQAnswer->removeIP4Address(pIP4Address); + if (!pSQAnswer->m_pIP4Addresses) // NO IP4 address left -> remove content flag + { + pSQAnswer->m_u32ContentFlags &= ~ServiceQueryAnswerType_IP4Address; + } + // Notify client + if (pServiceQuery->m_fnCallback) + { + MDNSServiceInfo serviceInfo(*this, (hMDNSServiceQuery)pServiceQuery, pServiceQuery->indexOfAnswer(pSQAnswer)); + pServiceQuery->m_fnCallback(serviceInfo, static_cast(ServiceQueryAnswerType_IP4Address), false); + } } - } - else + } // IP4 flagged + + pIP4Address = pNextIP4Address; // Next + } // while +#endif +#ifdef MDNS_IP6_SUPPORT + // IP6Address (from AAAA) + stcMDNSServiceQuery::stcAnswer::stcIP6Address* pIP6Address = pSQAnswer->m_pIP6Addresses; + bool bAAAAUpdateQuerySent = false; + while ((pIP6Address) && (bResult)) + { + stcMDNSServiceQuery::stcAnswer::stcIP6Address* pNextIP6Address = pIP6Address->m_pNext; // Get 'next' early, as 'current' may be deleted at the end... + + if (pIP6Address->m_TTL.flagged()) { - // Timed out! -> Delete - DEBUG_EX_INFO( - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: Will remove answer for ")); - _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR(" IP6Address\n")); - printedInfo = true;); - pSQAnswer->removeIP6Address(pIP6Address); - if (!pSQAnswer->m_pIP6Addresses) // NO IP6 address left -> remove content flag + if (!pIP6Address->m_TTL.finalTimeoutLevel()) // Needs update { - pSQAnswer->m_u32ContentFlags &= ~ServiceQueryAnswerType_IP6Address; + if ((bAAAAUpdateQuerySent) || ((bResult = _sendMDNSQuery(pSQAnswer->m_HostDomain, DNS_RRTYPE_AAAA)))) + { + pIP6Address->m_TTL.restart(); + bAAAAUpdateQuerySent = true; + + DEBUG_EX_INFO( + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: IP6 update scheduled for ")); + _printRRDomain(pSQAnswer->m_ServiceDomain); + DEBUG_OUTPUT.printf_P(PSTR(" IP6 address (%s)\n"), (pIP6Address->m_IPAddress.toString().c_str())); + printedInfo = true;); + } } - // Notify client - if (pServiceQuery->m_fnCallback) + else { - pServiceQuery->m_fnCallback(this, (hMDNSServiceQuery)pServiceQuery, pServiceQuery->indexOfAnswer(pSQAnswer), ServiceQueryAnswerType_IP6Address, false, pServiceQuery->m_pUserdata); + // Timed out! -> Delete + DEBUG_EX_INFO( + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: Will remove answer for ")); + _printRRDomain(pSQAnswer->m_ServiceDomain); + DEBUG_OUTPUT.printf_P(PSTR(" IP6Address\n")); + printedInfo = true;); + pSQAnswer->removeIP6Address(pIP6Address); + if (!pSQAnswer->m_pIP6Addresses) // NO IP6 address left -> remove content flag + { + pSQAnswer->m_u32ContentFlags &= ~ServiceQueryAnswerType_IP6Address; + } + // Notify client + if (pServiceQuery->m_fnCallback) + { + pServiceQuery->m_fnCallback(this, (hMDNSServiceQuery)pServiceQuery, pServiceQuery->indexOfAnswer(pSQAnswer), ServiceQueryAnswerType_IP6Address, false, pServiceQuery->m_pUserdata); + } } - } - } // IP6 flagged + } // IP6 flagged - pIP6Address = pNextIP6Address; // Next - } // while + pIP6Address = pNextIP6Address; // Next + } // while #endif - pSQAnswer = pNextSQAnswer; + pSQAnswer = pNextSQAnswer; + } } } + DEBUG_EX_INFO( + if (printedInfo) + { + DEBUG_OUTPUT.printf_P(PSTR("\n")); + }); + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: FAILED!\n")); + }); + return bResult; } - DEBUG_EX_INFO( - if (printedInfo) - { - DEBUG_OUTPUT.printf_P(PSTR("\n")); - }); - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _checkServiceQueryCache: FAILED!\n")); - }); - return bResult; -} -/* + /* MDNSResponder::_replyMaskForHost Determines the relevant host answers for the given question. @@ -1882,77 +1829,71 @@ bool MDNSResponder::_checkServiceQueryCache(void) In addition, a full name match (question domain == host domain) is marked. */ -uint8_t MDNSResponder::_replyMaskForHost(const MDNSResponder::stcMDNS_RRHeader& p_RRHeader, - bool* p_pbFullNameMatch /*= 0*/) const -{ - //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _replyMaskForHost\n"));); + uint8_t MDNSResponder::_replyMaskForHost(const MDNSResponder::stcMDNS_RRHeader& p_RRHeader, + bool* p_pbFullNameMatch /*= 0*/) const + { + //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _replyMaskForHost\n"));); - uint8_t u8ReplyMask = 0; - (p_pbFullNameMatch ? * p_pbFullNameMatch = false : 0); + uint8_t u8ReplyMask = 0; + (p_pbFullNameMatch ? * p_pbFullNameMatch = false : 0); - if ((DNS_RRCLASS_IN == p_RRHeader.m_Attributes.m_u16Class) || - (DNS_RRCLASS_ANY == p_RRHeader.m_Attributes.m_u16Class)) - { - if ((DNS_RRTYPE_PTR == p_RRHeader.m_Attributes.m_u16Type) || - (DNS_RRTYPE_ANY == p_RRHeader.m_Attributes.m_u16Type)) + if ((DNS_RRCLASS_IN == p_RRHeader.m_Attributes.m_u16Class) || (DNS_RRCLASS_ANY == p_RRHeader.m_Attributes.m_u16Class)) { - // PTR request -#ifdef MDNS_IP4_SUPPORT - stcMDNS_RRDomain reverseIP4Domain; - for (netif* pNetIf = netif_list; pNetIf; pNetIf = pNetIf->next) + if ((DNS_RRTYPE_PTR == p_RRHeader.m_Attributes.m_u16Type) || (DNS_RRTYPE_ANY == p_RRHeader.m_Attributes.m_u16Type)) { - if (netif_is_up(pNetIf)) + // PTR request +#ifdef MDNS_IP4_SUPPORT + stcMDNS_RRDomain reverseIP4Domain; + for (netif* pNetIf = netif_list; pNetIf; pNetIf = pNetIf->next) { - if ((_buildDomainForReverseIP4(pNetIf->ip_addr, reverseIP4Domain)) && - (p_RRHeader.m_Domain == reverseIP4Domain)) + if (netif_is_up(pNetIf)) { - // Reverse domain match - u8ReplyMask |= ContentFlag_PTR_IP4; + if ((_buildDomainForReverseIP4(pNetIf->ip_addr, reverseIP4Domain)) && (p_RRHeader.m_Domain == reverseIP4Domain)) + { + // Reverse domain match + u8ReplyMask |= ContentFlag_PTR_IP4; + } } } - } #endif #ifdef MDNS_IP6_SUPPORT - // TODO + // TODO #endif - } // Address qeuest + } // Address qeuest - stcMDNS_RRDomain hostDomain; - if ((_buildDomainForHost(m_pcHostname, hostDomain)) && - (p_RRHeader.m_Domain == hostDomain)) // Host domain match - { - (p_pbFullNameMatch ? (*p_pbFullNameMatch = true) : (0)); + stcMDNS_RRDomain hostDomain; + if ((_buildDomainForHost(m_pcHostname, hostDomain)) && (p_RRHeader.m_Domain == hostDomain)) // Host domain match + { + (p_pbFullNameMatch ? (*p_pbFullNameMatch = true) : (0)); #ifdef MDNS_IP4_SUPPORT - if ((DNS_RRTYPE_A == p_RRHeader.m_Attributes.m_u16Type) || - (DNS_RRTYPE_ANY == p_RRHeader.m_Attributes.m_u16Type)) - { - // IP4 address request - u8ReplyMask |= ContentFlag_A; - } + if ((DNS_RRTYPE_A == p_RRHeader.m_Attributes.m_u16Type) || (DNS_RRTYPE_ANY == p_RRHeader.m_Attributes.m_u16Type)) + { + // IP4 address request + u8ReplyMask |= ContentFlag_A; + } #endif #ifdef MDNS_IP6_SUPPORT - if ((DNS_RRTYPE_AAAA == p_RRHeader.m_Attributes.m_u16Type) || - (DNS_RRTYPE_ANY == p_RRHeader.m_Attributes.m_u16Type)) - { - // IP6 address request - u8ReplyMask |= ContentFlag_AAAA; - } + if ((DNS_RRTYPE_AAAA == p_RRHeader.m_Attributes.m_u16Type) || (DNS_RRTYPE_ANY == p_RRHeader.m_Attributes.m_u16Type)) + { + // IP6 address request + u8ReplyMask |= ContentFlag_AAAA; + } #endif + } } + else + { + //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _replyMaskForHost: INVALID RR-class (0x%04X)!\n"), p_RRHeader.m_Attributes.m_u16Class);); + } + DEBUG_EX_INFO(if (u8ReplyMask) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _replyMaskForHost: 0x%X\n"), u8ReplyMask); + }); + return u8ReplyMask; } - else - { - //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _replyMaskForHost: INVALID RR-class (0x%04X)!\n"), p_RRHeader.m_Attributes.m_u16Class);); - } - DEBUG_EX_INFO(if (u8ReplyMask) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _replyMaskForHost: 0x%X\n"), u8ReplyMask); - }); - return u8ReplyMask; -} -/* + /* MDNSResponder::_replyMaskForService Determines the relevant service answers for the given question @@ -1964,65 +1905,58 @@ uint8_t MDNSResponder::_replyMaskForHost(const MDNSResponder::stcMDNS_RRHeader& In addition, a full name match (question domain == service instance domain) is marked. */ -uint8_t MDNSResponder::_replyMaskForService(const MDNSResponder::stcMDNS_RRHeader& p_RRHeader, - const MDNSResponder::stcMDNSService& p_Service, - bool* p_pbFullNameMatch /*= 0*/) const -{ - uint8_t u8ReplyMask = 0; - (p_pbFullNameMatch ? * p_pbFullNameMatch = false : 0); - - if ((DNS_RRCLASS_IN == p_RRHeader.m_Attributes.m_u16Class) || - (DNS_RRCLASS_ANY == p_RRHeader.m_Attributes.m_u16Class)) + uint8_t MDNSResponder::_replyMaskForService(const MDNSResponder::stcMDNS_RRHeader& p_RRHeader, + const MDNSResponder::stcMDNSService& p_Service, + bool* p_pbFullNameMatch /*= 0*/) const { - stcMDNS_RRDomain DNSSDDomain; - if ((_buildDomainForDNSSD(DNSSDDomain)) && // _services._dns-sd._udp.local - (p_RRHeader.m_Domain == DNSSDDomain) && - ((DNS_RRTYPE_PTR == p_RRHeader.m_Attributes.m_u16Type) || - (DNS_RRTYPE_ANY == p_RRHeader.m_Attributes.m_u16Type))) - { - // Common service info requested - u8ReplyMask |= ContentFlag_PTR_TYPE; - } - - stcMDNS_RRDomain serviceDomain; - if ((_buildDomainForService(p_Service, false, serviceDomain)) && // eg. _http._tcp.local - (p_RRHeader.m_Domain == serviceDomain) && - ((DNS_RRTYPE_PTR == p_RRHeader.m_Attributes.m_u16Type) || - (DNS_RRTYPE_ANY == p_RRHeader.m_Attributes.m_u16Type))) - { - // Special service info requested - u8ReplyMask |= ContentFlag_PTR_NAME; - } + uint8_t u8ReplyMask = 0; + (p_pbFullNameMatch ? * p_pbFullNameMatch = false : 0); - if ((_buildDomainForService(p_Service, true, serviceDomain)) && // eg. MyESP._http._tcp.local - (p_RRHeader.m_Domain == serviceDomain)) + if ((DNS_RRCLASS_IN == p_RRHeader.m_Attributes.m_u16Class) || (DNS_RRCLASS_ANY == p_RRHeader.m_Attributes.m_u16Class)) { - (p_pbFullNameMatch ? (*p_pbFullNameMatch = true) : (0)); + stcMDNS_RRDomain DNSSDDomain; + if ((_buildDomainForDNSSD(DNSSDDomain)) && // _services._dns-sd._udp.local + (p_RRHeader.m_Domain == DNSSDDomain) && ((DNS_RRTYPE_PTR == p_RRHeader.m_Attributes.m_u16Type) || (DNS_RRTYPE_ANY == p_RRHeader.m_Attributes.m_u16Type))) + { + // Common service info requested + u8ReplyMask |= ContentFlag_PTR_TYPE; + } - if ((DNS_RRTYPE_SRV == p_RRHeader.m_Attributes.m_u16Type) || - (DNS_RRTYPE_ANY == p_RRHeader.m_Attributes.m_u16Type)) + stcMDNS_RRDomain serviceDomain; + if ((_buildDomainForService(p_Service, false, serviceDomain)) && // eg. _http._tcp.local + (p_RRHeader.m_Domain == serviceDomain) && ((DNS_RRTYPE_PTR == p_RRHeader.m_Attributes.m_u16Type) || (DNS_RRTYPE_ANY == p_RRHeader.m_Attributes.m_u16Type))) { - // Instance info SRV requested - u8ReplyMask |= ContentFlag_SRV; + // Special service info requested + u8ReplyMask |= ContentFlag_PTR_NAME; } - if ((DNS_RRTYPE_TXT == p_RRHeader.m_Attributes.m_u16Type) || - (DNS_RRTYPE_ANY == p_RRHeader.m_Attributes.m_u16Type)) + + if ((_buildDomainForService(p_Service, true, serviceDomain)) && // eg. MyESP._http._tcp.local + (p_RRHeader.m_Domain == serviceDomain)) { - // Instance info TXT requested - u8ReplyMask |= ContentFlag_TXT; + (p_pbFullNameMatch ? (*p_pbFullNameMatch = true) : (0)); + + if ((DNS_RRTYPE_SRV == p_RRHeader.m_Attributes.m_u16Type) || (DNS_RRTYPE_ANY == p_RRHeader.m_Attributes.m_u16Type)) + { + // Instance info SRV requested + u8ReplyMask |= ContentFlag_SRV; + } + if ((DNS_RRTYPE_TXT == p_RRHeader.m_Attributes.m_u16Type) || (DNS_RRTYPE_ANY == p_RRHeader.m_Attributes.m_u16Type)) + { + // Instance info TXT requested + u8ReplyMask |= ContentFlag_TXT; + } } } + else + { + //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _replyMaskForService: INVALID RR-class (0x%04X)!\n"), p_RRHeader.m_Attributes.m_u16Class);); + } + DEBUG_EX_INFO(if (u8ReplyMask) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _replyMaskForService(%s.%s.%s): 0x%X\n"), p_Service.m_pcName, p_Service.m_pcService, p_Service.m_pcProtocol, u8ReplyMask); + }); + return u8ReplyMask; } - else - { - //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _replyMaskForService: INVALID RR-class (0x%04X)!\n"), p_RRHeader.m_Attributes.m_u16Class);); - } - DEBUG_EX_INFO(if (u8ReplyMask) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _replyMaskForService(%s.%s.%s): 0x%X\n"), p_Service.m_pcName, p_Service.m_pcService, p_Service.m_pcProtocol, u8ReplyMask); - }); - return u8ReplyMask; -} } // namespace MDNSImplementation diff --git a/libraries/ESP8266mDNS/src/LEAmDNS_Helpers.cpp b/libraries/ESP8266mDNS/src/LEAmDNS_Helpers.cpp index 74255552e6..2803565d02 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS_Helpers.cpp +++ b/libraries/ESP8266mDNS/src/LEAmDNS_Helpers.cpp @@ -36,11 +36,11 @@ namespace esp8266 */ namespace MDNSImplementation { -/** + /** HELPERS */ -/* + /* MDNSResponder::indexDomain (static) Updates the given domain 'p_rpcHostname' by appending a delimiter and an index number. @@ -52,35 +52,57 @@ namespace MDNSImplementation if no default is given, 'esp8266' is used. */ -/*static*/ bool MDNSResponder::indexDomain(char*& p_rpcDomain, - const char* p_pcDivider /*= "-"*/, - const char* p_pcDefaultDomain /*= 0*/) -{ - bool bResult = false; + /*static*/ bool MDNSResponder::indexDomain(char*& p_rpcDomain, + const char* p_pcDivider /*= "-"*/, + const char* p_pcDefaultDomain /*= 0*/) + { + bool bResult = false; - // Ensure a divider exists; use '-' as default - const char* pcDivider = (p_pcDivider ?: "-"); + // Ensure a divider exists; use '-' as default + const char* pcDivider = (p_pcDivider ?: "-"); - if (p_rpcDomain) - { - const char* pFoundDivider = strrstr(p_rpcDomain, pcDivider); - if (pFoundDivider) // maybe already extended + if (p_rpcDomain) { - char* pEnd = 0; - unsigned long ulIndex = strtoul((pFoundDivider + strlen(pcDivider)), &pEnd, 10); - if ((ulIndex) && - ((pEnd - p_rpcDomain) == (ptrdiff_t)strlen(p_rpcDomain)) && - (!*pEnd)) // Valid (old) index found + const char* pFoundDivider = strrstr(p_rpcDomain, pcDivider); + if (pFoundDivider) // maybe already extended { - char acIndexBuffer[16]; - sprintf(acIndexBuffer, "%lu", (++ulIndex)); - size_t stLength = ((pFoundDivider - p_rpcDomain + strlen(pcDivider)) + strlen(acIndexBuffer) + 1); + char* pEnd = 0; + unsigned long ulIndex = strtoul((pFoundDivider + strlen(pcDivider)), &pEnd, 10); + if ((ulIndex) && ((pEnd - p_rpcDomain) == (ptrdiff_t)strlen(p_rpcDomain)) && (!*pEnd)) // Valid (old) index found + { + char acIndexBuffer[16]; + sprintf(acIndexBuffer, "%lu", (++ulIndex)); + size_t stLength = ((pFoundDivider - p_rpcDomain + strlen(pcDivider)) + strlen(acIndexBuffer) + 1); + char* pNewHostname = new char[stLength]; + if (pNewHostname) + { + memcpy(pNewHostname, p_rpcDomain, (pFoundDivider - p_rpcDomain + strlen(pcDivider))); + pNewHostname[pFoundDivider - p_rpcDomain + strlen(pcDivider)] = 0; + strcat(pNewHostname, acIndexBuffer); + + delete[] p_rpcDomain; + p_rpcDomain = pNewHostname; + + bResult = true; + } + else + { + DEBUG_EX_ERR(DEBUG_OUTPUT.println(F("[MDNSResponder] indexDomain: FAILED to alloc new hostname!"));); + } + } + else + { + pFoundDivider = 0; // Flag the need to (base) extend the hostname + } + } + + if (!pFoundDivider) // not yet extended (or failed to increment extension) -> start indexing + { + size_t stLength = strlen(p_rpcDomain) + (strlen(pcDivider) + 1 + 1); // Name + Divider + '2' + '\0' char* pNewHostname = new char[stLength]; if (pNewHostname) { - memcpy(pNewHostname, p_rpcDomain, (pFoundDivider - p_rpcDomain + strlen(pcDivider))); - pNewHostname[pFoundDivider - p_rpcDomain + strlen(pcDivider)] = 0; - strcat(pNewHostname, acIndexBuffer); + sprintf(pNewHostname, "%s%s2", p_rpcDomain, pcDivider); delete[] p_rpcDomain; p_rpcDomain = pNewHostname; @@ -92,23 +114,17 @@ namespace MDNSImplementation DEBUG_EX_ERR(DEBUG_OUTPUT.println(F("[MDNSResponder] indexDomain: FAILED to alloc new hostname!"));); } } - else - { - pFoundDivider = 0; // Flag the need to (base) extend the hostname - } } - - if (!pFoundDivider) // not yet extended (or failed to increment extension) -> start indexing + else { - size_t stLength = strlen(p_rpcDomain) + (strlen(pcDivider) + 1 + 1); // Name + Divider + '2' + '\0' - char* pNewHostname = new char[stLength]; - if (pNewHostname) - { - sprintf(pNewHostname, "%s%s2", p_rpcDomain, pcDivider); - - delete[] p_rpcDomain; - p_rpcDomain = pNewHostname; + // No given host domain, use base or default + const char* cpcDefaultName = (p_pcDefaultDomain ?: "esp8266"); + size_t stLength = strlen(cpcDefaultName) + 1; // '\0' + p_rpcDomain = new char[stLength]; + if (p_rpcDomain) + { + strncpy(p_rpcDomain, cpcDefaultName, stLength); bResult = true; } else @@ -116,40 +132,22 @@ namespace MDNSImplementation DEBUG_EX_ERR(DEBUG_OUTPUT.println(F("[MDNSResponder] indexDomain: FAILED to alloc new hostname!"));); } } + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] indexDomain: %s\n"), p_rpcDomain);); + return bResult; } - else - { - // No given host domain, use base or default - const char* cpcDefaultName = (p_pcDefaultDomain ?: "esp8266"); - size_t stLength = strlen(cpcDefaultName) + 1; // '\0' - p_rpcDomain = new char[stLength]; - if (p_rpcDomain) - { - strncpy(p_rpcDomain, cpcDefaultName, stLength); - bResult = true; - } - else - { - DEBUG_EX_ERR(DEBUG_OUTPUT.println(F("[MDNSResponder] indexDomain: FAILED to alloc new hostname!"));); - } - } - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] indexDomain: %s\n"), p_rpcDomain);); - return bResult; -} - -/* + /* UDP CONTEXT */ -bool MDNSResponder::_callProcess(void) -{ - DEBUG_EX_INFO(DEBUG_OUTPUT.printf("[MDNSResponder] _callProcess (%lu, triggered by: %s)\n", millis(), IPAddress(m_pUDPContext->getRemoteAddress()).toString().c_str());); + bool MDNSResponder::_callProcess(void) + { + DEBUG_EX_INFO(DEBUG_OUTPUT.printf("[MDNSResponder] _callProcess (%lu, triggered by: %s)\n", millis(), IPAddress(m_pUDPContext->getRemoteAddress()).toString().c_str());); - return _process(false); -} + return _process(false); + } -/* + /* MDNSResponder::_allocUDPContext (Re-)Creates the one-and-only UDP context for the MDNS responder. @@ -159,566 +157,539 @@ bool MDNSResponder::_callProcess(void) is called from the WiFi stack side of the ESP stack system. */ -bool MDNSResponder::_allocUDPContext(void) -{ - DEBUG_EX_INFO(DEBUG_OUTPUT.println("[MDNSResponder] _allocUDPContext");); + bool MDNSResponder::_allocUDPContext(void) + { + DEBUG_EX_INFO(DEBUG_OUTPUT.println("[MDNSResponder] _allocUDPContext");); - _releaseUDPContext(); - _joinMulticastGroups(); + _releaseUDPContext(); + _joinMulticastGroups(); - m_pUDPContext = new UdpContext; - m_pUDPContext->ref(); + m_pUDPContext = new UdpContext; + m_pUDPContext->ref(); - if (m_pUDPContext->listen(IP4_ADDR_ANY, DNS_MQUERY_PORT)) - { - m_pUDPContext->setMulticastTTL(MDNS_MULTICAST_TTL); - m_pUDPContext->onRx(std::bind(&MDNSResponder::_callProcess, this)); - } - else - { - return false; - } + if (m_pUDPContext->listen(IP4_ADDR_ANY, DNS_MQUERY_PORT)) + { + m_pUDPContext->setMulticastTTL(MDNS_MULTICAST_TTL); + m_pUDPContext->onRx(std::bind(&MDNSResponder::_callProcess, this)); + } + else + { + return false; + } - return true; -} + return true; + } -/* + /* MDNSResponder::_releaseUDPContext */ -bool MDNSResponder::_releaseUDPContext(void) -{ - if (m_pUDPContext) + bool MDNSResponder::_releaseUDPContext(void) { - m_pUDPContext->unref(); - m_pUDPContext = 0; - _leaveMulticastGroups(); + if (m_pUDPContext) + { + m_pUDPContext->unref(); + m_pUDPContext = 0; + _leaveMulticastGroups(); + } + return true; } - return true; -} -/* + /* SERVICE QUERY */ -/* + /* MDNSResponder::_allocServiceQuery */ -MDNSResponder::stcMDNSServiceQuery* MDNSResponder::_allocServiceQuery(void) -{ - stcMDNSServiceQuery* pServiceQuery = new stcMDNSServiceQuery; - if (pServiceQuery) + MDNSResponder::stcMDNSServiceQuery* MDNSResponder::_allocServiceQuery(void) { - // Link to query list - pServiceQuery->m_pNext = m_pServiceQueries; - m_pServiceQueries = pServiceQuery; + stcMDNSServiceQuery* pServiceQuery = new stcMDNSServiceQuery; + if (pServiceQuery) + { + // Link to query list + pServiceQuery->m_pNext = m_pServiceQueries; + m_pServiceQueries = pServiceQuery; + } + return m_pServiceQueries; } - return m_pServiceQueries; -} -/* + /* MDNSResponder::_removeServiceQuery */ -bool MDNSResponder::_removeServiceQuery(MDNSResponder::stcMDNSServiceQuery* p_pServiceQuery) -{ - bool bResult = false; - - if (p_pServiceQuery) + bool MDNSResponder::_removeServiceQuery(MDNSResponder::stcMDNSServiceQuery* p_pServiceQuery) { - stcMDNSServiceQuery* pPred = m_pServiceQueries; - while ((pPred) && - (pPred->m_pNext != p_pServiceQuery)) - { - pPred = pPred->m_pNext; - } - if (pPred) - { - pPred->m_pNext = p_pServiceQuery->m_pNext; - delete p_pServiceQuery; - bResult = true; - } - else // No predecessor + bool bResult = false; + + if (p_pServiceQuery) { - if (m_pServiceQueries == p_pServiceQuery) + stcMDNSServiceQuery* pPred = m_pServiceQueries; + while ((pPred) && (pPred->m_pNext != p_pServiceQuery)) { - m_pServiceQueries = p_pServiceQuery->m_pNext; + pPred = pPred->m_pNext; + } + if (pPred) + { + pPred->m_pNext = p_pServiceQuery->m_pNext; delete p_pServiceQuery; bResult = true; } - else + else // No predecessor { - DEBUG_EX_ERR(DEBUG_OUTPUT.println("[MDNSResponder] _releaseServiceQuery: INVALID service query!");); + if (m_pServiceQueries == p_pServiceQuery) + { + m_pServiceQueries = p_pServiceQuery->m_pNext; + delete p_pServiceQuery; + bResult = true; + } + else + { + DEBUG_EX_ERR(DEBUG_OUTPUT.println("[MDNSResponder] _releaseServiceQuery: INVALID service query!");); + } } } + return bResult; } - return bResult; -} -/* + /* MDNSResponder::_removeLegacyServiceQuery */ -bool MDNSResponder::_removeLegacyServiceQuery(void) -{ - stcMDNSServiceQuery* pLegacyServiceQuery = _findLegacyServiceQuery(); - return (pLegacyServiceQuery ? _removeServiceQuery(pLegacyServiceQuery) : true); -} + bool MDNSResponder::_removeLegacyServiceQuery(void) + { + stcMDNSServiceQuery* pLegacyServiceQuery = _findLegacyServiceQuery(); + return (pLegacyServiceQuery ? _removeServiceQuery(pLegacyServiceQuery) : true); + } -/* + /* MDNSResponder::_findServiceQuery 'Convert' hMDNSServiceQuery to stcMDNSServiceQuery* (ensure existence) */ -MDNSResponder::stcMDNSServiceQuery* MDNSResponder::_findServiceQuery(MDNSResponder::hMDNSServiceQuery p_hServiceQuery) -{ - stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; - while (pServiceQuery) + MDNSResponder::stcMDNSServiceQuery* MDNSResponder::_findServiceQuery(MDNSResponder::hMDNSServiceQuery p_hServiceQuery) { - if ((hMDNSServiceQuery)pServiceQuery == p_hServiceQuery) + stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; + while (pServiceQuery) { - break; + if ((hMDNSServiceQuery)pServiceQuery == p_hServiceQuery) + { + break; + } + pServiceQuery = pServiceQuery->m_pNext; } - pServiceQuery = pServiceQuery->m_pNext; + return pServiceQuery; } - return pServiceQuery; -} -/* + /* MDNSResponder::_findLegacyServiceQuery */ -MDNSResponder::stcMDNSServiceQuery* MDNSResponder::_findLegacyServiceQuery(void) -{ - stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; - while (pServiceQuery) + MDNSResponder::stcMDNSServiceQuery* MDNSResponder::_findLegacyServiceQuery(void) { - if (pServiceQuery->m_bLegacyQuery) + stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; + while (pServiceQuery) { - break; + if (pServiceQuery->m_bLegacyQuery) + { + break; + } + pServiceQuery = pServiceQuery->m_pNext; } - pServiceQuery = pServiceQuery->m_pNext; + return pServiceQuery; } - return pServiceQuery; -} -/* + /* MDNSResponder::_releaseServiceQueries */ -bool MDNSResponder::_releaseServiceQueries(void) -{ - while (m_pServiceQueries) + bool MDNSResponder::_releaseServiceQueries(void) { - stcMDNSServiceQuery* pNext = m_pServiceQueries->m_pNext; - delete m_pServiceQueries; - m_pServiceQueries = pNext; + while (m_pServiceQueries) + { + stcMDNSServiceQuery* pNext = m_pServiceQueries->m_pNext; + delete m_pServiceQueries; + m_pServiceQueries = pNext; + } + return true; } - return true; -} -/* + /* MDNSResponder::_findNextServiceQueryByServiceType */ -MDNSResponder::stcMDNSServiceQuery* MDNSResponder::_findNextServiceQueryByServiceType(const stcMDNS_RRDomain& p_ServiceTypeDomain, - const stcMDNSServiceQuery* p_pPrevServiceQuery) -{ - stcMDNSServiceQuery* pMatchingServiceQuery = 0; - - stcMDNSServiceQuery* pServiceQuery = (p_pPrevServiceQuery ? p_pPrevServiceQuery->m_pNext : m_pServiceQueries); - while (pServiceQuery) + MDNSResponder::stcMDNSServiceQuery* MDNSResponder::_findNextServiceQueryByServiceType(const stcMDNS_RRDomain& p_ServiceTypeDomain, + const stcMDNSServiceQuery* p_pPrevServiceQuery) { - if (p_ServiceTypeDomain == pServiceQuery->m_ServiceTypeDomain) + stcMDNSServiceQuery* pMatchingServiceQuery = 0; + + stcMDNSServiceQuery* pServiceQuery = (p_pPrevServiceQuery ? p_pPrevServiceQuery->m_pNext : m_pServiceQueries); + while (pServiceQuery) { - pMatchingServiceQuery = pServiceQuery; - break; + if (p_ServiceTypeDomain == pServiceQuery->m_ServiceTypeDomain) + { + pMatchingServiceQuery = pServiceQuery; + break; + } + pServiceQuery = pServiceQuery->m_pNext; } - pServiceQuery = pServiceQuery->m_pNext; + return pMatchingServiceQuery; } - return pMatchingServiceQuery; -} -/* + /* HOSTNAME */ -/* + /* MDNSResponder::_setHostname */ -bool MDNSResponder::_setHostname(const char* p_pcHostname) -{ - //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _allocHostname (%s)\n"), p_pcHostname);); + bool MDNSResponder::_setHostname(const char* p_pcHostname) + { + //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _allocHostname (%s)\n"), p_pcHostname);); - bool bResult = false; + bool bResult = false; - _releaseHostname(); + _releaseHostname(); - size_t stLength = 0; - if ((p_pcHostname) && - (MDNS_DOMAIN_LABEL_MAXLENGTH >= (stLength = strlen(p_pcHostname)))) // char max size for a single label - { - // Copy in hostname characters as lowercase - if ((bResult = (0 != (m_pcHostname = new char[stLength + 1])))) + size_t stLength = 0; + if ((p_pcHostname) && (MDNS_DOMAIN_LABEL_MAXLENGTH >= (stLength = strlen(p_pcHostname)))) // char max size for a single label { -#ifdef MDNS_FORCE_LOWERCASE_HOSTNAME - size_t i = 0; - for (; i < stLength; ++i) + // Copy in hostname characters as lowercase + if ((bResult = (0 != (m_pcHostname = new char[stLength + 1])))) { - m_pcHostname[i] = (isupper(p_pcHostname[i]) ? tolower(p_pcHostname[i]) : p_pcHostname[i]); - } - m_pcHostname[i] = 0; +#ifdef MDNS_FORCE_LOWERCASE_HOSTNAME + size_t i = 0; + for (; i < stLength; ++i) + { + m_pcHostname[i] = (isupper(p_pcHostname[i]) ? tolower(p_pcHostname[i]) : p_pcHostname[i]); + } + m_pcHostname[i] = 0; #else - strncpy(m_pcHostname, p_pcHostname, (stLength + 1)); + strncpy(m_pcHostname, p_pcHostname, (stLength + 1)); #endif + } } + return bResult; } - return bResult; -} -/* + /* MDNSResponder::_releaseHostname */ -bool MDNSResponder::_releaseHostname(void) -{ - if (m_pcHostname) + bool MDNSResponder::_releaseHostname(void) { - delete[] m_pcHostname; - m_pcHostname = 0; + if (m_pcHostname) + { + delete[] m_pcHostname; + m_pcHostname = 0; + } + return true; } - return true; -} -/* + /* SERVICE */ -/* + /* MDNSResponder::_allocService */ -MDNSResponder::stcMDNSService* MDNSResponder::_allocService(const char* p_pcName, - const char* p_pcService, - const char* p_pcProtocol, - uint16_t p_u16Port) -{ - stcMDNSService* pService = 0; - if (((!p_pcName) || - (MDNS_DOMAIN_LABEL_MAXLENGTH >= strlen(p_pcName))) && - (p_pcService) && - (MDNS_SERVICE_NAME_LENGTH >= strlen(p_pcService)) && - (p_pcProtocol) && - (MDNS_SERVICE_PROTOCOL_LENGTH >= strlen(p_pcProtocol)) && - (p_u16Port) && - (0 != (pService = new stcMDNSService)) && - (pService->setName(p_pcName ?: m_pcHostname)) && - (pService->setService(p_pcService)) && - (pService->setProtocol(p_pcProtocol))) + MDNSResponder::stcMDNSService* MDNSResponder::_allocService(const char* p_pcName, + const char* p_pcService, + const char* p_pcProtocol, + uint16_t p_u16Port) { - pService->m_bAutoName = (0 == p_pcName); - pService->m_u16Port = p_u16Port; + stcMDNSService* pService = 0; + if (((!p_pcName) || (MDNS_DOMAIN_LABEL_MAXLENGTH >= strlen(p_pcName))) && (p_pcService) && (MDNS_SERVICE_NAME_LENGTH >= strlen(p_pcService)) && (p_pcProtocol) && (MDNS_SERVICE_PROTOCOL_LENGTH >= strlen(p_pcProtocol)) && (p_u16Port) && (0 != (pService = new stcMDNSService)) && (pService->setName(p_pcName ?: m_pcHostname)) && (pService->setService(p_pcService)) && (pService->setProtocol(p_pcProtocol))) + { + pService->m_bAutoName = (0 == p_pcName); + pService->m_u16Port = p_u16Port; - // Add to list (or start list) - pService->m_pNext = m_pServices; - m_pServices = pService; + // Add to list (or start list) + pService->m_pNext = m_pServices; + m_pServices = pService; + } + return pService; } - return pService; -} -/* + /* MDNSResponder::_releaseService */ -bool MDNSResponder::_releaseService(MDNSResponder::stcMDNSService* p_pService) -{ - bool bResult = false; - - if (p_pService) + bool MDNSResponder::_releaseService(MDNSResponder::stcMDNSService* p_pService) { - stcMDNSService* pPred = m_pServices; - while ((pPred) && - (pPred->m_pNext != p_pService)) - { - pPred = pPred->m_pNext; - } - if (pPred) - { - pPred->m_pNext = p_pService->m_pNext; - delete p_pService; - bResult = true; - } - else // No predecessor + bool bResult = false; + + if (p_pService) { - if (m_pServices == p_pService) + stcMDNSService* pPred = m_pServices; + while ((pPred) && (pPred->m_pNext != p_pService)) + { + pPred = pPred->m_pNext; + } + if (pPred) { - m_pServices = p_pService->m_pNext; + pPred->m_pNext = p_pService->m_pNext; delete p_pService; bResult = true; } - else + else // No predecessor { - DEBUG_EX_ERR(DEBUG_OUTPUT.println("[MDNSResponder] _releaseService: INVALID service!");); + if (m_pServices == p_pService) + { + m_pServices = p_pService->m_pNext; + delete p_pService; + bResult = true; + } + else + { + DEBUG_EX_ERR(DEBUG_OUTPUT.println("[MDNSResponder] _releaseService: INVALID service!");); + } } } + return bResult; } - return bResult; -} -/* + /* MDNSResponder::_releaseServices */ -bool MDNSResponder::_releaseServices(void) -{ - stcMDNSService* pService = m_pServices; - while (pService) + bool MDNSResponder::_releaseServices(void) { - _releaseService(pService); - pService = m_pServices; + stcMDNSService* pService = m_pServices; + while (pService) + { + _releaseService(pService); + pService = m_pServices; + } + return true; } - return true; -} -/* + /* MDNSResponder::_findService */ -MDNSResponder::stcMDNSService* MDNSResponder::_findService(const char* p_pcName, - const char* p_pcService, - const char* p_pcProtocol) -{ - stcMDNSService* pService = m_pServices; - while (pService) + MDNSResponder::stcMDNSService* MDNSResponder::_findService(const char* p_pcName, + const char* p_pcService, + const char* p_pcProtocol) { - if ((0 == strcmp(pService->m_pcName, p_pcName)) && - (0 == strcmp(pService->m_pcService, p_pcService)) && - (0 == strcmp(pService->m_pcProtocol, p_pcProtocol))) + stcMDNSService* pService = m_pServices; + while (pService) { - break; + if ((0 == strcmp(pService->m_pcName, p_pcName)) && (0 == strcmp(pService->m_pcService, p_pcService)) && (0 == strcmp(pService->m_pcProtocol, p_pcProtocol))) + { + break; + } + pService = pService->m_pNext; } - pService = pService->m_pNext; + return pService; } - return pService; -} -/* + /* MDNSResponder::_findService */ -MDNSResponder::stcMDNSService* MDNSResponder::_findService(const MDNSResponder::hMDNSService p_hService) -{ - stcMDNSService* pService = m_pServices; - while (pService) + MDNSResponder::stcMDNSService* MDNSResponder::_findService(const MDNSResponder::hMDNSService p_hService) { - if (p_hService == (hMDNSService)pService) + stcMDNSService* pService = m_pServices; + while (pService) { - break; + if (p_hService == (hMDNSService)pService) + { + break; + } + pService = pService->m_pNext; } - pService = pService->m_pNext; + return pService; } - return pService; -} -/* + /* SERVICE TXT */ -/* + /* MDNSResponder::_allocServiceTxt */ -MDNSResponder::stcMDNSServiceTxt* MDNSResponder::_allocServiceTxt(MDNSResponder::stcMDNSService* p_pService, - const char* p_pcKey, - const char* p_pcValue, - bool p_bTemp) -{ - stcMDNSServiceTxt* pTxt = 0; - - if ((p_pService) && - (p_pcKey) && - (MDNS_SERVICE_TXT_MAXLENGTH > (p_pService->m_Txts.length() + - 1 + // Length byte - (p_pcKey ? strlen(p_pcKey) : 0) + - 1 + // '=' - (p_pcValue ? strlen(p_pcValue) : 0)))) + MDNSResponder::stcMDNSServiceTxt* MDNSResponder::_allocServiceTxt(MDNSResponder::stcMDNSService* p_pService, + const char* p_pcKey, + const char* p_pcValue, + bool p_bTemp) { - pTxt = new stcMDNSServiceTxt; - if (pTxt) + stcMDNSServiceTxt* pTxt = 0; + + if ((p_pService) && (p_pcKey) && (MDNS_SERVICE_TXT_MAXLENGTH > (p_pService->m_Txts.length() + 1 + // Length byte + (p_pcKey ? strlen(p_pcKey) : 0) + 1 + // '=' + (p_pcValue ? strlen(p_pcValue) : 0)))) { - size_t stLength = (p_pcKey ? strlen(p_pcKey) : 0); - pTxt->m_pcKey = new char[stLength + 1]; - if (pTxt->m_pcKey) + pTxt = new stcMDNSServiceTxt; + if (pTxt) { - strncpy(pTxt->m_pcKey, p_pcKey, stLength); - pTxt->m_pcKey[stLength] = 0; - } + size_t stLength = (p_pcKey ? strlen(p_pcKey) : 0); + pTxt->m_pcKey = new char[stLength + 1]; + if (pTxt->m_pcKey) + { + strncpy(pTxt->m_pcKey, p_pcKey, stLength); + pTxt->m_pcKey[stLength] = 0; + } - if (p_pcValue) - { - stLength = (p_pcValue ? strlen(p_pcValue) : 0); - pTxt->m_pcValue = new char[stLength + 1]; - if (pTxt->m_pcValue) + if (p_pcValue) { - strncpy(pTxt->m_pcValue, p_pcValue, stLength); - pTxt->m_pcValue[stLength] = 0; + stLength = (p_pcValue ? strlen(p_pcValue) : 0); + pTxt->m_pcValue = new char[stLength + 1]; + if (pTxt->m_pcValue) + { + strncpy(pTxt->m_pcValue, p_pcValue, stLength); + pTxt->m_pcValue[stLength] = 0; + } } - } - pTxt->m_bTemp = p_bTemp; + pTxt->m_bTemp = p_bTemp; - // Add to list (or start list) - p_pService->m_Txts.add(pTxt); + // Add to list (or start list) + p_pService->m_Txts.add(pTxt); + } } + return pTxt; } - return pTxt; -} -/* + /* MDNSResponder::_releaseServiceTxt */ -bool MDNSResponder::_releaseServiceTxt(MDNSResponder::stcMDNSService* p_pService, - MDNSResponder::stcMDNSServiceTxt* p_pTxt) -{ - return ((p_pService) && - (p_pTxt) && - (p_pService->m_Txts.remove(p_pTxt))); -} + bool MDNSResponder::_releaseServiceTxt(MDNSResponder::stcMDNSService* p_pService, + MDNSResponder::stcMDNSServiceTxt* p_pTxt) + { + return ((p_pService) && (p_pTxt) && (p_pService->m_Txts.remove(p_pTxt))); + } -/* + /* MDNSResponder::_updateServiceTxt */ -MDNSResponder::stcMDNSServiceTxt* MDNSResponder::_updateServiceTxt(MDNSResponder::stcMDNSService* p_pService, - MDNSResponder::stcMDNSServiceTxt* p_pTxt, - const char* p_pcValue, - bool p_bTemp) -{ - if ((p_pService) && - (p_pTxt) && - (MDNS_SERVICE_TXT_MAXLENGTH > (p_pService->m_Txts.length() - - (p_pTxt->m_pcValue ? strlen(p_pTxt->m_pcValue) : 0) + - (p_pcValue ? strlen(p_pcValue) : 0)))) + MDNSResponder::stcMDNSServiceTxt* MDNSResponder::_updateServiceTxt(MDNSResponder::stcMDNSService* p_pService, + MDNSResponder::stcMDNSServiceTxt* p_pTxt, + const char* p_pcValue, + bool p_bTemp) { - p_pTxt->update(p_pcValue); - p_pTxt->m_bTemp = p_bTemp; + if ((p_pService) && (p_pTxt) && (MDNS_SERVICE_TXT_MAXLENGTH > (p_pService->m_Txts.length() - (p_pTxt->m_pcValue ? strlen(p_pTxt->m_pcValue) : 0) + (p_pcValue ? strlen(p_pcValue) : 0)))) + { + p_pTxt->update(p_pcValue); + p_pTxt->m_bTemp = p_bTemp; + } + return p_pTxt; } - return p_pTxt; -} -/* + /* MDNSResponder::_findServiceTxt */ -MDNSResponder::stcMDNSServiceTxt* MDNSResponder::_findServiceTxt(MDNSResponder::stcMDNSService* p_pService, - const char* p_pcKey) -{ - return (p_pService ? p_pService->m_Txts.find(p_pcKey) : 0); -} + MDNSResponder::stcMDNSServiceTxt* MDNSResponder::_findServiceTxt(MDNSResponder::stcMDNSService* p_pService, + const char* p_pcKey) + { + return (p_pService ? p_pService->m_Txts.find(p_pcKey) : 0); + } -/* + /* MDNSResponder::_findServiceTxt */ -MDNSResponder::stcMDNSServiceTxt* MDNSResponder::_findServiceTxt(MDNSResponder::stcMDNSService* p_pService, - const hMDNSTxt p_hTxt) -{ - return (((p_pService) && (p_hTxt)) ? p_pService->m_Txts.find((stcMDNSServiceTxt*)p_hTxt) : 0); -} + MDNSResponder::stcMDNSServiceTxt* MDNSResponder::_findServiceTxt(MDNSResponder::stcMDNSService* p_pService, + const hMDNSTxt p_hTxt) + { + return (((p_pService) && (p_hTxt)) ? p_pService->m_Txts.find((stcMDNSServiceTxt*)p_hTxt) : 0); + } -/* + /* MDNSResponder::_addServiceTxt */ -MDNSResponder::stcMDNSServiceTxt* MDNSResponder::_addServiceTxt(MDNSResponder::stcMDNSService* p_pService, - const char* p_pcKey, - const char* p_pcValue, - bool p_bTemp) -{ - stcMDNSServiceTxt* pResult = 0; - - if ((p_pService) && - (p_pcKey) && - (strlen(p_pcKey))) + MDNSResponder::stcMDNSServiceTxt* MDNSResponder::_addServiceTxt(MDNSResponder::stcMDNSService* p_pService, + const char* p_pcKey, + const char* p_pcValue, + bool p_bTemp) { - stcMDNSServiceTxt* pTxt = p_pService->m_Txts.find(p_pcKey); - if (pTxt) - { - pResult = _updateServiceTxt(p_pService, pTxt, p_pcValue, p_bTemp); - } - else + stcMDNSServiceTxt* pResult = 0; + + if ((p_pService) && (p_pcKey) && (strlen(p_pcKey))) { - pResult = _allocServiceTxt(p_pService, p_pcKey, p_pcValue, p_bTemp); + stcMDNSServiceTxt* pTxt = p_pService->m_Txts.find(p_pcKey); + if (pTxt) + { + pResult = _updateServiceTxt(p_pService, pTxt, p_pcValue, p_bTemp); + } + else + { + pResult = _allocServiceTxt(p_pService, p_pcKey, p_pcValue, p_bTemp); + } } + return pResult; } - return pResult; -} -MDNSResponder::stcMDNSServiceTxt* MDNSResponder::_answerKeyValue(const hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) -{ - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); - stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - // Fill m_pcTxts (if not already done) - return (pSQAnswer) ? pSQAnswer->m_Txts.m_pTxts : 0; -} + MDNSResponder::stcMDNSServiceTxt* MDNSResponder::_answerKeyValue(const hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex) + { + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); + // Fill m_pcTxts (if not already done) + return (pSQAnswer) ? pSQAnswer->m_Txts.m_pTxts : 0; + } -/* + /* MDNSResponder::_collectServiceTxts */ -bool MDNSResponder::_collectServiceTxts(MDNSResponder::stcMDNSService& p_rService) -{ - // Call Dynamic service callbacks - if (m_fnServiceTxtCallback) - { - m_fnServiceTxtCallback((hMDNSService)&p_rService); - } - if (p_rService.m_fnTxtCallback) + bool MDNSResponder::_collectServiceTxts(MDNSResponder::stcMDNSService& p_rService) { - p_rService.m_fnTxtCallback((hMDNSService)&p_rService); + // Call Dynamic service callbacks + if (m_fnServiceTxtCallback) + { + m_fnServiceTxtCallback((hMDNSService)&p_rService); + } + if (p_rService.m_fnTxtCallback) + { + p_rService.m_fnTxtCallback((hMDNSService)&p_rService); + } + return true; } - return true; -} -/* + /* MDNSResponder::_releaseTempServiceTxts */ -bool MDNSResponder::_releaseTempServiceTxts(MDNSResponder::stcMDNSService& p_rService) -{ - return (p_rService.m_Txts.removeTempTxts()); -} + bool MDNSResponder::_releaseTempServiceTxts(MDNSResponder::stcMDNSService& p_rService) + { + return (p_rService.m_Txts.removeTempTxts()); + } -/* + /* MISC */ #ifdef DEBUG_ESP_MDNS_RESPONDER -/* + /* MDNSResponder::_printRRDomain */ -bool MDNSResponder::_printRRDomain(const MDNSResponder::stcMDNS_RRDomain& p_RRDomain) const -{ - //DEBUG_OUTPUT.printf_P(PSTR("Domain: ")); - - const char* pCursor = p_RRDomain.m_acName; - uint8_t u8Length = *pCursor++; - if (u8Length) + bool MDNSResponder::_printRRDomain(const MDNSResponder::stcMDNS_RRDomain& p_RRDomain) const { - while (u8Length) + //DEBUG_OUTPUT.printf_P(PSTR("Domain: ")); + + const char* pCursor = p_RRDomain.m_acName; + uint8_t u8Length = *pCursor++; + if (u8Length) { - for (uint8_t u = 0; u < u8Length; ++u) + while (u8Length) { - DEBUG_OUTPUT.printf_P(PSTR("%c"), *(pCursor++)); - } - u8Length = *pCursor++; - if (u8Length) - { - DEBUG_OUTPUT.printf_P(PSTR(".")); + for (uint8_t u = 0; u < u8Length; ++u) + { + DEBUG_OUTPUT.printf_P(PSTR("%c"), *(pCursor++)); + } + u8Length = *pCursor++; + if (u8Length) + { + DEBUG_OUTPUT.printf_P(PSTR(".")); + } } } - } - else // empty domain - { - DEBUG_OUTPUT.printf_P(PSTR("-empty-")); - } - //DEBUG_OUTPUT.printf_P(PSTR("\n")); + else // empty domain + { + DEBUG_OUTPUT.printf_P(PSTR("-empty-")); + } + //DEBUG_OUTPUT.printf_P(PSTR("\n")); - return true; -} + return true; + } -/* + /* MDNSResponder::_printRRAnswer */ -bool MDNSResponder::_printRRAnswer(const MDNSResponder::stcMDNS_RRAnswer& p_RRAnswer) const -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] RRAnswer: ")); - _printRRDomain(p_RRAnswer.m_Header.m_Domain); - DEBUG_OUTPUT.printf_P(PSTR(" Type:0x%04X Class:0x%04X TTL:%u, "), p_RRAnswer.m_Header.m_Attributes.m_u16Type, p_RRAnswer.m_Header.m_Attributes.m_u16Class, p_RRAnswer.m_u32TTL); - switch (p_RRAnswer.m_Header.m_Attributes.m_u16Type & (~0x8000)) // Topmost bit might carry 'cache flush' flag + bool MDNSResponder::_printRRAnswer(const MDNSResponder::stcMDNS_RRAnswer& p_RRAnswer) const { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] RRAnswer: ")); + _printRRDomain(p_RRAnswer.m_Header.m_Domain); + DEBUG_OUTPUT.printf_P(PSTR(" Type:0x%04X Class:0x%04X TTL:%u, "), p_RRAnswer.m_Header.m_Attributes.m_u16Type, p_RRAnswer.m_Header.m_Attributes.m_u16Class, p_RRAnswer.m_u32TTL); + switch (p_RRAnswer.m_Header.m_Attributes.m_u16Type & (~0x8000)) // Topmost bit might carry 'cache flush' flag + { #ifdef MDNS_IP4_SUPPORT case DNS_RRTYPE_A: DEBUG_OUTPUT.printf_P(PSTR("A IP:%s"), ((const stcMDNS_RRAnswerA*)&p_RRAnswer)->m_IPAddress.toString().c_str()); @@ -752,11 +723,11 @@ bool MDNSResponder::_printRRAnswer(const MDNSResponder::stcMDNS_RRAnswer& p_RRAn default: DEBUG_OUTPUT.printf_P(PSTR("generic ")); break; - } - DEBUG_OUTPUT.printf_P(PSTR("\n")); + } + DEBUG_OUTPUT.printf_P(PSTR("\n")); - return true; -} + return true; + } #endif } // namespace MDNSImplementation diff --git a/libraries/ESP8266mDNS/src/LEAmDNS_Priv.h b/libraries/ESP8266mDNS/src/LEAmDNS_Priv.h index 70e81de5e6..f57e48f0c5 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS_Priv.h +++ b/libraries/ESP8266mDNS/src/LEAmDNS_Priv.h @@ -35,7 +35,7 @@ namespace MDNSImplementation { // Enable class debug functions #define ESP_8266_MDNS_INCLUDE -//#define DEBUG_ESP_MDNS_RESPONDER + //#define DEBUG_ESP_MDNS_RESPONDER #if !defined(DEBUG_ESP_MDNS_RESPONDER) && defined(DEBUG_ESP_MDNS) #define DEBUG_ESP_MDNS_RESPONDER diff --git a/libraries/ESP8266mDNS/src/LEAmDNS_Structs.cpp b/libraries/ESP8266mDNS/src/LEAmDNS_Structs.cpp index f6bf0bf543..b1bfd98ccf 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS_Structs.cpp +++ b/libraries/ESP8266mDNS/src/LEAmDNS_Structs.cpp @@ -33,11 +33,11 @@ namespace esp8266 */ namespace MDNSImplementation { -/** + /** STRUCTS */ -/** + /** MDNSResponder::stcMDNSServiceTxt One MDNS TXT item. @@ -47,216 +47,215 @@ namespace MDNSImplementation Output as byte array 'c#=1' is supported. */ -/* + /* MDNSResponder::stcMDNSServiceTxt::stcMDNSServiceTxt constructor */ -MDNSResponder::stcMDNSServiceTxt::stcMDNSServiceTxt(const char* p_pcKey /*= 0*/, - const char* p_pcValue /*= 0*/, - bool p_bTemp /*= false*/) - : m_pNext(0), - m_pcKey(0), - m_pcValue(0), - m_bTemp(p_bTemp) -{ - setKey(p_pcKey); - setValue(p_pcValue); -} + MDNSResponder::stcMDNSServiceTxt::stcMDNSServiceTxt(const char* p_pcKey /*= 0*/, + const char* p_pcValue /*= 0*/, + bool p_bTemp /*= false*/) + : m_pNext(0) + , m_pcKey(0) + , m_pcValue(0) + , m_bTemp(p_bTemp) + { + setKey(p_pcKey); + setValue(p_pcValue); + } -/* + /* MDNSResponder::stcMDNSServiceTxt::stcMDNSServiceTxt copy-constructor */ -MDNSResponder::stcMDNSServiceTxt::stcMDNSServiceTxt(const MDNSResponder::stcMDNSServiceTxt& p_Other) - : m_pNext(0), - m_pcKey(0), - m_pcValue(0), - m_bTemp(false) -{ - operator=(p_Other); -} + MDNSResponder::stcMDNSServiceTxt::stcMDNSServiceTxt(const MDNSResponder::stcMDNSServiceTxt& p_Other) + : m_pNext(0) + , m_pcKey(0) + , m_pcValue(0) + , m_bTemp(false) + { + operator=(p_Other); + } -/* + /* MDNSResponder::stcMDNSServiceTxt::~stcMDNSServiceTxt destructor */ -MDNSResponder::stcMDNSServiceTxt::~stcMDNSServiceTxt(void) -{ - clear(); -} + MDNSResponder::stcMDNSServiceTxt::~stcMDNSServiceTxt(void) + { + clear(); + } -/* + /* MDNSResponder::stcMDNSServiceTxt::operator= */ -MDNSResponder::stcMDNSServiceTxt& MDNSResponder::stcMDNSServiceTxt::operator=(const MDNSResponder::stcMDNSServiceTxt& p_Other) -{ - if (&p_Other != this) + MDNSResponder::stcMDNSServiceTxt& MDNSResponder::stcMDNSServiceTxt::operator=(const MDNSResponder::stcMDNSServiceTxt& p_Other) { - clear(); - set(p_Other.m_pcKey, p_Other.m_pcValue, p_Other.m_bTemp); + if (&p_Other != this) + { + clear(); + set(p_Other.m_pcKey, p_Other.m_pcValue, p_Other.m_bTemp); + } + return *this; } - return *this; -} -/* + /* MDNSResponder::stcMDNSServiceTxt::clear */ -bool MDNSResponder::stcMDNSServiceTxt::clear(void) -{ - releaseKey(); - releaseValue(); - return true; -} + bool MDNSResponder::stcMDNSServiceTxt::clear(void) + { + releaseKey(); + releaseValue(); + return true; + } -/* + /* MDNSResponder::stcMDNSServiceTxt::allocKey */ -char* MDNSResponder::stcMDNSServiceTxt::allocKey(size_t p_stLength) -{ - releaseKey(); - if (p_stLength) + char* MDNSResponder::stcMDNSServiceTxt::allocKey(size_t p_stLength) { - m_pcKey = new char[p_stLength + 1]; + releaseKey(); + if (p_stLength) + { + m_pcKey = new char[p_stLength + 1]; + } + return m_pcKey; } - return m_pcKey; -} -/* + /* MDNSResponder::stcMDNSServiceTxt::setKey */ -bool MDNSResponder::stcMDNSServiceTxt::setKey(const char* p_pcKey, - size_t p_stLength) -{ - bool bResult = false; - - releaseKey(); - if (p_stLength) + bool MDNSResponder::stcMDNSServiceTxt::setKey(const char* p_pcKey, + size_t p_stLength) { - if (allocKey(p_stLength)) + bool bResult = false; + + releaseKey(); + if (p_stLength) { - strncpy(m_pcKey, p_pcKey, p_stLength); - m_pcKey[p_stLength] = 0; - bResult = true; + if (allocKey(p_stLength)) + { + strncpy(m_pcKey, p_pcKey, p_stLength); + m_pcKey[p_stLength] = 0; + bResult = true; + } } + return bResult; } - return bResult; -} -/* + /* MDNSResponder::stcMDNSServiceTxt::setKey */ -bool MDNSResponder::stcMDNSServiceTxt::setKey(const char* p_pcKey) -{ - return setKey(p_pcKey, (p_pcKey ? strlen(p_pcKey) : 0)); -} + bool MDNSResponder::stcMDNSServiceTxt::setKey(const char* p_pcKey) + { + return setKey(p_pcKey, (p_pcKey ? strlen(p_pcKey) : 0)); + } -/* + /* MDNSResponder::stcMDNSServiceTxt::releaseKey */ -bool MDNSResponder::stcMDNSServiceTxt::releaseKey(void) -{ - if (m_pcKey) + bool MDNSResponder::stcMDNSServiceTxt::releaseKey(void) { - delete[] m_pcKey; - m_pcKey = 0; + if (m_pcKey) + { + delete[] m_pcKey; + m_pcKey = 0; + } + return true; } - return true; -} -/* + /* MDNSResponder::stcMDNSServiceTxt::allocValue */ -char* MDNSResponder::stcMDNSServiceTxt::allocValue(size_t p_stLength) -{ - releaseValue(); - if (p_stLength) + char* MDNSResponder::stcMDNSServiceTxt::allocValue(size_t p_stLength) { - m_pcValue = new char[p_stLength + 1]; + releaseValue(); + if (p_stLength) + { + m_pcValue = new char[p_stLength + 1]; + } + return m_pcValue; } - return m_pcValue; -} -/* + /* MDNSResponder::stcMDNSServiceTxt::setValue */ -bool MDNSResponder::stcMDNSServiceTxt::setValue(const char* p_pcValue, - size_t p_stLength) -{ - bool bResult = false; - - releaseValue(); - if (p_stLength) + bool MDNSResponder::stcMDNSServiceTxt::setValue(const char* p_pcValue, + size_t p_stLength) { - if (allocValue(p_stLength)) + bool bResult = false; + + releaseValue(); + if (p_stLength) + { + if (allocValue(p_stLength)) + { + strncpy(m_pcValue, p_pcValue, p_stLength); + m_pcValue[p_stLength] = 0; + bResult = true; + } + } + else // No value -> also OK { - strncpy(m_pcValue, p_pcValue, p_stLength); - m_pcValue[p_stLength] = 0; bResult = true; } + return bResult; } - else // No value -> also OK - { - bResult = true; - } - return bResult; -} -/* + /* MDNSResponder::stcMDNSServiceTxt::setValue */ -bool MDNSResponder::stcMDNSServiceTxt::setValue(const char* p_pcValue) -{ - return setValue(p_pcValue, (p_pcValue ? strlen(p_pcValue) : 0)); -} + bool MDNSResponder::stcMDNSServiceTxt::setValue(const char* p_pcValue) + { + return setValue(p_pcValue, (p_pcValue ? strlen(p_pcValue) : 0)); + } -/* + /* MDNSResponder::stcMDNSServiceTxt::releaseValue */ -bool MDNSResponder::stcMDNSServiceTxt::releaseValue(void) -{ - if (m_pcValue) + bool MDNSResponder::stcMDNSServiceTxt::releaseValue(void) { - delete[] m_pcValue; - m_pcValue = 0; + if (m_pcValue) + { + delete[] m_pcValue; + m_pcValue = 0; + } + return true; } - return true; -} -/* + /* MDNSResponder::stcMDNSServiceTxt::set */ -bool MDNSResponder::stcMDNSServiceTxt::set(const char* p_pcKey, - const char* p_pcValue, - bool p_bTemp /*= false*/) -{ - m_bTemp = p_bTemp; - return ((setKey(p_pcKey)) && - (setValue(p_pcValue))); -} + bool MDNSResponder::stcMDNSServiceTxt::set(const char* p_pcKey, + const char* p_pcValue, + bool p_bTemp /*= false*/) + { + m_bTemp = p_bTemp; + return ((setKey(p_pcKey)) && (setValue(p_pcValue))); + } -/* + /* MDNSResponder::stcMDNSServiceTxt::update */ -bool MDNSResponder::stcMDNSServiceTxt::update(const char* p_pcValue) -{ - return setValue(p_pcValue); -} + bool MDNSResponder::stcMDNSServiceTxt::update(const char* p_pcValue) + { + return setValue(p_pcValue); + } -/* + /* MDNSResponder::stcMDNSServiceTxt::length length of eg. 'c#=1' without any closing '\0' */ -size_t MDNSResponder::stcMDNSServiceTxt::length(void) const -{ - size_t stLength = 0; - if (m_pcKey) + size_t MDNSResponder::stcMDNSServiceTxt::length(void) const { - stLength += strlen(m_pcKey); // Key - stLength += 1; // '=' - stLength += (m_pcValue ? strlen(m_pcValue) : 0); // Value + size_t stLength = 0; + if (m_pcKey) + { + stLength += strlen(m_pcKey); // Key + stLength += 1; // '=' + stLength += (m_pcValue ? strlen(m_pcValue) : 0); // Value + } + return stLength; } - return stLength; -} -/** + /** MDNSResponder::stcMDNSServiceTxts A list of zero or more MDNS TXT items. @@ -268,382 +267,370 @@ size_t MDNSResponder::stcMDNSServiceTxt::length(void) const */ -/* + /* MDNSResponder::stcMDNSServiceTxts::stcMDNSServiceTxts constructor */ -MDNSResponder::stcMDNSServiceTxts::stcMDNSServiceTxts(void) - : m_pTxts(0) -{ -} + MDNSResponder::stcMDNSServiceTxts::stcMDNSServiceTxts(void) + : m_pTxts(0) + { + } -/* + /* MDNSResponder::stcMDNSServiceTxts::stcMDNSServiceTxts copy-constructor */ -MDNSResponder::stcMDNSServiceTxts::stcMDNSServiceTxts(const stcMDNSServiceTxts& p_Other) - : m_pTxts(0) -{ - operator=(p_Other); -} + MDNSResponder::stcMDNSServiceTxts::stcMDNSServiceTxts(const stcMDNSServiceTxts& p_Other) + : m_pTxts(0) + { + operator=(p_Other); + } -/* + /* MDNSResponder::stcMDNSServiceTxts::~stcMDNSServiceTxts destructor */ -MDNSResponder::stcMDNSServiceTxts::~stcMDNSServiceTxts(void) -{ - clear(); -} + MDNSResponder::stcMDNSServiceTxts::~stcMDNSServiceTxts(void) + { + clear(); + } -/* + /* MDNSResponder::stcMDNSServiceTxts::operator= */ -MDNSResponder::stcMDNSServiceTxts& MDNSResponder::stcMDNSServiceTxts::operator=(const stcMDNSServiceTxts& p_Other) -{ - if (this != &p_Other) + MDNSResponder::stcMDNSServiceTxts& MDNSResponder::stcMDNSServiceTxts::operator=(const stcMDNSServiceTxts& p_Other) { - clear(); - - for (stcMDNSServiceTxt* pOtherTxt = p_Other.m_pTxts; pOtherTxt; pOtherTxt = pOtherTxt->m_pNext) + if (this != &p_Other) { - add(new stcMDNSServiceTxt(*pOtherTxt)); + clear(); + + for (stcMDNSServiceTxt* pOtherTxt = p_Other.m_pTxts; pOtherTxt; pOtherTxt = pOtherTxt->m_pNext) + { + add(new stcMDNSServiceTxt(*pOtherTxt)); + } } + return *this; } - return *this; -} -/* + /* MDNSResponder::stcMDNSServiceTxts::clear */ -bool MDNSResponder::stcMDNSServiceTxts::clear(void) -{ - while (m_pTxts) + bool MDNSResponder::stcMDNSServiceTxts::clear(void) { - stcMDNSServiceTxt* pNext = m_pTxts->m_pNext; - delete m_pTxts; - m_pTxts = pNext; + while (m_pTxts) + { + stcMDNSServiceTxt* pNext = m_pTxts->m_pNext; + delete m_pTxts; + m_pTxts = pNext; + } + return true; } - return true; -} -/* + /* MDNSResponder::stcMDNSServiceTxts::add */ -bool MDNSResponder::stcMDNSServiceTxts::add(MDNSResponder::stcMDNSServiceTxt* p_pTxt) -{ - bool bResult = false; - - if (p_pTxt) + bool MDNSResponder::stcMDNSServiceTxts::add(MDNSResponder::stcMDNSServiceTxt* p_pTxt) { - p_pTxt->m_pNext = m_pTxts; - m_pTxts = p_pTxt; - bResult = true; + bool bResult = false; + + if (p_pTxt) + { + p_pTxt->m_pNext = m_pTxts; + m_pTxts = p_pTxt; + bResult = true; + } + return bResult; } - return bResult; -} -/* + /* MDNSResponder::stcMDNSServiceTxts::remove */ -bool MDNSResponder::stcMDNSServiceTxts::remove(stcMDNSServiceTxt* p_pTxt) -{ - bool bResult = false; - - if (p_pTxt) + bool MDNSResponder::stcMDNSServiceTxts::remove(stcMDNSServiceTxt* p_pTxt) { - stcMDNSServiceTxt* pPred = m_pTxts; - while ((pPred) && - (pPred->m_pNext != p_pTxt)) - { - pPred = pPred->m_pNext; - } - if (pPred) - { - pPred->m_pNext = p_pTxt->m_pNext; - delete p_pTxt; - bResult = true; - } - else if (m_pTxts == p_pTxt) // No predecessor, but first item + bool bResult = false; + + if (p_pTxt) { - m_pTxts = p_pTxt->m_pNext; - delete p_pTxt; - bResult = true; + stcMDNSServiceTxt* pPred = m_pTxts; + while ((pPred) && (pPred->m_pNext != p_pTxt)) + { + pPred = pPred->m_pNext; + } + if (pPred) + { + pPred->m_pNext = p_pTxt->m_pNext; + delete p_pTxt; + bResult = true; + } + else if (m_pTxts == p_pTxt) // No predecessor, but first item + { + m_pTxts = p_pTxt->m_pNext; + delete p_pTxt; + bResult = true; + } } + return bResult; } - return bResult; -} -/* + /* MDNSResponder::stcMDNSServiceTxts::removeTempTxts */ -bool MDNSResponder::stcMDNSServiceTxts::removeTempTxts(void) -{ - bool bResult = true; - - stcMDNSServiceTxt* pTxt = m_pTxts; - while ((bResult) && - (pTxt)) + bool MDNSResponder::stcMDNSServiceTxts::removeTempTxts(void) { - stcMDNSServiceTxt* pNext = pTxt->m_pNext; - if (pTxt->m_bTemp) + bool bResult = true; + + stcMDNSServiceTxt* pTxt = m_pTxts; + while ((bResult) && (pTxt)) { - bResult = remove(pTxt); + stcMDNSServiceTxt* pNext = pTxt->m_pNext; + if (pTxt->m_bTemp) + { + bResult = remove(pTxt); + } + pTxt = pNext; } - pTxt = pNext; + return bResult; } - return bResult; -} -/* + /* MDNSResponder::stcMDNSServiceTxts::find */ -MDNSResponder::stcMDNSServiceTxt* MDNSResponder::stcMDNSServiceTxts::find(const char* p_pcKey) -{ - stcMDNSServiceTxt* pResult = 0; - - for (stcMDNSServiceTxt* pTxt = m_pTxts; pTxt; pTxt = pTxt->m_pNext) + MDNSResponder::stcMDNSServiceTxt* MDNSResponder::stcMDNSServiceTxts::find(const char* p_pcKey) { - if ((p_pcKey) && - (0 == strcmp(pTxt->m_pcKey, p_pcKey))) + stcMDNSServiceTxt* pResult = 0; + + for (stcMDNSServiceTxt* pTxt = m_pTxts; pTxt; pTxt = pTxt->m_pNext) { - pResult = pTxt; - break; + if ((p_pcKey) && (0 == strcmp(pTxt->m_pcKey, p_pcKey))) + { + pResult = pTxt; + break; + } } + return pResult; } - return pResult; -} -/* + /* MDNSResponder::stcMDNSServiceTxts::find */ -const MDNSResponder::stcMDNSServiceTxt* MDNSResponder::stcMDNSServiceTxts::find(const char* p_pcKey) const -{ - const stcMDNSServiceTxt* pResult = 0; - - for (const stcMDNSServiceTxt* pTxt = m_pTxts; pTxt; pTxt = pTxt->m_pNext) + const MDNSResponder::stcMDNSServiceTxt* MDNSResponder::stcMDNSServiceTxts::find(const char* p_pcKey) const { - if ((p_pcKey) && - (0 == strcmp(pTxt->m_pcKey, p_pcKey))) + const stcMDNSServiceTxt* pResult = 0; + + for (const stcMDNSServiceTxt* pTxt = m_pTxts; pTxt; pTxt = pTxt->m_pNext) { - pResult = pTxt; - break; + if ((p_pcKey) && (0 == strcmp(pTxt->m_pcKey, p_pcKey))) + { + pResult = pTxt; + break; + } } + return pResult; } - return pResult; -} -/* + /* MDNSResponder::stcMDNSServiceTxts::find */ -MDNSResponder::stcMDNSServiceTxt* MDNSResponder::stcMDNSServiceTxts::find(const stcMDNSServiceTxt* p_pTxt) -{ - stcMDNSServiceTxt* pResult = 0; - - for (stcMDNSServiceTxt* pTxt = m_pTxts; pTxt; pTxt = pTxt->m_pNext) + MDNSResponder::stcMDNSServiceTxt* MDNSResponder::stcMDNSServiceTxts::find(const stcMDNSServiceTxt* p_pTxt) { - if (p_pTxt == pTxt) + stcMDNSServiceTxt* pResult = 0; + + for (stcMDNSServiceTxt* pTxt = m_pTxts; pTxt; pTxt = pTxt->m_pNext) { - pResult = pTxt; - break; + if (p_pTxt == pTxt) + { + pResult = pTxt; + break; + } } + return pResult; } - return pResult; -} -/* + /* MDNSResponder::stcMDNSServiceTxts::length */ -uint16_t MDNSResponder::stcMDNSServiceTxts::length(void) const -{ - uint16_t u16Length = 0; - - stcMDNSServiceTxt* pTxt = m_pTxts; - while (pTxt) + uint16_t MDNSResponder::stcMDNSServiceTxts::length(void) const { - u16Length += 1; // Length byte - u16Length += pTxt->length(); // Text - pTxt = pTxt->m_pNext; + uint16_t u16Length = 0; + + stcMDNSServiceTxt* pTxt = m_pTxts; + while (pTxt) + { + u16Length += 1; // Length byte + u16Length += pTxt->length(); // Text + pTxt = pTxt->m_pNext; + } + return u16Length; } - return u16Length; -} -/* + /* MDNSResponder::stcMDNSServiceTxts::c_strLength (incl. closing '\0'). Length bytes place is used for delimiting ';' and closing '\0' */ -size_t MDNSResponder::stcMDNSServiceTxts::c_strLength(void) const -{ - return length(); -} + size_t MDNSResponder::stcMDNSServiceTxts::c_strLength(void) const + { + return length(); + } -/* + /* MDNSResponder::stcMDNSServiceTxts::c_str */ -bool MDNSResponder::stcMDNSServiceTxts::c_str(char* p_pcBuffer) -{ - bool bResult = false; - - if (p_pcBuffer) + bool MDNSResponder::stcMDNSServiceTxts::c_str(char* p_pcBuffer) { - bResult = true; + bool bResult = false; - *p_pcBuffer = 0; - for (stcMDNSServiceTxt* pTxt = m_pTxts; ((bResult) && (pTxt)); pTxt = pTxt->m_pNext) + if (p_pcBuffer) { - size_t stLength; - if ((bResult = (0 != (stLength = (pTxt->m_pcKey ? strlen(pTxt->m_pcKey) : 0))))) + bResult = true; + + *p_pcBuffer = 0; + for (stcMDNSServiceTxt* pTxt = m_pTxts; ((bResult) && (pTxt)); pTxt = pTxt->m_pNext) { - if (pTxt != m_pTxts) + size_t stLength; + if ((bResult = (0 != (stLength = (pTxt->m_pcKey ? strlen(pTxt->m_pcKey) : 0))))) { - *p_pcBuffer++ = ';'; - } - strncpy(p_pcBuffer, pTxt->m_pcKey, stLength); - p_pcBuffer[stLength] = 0; - p_pcBuffer += stLength; - *p_pcBuffer++ = '='; - if ((stLength = (pTxt->m_pcValue ? strlen(pTxt->m_pcValue) : 0))) - { - strncpy(p_pcBuffer, pTxt->m_pcValue, stLength); + if (pTxt != m_pTxts) + { + *p_pcBuffer++ = ';'; + } + strncpy(p_pcBuffer, pTxt->m_pcKey, stLength); p_pcBuffer[stLength] = 0; p_pcBuffer += stLength; + *p_pcBuffer++ = '='; + if ((stLength = (pTxt->m_pcValue ? strlen(pTxt->m_pcValue) : 0))) + { + strncpy(p_pcBuffer, pTxt->m_pcValue, stLength); + p_pcBuffer[stLength] = 0; + p_pcBuffer += stLength; + } } } + *p_pcBuffer++ = 0; } - *p_pcBuffer++ = 0; + return bResult; } - return bResult; -} -/* + /* MDNSResponder::stcMDNSServiceTxts::bufferLength (incl. closing '\0'). */ -size_t MDNSResponder::stcMDNSServiceTxts::bufferLength(void) const -{ - return (length() + 1); -} + size_t MDNSResponder::stcMDNSServiceTxts::bufferLength(void) const + { + return (length() + 1); + } -/* + /* MDNSResponder::stcMDNSServiceTxts::toBuffer */ -bool MDNSResponder::stcMDNSServiceTxts::buffer(char* p_pcBuffer) -{ - bool bResult = false; - - if (p_pcBuffer) + bool MDNSResponder::stcMDNSServiceTxts::buffer(char* p_pcBuffer) { - bResult = true; + bool bResult = false; - *p_pcBuffer = 0; - for (stcMDNSServiceTxt* pTxt = m_pTxts; ((bResult) && (pTxt)); pTxt = pTxt->m_pNext) + if (p_pcBuffer) { - *(unsigned char*)p_pcBuffer++ = pTxt->length(); - size_t stLength; - if ((bResult = (0 != (stLength = (pTxt->m_pcKey ? strlen(pTxt->m_pcKey) : 0))))) + bResult = true; + + *p_pcBuffer = 0; + for (stcMDNSServiceTxt* pTxt = m_pTxts; ((bResult) && (pTxt)); pTxt = pTxt->m_pNext) { - memcpy(p_pcBuffer, pTxt->m_pcKey, stLength); - p_pcBuffer += stLength; - *p_pcBuffer++ = '='; - if ((stLength = (pTxt->m_pcValue ? strlen(pTxt->m_pcValue) : 0))) + *(unsigned char*)p_pcBuffer++ = pTxt->length(); + size_t stLength; + if ((bResult = (0 != (stLength = (pTxt->m_pcKey ? strlen(pTxt->m_pcKey) : 0))))) { - memcpy(p_pcBuffer, pTxt->m_pcValue, stLength); + memcpy(p_pcBuffer, pTxt->m_pcKey, stLength); p_pcBuffer += stLength; + *p_pcBuffer++ = '='; + if ((stLength = (pTxt->m_pcValue ? strlen(pTxt->m_pcValue) : 0))) + { + memcpy(p_pcBuffer, pTxt->m_pcValue, stLength); + p_pcBuffer += stLength; + } } } + *p_pcBuffer++ = 0; } - *p_pcBuffer++ = 0; + return bResult; } - return bResult; -} -/* + /* MDNSResponder::stcMDNSServiceTxts::compare */ -bool MDNSResponder::stcMDNSServiceTxts::compare(const MDNSResponder::stcMDNSServiceTxts& p_Other) const -{ - bool bResult = false; - - if ((bResult = (length() == p_Other.length()))) + bool MDNSResponder::stcMDNSServiceTxts::compare(const MDNSResponder::stcMDNSServiceTxts& p_Other) const { - // Compare A->B - for (const stcMDNSServiceTxt* pTxt = m_pTxts; ((bResult) && (pTxt)); pTxt = pTxt->m_pNext) - { - const stcMDNSServiceTxt* pOtherTxt = p_Other.find(pTxt->m_pcKey); - bResult = ((pOtherTxt) && - (pTxt->m_pcValue) && - (pOtherTxt->m_pcValue) && - (strlen(pTxt->m_pcValue) == strlen(pOtherTxt->m_pcValue)) && - (0 == strcmp(pTxt->m_pcValue, pOtherTxt->m_pcValue))); - } - // Compare B->A - for (const stcMDNSServiceTxt* pOtherTxt = p_Other.m_pTxts; ((bResult) && (pOtherTxt)); pOtherTxt = pOtherTxt->m_pNext) + bool bResult = false; + + if ((bResult = (length() == p_Other.length()))) { - const stcMDNSServiceTxt* pTxt = find(pOtherTxt->m_pcKey); - bResult = ((pTxt) && - (pOtherTxt->m_pcValue) && - (pTxt->m_pcValue) && - (strlen(pOtherTxt->m_pcValue) == strlen(pTxt->m_pcValue)) && - (0 == strcmp(pOtherTxt->m_pcValue, pTxt->m_pcValue))); + // Compare A->B + for (const stcMDNSServiceTxt* pTxt = m_pTxts; ((bResult) && (pTxt)); pTxt = pTxt->m_pNext) + { + const stcMDNSServiceTxt* pOtherTxt = p_Other.find(pTxt->m_pcKey); + bResult = ((pOtherTxt) && (pTxt->m_pcValue) && (pOtherTxt->m_pcValue) && (strlen(pTxt->m_pcValue) == strlen(pOtherTxt->m_pcValue)) && (0 == strcmp(pTxt->m_pcValue, pOtherTxt->m_pcValue))); + } + // Compare B->A + for (const stcMDNSServiceTxt* pOtherTxt = p_Other.m_pTxts; ((bResult) && (pOtherTxt)); pOtherTxt = pOtherTxt->m_pNext) + { + const stcMDNSServiceTxt* pTxt = find(pOtherTxt->m_pcKey); + bResult = ((pTxt) && (pOtherTxt->m_pcValue) && (pTxt->m_pcValue) && (strlen(pOtherTxt->m_pcValue) == strlen(pTxt->m_pcValue)) && (0 == strcmp(pOtherTxt->m_pcValue, pTxt->m_pcValue))); + } } + return bResult; } - return bResult; -} -/* + /* MDNSResponder::stcMDNSServiceTxts::operator== */ -bool MDNSResponder::stcMDNSServiceTxts::operator==(const stcMDNSServiceTxts& p_Other) const -{ - return compare(p_Other); -} + bool MDNSResponder::stcMDNSServiceTxts::operator==(const stcMDNSServiceTxts& p_Other) const + { + return compare(p_Other); + } -/* + /* MDNSResponder::stcMDNSServiceTxts::operator!= */ -bool MDNSResponder::stcMDNSServiceTxts::operator!=(const stcMDNSServiceTxts& p_Other) const -{ - return !compare(p_Other); -} + bool MDNSResponder::stcMDNSServiceTxts::operator!=(const stcMDNSServiceTxts& p_Other) const + { + return !compare(p_Other); + } -/** + /** MDNSResponder::stcMDNS_MsgHeader A MDNS message header. */ -/* + /* MDNSResponder::stcMDNS_MsgHeader::stcMDNS_MsgHeader */ -MDNSResponder::stcMDNS_MsgHeader::stcMDNS_MsgHeader(uint16_t p_u16ID /*= 0*/, - bool p_bQR /*= false*/, - unsigned char p_ucOpcode /*= 0*/, - bool p_bAA /*= false*/, - bool p_bTC /*= false*/, - bool p_bRD /*= false*/, - bool p_bRA /*= false*/, - unsigned char p_ucRCode /*= 0*/, - uint16_t p_u16QDCount /*= 0*/, - uint16_t p_u16ANCount /*= 0*/, - uint16_t p_u16NSCount /*= 0*/, - uint16_t p_u16ARCount /*= 0*/) - : m_u16ID(p_u16ID), - m_1bQR(p_bQR), - m_4bOpcode(p_ucOpcode), - m_1bAA(p_bAA), - m_1bTC(p_bTC), - m_1bRD(p_bRD), - m_1bRA(p_bRA), - m_3bZ(0), - m_4bRCode(p_ucRCode), - m_u16QDCount(p_u16QDCount), - m_u16ANCount(p_u16ANCount), - m_u16NSCount(p_u16NSCount), - m_u16ARCount(p_u16ARCount) -{ -} - -/** + MDNSResponder::stcMDNS_MsgHeader::stcMDNS_MsgHeader(uint16_t p_u16ID /*= 0*/, + bool p_bQR /*= false*/, + unsigned char p_ucOpcode /*= 0*/, + bool p_bAA /*= false*/, + bool p_bTC /*= false*/, + bool p_bRD /*= false*/, + bool p_bRA /*= false*/, + unsigned char p_ucRCode /*= 0*/, + uint16_t p_u16QDCount /*= 0*/, + uint16_t p_u16ANCount /*= 0*/, + uint16_t p_u16NSCount /*= 0*/, + uint16_t p_u16ARCount /*= 0*/) + : m_u16ID(p_u16ID) + , m_1bQR(p_bQR) + , m_4bOpcode(p_ucOpcode) + , m_1bAA(p_bAA) + , m_1bTC(p_bTC) + , m_1bRD(p_bRD) + , m_1bRA(p_bRA) + , m_3bZ(0) + , m_4bRCode(p_ucRCode) + , m_u16QDCount(p_u16QDCount) + , m_u16ANCount(p_u16ANCount) + , m_u16NSCount(p_u16NSCount) + , m_u16ARCount(p_u16ARCount) + { + } + + /** MDNSResponder::stcMDNS_RRDomain A MDNS domain object. @@ -656,275 +643,272 @@ MDNSResponder::stcMDNS_MsgHeader::stcMDNS_MsgHeader(uint16_t p_u16ID /*= 0*/, */ -/* + /* MDNSResponder::stcMDNS_RRDomain::stcMDNS_RRDomain constructor */ -MDNSResponder::stcMDNS_RRDomain::stcMDNS_RRDomain(void) - : m_u16NameLength(0) -{ - clear(); -} + MDNSResponder::stcMDNS_RRDomain::stcMDNS_RRDomain(void) + : m_u16NameLength(0) + { + clear(); + } -/* + /* MDNSResponder::stcMDNS_RRDomain::stcMDNS_RRDomain copy-constructor */ -MDNSResponder::stcMDNS_RRDomain::stcMDNS_RRDomain(const stcMDNS_RRDomain& p_Other) - : m_u16NameLength(0) -{ - operator=(p_Other); -} + MDNSResponder::stcMDNS_RRDomain::stcMDNS_RRDomain(const stcMDNS_RRDomain& p_Other) + : m_u16NameLength(0) + { + operator=(p_Other); + } -/* + /* MDNSResponder::stcMDNS_RRDomain::operator = */ -MDNSResponder::stcMDNS_RRDomain& MDNSResponder::stcMDNS_RRDomain::operator=(const stcMDNS_RRDomain& p_Other) -{ - if (&p_Other != this) + MDNSResponder::stcMDNS_RRDomain& MDNSResponder::stcMDNS_RRDomain::operator=(const stcMDNS_RRDomain& p_Other) { - memcpy(m_acName, p_Other.m_acName, sizeof(m_acName)); - m_u16NameLength = p_Other.m_u16NameLength; + if (&p_Other != this) + { + memcpy(m_acName, p_Other.m_acName, sizeof(m_acName)); + m_u16NameLength = p_Other.m_u16NameLength; + } + return *this; } - return *this; -} -/* + /* MDNSResponder::stcMDNS_RRDomain::clear */ -bool MDNSResponder::stcMDNS_RRDomain::clear(void) -{ - memset(m_acName, 0, sizeof(m_acName)); - m_u16NameLength = 0; - return true; -} + bool MDNSResponder::stcMDNS_RRDomain::clear(void) + { + memset(m_acName, 0, sizeof(m_acName)); + m_u16NameLength = 0; + return true; + } -/* + /* MDNSResponder::stcMDNS_RRDomain::addLabel */ -bool MDNSResponder::stcMDNS_RRDomain::addLabel(const char* p_pcLabel, - bool p_bPrependUnderline /*= false*/) -{ - bool bResult = false; - - size_t stLength = (p_pcLabel - ? (strlen(p_pcLabel) + (p_bPrependUnderline ? 1 : 0)) - : 0); - if ((MDNS_DOMAIN_LABEL_MAXLENGTH >= stLength) && - (MDNS_DOMAIN_MAXLENGTH >= (m_u16NameLength + (1 + stLength)))) - { - // Length byte - m_acName[m_u16NameLength] = (unsigned char)stLength; // Might be 0! - ++m_u16NameLength; - // Label - if (stLength) + bool MDNSResponder::stcMDNS_RRDomain::addLabel(const char* p_pcLabel, + bool p_bPrependUnderline /*= false*/) + { + bool bResult = false; + + size_t stLength = (p_pcLabel + ? (strlen(p_pcLabel) + (p_bPrependUnderline ? 1 : 0)) + : 0); + if ((MDNS_DOMAIN_LABEL_MAXLENGTH >= stLength) && (MDNS_DOMAIN_MAXLENGTH >= (m_u16NameLength + (1 + stLength)))) { - if (p_bPrependUnderline) + // Length byte + m_acName[m_u16NameLength] = (unsigned char)stLength; // Might be 0! + ++m_u16NameLength; + // Label + if (stLength) { - m_acName[m_u16NameLength++] = '_'; - --stLength; + if (p_bPrependUnderline) + { + m_acName[m_u16NameLength++] = '_'; + --stLength; + } + strncpy(&(m_acName[m_u16NameLength]), p_pcLabel, stLength); + m_acName[m_u16NameLength + stLength] = 0; + m_u16NameLength += stLength; } - strncpy(&(m_acName[m_u16NameLength]), p_pcLabel, stLength); - m_acName[m_u16NameLength + stLength] = 0; - m_u16NameLength += stLength; + bResult = true; } - bResult = true; + return bResult; } - return bResult; -} -/* + /* MDNSResponder::stcMDNS_RRDomain::compare */ -bool MDNSResponder::stcMDNS_RRDomain::compare(const stcMDNS_RRDomain& p_Other) const -{ - bool bResult = false; - - if (m_u16NameLength == p_Other.m_u16NameLength) + bool MDNSResponder::stcMDNS_RRDomain::compare(const stcMDNS_RRDomain& p_Other) const { - const char* pT = m_acName; - const char* pO = p_Other.m_acName; - while ((pT) && - (pO) && - (*((unsigned char*)pT) == *((unsigned char*)pO)) && // Same length AND - (0 == strncasecmp((pT + 1), (pO + 1), *((unsigned char*)pT)))) // Same content + bool bResult = false; + + if (m_u16NameLength == p_Other.m_u16NameLength) { - if (*((unsigned char*)pT)) // Not 0 - { - pT += (1 + *((unsigned char*)pT)); // Shift by length byte and length - pO += (1 + *((unsigned char*)pO)); - } - else // Is 0 -> Successfully reached the end + const char* pT = m_acName; + const char* pO = p_Other.m_acName; + while ((pT) && (pO) && (*((unsigned char*)pT) == *((unsigned char*)pO)) && // Same length AND + (0 == strncasecmp((pT + 1), (pO + 1), *((unsigned char*)pT)))) // Same content { - bResult = true; - break; + if (*((unsigned char*)pT)) // Not 0 + { + pT += (1 + *((unsigned char*)pT)); // Shift by length byte and length + pO += (1 + *((unsigned char*)pO)); + } + else // Is 0 -> Successfully reached the end + { + bResult = true; + break; + } } } + return bResult; } - return bResult; -} -/* + /* MDNSResponder::stcMDNS_RRDomain::operator == */ -bool MDNSResponder::stcMDNS_RRDomain::operator==(const stcMDNS_RRDomain& p_Other) const -{ - return compare(p_Other); -} + bool MDNSResponder::stcMDNS_RRDomain::operator==(const stcMDNS_RRDomain& p_Other) const + { + return compare(p_Other); + } -/* + /* MDNSResponder::stcMDNS_RRDomain::operator != */ -bool MDNSResponder::stcMDNS_RRDomain::operator!=(const stcMDNS_RRDomain& p_Other) const -{ - return !compare(p_Other); -} + bool MDNSResponder::stcMDNS_RRDomain::operator!=(const stcMDNS_RRDomain& p_Other) const + { + return !compare(p_Other); + } -/* + /* MDNSResponder::stcMDNS_RRDomain::operator > */ -bool MDNSResponder::stcMDNS_RRDomain::operator>(const stcMDNS_RRDomain& p_Other) const -{ - // TODO: Check, if this is a good idea... - return !compare(p_Other); -} + bool MDNSResponder::stcMDNS_RRDomain::operator>(const stcMDNS_RRDomain& p_Other) const + { + // TODO: Check, if this is a good idea... + return !compare(p_Other); + } -/* + /* MDNSResponder::stcMDNS_RRDomain::c_strLength */ -size_t MDNSResponder::stcMDNS_RRDomain::c_strLength(void) const -{ - size_t stLength = 0; - - unsigned char* pucLabelLength = (unsigned char*)m_acName; - while (*pucLabelLength) + size_t MDNSResponder::stcMDNS_RRDomain::c_strLength(void) const { - stLength += (*pucLabelLength + 1 /* +1 for '.' or '\0'*/); - pucLabelLength += (*pucLabelLength + 1); + size_t stLength = 0; + + unsigned char* pucLabelLength = (unsigned char*)m_acName; + while (*pucLabelLength) + { + stLength += (*pucLabelLength + 1 /* +1 for '.' or '\0'*/); + pucLabelLength += (*pucLabelLength + 1); + } + return stLength; } - return stLength; -} -/* + /* MDNSResponder::stcMDNS_RRDomain::c_str */ -bool MDNSResponder::stcMDNS_RRDomain::c_str(char* p_pcBuffer) -{ - bool bResult = false; - - if (p_pcBuffer) + bool MDNSResponder::stcMDNS_RRDomain::c_str(char* p_pcBuffer) { - *p_pcBuffer = 0; - unsigned char* pucLabelLength = (unsigned char*)m_acName; - while (*pucLabelLength) + bool bResult = false; + + if (p_pcBuffer) { - memcpy(p_pcBuffer, (const char*)(pucLabelLength + 1), *pucLabelLength); - p_pcBuffer += *pucLabelLength; - pucLabelLength += (*pucLabelLength + 1); - *p_pcBuffer++ = (*pucLabelLength ? '.' : '\0'); + *p_pcBuffer = 0; + unsigned char* pucLabelLength = (unsigned char*)m_acName; + while (*pucLabelLength) + { + memcpy(p_pcBuffer, (const char*)(pucLabelLength + 1), *pucLabelLength); + p_pcBuffer += *pucLabelLength; + pucLabelLength += (*pucLabelLength + 1); + *p_pcBuffer++ = (*pucLabelLength ? '.' : '\0'); + } + bResult = true; } - bResult = true; + return bResult; } - return bResult; -} -/** + /** MDNSResponder::stcMDNS_RRAttributes A MDNS attributes object. */ -/* + /* MDNSResponder::stcMDNS_RRAttributes::stcMDNS_RRAttributes constructor */ -MDNSResponder::stcMDNS_RRAttributes::stcMDNS_RRAttributes(uint16_t p_u16Type /*= 0*/, - uint16_t p_u16Class /*= 1 DNS_RRCLASS_IN Internet*/) - : m_u16Type(p_u16Type), - m_u16Class(p_u16Class) -{ -} + MDNSResponder::stcMDNS_RRAttributes::stcMDNS_RRAttributes(uint16_t p_u16Type /*= 0*/, + uint16_t p_u16Class /*= 1 DNS_RRCLASS_IN Internet*/) + : m_u16Type(p_u16Type) + , m_u16Class(p_u16Class) + { + } -/* + /* MDNSResponder::stcMDNS_RRAttributes::stcMDNS_RRAttributes copy-constructor */ -MDNSResponder::stcMDNS_RRAttributes::stcMDNS_RRAttributes(const MDNSResponder::stcMDNS_RRAttributes& p_Other) -{ - operator=(p_Other); -} + MDNSResponder::stcMDNS_RRAttributes::stcMDNS_RRAttributes(const MDNSResponder::stcMDNS_RRAttributes& p_Other) + { + operator=(p_Other); + } -/* + /* MDNSResponder::stcMDNS_RRAttributes::operator = */ -MDNSResponder::stcMDNS_RRAttributes& MDNSResponder::stcMDNS_RRAttributes::operator=(const MDNSResponder::stcMDNS_RRAttributes& p_Other) -{ - if (&p_Other != this) + MDNSResponder::stcMDNS_RRAttributes& MDNSResponder::stcMDNS_RRAttributes::operator=(const MDNSResponder::stcMDNS_RRAttributes& p_Other) { - m_u16Type = p_Other.m_u16Type; - m_u16Class = p_Other.m_u16Class; + if (&p_Other != this) + { + m_u16Type = p_Other.m_u16Type; + m_u16Class = p_Other.m_u16Class; + } + return *this; } - return *this; -} -/** + /** MDNSResponder::stcMDNS_RRHeader A MDNS record header (domain and attributes) object. */ -/* + /* MDNSResponder::stcMDNS_RRHeader::stcMDNS_RRHeader constructor */ -MDNSResponder::stcMDNS_RRHeader::stcMDNS_RRHeader(void) -{ -} + MDNSResponder::stcMDNS_RRHeader::stcMDNS_RRHeader(void) + { + } -/* + /* MDNSResponder::stcMDNS_RRHeader::stcMDNS_RRHeader copy-constructor */ -MDNSResponder::stcMDNS_RRHeader::stcMDNS_RRHeader(const stcMDNS_RRHeader& p_Other) -{ - operator=(p_Other); -} + MDNSResponder::stcMDNS_RRHeader::stcMDNS_RRHeader(const stcMDNS_RRHeader& p_Other) + { + operator=(p_Other); + } -/* + /* MDNSResponder::stcMDNS_RRHeader::operator = */ -MDNSResponder::stcMDNS_RRHeader& MDNSResponder::stcMDNS_RRHeader::operator=(const MDNSResponder::stcMDNS_RRHeader& p_Other) -{ - if (&p_Other != this) + MDNSResponder::stcMDNS_RRHeader& MDNSResponder::stcMDNS_RRHeader::operator=(const MDNSResponder::stcMDNS_RRHeader& p_Other) { - m_Domain = p_Other.m_Domain; - m_Attributes = p_Other.m_Attributes; + if (&p_Other != this) + { + m_Domain = p_Other.m_Domain; + m_Attributes = p_Other.m_Attributes; + } + return *this; } - return *this; -} -/* + /* MDNSResponder::stcMDNS_RRHeader::clear */ -bool MDNSResponder::stcMDNS_RRHeader::clear(void) -{ - m_Domain.clear(); - return true; -} + bool MDNSResponder::stcMDNS_RRHeader::clear(void) + { + m_Domain.clear(); + return true; + } -/** + /** MDNSResponder::stcMDNS_RRQuestion A MDNS question record object (header + question flags) */ -/* + /* MDNSResponder::stcMDNS_RRQuestion::stcMDNS_RRQuestion constructor */ -MDNSResponder::stcMDNS_RRQuestion::stcMDNS_RRQuestion(void) - : m_pNext(0), - m_bUnicast(false) -{ -} + MDNSResponder::stcMDNS_RRQuestion::stcMDNS_RRQuestion(void) + : m_pNext(0) + , m_bUnicast(false) + { + } -/** + /** MDNSResponder::stcMDNS_RRAnswer A MDNS answer record object (header + answer content). @@ -932,48 +916,48 @@ MDNSResponder::stcMDNS_RRQuestion::stcMDNS_RRQuestion(void) */ -/* + /* MDNSResponder::stcMDNS_RRAnswer::stcMDNS_RRAnswer constructor */ -MDNSResponder::stcMDNS_RRAnswer::stcMDNS_RRAnswer(enuAnswerType p_AnswerType, - const MDNSResponder::stcMDNS_RRHeader& p_Header, - uint32_t p_u32TTL) - : m_pNext(0), - m_AnswerType(p_AnswerType), - m_Header(p_Header), - m_u32TTL(p_u32TTL) -{ - // Extract 'cache flush'-bit - m_bCacheFlush = (m_Header.m_Attributes.m_u16Class & 0x8000); - m_Header.m_Attributes.m_u16Class &= (~0x8000); -} + MDNSResponder::stcMDNS_RRAnswer::stcMDNS_RRAnswer(enuAnswerType p_AnswerType, + const MDNSResponder::stcMDNS_RRHeader& p_Header, + uint32_t p_u32TTL) + : m_pNext(0) + , m_AnswerType(p_AnswerType) + , m_Header(p_Header) + , m_u32TTL(p_u32TTL) + { + // Extract 'cache flush'-bit + m_bCacheFlush = (m_Header.m_Attributes.m_u16Class & 0x8000); + m_Header.m_Attributes.m_u16Class &= (~0x8000); + } -/* + /* MDNSResponder::stcMDNS_RRAnswer::~stcMDNS_RRAnswer destructor */ -MDNSResponder::stcMDNS_RRAnswer::~stcMDNS_RRAnswer(void) -{ -} + MDNSResponder::stcMDNS_RRAnswer::~stcMDNS_RRAnswer(void) + { + } -/* + /* MDNSResponder::stcMDNS_RRAnswer::answerType */ -MDNSResponder::enuAnswerType MDNSResponder::stcMDNS_RRAnswer::answerType(void) const -{ - return m_AnswerType; -} + MDNSResponder::enuAnswerType MDNSResponder::stcMDNS_RRAnswer::answerType(void) const + { + return m_AnswerType; + } -/* + /* MDNSResponder::stcMDNS_RRAnswer::clear */ -bool MDNSResponder::stcMDNS_RRAnswer::clear(void) -{ - m_pNext = 0; - m_Header.clear(); - return true; -} + bool MDNSResponder::stcMDNS_RRAnswer::clear(void) + { + m_pNext = 0; + m_Header.clear(); + return true; + } -/** + /** MDNSResponder::stcMDNS_RRAnswerA A MDNS A answer object. @@ -982,35 +966,35 @@ bool MDNSResponder::stcMDNS_RRAnswer::clear(void) */ #ifdef MDNS_IP4_SUPPORT -/* + /* MDNSResponder::stcMDNS_RRAnswerA::stcMDNS_RRAnswerA constructor */ -MDNSResponder::stcMDNS_RRAnswerA::stcMDNS_RRAnswerA(const MDNSResponder::stcMDNS_RRHeader& p_Header, - uint32_t p_u32TTL) - : stcMDNS_RRAnswer(AnswerType_A, p_Header, p_u32TTL), - m_IPAddress(0, 0, 0, 0) -{ -} + MDNSResponder::stcMDNS_RRAnswerA::stcMDNS_RRAnswerA(const MDNSResponder::stcMDNS_RRHeader& p_Header, + uint32_t p_u32TTL) + : stcMDNS_RRAnswer(AnswerType_A, p_Header, p_u32TTL) + , m_IPAddress(0, 0, 0, 0) + { + } -/* + /* MDNSResponder::stcMDNS_RRAnswerA::stcMDNS_RRAnswerA destructor */ -MDNSResponder::stcMDNS_RRAnswerA::~stcMDNS_RRAnswerA(void) -{ - clear(); -} + MDNSResponder::stcMDNS_RRAnswerA::~stcMDNS_RRAnswerA(void) + { + clear(); + } -/* + /* MDNSResponder::stcMDNS_RRAnswerA::clear */ -bool MDNSResponder::stcMDNS_RRAnswerA::clear(void) -{ - m_IPAddress = IPAddress(0, 0, 0, 0); - return true; -} + bool MDNSResponder::stcMDNS_RRAnswerA::clear(void) + { + m_IPAddress = IPAddress(0, 0, 0, 0); + return true; + } #endif -/** + /** MDNSResponder::stcMDNS_RRAnswerPTR A MDNS PTR answer object. @@ -1018,33 +1002,33 @@ bool MDNSResponder::stcMDNS_RRAnswerA::clear(void) */ -/* + /* MDNSResponder::stcMDNS_RRAnswerPTR::stcMDNS_RRAnswerPTR constructor */ -MDNSResponder::stcMDNS_RRAnswerPTR::stcMDNS_RRAnswerPTR(const MDNSResponder::stcMDNS_RRHeader& p_Header, - uint32_t p_u32TTL) - : stcMDNS_RRAnswer(AnswerType_PTR, p_Header, p_u32TTL) -{ -} + MDNSResponder::stcMDNS_RRAnswerPTR::stcMDNS_RRAnswerPTR(const MDNSResponder::stcMDNS_RRHeader& p_Header, + uint32_t p_u32TTL) + : stcMDNS_RRAnswer(AnswerType_PTR, p_Header, p_u32TTL) + { + } -/* + /* MDNSResponder::stcMDNS_RRAnswerPTR::~stcMDNS_RRAnswerPTR destructor */ -MDNSResponder::stcMDNS_RRAnswerPTR::~stcMDNS_RRAnswerPTR(void) -{ - clear(); -} + MDNSResponder::stcMDNS_RRAnswerPTR::~stcMDNS_RRAnswerPTR(void) + { + clear(); + } -/* + /* MDNSResponder::stcMDNS_RRAnswerPTR::clear */ -bool MDNSResponder::stcMDNS_RRAnswerPTR::clear(void) -{ - m_PTRDomain.clear(); - return true; -} + bool MDNSResponder::stcMDNS_RRAnswerPTR::clear(void) + { + m_PTRDomain.clear(); + return true; + } -/** + /** MDNSResponder::stcMDNS_RRAnswerTXT A MDNS TXT answer object. @@ -1052,33 +1036,33 @@ bool MDNSResponder::stcMDNS_RRAnswerPTR::clear(void) */ -/* + /* MDNSResponder::stcMDNS_RRAnswerTXT::stcMDNS_RRAnswerTXT constructor */ -MDNSResponder::stcMDNS_RRAnswerTXT::stcMDNS_RRAnswerTXT(const MDNSResponder::stcMDNS_RRHeader& p_Header, - uint32_t p_u32TTL) - : stcMDNS_RRAnswer(AnswerType_TXT, p_Header, p_u32TTL) -{ -} + MDNSResponder::stcMDNS_RRAnswerTXT::stcMDNS_RRAnswerTXT(const MDNSResponder::stcMDNS_RRHeader& p_Header, + uint32_t p_u32TTL) + : stcMDNS_RRAnswer(AnswerType_TXT, p_Header, p_u32TTL) + { + } -/* + /* MDNSResponder::stcMDNS_RRAnswerTXT::~stcMDNS_RRAnswerTXT destructor */ -MDNSResponder::stcMDNS_RRAnswerTXT::~stcMDNS_RRAnswerTXT(void) -{ - clear(); -} + MDNSResponder::stcMDNS_RRAnswerTXT::~stcMDNS_RRAnswerTXT(void) + { + clear(); + } -/* + /* MDNSResponder::stcMDNS_RRAnswerTXT::clear */ -bool MDNSResponder::stcMDNS_RRAnswerTXT::clear(void) -{ - m_Txts.clear(); - return true; -} + bool MDNSResponder::stcMDNS_RRAnswerTXT::clear(void) + { + m_Txts.clear(); + return true; + } -/** + /** MDNSResponder::stcMDNS_RRAnswerAAAA A MDNS AAAA answer object. @@ -1087,33 +1071,33 @@ bool MDNSResponder::stcMDNS_RRAnswerTXT::clear(void) */ #ifdef MDNS_IP6_SUPPORT -/* + /* MDNSResponder::stcMDNS_RRAnswerAAAA::stcMDNS_RRAnswerAAAA constructor */ -MDNSResponder::stcMDNS_RRAnswerAAAA::stcMDNS_RRAnswerAAAA(const MDNSResponder::stcMDNS_RRHeader& p_Header, - uint32_t p_u32TTL) - : stcMDNS_RRAnswer(AnswerType_AAAA, p_Header, p_u32TTL) -{ -} + MDNSResponder::stcMDNS_RRAnswerAAAA::stcMDNS_RRAnswerAAAA(const MDNSResponder::stcMDNS_RRHeader& p_Header, + uint32_t p_u32TTL) + : stcMDNS_RRAnswer(AnswerType_AAAA, p_Header, p_u32TTL) + { + } -/* + /* MDNSResponder::stcMDNS_RRAnswerAAAA::~stcMDNS_RRAnswerAAAA destructor */ -MDNSResponder::stcMDNS_RRAnswerAAAA::~stcMDNS_RRAnswerAAAA(void) -{ - clear(); -} + MDNSResponder::stcMDNS_RRAnswerAAAA::~stcMDNS_RRAnswerAAAA(void) + { + clear(); + } -/* + /* MDNSResponder::stcMDNS_RRAnswerAAAA::clear */ -bool MDNSResponder::stcMDNS_RRAnswerAAAA::clear(void) -{ - return true; -} + bool MDNSResponder::stcMDNS_RRAnswerAAAA::clear(void) + { + return true; + } #endif -/** + /** MDNSResponder::stcMDNS_RRAnswerSRV A MDNS SRV answer object. @@ -1121,39 +1105,39 @@ bool MDNSResponder::stcMDNS_RRAnswerAAAA::clear(void) */ -/* + /* MDNSResponder::stcMDNS_RRAnswerSRV::stcMDNS_RRAnswerSRV constructor */ -MDNSResponder::stcMDNS_RRAnswerSRV::stcMDNS_RRAnswerSRV(const MDNSResponder::stcMDNS_RRHeader& p_Header, - uint32_t p_u32TTL) - : stcMDNS_RRAnswer(AnswerType_SRV, p_Header, p_u32TTL), - m_u16Priority(0), - m_u16Weight(0), - m_u16Port(0) -{ -} + MDNSResponder::stcMDNS_RRAnswerSRV::stcMDNS_RRAnswerSRV(const MDNSResponder::stcMDNS_RRHeader& p_Header, + uint32_t p_u32TTL) + : stcMDNS_RRAnswer(AnswerType_SRV, p_Header, p_u32TTL) + , m_u16Priority(0) + , m_u16Weight(0) + , m_u16Port(0) + { + } -/* + /* MDNSResponder::stcMDNS_RRAnswerSRV::~stcMDNS_RRAnswerSRV destructor */ -MDNSResponder::stcMDNS_RRAnswerSRV::~stcMDNS_RRAnswerSRV(void) -{ - clear(); -} + MDNSResponder::stcMDNS_RRAnswerSRV::~stcMDNS_RRAnswerSRV(void) + { + clear(); + } -/* + /* MDNSResponder::stcMDNS_RRAnswerSRV::clear */ -bool MDNSResponder::stcMDNS_RRAnswerSRV::clear(void) -{ - m_u16Priority = 0; - m_u16Weight = 0; - m_u16Port = 0; - m_SRVDomain.clear(); - return true; -} + bool MDNSResponder::stcMDNS_RRAnswerSRV::clear(void) + { + m_u16Priority = 0; + m_u16Weight = 0; + m_u16Port = 0; + m_SRVDomain.clear(); + return true; + } -/** + /** MDNSResponder::stcMDNS_RRAnswerGeneric An unknown (generic) MDNS answer object. @@ -1161,80 +1145,80 @@ bool MDNSResponder::stcMDNS_RRAnswerSRV::clear(void) */ -/* + /* MDNSResponder::stcMDNS_RRAnswerGeneric::stcMDNS_RRAnswerGeneric constructor */ -MDNSResponder::stcMDNS_RRAnswerGeneric::stcMDNS_RRAnswerGeneric(const stcMDNS_RRHeader& p_Header, - uint32_t p_u32TTL) - : stcMDNS_RRAnswer(AnswerType_Generic, p_Header, p_u32TTL), - m_u16RDLength(0), - m_pu8RDData(0) -{ -} + MDNSResponder::stcMDNS_RRAnswerGeneric::stcMDNS_RRAnswerGeneric(const stcMDNS_RRHeader& p_Header, + uint32_t p_u32TTL) + : stcMDNS_RRAnswer(AnswerType_Generic, p_Header, p_u32TTL) + , m_u16RDLength(0) + , m_pu8RDData(0) + { + } -/* + /* MDNSResponder::stcMDNS_RRAnswerGeneric::~stcMDNS_RRAnswerGeneric destructor */ -MDNSResponder::stcMDNS_RRAnswerGeneric::~stcMDNS_RRAnswerGeneric(void) -{ - clear(); -} + MDNSResponder::stcMDNS_RRAnswerGeneric::~stcMDNS_RRAnswerGeneric(void) + { + clear(); + } -/* + /* MDNSResponder::stcMDNS_RRAnswerGeneric::clear */ -bool MDNSResponder::stcMDNS_RRAnswerGeneric::clear(void) -{ - if (m_pu8RDData) + bool MDNSResponder::stcMDNS_RRAnswerGeneric::clear(void) { - delete[] m_pu8RDData; - m_pu8RDData = 0; - } - m_u16RDLength = 0; + if (m_pu8RDData) + { + delete[] m_pu8RDData; + m_pu8RDData = 0; + } + m_u16RDLength = 0; - return true; -} + return true; + } -/** + /** MDNSResponder::stcProbeInformation Probing status information for a host or service domain */ -/* + /* MDNSResponder::stcProbeInformation::stcProbeInformation constructor */ -MDNSResponder::stcProbeInformation::stcProbeInformation(void) - : m_ProbingStatus(ProbingStatus_WaitingForData), - m_u8SentCount(0), - m_Timeout(esp8266::polledTimeout::oneShotMs::neverExpires), - m_bConflict(false), - m_bTiebreakNeeded(false), - m_fnHostProbeResultCallback(0), - m_fnServiceProbeResultCallback(0) -{ -} + MDNSResponder::stcProbeInformation::stcProbeInformation(void) + : m_ProbingStatus(ProbingStatus_WaitingForData) + , m_u8SentCount(0) + , m_Timeout(esp8266::polledTimeout::oneShotMs::neverExpires) + , m_bConflict(false) + , m_bTiebreakNeeded(false) + , m_fnHostProbeResultCallback(0) + , m_fnServiceProbeResultCallback(0) + { + } -/* + /* MDNSResponder::stcProbeInformation::clear */ -bool MDNSResponder::stcProbeInformation::clear(bool p_bClearUserdata /*= false*/) -{ - m_ProbingStatus = ProbingStatus_WaitingForData; - m_u8SentCount = 0; - m_Timeout.resetToNeverExpires(); - m_bConflict = false; - m_bTiebreakNeeded = false; - if (p_bClearUserdata) + bool MDNSResponder::stcProbeInformation::clear(bool p_bClearUserdata /*= false*/) { - m_fnHostProbeResultCallback = 0; - m_fnServiceProbeResultCallback = 0; + m_ProbingStatus = ProbingStatus_WaitingForData; + m_u8SentCount = 0; + m_Timeout.resetToNeverExpires(); + m_bConflict = false; + m_bTiebreakNeeded = false; + if (p_bClearUserdata) + { + m_fnHostProbeResultCallback = 0; + m_fnServiceProbeResultCallback = 0; + } + return true; } - return true; -} -/** + /** MDNSResponder::stcMDNSService A MDNS service object (to be announced by the MDNS responder) @@ -1245,148 +1229,148 @@ bool MDNSResponder::stcProbeInformation::clear(bool p_bClearUserdata /*= false*/ reset in '_sendMDNSMessage' afterwards. */ -/* + /* MDNSResponder::stcMDNSService::stcMDNSService constructor */ -MDNSResponder::stcMDNSService::stcMDNSService(const char* p_pcName /*= 0*/, - const char* p_pcService /*= 0*/, - const char* p_pcProtocol /*= 0*/) - : m_pNext(0), - m_pcName(0), - m_bAutoName(false), - m_pcService(0), - m_pcProtocol(0), - m_u16Port(0), - m_u8ReplyMask(0), - m_fnTxtCallback(0) -{ - setName(p_pcName); - setService(p_pcService); - setProtocol(p_pcProtocol); -} + MDNSResponder::stcMDNSService::stcMDNSService(const char* p_pcName /*= 0*/, + const char* p_pcService /*= 0*/, + const char* p_pcProtocol /*= 0*/) + : m_pNext(0) + , m_pcName(0) + , m_bAutoName(false) + , m_pcService(0) + , m_pcProtocol(0) + , m_u16Port(0) + , m_u8ReplyMask(0) + , m_fnTxtCallback(0) + { + setName(p_pcName); + setService(p_pcService); + setProtocol(p_pcProtocol); + } -/* + /* MDNSResponder::stcMDNSService::~stcMDNSService destructor */ -MDNSResponder::stcMDNSService::~stcMDNSService(void) -{ - releaseName(); - releaseService(); - releaseProtocol(); -} + MDNSResponder::stcMDNSService::~stcMDNSService(void) + { + releaseName(); + releaseService(); + releaseProtocol(); + } -/* + /* MDNSResponder::stcMDNSService::setName */ -bool MDNSResponder::stcMDNSService::setName(const char* p_pcName) -{ - bool bResult = false; - - releaseName(); - size_t stLength = (p_pcName ? strlen(p_pcName) : 0); - if (stLength) + bool MDNSResponder::stcMDNSService::setName(const char* p_pcName) { - if ((bResult = (0 != (m_pcName = new char[stLength + 1])))) + bool bResult = false; + + releaseName(); + size_t stLength = (p_pcName ? strlen(p_pcName) : 0); + if (stLength) + { + if ((bResult = (0 != (m_pcName = new char[stLength + 1])))) + { + strncpy(m_pcName, p_pcName, stLength); + m_pcName[stLength] = 0; + } + } + else { - strncpy(m_pcName, p_pcName, stLength); - m_pcName[stLength] = 0; + bResult = true; } + return bResult; } - else - { - bResult = true; - } - return bResult; -} -/* + /* MDNSResponder::stcMDNSService::releaseName */ -bool MDNSResponder::stcMDNSService::releaseName(void) -{ - if (m_pcName) + bool MDNSResponder::stcMDNSService::releaseName(void) { - delete[] m_pcName; - m_pcName = 0; + if (m_pcName) + { + delete[] m_pcName; + m_pcName = 0; + } + return true; } - return true; -} -/* + /* MDNSResponder::stcMDNSService::setService */ -bool MDNSResponder::stcMDNSService::setService(const char* p_pcService) -{ - bool bResult = false; - - releaseService(); - size_t stLength = (p_pcService ? strlen(p_pcService) : 0); - if (stLength) + bool MDNSResponder::stcMDNSService::setService(const char* p_pcService) { - if ((bResult = (0 != (m_pcService = new char[stLength + 1])))) + bool bResult = false; + + releaseService(); + size_t stLength = (p_pcService ? strlen(p_pcService) : 0); + if (stLength) { - strncpy(m_pcService, p_pcService, stLength); - m_pcService[stLength] = 0; + if ((bResult = (0 != (m_pcService = new char[stLength + 1])))) + { + strncpy(m_pcService, p_pcService, stLength); + m_pcService[stLength] = 0; + } } + else + { + bResult = true; + } + return bResult; } - else - { - bResult = true; - } - return bResult; -} -/* + /* MDNSResponder::stcMDNSService::releaseService */ -bool MDNSResponder::stcMDNSService::releaseService(void) -{ - if (m_pcService) + bool MDNSResponder::stcMDNSService::releaseService(void) { - delete[] m_pcService; - m_pcService = 0; + if (m_pcService) + { + delete[] m_pcService; + m_pcService = 0; + } + return true; } - return true; -} -/* + /* MDNSResponder::stcMDNSService::setProtocol */ -bool MDNSResponder::stcMDNSService::setProtocol(const char* p_pcProtocol) -{ - bool bResult = false; - - releaseProtocol(); - size_t stLength = (p_pcProtocol ? strlen(p_pcProtocol) : 0); - if (stLength) + bool MDNSResponder::stcMDNSService::setProtocol(const char* p_pcProtocol) { - if ((bResult = (0 != (m_pcProtocol = new char[stLength + 1])))) + bool bResult = false; + + releaseProtocol(); + size_t stLength = (p_pcProtocol ? strlen(p_pcProtocol) : 0); + if (stLength) { - strncpy(m_pcProtocol, p_pcProtocol, stLength); - m_pcProtocol[stLength] = 0; + if ((bResult = (0 != (m_pcProtocol = new char[stLength + 1])))) + { + strncpy(m_pcProtocol, p_pcProtocol, stLength); + m_pcProtocol[stLength] = 0; + } } + else + { + bResult = true; + } + return bResult; } - else - { - bResult = true; - } - return bResult; -} -/* + /* MDNSResponder::stcMDNSService::releaseProtocol */ -bool MDNSResponder::stcMDNSService::releaseProtocol(void) -{ - if (m_pcProtocol) + bool MDNSResponder::stcMDNSService::releaseProtocol(void) { - delete[] m_pcProtocol; - m_pcProtocol = 0; + if (m_pcProtocol) + { + delete[] m_pcProtocol; + m_pcProtocol = 0; + } + return true; } - return true; -} -/** + /** MDNSResponder::stcMDNSServiceQuery A MDNS service query object. @@ -1397,7 +1381,7 @@ bool MDNSResponder::stcMDNSService::releaseProtocol(void) */ -/** + /** MDNSResponder::stcMDNSServiceQuery::stcAnswer One answer for a service query. @@ -1418,7 +1402,7 @@ bool MDNSResponder::stcMDNSService::releaseProtocol(void) */ -/** + /** MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL The TTL (Time-To-Live) for an specific answer content. @@ -1467,7 +1451,7 @@ bool MDNSResponder::stcMDNSService::releaseProtocol(void) (m_TTLTimeFlag.flagged())); }*/ -/** + /** MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL The TTL (Time-To-Live) for an specific answer content. @@ -1477,514 +1461,511 @@ bool MDNSResponder::stcMDNSService::releaseProtocol(void) */ -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::stcTTL constructor */ -MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::stcTTL(void) - : m_u32TTL(0), - m_TTLTimeout(esp8266::polledTimeout::oneShotMs::neverExpires), - m_timeoutLevel(TIMEOUTLEVEL_UNSET) -{ -} + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::stcTTL(void) + : m_u32TTL(0) + , m_TTLTimeout(esp8266::polledTimeout::oneShotMs::neverExpires) + , m_timeoutLevel(TIMEOUTLEVEL_UNSET) + { + } -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::set */ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::set(uint32_t p_u32TTL) -{ - m_u32TTL = p_u32TTL; - if (m_u32TTL) - { - m_timeoutLevel = TIMEOUTLEVEL_BASE; // Set to 80% - m_TTLTimeout.reset(timeout()); - } - else + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::set(uint32_t p_u32TTL) { - m_timeoutLevel = TIMEOUTLEVEL_UNSET; // undef - m_TTLTimeout.resetToNeverExpires(); + m_u32TTL = p_u32TTL; + if (m_u32TTL) + { + m_timeoutLevel = TIMEOUTLEVEL_BASE; // Set to 80% + m_TTLTimeout.reset(timeout()); + } + else + { + m_timeoutLevel = TIMEOUTLEVEL_UNSET; // undef + m_TTLTimeout.resetToNeverExpires(); + } + return true; } - return true; -} -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::flagged */ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::flagged(void) -{ - return ((m_u32TTL) && - (TIMEOUTLEVEL_UNSET != m_timeoutLevel) && - (m_TTLTimeout.expired())); -} + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::flagged(void) + { + return ((m_u32TTL) && (TIMEOUTLEVEL_UNSET != m_timeoutLevel) && (m_TTLTimeout.expired())); + } -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::restart */ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::restart(void) -{ - bool bResult = true; - - if ((TIMEOUTLEVEL_BASE <= m_timeoutLevel) && // >= 80% AND - (TIMEOUTLEVEL_FINAL > m_timeoutLevel)) // < 100% - { - m_timeoutLevel += TIMEOUTLEVEL_INTERVAL; // increment by 5% - m_TTLTimeout.reset(timeout()); - } - else + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::restart(void) { - bResult = false; - m_TTLTimeout.resetToNeverExpires(); - m_timeoutLevel = TIMEOUTLEVEL_UNSET; + bool bResult = true; + + if ((TIMEOUTLEVEL_BASE <= m_timeoutLevel) && // >= 80% AND + (TIMEOUTLEVEL_FINAL > m_timeoutLevel)) // < 100% + { + m_timeoutLevel += TIMEOUTLEVEL_INTERVAL; // increment by 5% + m_TTLTimeout.reset(timeout()); + } + else + { + bResult = false; + m_TTLTimeout.resetToNeverExpires(); + m_timeoutLevel = TIMEOUTLEVEL_UNSET; + } + return bResult; } - return bResult; -} -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::prepareDeletion */ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::prepareDeletion(void) -{ - m_timeoutLevel = TIMEOUTLEVEL_FINAL; - m_TTLTimeout.reset(1 * 1000); // See RFC 6762, 10.1 + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::prepareDeletion(void) + { + m_timeoutLevel = TIMEOUTLEVEL_FINAL; + m_TTLTimeout.reset(1 * 1000); // See RFC 6762, 10.1 - return true; -} + return true; + } -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::finalTimeoutLevel */ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::finalTimeoutLevel(void) const -{ - return (TIMEOUTLEVEL_FINAL == m_timeoutLevel); -} - -/* + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::finalTimeoutLevel(void) const + { + return (TIMEOUTLEVEL_FINAL == m_timeoutLevel); + } + + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::timeout */ -MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::timeoutBase::timeType MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::timeout(void) const -{ - if (TIMEOUTLEVEL_BASE == m_timeoutLevel) // 80% + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::timeoutBase::timeType MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::timeout(void) const { - return (m_u32TTL * 800L); // to milliseconds + if (TIMEOUTLEVEL_BASE == m_timeoutLevel) // 80% + { + return (m_u32TTL * 800L); // to milliseconds + } + else if ((TIMEOUTLEVEL_BASE < m_timeoutLevel) && // >80% AND + (TIMEOUTLEVEL_FINAL >= m_timeoutLevel)) // <= 100% + { + return (m_u32TTL * 50L); + } // else: invalid + return MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::timeoutBase::neverExpires; } - else if ((TIMEOUTLEVEL_BASE < m_timeoutLevel) && // >80% AND - (TIMEOUTLEVEL_FINAL >= m_timeoutLevel)) // <= 100% - { - return (m_u32TTL * 50L); - } // else: invalid - return MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::timeoutBase::neverExpires; -} #ifdef MDNS_IP4_SUPPORT -/** + /** MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address */ -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address::stcIP4Address constructor */ -MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address::stcIP4Address(IPAddress p_IPAddress, - uint32_t p_u32TTL /*= 0*/) - : m_pNext(0), - m_IPAddress(p_IPAddress) -{ - m_TTL.set(p_u32TTL); -} + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address::stcIP4Address(IPAddress p_IPAddress, + uint32_t p_u32TTL /*= 0*/) + : m_pNext(0) + , m_IPAddress(p_IPAddress) + { + m_TTL.set(p_u32TTL); + } #endif -/** + /** MDNSResponder::stcMDNSServiceQuery::stcAnswer */ -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcAnswer constructor */ -MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcAnswer(void) - : m_pNext(0), - m_pcServiceDomain(0), - m_pcHostDomain(0), - m_u16Port(0), - m_pcTxts(0), + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcAnswer(void) + : m_pNext(0) + , m_pcServiceDomain(0) + , m_pcHostDomain(0) + , m_u16Port(0) + , m_pcTxts(0) + , #ifdef MDNS_IP4_SUPPORT - m_pIP4Addresses(0), + m_pIP4Addresses(0) + , #endif #ifdef MDNS_IP6_SUPPORT - m_pIP6Addresses(0), + m_pIP6Addresses(0) + , #endif - m_u32ContentFlags(0) -{ -} + m_u32ContentFlags(0) + { + } -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::~stcAnswer destructor */ -MDNSResponder::stcMDNSServiceQuery::stcAnswer::~stcAnswer(void) -{ - clear(); -} + MDNSResponder::stcMDNSServiceQuery::stcAnswer::~stcAnswer(void) + { + clear(); + } -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::clear */ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::clear(void) -{ - return ((releaseTxts()) && + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::clear(void) + { + return ((releaseTxts()) && #ifdef MDNS_IP4_SUPPORT (releaseIP4Addresses()) && #endif #ifdef MDNS_IP6_SUPPORT (releaseIP6Addresses()) #endif - (releaseHostDomain()) && - (releaseServiceDomain())); -} + (releaseHostDomain()) + && (releaseServiceDomain())); + } -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocServiceDomain Alloc memory for the char array representation of the service domain. */ -char* MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocServiceDomain(size_t p_stLength) -{ - releaseServiceDomain(); - if (p_stLength) + char* MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocServiceDomain(size_t p_stLength) { - m_pcServiceDomain = new char[p_stLength]; + releaseServiceDomain(); + if (p_stLength) + { + m_pcServiceDomain = new char[p_stLength]; + } + return m_pcServiceDomain; } - return m_pcServiceDomain; -} -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseServiceDomain */ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseServiceDomain(void) -{ - if (m_pcServiceDomain) + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseServiceDomain(void) { - delete[] m_pcServiceDomain; - m_pcServiceDomain = 0; + if (m_pcServiceDomain) + { + delete[] m_pcServiceDomain; + m_pcServiceDomain = 0; + } + return true; } - return true; -} -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocHostDomain Alloc memory for the char array representation of the host domain. */ -char* MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocHostDomain(size_t p_stLength) -{ - releaseHostDomain(); - if (p_stLength) + char* MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocHostDomain(size_t p_stLength) { - m_pcHostDomain = new char[p_stLength]; + releaseHostDomain(); + if (p_stLength) + { + m_pcHostDomain = new char[p_stLength]; + } + return m_pcHostDomain; } - return m_pcHostDomain; -} -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseHostDomain */ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseHostDomain(void) -{ - if (m_pcHostDomain) + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseHostDomain(void) { - delete[] m_pcHostDomain; - m_pcHostDomain = 0; + if (m_pcHostDomain) + { + delete[] m_pcHostDomain; + m_pcHostDomain = 0; + } + return true; } - return true; -} -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocTxts Alloc memory for the char array representation of the TXT items. */ -char* MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocTxts(size_t p_stLength) -{ - releaseTxts(); - if (p_stLength) + char* MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocTxts(size_t p_stLength) { - m_pcTxts = new char[p_stLength]; + releaseTxts(); + if (p_stLength) + { + m_pcTxts = new char[p_stLength]; + } + return m_pcTxts; } - return m_pcTxts; -} -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseTxts */ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseTxts(void) -{ - if (m_pcTxts) + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseTxts(void) { - delete[] m_pcTxts; - m_pcTxts = 0; + if (m_pcTxts) + { + delete[] m_pcTxts; + m_pcTxts = 0; + } + return true; } - return true; -} #ifdef MDNS_IP4_SUPPORT -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseIP4Addresses */ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseIP4Addresses(void) -{ - while (m_pIP4Addresses) + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseIP4Addresses(void) { - stcIP4Address* pNext = m_pIP4Addresses->m_pNext; - delete m_pIP4Addresses; - m_pIP4Addresses = pNext; + while (m_pIP4Addresses) + { + stcIP4Address* pNext = m_pIP4Addresses->m_pNext; + delete m_pIP4Addresses; + m_pIP4Addresses = pNext; + } + return true; } - return true; -} -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::addIP4Address */ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::addIP4Address(MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* p_pIP4Address) -{ - bool bResult = false; - - if (p_pIP4Address) + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::addIP4Address(MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* p_pIP4Address) { - p_pIP4Address->m_pNext = m_pIP4Addresses; - m_pIP4Addresses = p_pIP4Address; - bResult = true; + bool bResult = false; + + if (p_pIP4Address) + { + p_pIP4Address->m_pNext = m_pIP4Addresses; + m_pIP4Addresses = p_pIP4Address; + bResult = true; + } + return bResult; } - return bResult; -} -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::removeIP4Address */ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::removeIP4Address(MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* p_pIP4Address) -{ - bool bResult = false; - - if (p_pIP4Address) + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::removeIP4Address(MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* p_pIP4Address) { - stcIP4Address* pPred = m_pIP4Addresses; - while ((pPred) && - (pPred->m_pNext != p_pIP4Address)) - { - pPred = pPred->m_pNext; - } - if (pPred) - { - pPred->m_pNext = p_pIP4Address->m_pNext; - delete p_pIP4Address; - bResult = true; - } - else if (m_pIP4Addresses == p_pIP4Address) // No predecessor, but first item + bool bResult = false; + + if (p_pIP4Address) { - m_pIP4Addresses = p_pIP4Address->m_pNext; - delete p_pIP4Address; - bResult = true; + stcIP4Address* pPred = m_pIP4Addresses; + while ((pPred) && (pPred->m_pNext != p_pIP4Address)) + { + pPred = pPred->m_pNext; + } + if (pPred) + { + pPred->m_pNext = p_pIP4Address->m_pNext; + delete p_pIP4Address; + bResult = true; + } + else if (m_pIP4Addresses == p_pIP4Address) // No predecessor, but first item + { + m_pIP4Addresses = p_pIP4Address->m_pNext; + delete p_pIP4Address; + bResult = true; + } } + return bResult; } - return bResult; -} -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::findIP4Address (const) */ -const MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::findIP4Address(const IPAddress& p_IPAddress) const -{ - return (stcIP4Address*)(((const stcAnswer*)this)->findIP4Address(p_IPAddress)); -} + const MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::findIP4Address(const IPAddress& p_IPAddress) const + { + return (stcIP4Address*)(((const stcAnswer*)this)->findIP4Address(p_IPAddress)); + } -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::findIP4Address */ -MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::findIP4Address(const IPAddress& p_IPAddress) -{ - stcIP4Address* pIP4Address = m_pIP4Addresses; - while (pIP4Address) + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::findIP4Address(const IPAddress& p_IPAddress) { - if (pIP4Address->m_IPAddress == p_IPAddress) + stcIP4Address* pIP4Address = m_pIP4Addresses; + while (pIP4Address) { - break; + if (pIP4Address->m_IPAddress == p_IPAddress) + { + break; + } + pIP4Address = pIP4Address->m_pNext; } - pIP4Address = pIP4Address->m_pNext; + return pIP4Address; } - return pIP4Address; -} -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP4AddressCount */ -uint32_t MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP4AddressCount(void) const -{ - uint32_t u32Count = 0; - - stcIP4Address* pIP4Address = m_pIP4Addresses; - while (pIP4Address) + uint32_t MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP4AddressCount(void) const { - ++u32Count; - pIP4Address = pIP4Address->m_pNext; + uint32_t u32Count = 0; + + stcIP4Address* pIP4Address = m_pIP4Addresses; + while (pIP4Address) + { + ++u32Count; + pIP4Address = pIP4Address->m_pNext; + } + return u32Count; } - return u32Count; -} -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP4AddressAtIndex */ -MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP4AddressAtIndex(uint32_t p_u32Index) -{ - return (stcIP4Address*)(((const stcAnswer*)this)->IP4AddressAtIndex(p_u32Index)); -} + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP4AddressAtIndex(uint32_t p_u32Index) + { + return (stcIP4Address*)(((const stcAnswer*)this)->IP4AddressAtIndex(p_u32Index)); + } -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP4AddressAtIndex (const) */ -const MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP4AddressAtIndex(uint32_t p_u32Index) const -{ - const stcIP4Address* pIP4Address = 0; - - if (((uint32_t)(-1) != p_u32Index) && - (m_pIP4Addresses)) + const MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP4AddressAtIndex(uint32_t p_u32Index) const { - uint32_t u32Index; - for (pIP4Address = m_pIP4Addresses, u32Index = 0; ((pIP4Address) && (u32Index < p_u32Index)); pIP4Address = pIP4Address->m_pNext, ++u32Index) - ; + const stcIP4Address* pIP4Address = 0; + + if (((uint32_t)(-1) != p_u32Index) && (m_pIP4Addresses)) + { + uint32_t u32Index; + for (pIP4Address = m_pIP4Addresses, u32Index = 0; ((pIP4Address) && (u32Index < p_u32Index)); pIP4Address = pIP4Address->m_pNext, ++u32Index) + ; + } + return pIP4Address; } - return pIP4Address; -} #endif #ifdef MDNS_IP6_SUPPORT -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseIP6Addresses */ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseIP6Addresses(void) -{ - while (m_pIP6Addresses) + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseIP6Addresses(void) { - stcIP6Address* pNext = m_pIP6Addresses->m_pNext; - delete m_pIP6Addresses; - m_pIP6Addresses = pNext; + while (m_pIP6Addresses) + { + stcIP6Address* pNext = m_pIP6Addresses->m_pNext; + delete m_pIP6Addresses; + m_pIP6Addresses = pNext; + } + return true; } - return true; -} -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::addIP6Address */ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::addIP6Address(MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* p_pIP6Address) -{ - bool bResult = false; - - if (p_pIP6Address) + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::addIP6Address(MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* p_pIP6Address) { - p_pIP6Address->m_pNext = m_pIP6Addresses; - m_pIP6Addresses = p_pIP6Address; - bResult = true; + bool bResult = false; + + if (p_pIP6Address) + { + p_pIP6Address->m_pNext = m_pIP6Addresses; + m_pIP6Addresses = p_pIP6Address; + bResult = true; + } + return bResult; } - return bResult; -} -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::removeIP6Address */ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::removeIP6Address(MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* p_pIP6Address) -{ - bool bResult = false; - - if (p_pIP6Address) + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::removeIP6Address(MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* p_pIP6Address) { - stcIP6Address* pPred = m_pIP6Addresses; - while ((pPred) && - (pPred->m_pNext != p_pIP6Address)) - { - pPred = pPred->m_pNext; - } - if (pPred) - { - pPred->m_pNext = p_pIP6Address->m_pNext; - delete p_pIP6Address; - bResult = true; - } - else if (m_pIP6Addresses == p_pIP6Address) // No predecessor, but first item + bool bResult = false; + + if (p_pIP6Address) { - m_pIP6Addresses = p_pIP6Address->m_pNext; - delete p_pIP6Address; - bResult = true; + stcIP6Address* pPred = m_pIP6Addresses; + while ((pPred) && (pPred->m_pNext != p_pIP6Address)) + { + pPred = pPred->m_pNext; + } + if (pPred) + { + pPred->m_pNext = p_pIP6Address->m_pNext; + delete p_pIP6Address; + bResult = true; + } + else if (m_pIP6Addresses == p_pIP6Address) // No predecessor, but first item + { + m_pIP6Addresses = p_pIP6Address->m_pNext; + delete p_pIP6Address; + bResult = true; + } } + return bResult; } - return bResult; -} -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::findIP6Address */ -MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::findIP6Address(const IP6Address& p_IPAddress) -{ - return (stcIP6Address*)(((const stcAnswer*)this)->findIP6Address(p_IPAddress)); -} + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::findIP6Address(const IP6Address& p_IPAddress) + { + return (stcIP6Address*)(((const stcAnswer*)this)->findIP6Address(p_IPAddress)); + } -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::findIP6Address (const) */ -const MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::findIP6Address(const IPAddress& p_IPAddress) const -{ - const stcIP6Address* pIP6Address = m_pIP6Addresses; - while (pIP6Address) + const MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::findIP6Address(const IPAddress& p_IPAddress) const { - if (p_IP6Address->m_IPAddress == p_IPAddress) + const stcIP6Address* pIP6Address = m_pIP6Addresses; + while (pIP6Address) { - break; + if (p_IP6Address->m_IPAddress == p_IPAddress) + { + break; + } + pIP6Address = pIP6Address->m_pNext; } - pIP6Address = pIP6Address->m_pNext; + return pIP6Address; } - return pIP6Address; -} -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP6AddressCount */ -uint32_t MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP6AddressCount(void) const -{ - uint32_t u32Count = 0; - - stcIP6Address* pIP6Address = m_pIP6Addresses; - while (pIP6Address) + uint32_t MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP6AddressCount(void) const { - ++u32Count; - pIP6Address = pIP6Address->m_pNext; + uint32_t u32Count = 0; + + stcIP6Address* pIP6Address = m_pIP6Addresses; + while (pIP6Address) + { + ++u32Count; + pIP6Address = pIP6Address->m_pNext; + } + return u32Count; } - return u32Count; -} -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP6AddressAtIndex (const) */ -const MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP6AddressAtIndex(uint32_t p_u32Index) const -{ - return (stcIP6Address*)(((const stcAnswer*)this)->IP6AddressAtIndex(p_u32Index)); -} + const MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP6AddressAtIndex(uint32_t p_u32Index) const + { + return (stcIP6Address*)(((const stcAnswer*)this)->IP6AddressAtIndex(p_u32Index)); + } -/* + /* MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP6AddressAtIndex */ -MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP6AddressAtIndex(uint32_t p_u32Index) -{ - stcIP6Address* pIP6Address = 0; - - if (((uint32_t)(-1) != p_u32Index) && - (m_pIP6Addresses)) + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP6AddressAtIndex(uint32_t p_u32Index) { - uint32_t u32Index; - for (pIP6Address = m_pIP6Addresses, u32Index = 0; ((pIP6Address) && (u32Index < p_u32Index)); pIP6Address = pIP6Address->m_pNext, ++u32Index) - ; + stcIP6Address* pIP6Address = 0; + + if (((uint32_t)(-1) != p_u32Index) && (m_pIP6Addresses)) + { + uint32_t u32Index; + for (pIP6Address = m_pIP6Addresses, u32Index = 0; ((pIP6Address) && (u32Index < p_u32Index)); pIP6Address = pIP6Address->m_pNext, ++u32Index) + ; + } + return pIP6Address; } - return pIP6Address; -} #endif -/** + /** MDNSResponder::stcMDNSServiceQuery A service query object. @@ -2001,188 +1982,186 @@ MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* MDNSResponder::stc Service query object may be connected to a linked list. */ -/* + /* MDNSResponder::stcMDNSServiceQuery::stcMDNSServiceQuery constructor */ -MDNSResponder::stcMDNSServiceQuery::stcMDNSServiceQuery(void) - : m_pNext(0), - m_fnCallback(0), - m_bLegacyQuery(false), - m_u8SentCount(0), - m_ResendTimeout(esp8266::polledTimeout::oneShotMs::neverExpires), - m_bAwaitingAnswers(true), - m_pAnswers(0) -{ - clear(); -} + MDNSResponder::stcMDNSServiceQuery::stcMDNSServiceQuery(void) + : m_pNext(0) + , m_fnCallback(0) + , m_bLegacyQuery(false) + , m_u8SentCount(0) + , m_ResendTimeout(esp8266::polledTimeout::oneShotMs::neverExpires) + , m_bAwaitingAnswers(true) + , m_pAnswers(0) + { + clear(); + } -/* + /* MDNSResponder::stcMDNSServiceQuery::~stcMDNSServiceQuery destructor */ -MDNSResponder::stcMDNSServiceQuery::~stcMDNSServiceQuery(void) -{ - clear(); -} + MDNSResponder::stcMDNSServiceQuery::~stcMDNSServiceQuery(void) + { + clear(); + } -/* + /* MDNSResponder::stcMDNSServiceQuery::clear */ -bool MDNSResponder::stcMDNSServiceQuery::clear(void) -{ - m_fnCallback = 0; - m_bLegacyQuery = false; - m_u8SentCount = 0; - m_ResendTimeout.resetToNeverExpires(); - m_bAwaitingAnswers = true; - while (m_pAnswers) + bool MDNSResponder::stcMDNSServiceQuery::clear(void) { - stcAnswer* pNext = m_pAnswers->m_pNext; - delete m_pAnswers; - m_pAnswers = pNext; + m_fnCallback = 0; + m_bLegacyQuery = false; + m_u8SentCount = 0; + m_ResendTimeout.resetToNeverExpires(); + m_bAwaitingAnswers = true; + while (m_pAnswers) + { + stcAnswer* pNext = m_pAnswers->m_pNext; + delete m_pAnswers; + m_pAnswers = pNext; + } + return true; } - return true; -} -/* + /* MDNSResponder::stcMDNSServiceQuery::answerCount */ -uint32_t MDNSResponder::stcMDNSServiceQuery::answerCount(void) const -{ - uint32_t u32Count = 0; - - stcAnswer* pAnswer = m_pAnswers; - while (pAnswer) + uint32_t MDNSResponder::stcMDNSServiceQuery::answerCount(void) const { - ++u32Count; - pAnswer = pAnswer->m_pNext; + uint32_t u32Count = 0; + + stcAnswer* pAnswer = m_pAnswers; + while (pAnswer) + { + ++u32Count; + pAnswer = pAnswer->m_pNext; + } + return u32Count; } - return u32Count; -} -/* + /* MDNSResponder::stcMDNSServiceQuery::answerAtIndex */ -const MDNSResponder::stcMDNSServiceQuery::stcAnswer* MDNSResponder::stcMDNSServiceQuery::answerAtIndex(uint32_t p_u32Index) const -{ - const stcAnswer* pAnswer = 0; - - if (((uint32_t)(-1) != p_u32Index) && - (m_pAnswers)) + const MDNSResponder::stcMDNSServiceQuery::stcAnswer* MDNSResponder::stcMDNSServiceQuery::answerAtIndex(uint32_t p_u32Index) const { - uint32_t u32Index; - for (pAnswer = m_pAnswers, u32Index = 0; ((pAnswer) && (u32Index < p_u32Index)); pAnswer = pAnswer->m_pNext, ++u32Index) - ; + const stcAnswer* pAnswer = 0; + + if (((uint32_t)(-1) != p_u32Index) && (m_pAnswers)) + { + uint32_t u32Index; + for (pAnswer = m_pAnswers, u32Index = 0; ((pAnswer) && (u32Index < p_u32Index)); pAnswer = pAnswer->m_pNext, ++u32Index) + ; + } + return pAnswer; } - return pAnswer; -} -/* + /* MDNSResponder::stcMDNSServiceQuery::answerAtIndex */ -MDNSResponder::stcMDNSServiceQuery::stcAnswer* MDNSResponder::stcMDNSServiceQuery::answerAtIndex(uint32_t p_u32Index) -{ - return (stcAnswer*)(((const stcMDNSServiceQuery*)this)->answerAtIndex(p_u32Index)); -} + MDNSResponder::stcMDNSServiceQuery::stcAnswer* MDNSResponder::stcMDNSServiceQuery::answerAtIndex(uint32_t p_u32Index) + { + return (stcAnswer*)(((const stcMDNSServiceQuery*)this)->answerAtIndex(p_u32Index)); + } -/* + /* MDNSResponder::stcMDNSServiceQuery::indexOfAnswer */ -uint32_t MDNSResponder::stcMDNSServiceQuery::indexOfAnswer(const MDNSResponder::stcMDNSServiceQuery::stcAnswer* p_pAnswer) const -{ - uint32_t u32Index = 0; - - for (const stcAnswer* pAnswer = m_pAnswers; pAnswer; pAnswer = pAnswer->m_pNext, ++u32Index) + uint32_t MDNSResponder::stcMDNSServiceQuery::indexOfAnswer(const MDNSResponder::stcMDNSServiceQuery::stcAnswer* p_pAnswer) const { - if (pAnswer == p_pAnswer) + uint32_t u32Index = 0; + + for (const stcAnswer* pAnswer = m_pAnswers; pAnswer; pAnswer = pAnswer->m_pNext, ++u32Index) { - return u32Index; + if (pAnswer == p_pAnswer) + { + return u32Index; + } } + return ((uint32_t)(-1)); } - return ((uint32_t)(-1)); -} -/* + /* MDNSResponder::stcMDNSServiceQuery::addAnswer */ -bool MDNSResponder::stcMDNSServiceQuery::addAnswer(MDNSResponder::stcMDNSServiceQuery::stcAnswer* p_pAnswer) -{ - bool bResult = false; - - if (p_pAnswer) + bool MDNSResponder::stcMDNSServiceQuery::addAnswer(MDNSResponder::stcMDNSServiceQuery::stcAnswer* p_pAnswer) { - p_pAnswer->m_pNext = m_pAnswers; - m_pAnswers = p_pAnswer; - bResult = true; + bool bResult = false; + + if (p_pAnswer) + { + p_pAnswer->m_pNext = m_pAnswers; + m_pAnswers = p_pAnswer; + bResult = true; + } + return bResult; } - return bResult; -} -/* + /* MDNSResponder::stcMDNSServiceQuery::removeAnswer */ -bool MDNSResponder::stcMDNSServiceQuery::removeAnswer(MDNSResponder::stcMDNSServiceQuery::stcAnswer* p_pAnswer) -{ - bool bResult = false; - - if (p_pAnswer) + bool MDNSResponder::stcMDNSServiceQuery::removeAnswer(MDNSResponder::stcMDNSServiceQuery::stcAnswer* p_pAnswer) { - stcAnswer* pPred = m_pAnswers; - while ((pPred) && - (pPred->m_pNext != p_pAnswer)) - { - pPred = pPred->m_pNext; - } - if (pPred) - { - pPred->m_pNext = p_pAnswer->m_pNext; - delete p_pAnswer; - bResult = true; - } - else if (m_pAnswers == p_pAnswer) // No predecessor, but first item + bool bResult = false; + + if (p_pAnswer) { - m_pAnswers = p_pAnswer->m_pNext; - delete p_pAnswer; - bResult = true; + stcAnswer* pPred = m_pAnswers; + while ((pPred) && (pPred->m_pNext != p_pAnswer)) + { + pPred = pPred->m_pNext; + } + if (pPred) + { + pPred->m_pNext = p_pAnswer->m_pNext; + delete p_pAnswer; + bResult = true; + } + else if (m_pAnswers == p_pAnswer) // No predecessor, but first item + { + m_pAnswers = p_pAnswer->m_pNext; + delete p_pAnswer; + bResult = true; + } } + return bResult; } - return bResult; -} -/* + /* MDNSResponder::stcMDNSServiceQuery::findAnswerForServiceDomain */ -MDNSResponder::stcMDNSServiceQuery::stcAnswer* MDNSResponder::stcMDNSServiceQuery::findAnswerForServiceDomain(const MDNSResponder::stcMDNS_RRDomain& p_ServiceDomain) -{ - stcAnswer* pAnswer = m_pAnswers; - while (pAnswer) + MDNSResponder::stcMDNSServiceQuery::stcAnswer* MDNSResponder::stcMDNSServiceQuery::findAnswerForServiceDomain(const MDNSResponder::stcMDNS_RRDomain& p_ServiceDomain) { - if (pAnswer->m_ServiceDomain == p_ServiceDomain) + stcAnswer* pAnswer = m_pAnswers; + while (pAnswer) { - break; + if (pAnswer->m_ServiceDomain == p_ServiceDomain) + { + break; + } + pAnswer = pAnswer->m_pNext; } - pAnswer = pAnswer->m_pNext; + return pAnswer; } - return pAnswer; -} -/* + /* MDNSResponder::stcMDNSServiceQuery::findAnswerForHostDomain */ -MDNSResponder::stcMDNSServiceQuery::stcAnswer* MDNSResponder::stcMDNSServiceQuery::findAnswerForHostDomain(const MDNSResponder::stcMDNS_RRDomain& p_HostDomain) -{ - stcAnswer* pAnswer = m_pAnswers; - while (pAnswer) + MDNSResponder::stcMDNSServiceQuery::stcAnswer* MDNSResponder::stcMDNSServiceQuery::findAnswerForHostDomain(const MDNSResponder::stcMDNS_RRDomain& p_HostDomain) { - if (pAnswer->m_HostDomain == p_HostDomain) + stcAnswer* pAnswer = m_pAnswers; + while (pAnswer) { - break; + if (pAnswer->m_HostDomain == p_HostDomain) + { + break; + } + pAnswer = pAnswer->m_pNext; } - pAnswer = pAnswer->m_pNext; + return pAnswer; } - return pAnswer; -} -/** + /** MDNSResponder::stcMDNSSendParameter A 'collection' of properties and flags for one MDNS query or response. @@ -2192,140 +2171,137 @@ MDNSResponder::stcMDNSServiceQuery::stcAnswer* MDNSResponder::stcMDNSServiceQuer */ -/** + /** MDNSResponder::stcMDNSSendParameter::stcDomainCacheItem A cached host or service domain, incl. the offset in the UDP output buffer. */ -/* + /* MDNSResponder::stcMDNSSendParameter::stcDomainCacheItem::stcDomainCacheItem constructor */ -MDNSResponder::stcMDNSSendParameter::stcDomainCacheItem::stcDomainCacheItem(const void* p_pHostnameOrService, - bool p_bAdditionalData, - uint32_t p_u16Offset) - : m_pNext(0), - m_pHostnameOrService(p_pHostnameOrService), - m_bAdditionalData(p_bAdditionalData), - m_u16Offset(p_u16Offset) -{ -} + MDNSResponder::stcMDNSSendParameter::stcDomainCacheItem::stcDomainCacheItem(const void* p_pHostnameOrService, + bool p_bAdditionalData, + uint32_t p_u16Offset) + : m_pNext(0) + , m_pHostnameOrService(p_pHostnameOrService) + , m_bAdditionalData(p_bAdditionalData) + , m_u16Offset(p_u16Offset) + { + } -/** + /** MDNSResponder::stcMDNSSendParameter */ -/* + /* MDNSResponder::stcMDNSSendParameter::stcMDNSSendParameter constructor */ -MDNSResponder::stcMDNSSendParameter::stcMDNSSendParameter(void) - : m_pQuestions(0), - m_pDomainCacheItems(0) -{ - clear(); -} + MDNSResponder::stcMDNSSendParameter::stcMDNSSendParameter(void) + : m_pQuestions(0) + , m_pDomainCacheItems(0) + { + clear(); + } -/* + /* MDNSResponder::stcMDNSSendParameter::~stcMDNSSendParameter destructor */ -MDNSResponder::stcMDNSSendParameter::~stcMDNSSendParameter(void) -{ - clear(); -} + MDNSResponder::stcMDNSSendParameter::~stcMDNSSendParameter(void) + { + clear(); + } -/* + /* MDNSResponder::stcMDNSSendParameter::clear */ -bool MDNSResponder::stcMDNSSendParameter::clear(void) -{ - m_u16ID = 0; - m_u8HostReplyMask = 0; - m_u16Offset = 0; + bool MDNSResponder::stcMDNSSendParameter::clear(void) + { + m_u16ID = 0; + m_u8HostReplyMask = 0; + m_u16Offset = 0; - m_bLegacyQuery = false; - m_bResponse = false; - m_bAuthorative = false; - m_bUnicast = false; - m_bUnannounce = false; + m_bLegacyQuery = false; + m_bResponse = false; + m_bAuthorative = false; + m_bUnicast = false; + m_bUnannounce = false; - m_bCacheFlush = true; + m_bCacheFlush = true; - while (m_pQuestions) - { - stcMDNS_RRQuestion* pNext = m_pQuestions->m_pNext; - delete m_pQuestions; - m_pQuestions = pNext; - } + while (m_pQuestions) + { + stcMDNS_RRQuestion* pNext = m_pQuestions->m_pNext; + delete m_pQuestions; + m_pQuestions = pNext; + } - return clearCachedNames(); - ; -} -/* + return clearCachedNames(); + ; + } + /* MDNSResponder::stcMDNSSendParameter::clear cached names */ -bool MDNSResponder::stcMDNSSendParameter::clearCachedNames(void) -{ - m_u16Offset = 0; - - while (m_pDomainCacheItems) + bool MDNSResponder::stcMDNSSendParameter::clearCachedNames(void) { - stcDomainCacheItem* pNext = m_pDomainCacheItems->m_pNext; - delete m_pDomainCacheItems; - m_pDomainCacheItems = pNext; - } - m_pDomainCacheItems = nullptr; + m_u16Offset = 0; - return true; -} + while (m_pDomainCacheItems) + { + stcDomainCacheItem* pNext = m_pDomainCacheItems->m_pNext; + delete m_pDomainCacheItems; + m_pDomainCacheItems = pNext; + } + m_pDomainCacheItems = nullptr; -/* + return true; + } + + /* MDNSResponder::stcMDNSSendParameter::shiftOffset */ -bool MDNSResponder::stcMDNSSendParameter::shiftOffset(uint16_t p_u16Shift) -{ - m_u16Offset += p_u16Shift; - return true; -} + bool MDNSResponder::stcMDNSSendParameter::shiftOffset(uint16_t p_u16Shift) + { + m_u16Offset += p_u16Shift; + return true; + } -/* + /* MDNSResponder::stcMDNSSendParameter::addDomainCacheItem */ -bool MDNSResponder::stcMDNSSendParameter::addDomainCacheItem(const void* p_pHostnameOrService, - bool p_bAdditionalData, - uint16_t p_u16Offset) -{ - bool bResult = false; - - stcDomainCacheItem* pNewItem = 0; - if ((p_pHostnameOrService) && - (p_u16Offset) && - ((pNewItem = new stcDomainCacheItem(p_pHostnameOrService, p_bAdditionalData, p_u16Offset)))) + bool MDNSResponder::stcMDNSSendParameter::addDomainCacheItem(const void* p_pHostnameOrService, + bool p_bAdditionalData, + uint16_t p_u16Offset) { - pNewItem->m_pNext = m_pDomainCacheItems; - bResult = ((m_pDomainCacheItems = pNewItem)); + bool bResult = false; + + stcDomainCacheItem* pNewItem = 0; + if ((p_pHostnameOrService) && (p_u16Offset) && ((pNewItem = new stcDomainCacheItem(p_pHostnameOrService, p_bAdditionalData, p_u16Offset)))) + { + pNewItem->m_pNext = m_pDomainCacheItems; + bResult = ((m_pDomainCacheItems = pNewItem)); + } + return bResult; } - return bResult; -} -/* + /* MDNSResponder::stcMDNSSendParameter::findCachedDomainOffset */ -uint16_t MDNSResponder::stcMDNSSendParameter::findCachedDomainOffset(const void* p_pHostnameOrService, - bool p_bAdditionalData) const -{ - const stcDomainCacheItem* pCacheItem = m_pDomainCacheItems; - - for (; pCacheItem; pCacheItem = pCacheItem->m_pNext) + uint16_t MDNSResponder::stcMDNSSendParameter::findCachedDomainOffset(const void* p_pHostnameOrService, + bool p_bAdditionalData) const { - if ((pCacheItem->m_pHostnameOrService == p_pHostnameOrService) && - (pCacheItem->m_bAdditionalData == p_bAdditionalData)) // Found cache item + const stcDomainCacheItem* pCacheItem = m_pDomainCacheItems; + + for (; pCacheItem; pCacheItem = pCacheItem->m_pNext) { - break; + if ((pCacheItem->m_pHostnameOrService == p_pHostnameOrService) && (pCacheItem->m_bAdditionalData == p_bAdditionalData)) // Found cache item + { + break; + } } + return (pCacheItem ? pCacheItem->m_u16Offset : 0); } - return (pCacheItem ? pCacheItem->m_u16Offset : 0); -} } // namespace MDNSImplementation diff --git a/libraries/ESP8266mDNS/src/LEAmDNS_Transfer.cpp b/libraries/ESP8266mDNS/src/LEAmDNS_Transfer.cpp index 6509e42b05..7be63de401 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS_Transfer.cpp +++ b/libraries/ESP8266mDNS/src/LEAmDNS_Transfer.cpp @@ -38,32 +38,32 @@ namespace esp8266 */ namespace MDNSImplementation { -/** + /** CONST STRINGS */ -static const char* scpcLocal = "local"; -static const char* scpcServices = "services"; -static const char* scpcDNSSD = "dns-sd"; -static const char* scpcUDP = "udp"; -//static const char* scpcTCP = "tcp"; + static const char* scpcLocal = "local"; + static const char* scpcServices = "services"; + static const char* scpcDNSSD = "dns-sd"; + static const char* scpcUDP = "udp"; + //static const char* scpcTCP = "tcp"; #ifdef MDNS_IP4_SUPPORT -static const char* scpcReverseIP4Domain = "in-addr"; + static const char* scpcReverseIP4Domain = "in-addr"; #endif #ifdef MDNS_IP6_SUPPORT -static const char* scpcReverseIP6Domain = "ip6"; + static const char* scpcReverseIP6Domain = "ip6"; #endif -static const char* scpcReverseTopDomain = "arpa"; + static const char* scpcReverseTopDomain = "arpa"; -/** + /** TRANSFER */ -/** + /** SENDING */ -/* + /* MDNSResponder::_sendMDNSMessage Unicast responses are prepared and sent directly to the querier. @@ -72,80 +72,77 @@ static const char* scpcReverseTopDomain = "arpa"; Any reply flags in installed services are removed at the end! */ -bool MDNSResponder::_sendMDNSMessage(MDNSResponder::stcMDNSSendParameter& p_rSendParameter) -{ - bool bResult = true; - - if (p_rSendParameter.m_bResponse && - p_rSendParameter.m_bUnicast) // Unicast response -> Send to querier - { - DEBUG_EX_ERR(if (!m_pUDPContext->getRemoteAddress()) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendMDNSMessage: MISSING remote address for response!\n")); - }); - IPAddress ipRemote; - ipRemote = m_pUDPContext->getRemoteAddress(); - bResult = ((_prepareMDNSMessage(p_rSendParameter, m_pUDPContext->getInputNetif()->ip_addr)) && - (m_pUDPContext->sendTimeout(ipRemote, m_pUDPContext->getRemotePort(), MDNS_UDPCONTEXT_TIMEOUT))); - } - else // Multicast response + bool MDNSResponder::_sendMDNSMessage(MDNSResponder::stcMDNSSendParameter& p_rSendParameter) { - bResult = _sendMDNSMessage_Multicast(p_rSendParameter); - } + bool bResult = true; - // Finally clear service reply masks - for (stcMDNSService* pService = m_pServices; pService; pService = pService->m_pNext) - { - pService->m_u8ReplyMask = 0; - } + if (p_rSendParameter.m_bResponse && p_rSendParameter.m_bUnicast) // Unicast response -> Send to querier + { + DEBUG_EX_ERR(if (!m_pUDPContext->getRemoteAddress()) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendMDNSMessage: MISSING remote address for response!\n")); + }); + IPAddress ipRemote; + ipRemote = m_pUDPContext->getRemoteAddress(); + bResult = ((_prepareMDNSMessage(p_rSendParameter, m_pUDPContext->getInputNetif()->ip_addr)) && (m_pUDPContext->sendTimeout(ipRemote, m_pUDPContext->getRemotePort(), MDNS_UDPCONTEXT_TIMEOUT))); + } + else // Multicast response + { + bResult = _sendMDNSMessage_Multicast(p_rSendParameter); + } - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendMDNSMessage: FAILED!\n")); - }); - return bResult; -} + // Finally clear service reply masks + for (stcMDNSService* pService = m_pServices; pService; pService = pService->m_pNext) + { + pService->m_u8ReplyMask = 0; + } -/* + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendMDNSMessage: FAILED!\n")); + }); + return bResult; + } + + /* MDNSResponder::_sendMDNSMessage_Multicast Fills the UDP output buffer (via _prepareMDNSMessage) and sends the buffer via the selected WiFi interface (Station or AP) */ -bool MDNSResponder::_sendMDNSMessage_Multicast(MDNSResponder::stcMDNSSendParameter& p_rSendParameter) -{ - bool bResult = false; - - for (netif* pNetIf = netif_list; pNetIf; pNetIf = pNetIf->next) + bool MDNSResponder::_sendMDNSMessage_Multicast(MDNSResponder::stcMDNSSendParameter& p_rSendParameter) { - if (netif_is_up(pNetIf)) + bool bResult = false; + + for (netif* pNetIf = netif_list; pNetIf; pNetIf = pNetIf->next) { - IPAddress fromIPAddress; - //fromIPAddress = _getResponseMulticastInterface(); - fromIPAddress = pNetIf->ip_addr; - m_pUDPContext->setMulticastInterface(fromIPAddress); + if (netif_is_up(pNetIf)) + { + IPAddress fromIPAddress; + //fromIPAddress = _getResponseMulticastInterface(); + fromIPAddress = pNetIf->ip_addr; + m_pUDPContext->setMulticastInterface(fromIPAddress); #ifdef MDNS_IP4_SUPPORT - IPAddress toMulticastAddress(DNS_MQUERY_IPV4_GROUP_INIT); + IPAddress toMulticastAddress(DNS_MQUERY_IPV4_GROUP_INIT); #endif #ifdef MDNS_IP6_SUPPORT - //TODO: set multicast address - IPAddress toMulticastAddress(DNS_MQUERY_IPV6_GROUP_INIT); + //TODO: set multicast address + IPAddress toMulticastAddress(DNS_MQUERY_IPV6_GROUP_INIT); #endif - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendMDNSMessage_Multicast: Will send to '%s'.\n"), toMulticastAddress.toString().c_str());); - bResult = ((_prepareMDNSMessage(p_rSendParameter, fromIPAddress)) && - (m_pUDPContext->sendTimeout(toMulticastAddress, DNS_MQUERY_PORT, MDNS_UDPCONTEXT_TIMEOUT))); - - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendMDNSMessage_Multicast: FAILED!\n")); - }); + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendMDNSMessage_Multicast: Will send to '%s'.\n"), toMulticastAddress.toString().c_str());); + bResult = ((_prepareMDNSMessage(p_rSendParameter, fromIPAddress)) && (m_pUDPContext->sendTimeout(toMulticastAddress, DNS_MQUERY_PORT, MDNS_UDPCONTEXT_TIMEOUT))); + + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendMDNSMessage_Multicast: FAILED!\n")); + }); + } } + return bResult; } - return bResult; -} -/* + /* MDNSResponder::_prepareMDNSMessage The MDNS message is composed in a two-step process. @@ -154,289 +151,275 @@ bool MDNSResponder::_sendMDNSMessage_Multicast(MDNSResponder::stcMDNSSendParamet output buffer. */ -bool MDNSResponder::_prepareMDNSMessage(MDNSResponder::stcMDNSSendParameter& p_rSendParameter, - IPAddress p_IPAddress) -{ - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage\n"));); - bool bResult = true; - p_rSendParameter.clearCachedNames(); // Need to remove cached names, p_SendParameter might have been used before on other interface - - // Prepare header; count answers - stcMDNS_MsgHeader msgHeader(p_rSendParameter.m_u16ID, p_rSendParameter.m_bResponse, 0, p_rSendParameter.m_bAuthorative); - // If this is a response, the answers are anwers, - // else this is a query or probe and the answers go into auth section - uint16_t& ru16Answers = (p_rSendParameter.m_bResponse - ? msgHeader.m_u16ANCount - : msgHeader.m_u16NSCount); - - /** + bool MDNSResponder::_prepareMDNSMessage(MDNSResponder::stcMDNSSendParameter& p_rSendParameter, + IPAddress p_IPAddress) + { + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage\n"));); + bool bResult = true; + p_rSendParameter.clearCachedNames(); // Need to remove cached names, p_SendParameter might have been used before on other interface + + // Prepare header; count answers + stcMDNS_MsgHeader msgHeader(p_rSendParameter.m_u16ID, p_rSendParameter.m_bResponse, 0, p_rSendParameter.m_bAuthorative); + // If this is a response, the answers are anwers, + // else this is a query or probe and the answers go into auth section + uint16_t& ru16Answers = (p_rSendParameter.m_bResponse + ? msgHeader.m_u16ANCount + : msgHeader.m_u16NSCount); + + /** enuSequence */ - enum enuSequence - { - Sequence_Count = 0, - Sequence_Send = 1 - }; - - // Two step sequence: 'Count' and 'Send' - for (uint32_t sequence = Sequence_Count; ((bResult) && (sequence <= Sequence_Send)); ++sequence) - { - DEBUG_EX_INFO( - if (Sequence_Send == sequence) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: ID:%u QR:%u OP:%u AA:%u TC:%u RD:%u RA:%u R:%u QD:%u AN:%u NS:%u AR:%u\n"), - (unsigned)msgHeader.m_u16ID, - (unsigned)msgHeader.m_1bQR, (unsigned)msgHeader.m_4bOpcode, (unsigned)msgHeader.m_1bAA, (unsigned)msgHeader.m_1bTC, (unsigned)msgHeader.m_1bRD, - (unsigned)msgHeader.m_1bRA, (unsigned)msgHeader.m_4bRCode, - (unsigned)msgHeader.m_u16QDCount, - (unsigned)msgHeader.m_u16ANCount, - (unsigned)msgHeader.m_u16NSCount, - (unsigned)msgHeader.m_u16ARCount); - }); - // Count/send - // Header - bResult = ((Sequence_Count == sequence) - ? true - : _writeMDNSMsgHeader(msgHeader, p_rSendParameter)); - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSMsgHeader FAILED!\n"));); - // Questions - for (stcMDNS_RRQuestion* pQuestion = p_rSendParameter.m_pQuestions; ((bResult) && (pQuestion)); pQuestion = pQuestion->m_pNext) - { - ((Sequence_Count == sequence) - ? ++msgHeader.m_u16QDCount - : (bResult = _writeMDNSQuestion(*pQuestion, p_rSendParameter))); - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSQuestion FAILED!\n"));); - } - - // Answers and authoritative answers -#ifdef MDNS_IP4_SUPPORT - if ((bResult) && - (p_rSendParameter.m_u8HostReplyMask & ContentFlag_A)) - { - ((Sequence_Count == sequence) - ? ++ru16Answers - : (bResult = _writeMDNSAnswer_A(p_IPAddress, p_rSendParameter))); - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_A(A) FAILED!\n"));); - } - if ((bResult) && - (p_rSendParameter.m_u8HostReplyMask & ContentFlag_PTR_IP4)) - { - ((Sequence_Count == sequence) - ? ++ru16Answers - : (bResult = _writeMDNSAnswer_PTR_IP4(p_IPAddress, p_rSendParameter))); - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_PTR_IP4 FAILED!\n"));); - } -#endif -#ifdef MDNS_IP6_SUPPORT - if ((bResult) && - (p_rSendParameter.m_u8HostReplyMask & ContentFlag_AAAA)) + enum enuSequence { - ((Sequence_Count == sequence) - ? ++ru16Answers - : (bResult = _writeMDNSAnswer_AAAA(p_IPAddress, p_rSendParameter))); - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_AAAA(A) FAILED!\n"));); - } - if ((bResult) && - (p_rSendParameter.m_u8HostReplyMask & ContentFlag_PTR_IP6)) - { - ((Sequence_Count == sequence) - ? ++ru16Answers - : (bResult = _writeMDNSAnswer_PTR_IP6(p_IPAddress, p_rSendParameter))); - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_PTR_IP6 FAILED!\n"));); - } -#endif + Sequence_Count = 0, + Sequence_Send = 1 + }; - for (stcMDNSService* pService = m_pServices; ((bResult) && (pService)); pService = pService->m_pNext) + // Two step sequence: 'Count' and 'Send' + for (uint32_t sequence = Sequence_Count; ((bResult) && (sequence <= Sequence_Send)); ++sequence) { - if ((bResult) && - (pService->m_u8ReplyMask & ContentFlag_PTR_TYPE)) - { - ((Sequence_Count == sequence) - ? ++ru16Answers - : (bResult = _writeMDNSAnswer_PTR_TYPE(*pService, p_rSendParameter))); - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_PTR_TYPE FAILED!\n"));); - } - if ((bResult) && - (pService->m_u8ReplyMask & ContentFlag_PTR_NAME)) + DEBUG_EX_INFO( + if (Sequence_Send == sequence) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: ID:%u QR:%u OP:%u AA:%u TC:%u RD:%u RA:%u R:%u QD:%u AN:%u NS:%u AR:%u\n"), + (unsigned)msgHeader.m_u16ID, + (unsigned)msgHeader.m_1bQR, (unsigned)msgHeader.m_4bOpcode, (unsigned)msgHeader.m_1bAA, (unsigned)msgHeader.m_1bTC, (unsigned)msgHeader.m_1bRD, + (unsigned)msgHeader.m_1bRA, (unsigned)msgHeader.m_4bRCode, + (unsigned)msgHeader.m_u16QDCount, + (unsigned)msgHeader.m_u16ANCount, + (unsigned)msgHeader.m_u16NSCount, + (unsigned)msgHeader.m_u16ARCount); + }); + // Count/send + // Header + bResult = ((Sequence_Count == sequence) + ? true + : _writeMDNSMsgHeader(msgHeader, p_rSendParameter)); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSMsgHeader FAILED!\n"));); + // Questions + for (stcMDNS_RRQuestion* pQuestion = p_rSendParameter.m_pQuestions; ((bResult) && (pQuestion)); pQuestion = pQuestion->m_pNext) { ((Sequence_Count == sequence) - ? ++ru16Answers - : (bResult = _writeMDNSAnswer_PTR_NAME(*pService, p_rSendParameter))); - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_PTR_NAME FAILED!\n"));); + ? ++msgHeader.m_u16QDCount + : (bResult = _writeMDNSQuestion(*pQuestion, p_rSendParameter))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSQuestion FAILED!\n"));); } - if ((bResult) && - (pService->m_u8ReplyMask & ContentFlag_SRV)) + + // Answers and authoritative answers +#ifdef MDNS_IP4_SUPPORT + if ((bResult) && (p_rSendParameter.m_u8HostReplyMask & ContentFlag_A)) { ((Sequence_Count == sequence) - ? ++ru16Answers - : (bResult = _writeMDNSAnswer_SRV(*pService, p_rSendParameter))); - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_SRV(A) FAILED!\n"));); + ? ++ru16Answers + : (bResult = _writeMDNSAnswer_A(p_IPAddress, p_rSendParameter))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_A(A) FAILED!\n"));); } - if ((bResult) && - (pService->m_u8ReplyMask & ContentFlag_TXT)) + if ((bResult) && (p_rSendParameter.m_u8HostReplyMask & ContentFlag_PTR_IP4)) { ((Sequence_Count == sequence) - ? ++ru16Answers - : (bResult = _writeMDNSAnswer_TXT(*pService, p_rSendParameter))); - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_TXT(A) FAILED!\n"));); + ? ++ru16Answers + : (bResult = _writeMDNSAnswer_PTR_IP4(p_IPAddress, p_rSendParameter))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_PTR_IP4 FAILED!\n"));); } - } // for services - - // Additional answers -#ifdef MDNS_IP4_SUPPORT - bool bNeedsAdditionalAnswerA = false; #endif #ifdef MDNS_IP6_SUPPORT - bool bNeedsAdditionalAnswerAAAA = false; -#endif - for (stcMDNSService* pService = m_pServices; ((bResult) && (pService)); pService = pService->m_pNext) - { - if ((bResult) && - (pService->m_u8ReplyMask & ContentFlag_PTR_NAME) && // If PTR_NAME is requested, AND - (!(pService->m_u8ReplyMask & ContentFlag_SRV))) // NOT SRV -> add SRV as additional answer + if ((bResult) && (p_rSendParameter.m_u8HostReplyMask & ContentFlag_AAAA)) { ((Sequence_Count == sequence) - ? ++msgHeader.m_u16ARCount - : (bResult = _writeMDNSAnswer_SRV(*pService, p_rSendParameter))); - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_SRV(B) FAILED!\n"));); + ? ++ru16Answers + : (bResult = _writeMDNSAnswer_AAAA(p_IPAddress, p_rSendParameter))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_AAAA(A) FAILED!\n"));); } - if ((bResult) && - (pService->m_u8ReplyMask & ContentFlag_PTR_NAME) && // If PTR_NAME is requested, AND - (!(pService->m_u8ReplyMask & ContentFlag_TXT))) // NOT TXT -> add TXT as additional answer + if ((bResult) && (p_rSendParameter.m_u8HostReplyMask & ContentFlag_PTR_IP6)) { ((Sequence_Count == sequence) - ? ++msgHeader.m_u16ARCount - : (bResult = _writeMDNSAnswer_TXT(*pService, p_rSendParameter))); - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_TXT(B) FAILED!\n"));); + ? ++ru16Answers + : (bResult = _writeMDNSAnswer_PTR_IP6(p_IPAddress, p_rSendParameter))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_PTR_IP6 FAILED!\n"));); } - if ((pService->m_u8ReplyMask & (ContentFlag_PTR_NAME | ContentFlag_SRV)) || // If service instance name or SRV OR - (p_rSendParameter.m_u8HostReplyMask & (ContentFlag_A | ContentFlag_AAAA))) // any host IP address is requested +#endif + + for (stcMDNSService* pService = m_pServices; ((bResult) && (pService)); pService = pService->m_pNext) { -#ifdef MDNS_IP4_SUPPORT - if ((bResult) && - (!(p_rSendParameter.m_u8HostReplyMask & ContentFlag_A))) // Add IP4 address + if ((bResult) && (pService->m_u8ReplyMask & ContentFlag_PTR_TYPE)) + { + ((Sequence_Count == sequence) + ? ++ru16Answers + : (bResult = _writeMDNSAnswer_PTR_TYPE(*pService, p_rSendParameter))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_PTR_TYPE FAILED!\n"));); + } + if ((bResult) && (pService->m_u8ReplyMask & ContentFlag_PTR_NAME)) + { + ((Sequence_Count == sequence) + ? ++ru16Answers + : (bResult = _writeMDNSAnswer_PTR_NAME(*pService, p_rSendParameter))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_PTR_NAME FAILED!\n"));); + } + if ((bResult) && (pService->m_u8ReplyMask & ContentFlag_SRV)) + { + ((Sequence_Count == sequence) + ? ++ru16Answers + : (bResult = _writeMDNSAnswer_SRV(*pService, p_rSendParameter))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_SRV(A) FAILED!\n"));); + } + if ((bResult) && (pService->m_u8ReplyMask & ContentFlag_TXT)) { - bNeedsAdditionalAnswerA = true; + ((Sequence_Count == sequence) + ? ++ru16Answers + : (bResult = _writeMDNSAnswer_TXT(*pService, p_rSendParameter))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_TXT(A) FAILED!\n"));); } + } // for services + + // Additional answers +#ifdef MDNS_IP4_SUPPORT + bool bNeedsAdditionalAnswerA = false; #endif #ifdef MDNS_IP6_SUPPORT - if ((bResult) && - (!(p_rSendParameter.m_u8HostReplyMask & ContentFlag_AAAA))) // Add IP6 address + bool bNeedsAdditionalAnswerAAAA = false; +#endif + for (stcMDNSService* pService = m_pServices; ((bResult) && (pService)); pService = pService->m_pNext) + { + if ((bResult) && (pService->m_u8ReplyMask & ContentFlag_PTR_NAME) && // If PTR_NAME is requested, AND + (!(pService->m_u8ReplyMask & ContentFlag_SRV))) // NOT SRV -> add SRV as additional answer + { + ((Sequence_Count == sequence) + ? ++msgHeader.m_u16ARCount + : (bResult = _writeMDNSAnswer_SRV(*pService, p_rSendParameter))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_SRV(B) FAILED!\n"));); + } + if ((bResult) && (pService->m_u8ReplyMask & ContentFlag_PTR_NAME) && // If PTR_NAME is requested, AND + (!(pService->m_u8ReplyMask & ContentFlag_TXT))) // NOT TXT -> add TXT as additional answer { - bNeedsAdditionalAnswerAAAA = true; + ((Sequence_Count == sequence) + ? ++msgHeader.m_u16ARCount + : (bResult = _writeMDNSAnswer_TXT(*pService, p_rSendParameter))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_TXT(B) FAILED!\n"));); } + if ((pService->m_u8ReplyMask & (ContentFlag_PTR_NAME | ContentFlag_SRV)) || // If service instance name or SRV OR + (p_rSendParameter.m_u8HostReplyMask & (ContentFlag_A | ContentFlag_AAAA))) // any host IP address is requested + { +#ifdef MDNS_IP4_SUPPORT + if ((bResult) && (!(p_rSendParameter.m_u8HostReplyMask & ContentFlag_A))) // Add IP4 address + { + bNeedsAdditionalAnswerA = true; + } #endif - } - } // for services +#ifdef MDNS_IP6_SUPPORT + if ((bResult) && (!(p_rSendParameter.m_u8HostReplyMask & ContentFlag_AAAA))) // Add IP6 address + { + bNeedsAdditionalAnswerAAAA = true; + } +#endif + } + } // for services - // Answer A needed? + // Answer A needed? #ifdef MDNS_IP4_SUPPORT - if ((bResult) && - (bNeedsAdditionalAnswerA)) - { - ((Sequence_Count == sequence) - ? ++msgHeader.m_u16ARCount - : (bResult = _writeMDNSAnswer_A(p_IPAddress, p_rSendParameter))); - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_A(B) FAILED!\n"));); - } + if ((bResult) && (bNeedsAdditionalAnswerA)) + { + ((Sequence_Count == sequence) + ? ++msgHeader.m_u16ARCount + : (bResult = _writeMDNSAnswer_A(p_IPAddress, p_rSendParameter))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_A(B) FAILED!\n"));); + } #endif #ifdef MDNS_IP6_SUPPORT - // Answer AAAA needed? - if ((bResult) && - (bNeedsAdditionalAnswerAAAA)) - { - ((Sequence_Count == sequence) - ? ++msgHeader.m_u16ARCount - : (bResult = _writeMDNSAnswer_AAAA(p_IPAddress, p_rSendParameter))); - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_AAAA(B) FAILED!\n"));); - } + // Answer AAAA needed? + if ((bResult) && (bNeedsAdditionalAnswerAAAA)) + { + ((Sequence_Count == sequence) + ? ++msgHeader.m_u16ARCount + : (bResult = _writeMDNSAnswer_AAAA(p_IPAddress, p_rSendParameter))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_AAAA(B) FAILED!\n"));); + } #endif - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: Loop %i FAILED!\n"), sequence);); - } // for sequence - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: FAILED!\n"));); - return bResult; -} + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: Loop %i FAILED!\n"), sequence);); + } // for sequence + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: FAILED!\n"));); + return bResult; + } -/* + /* MDNSResponder::_sendMDNSServiceQuery Creates and sends a PTR query for the given service domain. */ -bool MDNSResponder::_sendMDNSServiceQuery(const MDNSResponder::stcMDNSServiceQuery& p_ServiceQuery) -{ - return _sendMDNSQuery(p_ServiceQuery.m_ServiceTypeDomain, DNS_RRTYPE_PTR); -} + bool MDNSResponder::_sendMDNSServiceQuery(const MDNSResponder::stcMDNSServiceQuery& p_ServiceQuery) + { + return _sendMDNSQuery(p_ServiceQuery.m_ServiceTypeDomain, DNS_RRTYPE_PTR); + } -/* + /* MDNSResponder::_sendMDNSQuery Creates and sends a query for the given domain and query type. */ -bool MDNSResponder::_sendMDNSQuery(const MDNSResponder::stcMDNS_RRDomain& p_QueryDomain, - uint16_t p_u16QueryType, - stcMDNSServiceQuery::stcAnswer* p_pKnownAnswers /*= 0*/) -{ - bool bResult = false; - - stcMDNSSendParameter sendParameter; - if (0 != ((sendParameter.m_pQuestions = new stcMDNS_RRQuestion))) + bool MDNSResponder::_sendMDNSQuery(const MDNSResponder::stcMDNS_RRDomain& p_QueryDomain, + uint16_t p_u16QueryType, + stcMDNSServiceQuery::stcAnswer* p_pKnownAnswers /*= 0*/) { - sendParameter.m_pQuestions->m_Header.m_Domain = p_QueryDomain; + bool bResult = false; - sendParameter.m_pQuestions->m_Header.m_Attributes.m_u16Type = p_u16QueryType; - // It seems, that some mDNS implementations don't support 'unicast response' questions... - sendParameter.m_pQuestions->m_Header.m_Attributes.m_u16Class = (/*0x8000 |*/ DNS_RRCLASS_IN); // /*Unicast &*/ INternet + stcMDNSSendParameter sendParameter; + if (0 != ((sendParameter.m_pQuestions = new stcMDNS_RRQuestion))) + { + sendParameter.m_pQuestions->m_Header.m_Domain = p_QueryDomain; - // TODO: Add known answer to the query - (void)p_pKnownAnswers; + sendParameter.m_pQuestions->m_Header.m_Attributes.m_u16Type = p_u16QueryType; + // It seems, that some mDNS implementations don't support 'unicast response' questions... + sendParameter.m_pQuestions->m_Header.m_Attributes.m_u16Class = (/*0x8000 |*/ DNS_RRCLASS_IN); // /*Unicast &*/ INternet - bResult = _sendMDNSMessage(sendParameter); - } // else: FAILED to alloc question - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendMDNSQuery: FAILED to alloc question!\n"));); - return bResult; -} + // TODO: Add known answer to the query + (void)p_pKnownAnswers; -/** + bResult = _sendMDNSMessage(sendParameter); + } // else: FAILED to alloc question + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendMDNSQuery: FAILED to alloc question!\n"));); + return bResult; + } + + /** HELPERS */ -/** + /** RESOURCE RECORDS */ -/* + /* MDNSResponder::_readRRQuestion Reads a question (eg. MyESP._http._tcp.local ANY IN) from the UPD input buffer. */ -bool MDNSResponder::_readRRQuestion(MDNSResponder::stcMDNS_RRQuestion& p_rRRQuestion) -{ - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRQuestion\n"));); + bool MDNSResponder::_readRRQuestion(MDNSResponder::stcMDNS_RRQuestion& p_rRRQuestion) + { + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRQuestion\n"));); - bool bResult = false; + bool bResult = false; - if ((bResult = _readRRHeader(p_rRRQuestion.m_Header))) - { - // Extract unicast flag from class field - p_rRRQuestion.m_bUnicast = (p_rRRQuestion.m_Header.m_Attributes.m_u16Class & 0x8000); - p_rRRQuestion.m_Header.m_Attributes.m_u16Class &= (~0x8000); - - DEBUG_EX_INFO( - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRQuestion ")); - _printRRDomain(p_rRRQuestion.m_Header.m_Domain); - DEBUG_OUTPUT.printf_P(PSTR(" Type:0x%04X Class:0x%04X %s\n"), (unsigned)p_rRRQuestion.m_Header.m_Attributes.m_u16Type, (unsigned)p_rRRQuestion.m_Header.m_Attributes.m_u16Class, (p_rRRQuestion.m_bUnicast ? "Unicast" : "Multicast"));); + if ((bResult = _readRRHeader(p_rRRQuestion.m_Header))) + { + // Extract unicast flag from class field + p_rRRQuestion.m_bUnicast = (p_rRRQuestion.m_Header.m_Attributes.m_u16Class & 0x8000); + p_rRRQuestion.m_Header.m_Attributes.m_u16Class &= (~0x8000); + + DEBUG_EX_INFO( + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRQuestion ")); + _printRRDomain(p_rRRQuestion.m_Header.m_Domain); + DEBUG_OUTPUT.printf_P(PSTR(" Type:0x%04X Class:0x%04X %s\n"), (unsigned)p_rRRQuestion.m_Header.m_Attributes.m_u16Type, (unsigned)p_rRRQuestion.m_Header.m_Attributes.m_u16Class, (p_rRRQuestion.m_bUnicast ? "Unicast" : "Multicast"));); + } + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRQuestion: FAILED!\n")); + }); + return bResult; } - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRQuestion: FAILED!\n")); - }); - return bResult; -} -/* + /* MDNSResponder::_readRRAnswer Reads an answer (eg. _http._tcp.local PTR OP TTL MyESP._http._tcp.local) @@ -447,27 +430,25 @@ bool MDNSResponder::_readRRQuestion(MDNSResponder::stcMDNS_RRQuestion& p_rRRQues from the input buffer). */ -bool MDNSResponder::_readRRAnswer(MDNSResponder::stcMDNS_RRAnswer*& p_rpRRAnswer) -{ - //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswer\n"));); + bool MDNSResponder::_readRRAnswer(MDNSResponder::stcMDNS_RRAnswer*& p_rpRRAnswer) + { + //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswer\n"));); - bool bResult = false; + bool bResult = false; - stcMDNS_RRHeader header; - uint32_t u32TTL; - uint16_t u16RDLength; - if ((_readRRHeader(header)) && - (_udpRead32(u32TTL)) && - (_udpRead16(u16RDLength))) - { - /* DEBUG_EX_INFO( + stcMDNS_RRHeader header; + uint32_t u32TTL; + uint16_t u16RDLength; + if ((_readRRHeader(header)) && (_udpRead32(u32TTL)) && (_udpRead16(u16RDLength))) + { + /* DEBUG_EX_INFO( DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswer: Reading 0x%04X answer (class:0x%04X, TTL:%u, RDLength:%u) for "), header.m_Attributes.m_u16Type, header.m_Attributes.m_u16Class, u32TTL, u16RDLength); _printRRDomain(header.m_Domain); DEBUG_OUTPUT.printf_P(PSTR("\n")); );*/ - switch (header.m_Attributes.m_u16Type & (~0x8000)) // Topmost bit might carry 'cache flush' flag - { + switch (header.m_Attributes.m_u16Type & (~0x8000)) // Topmost bit might carry 'cache flush' flag + { #ifdef MDNS_IP4_SUPPORT case DNS_RRTYPE_A: p_rpRRAnswer = new stcMDNS_RRAnswerA(header, u32TTL); @@ -496,16 +477,15 @@ bool MDNSResponder::_readRRAnswer(MDNSResponder::stcMDNS_RRAnswer*& p_rpRRAnswer p_rpRRAnswer = new stcMDNS_RRAnswerGeneric(header, u32TTL); bResult = _readRRAnswerGeneric(*(stcMDNS_RRAnswerGeneric*&)p_rpRRAnswer, u16RDLength); break; - } - DEBUG_EX_INFO( - if ((bResult) && - (p_rpRRAnswer)) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswer: ")); - _printRRDomain(p_rpRRAnswer->m_Header.m_Domain); - DEBUG_OUTPUT.printf_P(PSTR(" Type:0x%04X Class:0x%04X TTL:%u, RDLength:%u "), p_rpRRAnswer->m_Header.m_Attributes.m_u16Type, p_rpRRAnswer->m_Header.m_Attributes.m_u16Class, p_rpRRAnswer->m_u32TTL, u16RDLength); - switch (header.m_Attributes.m_u16Type & (~0x8000)) // Topmost bit might carry 'cache flush' flag + } + DEBUG_EX_INFO( + if ((bResult) && (p_rpRRAnswer)) { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswer: ")); + _printRRDomain(p_rpRRAnswer->m_Header.m_Domain); + DEBUG_OUTPUT.printf_P(PSTR(" Type:0x%04X Class:0x%04X TTL:%u, RDLength:%u "), p_rpRRAnswer->m_Header.m_Attributes.m_u16Type, p_rpRRAnswer->m_Header.m_Attributes.m_u16Class, p_rpRRAnswer->m_u32TTL, u16RDLength); + switch (header.m_Attributes.m_u16Type & (~0x8000)) // Topmost bit might carry 'cache flush' flag + { #ifdef MDNS_IP4_SUPPORT case DNS_RRTYPE_A: DEBUG_OUTPUT.printf_P(PSTR("A IP:%s"), ((stcMDNS_RRAnswerA*&)p_rpRRAnswer)->m_IPAddress.toString().c_str()); @@ -539,233 +519,218 @@ bool MDNSResponder::_readRRAnswer(MDNSResponder::stcMDNS_RRAnswer*& p_rpRRAnswer default: DEBUG_OUTPUT.printf_P(PSTR("generic ")); break; - } - DEBUG_OUTPUT.printf_P(PSTR("\n")); - } else - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswer: FAILED to read specific answer of type 0x%04X!\n"), p_rpRRAnswer->m_Header.m_Attributes.m_u16Type); - }); // DEBUG_EX_INFO + } + DEBUG_OUTPUT.printf_P(PSTR("\n")); + } else + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswer: FAILED to read specific answer of type 0x%04X!\n"), p_rpRRAnswer->m_Header.m_Attributes.m_u16Type); + }); // DEBUG_EX_INFO + } + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswer: FAILED!\n"));); + return bResult; } - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswer: FAILED!\n"));); - return bResult; -} #ifdef MDNS_IP4_SUPPORT -/* + /* MDNSResponder::_readRRAnswerA */ -bool MDNSResponder::_readRRAnswerA(MDNSResponder::stcMDNS_RRAnswerA& p_rRRAnswerA, - uint16_t p_u16RDLength) -{ - uint32_t u32IP4Address; - bool bResult = ((MDNS_IP4_SIZE == p_u16RDLength) && - (_udpReadBuffer((unsigned char*)&u32IP4Address, MDNS_IP4_SIZE)) && - ((p_rRRAnswerA.m_IPAddress = IPAddress(u32IP4Address)))); - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerA: FAILED!\n"));); - return bResult; -} + bool MDNSResponder::_readRRAnswerA(MDNSResponder::stcMDNS_RRAnswerA& p_rRRAnswerA, + uint16_t p_u16RDLength) + { + uint32_t u32IP4Address; + bool bResult = ((MDNS_IP4_SIZE == p_u16RDLength) && (_udpReadBuffer((unsigned char*)&u32IP4Address, MDNS_IP4_SIZE)) && ((p_rRRAnswerA.m_IPAddress = IPAddress(u32IP4Address)))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerA: FAILED!\n"));); + return bResult; + } #endif -/* + /* MDNSResponder::_readRRAnswerPTR */ -bool MDNSResponder::_readRRAnswerPTR(MDNSResponder::stcMDNS_RRAnswerPTR& p_rRRAnswerPTR, - uint16_t p_u16RDLength) -{ - bool bResult = ((p_u16RDLength) && - (_readRRDomain(p_rRRAnswerPTR.m_PTRDomain))); - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerPTR: FAILED!\n"));); - return bResult; -} + bool MDNSResponder::_readRRAnswerPTR(MDNSResponder::stcMDNS_RRAnswerPTR& p_rRRAnswerPTR, + uint16_t p_u16RDLength) + { + bool bResult = ((p_u16RDLength) && (_readRRDomain(p_rRRAnswerPTR.m_PTRDomain))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerPTR: FAILED!\n"));); + return bResult; + } -/* + /* MDNSResponder::_readRRAnswerTXT Read TXT items from a buffer like 4c#=15ff=20 */ -bool MDNSResponder::_readRRAnswerTXT(MDNSResponder::stcMDNS_RRAnswerTXT& p_rRRAnswerTXT, - uint16_t p_u16RDLength) -{ - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerTXT: RDLength:%u\n"), p_u16RDLength);); - bool bResult = true; - - p_rRRAnswerTXT.clear(); - if (p_u16RDLength) + bool MDNSResponder::_readRRAnswerTXT(MDNSResponder::stcMDNS_RRAnswerTXT& p_rRRAnswerTXT, + uint16_t p_u16RDLength) { - bResult = false; + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerTXT: RDLength:%u\n"), p_u16RDLength);); + bool bResult = true; - unsigned char* pucBuffer = new unsigned char[p_u16RDLength]; - if (pucBuffer) + p_rRRAnswerTXT.clear(); + if (p_u16RDLength) { - if (_udpReadBuffer(pucBuffer, p_u16RDLength)) - { - bResult = true; + bResult = false; - const unsigned char* pucCursor = pucBuffer; - while ((pucCursor < (pucBuffer + p_u16RDLength)) && - (bResult)) + unsigned char* pucBuffer = new unsigned char[p_u16RDLength]; + if (pucBuffer) + { + if (_udpReadBuffer(pucBuffer, p_u16RDLength)) { - bResult = false; + bResult = true; - stcMDNSServiceTxt* pTxt = 0; - unsigned char ucLength = *pucCursor++; // Length of the next txt item - if (ucLength) + const unsigned char* pucCursor = pucBuffer; + while ((pucCursor < (pucBuffer + p_u16RDLength)) && (bResult)) { - DEBUG_EX_INFO( - static char sacBuffer[64]; *sacBuffer = 0; - uint8_t u8MaxLength = ((ucLength > (sizeof(sacBuffer) - 1)) ? (sizeof(sacBuffer) - 1) : ucLength); - os_strncpy(sacBuffer, (const char*)pucCursor, u8MaxLength); sacBuffer[u8MaxLength] = 0; - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerTXT: Item(%u): %s\n"), ucLength, sacBuffer);); - - unsigned char* pucEqualSign = (unsigned char*)os_strchr((const char*)pucCursor, '='); // Position of the '=' sign - unsigned char ucKeyLength; - if ((pucEqualSign) && - ((ucKeyLength = (pucEqualSign - pucCursor)))) + bResult = false; + + stcMDNSServiceTxt* pTxt = 0; + unsigned char ucLength = *pucCursor++; // Length of the next txt item + if (ucLength) { - unsigned char ucValueLength = (ucLength - (pucEqualSign - pucCursor + 1)); - bResult = (((pTxt = new stcMDNSServiceTxt)) && - (pTxt->setKey((const char*)pucCursor, ucKeyLength)) && - (pTxt->setValue((const char*)(pucEqualSign + 1), ucValueLength))); + DEBUG_EX_INFO( + static char sacBuffer[64]; *sacBuffer = 0; + uint8_t u8MaxLength = ((ucLength > (sizeof(sacBuffer) - 1)) ? (sizeof(sacBuffer) - 1) : ucLength); + os_strncpy(sacBuffer, (const char*)pucCursor, u8MaxLength); sacBuffer[u8MaxLength] = 0; + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerTXT: Item(%u): %s\n"), ucLength, sacBuffer);); + + unsigned char* pucEqualSign = (unsigned char*)os_strchr((const char*)pucCursor, '='); // Position of the '=' sign + unsigned char ucKeyLength; + if ((pucEqualSign) && ((ucKeyLength = (pucEqualSign - pucCursor)))) + { + unsigned char ucValueLength = (ucLength - (pucEqualSign - pucCursor + 1)); + bResult = (((pTxt = new stcMDNSServiceTxt)) && (pTxt->setKey((const char*)pucCursor, ucKeyLength)) && (pTxt->setValue((const char*)(pucEqualSign + 1), ucValueLength))); + } + else + { + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerTXT: INVALID TXT format (No '=')!\n"));); + } + pucCursor += ucLength; } - else + else // no/zero length TXT { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerTXT: INVALID TXT format (No '=')!\n"));); + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerTXT: TXT answer contains no items.\n"));); + bResult = true; } - pucCursor += ucLength; - } - else // no/zero length TXT - { - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerTXT: TXT answer contains no items.\n"));); - bResult = true; - } - if ((bResult) && - (pTxt)) // Everything is fine so far - { - // Link TXT item to answer TXTs - pTxt->m_pNext = p_rRRAnswerTXT.m_Txts.m_pTxts; - p_rRRAnswerTXT.m_Txts.m_pTxts = pTxt; - } - else // At least no TXT (might be OK, if length was 0) OR an error - { - if (!bResult) + if ((bResult) && (pTxt)) // Everything is fine so far { - DEBUG_EX_ERR( - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerTXT: FAILED to read TXT item!\n")); - DEBUG_OUTPUT.printf_P(PSTR("RData dump:\n")); - _udpDump((m_pUDPContext->tell() - p_u16RDLength), p_u16RDLength); - DEBUG_OUTPUT.printf_P(PSTR("\n"));); + // Link TXT item to answer TXTs + pTxt->m_pNext = p_rRRAnswerTXT.m_Txts.m_pTxts; + p_rRRAnswerTXT.m_Txts.m_pTxts = pTxt; } - if (pTxt) + else // At least no TXT (might be OK, if length was 0) OR an error { - delete pTxt; - pTxt = 0; + if (!bResult) + { + DEBUG_EX_ERR( + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerTXT: FAILED to read TXT item!\n")); + DEBUG_OUTPUT.printf_P(PSTR("RData dump:\n")); + _udpDump((m_pUDPContext->tell() - p_u16RDLength), p_u16RDLength); + DEBUG_OUTPUT.printf_P(PSTR("\n"));); + } + if (pTxt) + { + delete pTxt; + pTxt = 0; + } + p_rRRAnswerTXT.clear(); } - p_rRRAnswerTXT.clear(); - } - } // while + } // while - DEBUG_EX_ERR( - if (!bResult) // Some failure - { - DEBUG_OUTPUT.printf_P(PSTR("RData dump:\n")); - _udpDump((m_pUDPContext->tell() - p_u16RDLength), p_u16RDLength); - DEBUG_OUTPUT.printf_P(PSTR("\n")); - }); + DEBUG_EX_ERR( + if (!bResult) // Some failure + { + DEBUG_OUTPUT.printf_P(PSTR("RData dump:\n")); + _udpDump((m_pUDPContext->tell() - p_u16RDLength), p_u16RDLength); + DEBUG_OUTPUT.printf_P(PSTR("\n")); + }); + } + else + { + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerTXT: FAILED to read TXT content!\n"));); + } + // Clean up + delete[] pucBuffer; } else { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerTXT: FAILED to read TXT content!\n"));); + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerTXT: FAILED to alloc buffer for TXT content!\n"));); } - // Clean up - delete[] pucBuffer; } else { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerTXT: FAILED to alloc buffer for TXT content!\n"));); + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerTXT: WARNING! No content!\n"));); } + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerTXT: FAILED!\n"));); + return bResult; } - else - { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerTXT: WARNING! No content!\n"));); - } - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerTXT: FAILED!\n"));); - return bResult; -} #ifdef MDNS_IP6_SUPPORT -bool MDNSResponder::_readRRAnswerAAAA(MDNSResponder::stcMDNS_RRAnswerAAAA& p_rRRAnswerAAAA, - uint16_t p_u16RDLength) -{ - bool bResult = false; - // TODO: Implement - return bResult; -} + bool MDNSResponder::_readRRAnswerAAAA(MDNSResponder::stcMDNS_RRAnswerAAAA& p_rRRAnswerAAAA, + uint16_t p_u16RDLength) + { + bool bResult = false; + // TODO: Implement + return bResult; + } #endif -/* + /* MDNSResponder::_readRRAnswerSRV */ -bool MDNSResponder::_readRRAnswerSRV(MDNSResponder::stcMDNS_RRAnswerSRV& p_rRRAnswerSRV, - uint16_t p_u16RDLength) -{ - bool bResult = (((3 * sizeof(uint16_t)) < p_u16RDLength) && - (_udpRead16(p_rRRAnswerSRV.m_u16Priority)) && - (_udpRead16(p_rRRAnswerSRV.m_u16Weight)) && - (_udpRead16(p_rRRAnswerSRV.m_u16Port)) && - (_readRRDomain(p_rRRAnswerSRV.m_SRVDomain))); - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerSRV: FAILED!\n"));); - return bResult; -} + bool MDNSResponder::_readRRAnswerSRV(MDNSResponder::stcMDNS_RRAnswerSRV& p_rRRAnswerSRV, + uint16_t p_u16RDLength) + { + bool bResult = (((3 * sizeof(uint16_t)) < p_u16RDLength) && (_udpRead16(p_rRRAnswerSRV.m_u16Priority)) && (_udpRead16(p_rRRAnswerSRV.m_u16Weight)) && (_udpRead16(p_rRRAnswerSRV.m_u16Port)) && (_readRRDomain(p_rRRAnswerSRV.m_SRVDomain))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerSRV: FAILED!\n"));); + return bResult; + } -/* + /* MDNSResponder::_readRRAnswerGeneric */ -bool MDNSResponder::_readRRAnswerGeneric(MDNSResponder::stcMDNS_RRAnswerGeneric& p_rRRAnswerGeneric, - uint16_t p_u16RDLength) -{ - bool bResult = (0 == p_u16RDLength); - - p_rRRAnswerGeneric.clear(); - if (((p_rRRAnswerGeneric.m_u16RDLength = p_u16RDLength)) && - ((p_rRRAnswerGeneric.m_pu8RDData = new unsigned char[p_rRRAnswerGeneric.m_u16RDLength]))) + bool MDNSResponder::_readRRAnswerGeneric(MDNSResponder::stcMDNS_RRAnswerGeneric& p_rRRAnswerGeneric, + uint16_t p_u16RDLength) { - bResult = _udpReadBuffer(p_rRRAnswerGeneric.m_pu8RDData, p_rRRAnswerGeneric.m_u16RDLength); + bool bResult = (0 == p_u16RDLength); + + p_rRRAnswerGeneric.clear(); + if (((p_rRRAnswerGeneric.m_u16RDLength = p_u16RDLength)) && ((p_rRRAnswerGeneric.m_pu8RDData = new unsigned char[p_rRRAnswerGeneric.m_u16RDLength]))) + { + bResult = _udpReadBuffer(p_rRRAnswerGeneric.m_pu8RDData, p_rRRAnswerGeneric.m_u16RDLength); + } + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerGeneric: FAILED!\n"));); + return bResult; } - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswerGeneric: FAILED!\n"));); - return bResult; -} -/* + /* MDNSResponder::_readRRHeader */ -bool MDNSResponder::_readRRHeader(MDNSResponder::stcMDNS_RRHeader& p_rRRHeader) -{ - //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRHeader\n"));); + bool MDNSResponder::_readRRHeader(MDNSResponder::stcMDNS_RRHeader& p_rRRHeader) + { + //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRHeader\n"));); - bool bResult = ((_readRRDomain(p_rRRHeader.m_Domain)) && - (_readRRAttributes(p_rRRHeader.m_Attributes))); - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRHeader: FAILED!\n"));); - return bResult; -} + bool bResult = ((_readRRDomain(p_rRRHeader.m_Domain)) && (_readRRAttributes(p_rRRHeader.m_Attributes))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRHeader: FAILED!\n"));); + return bResult; + } -/* + /* MDNSResponder::_readRRDomain Reads a (maybe multilevel compressed) domain from the UDP input buffer. */ -bool MDNSResponder::_readRRDomain(MDNSResponder::stcMDNS_RRDomain& p_rRRDomain) -{ - //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain\n"));); + bool MDNSResponder::_readRRDomain(MDNSResponder::stcMDNS_RRDomain& p_rRRDomain) + { + //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain\n"));); - bool bResult = ((p_rRRDomain.clear()) && - (_readRRDomain_Loop(p_rRRDomain, 0))); - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain: FAILED!\n"));); - return bResult; -} + bool bResult = ((p_rRRDomain.clear()) && (_readRRDomain_Loop(p_rRRDomain, 0))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain: FAILED!\n"));); + return bResult; + } -/* + /* MDNSResponder::_readRRDomain_Loop Reads a domain from the UDP input buffer. For every compression level, the functions @@ -773,394 +738,363 @@ bool MDNSResponder::_readRRDomain(MDNSResponder::stcMDNS_RRDomain& p_rRRDomain) the maximum recursion depth is set by MDNS_DOMAIN_MAX_REDIRCTION. */ -bool MDNSResponder::_readRRDomain_Loop(MDNSResponder::stcMDNS_RRDomain& p_rRRDomain, - uint8_t p_u8Depth) -{ - //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain_Loop(%u)\n"), p_u8Depth);); - - bool bResult = false; - - if (MDNS_DOMAIN_MAX_REDIRCTION >= p_u8Depth) + bool MDNSResponder::_readRRDomain_Loop(MDNSResponder::stcMDNS_RRDomain& p_rRRDomain, + uint8_t p_u8Depth) { - bResult = true; + //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain_Loop(%u)\n"), p_u8Depth);); - uint8_t u8Len = 0; - do + bool bResult = false; + + if (MDNS_DOMAIN_MAX_REDIRCTION >= p_u8Depth) { - //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain_Loop(%u): Offset:%u p0:%02x\n"), p_u8Depth, m_pUDPContext->tell(), m_pUDPContext->peek());); - _udpRead8(u8Len); + bResult = true; - if (u8Len & MDNS_DOMAIN_COMPRESS_MARK) + uint8_t u8Len = 0; + do { - // Compressed label(s) - uint16_t u16Offset = ((u8Len & ~MDNS_DOMAIN_COMPRESS_MARK) << 8); // Implicit BE to LE conversion! + //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain_Loop(%u): Offset:%u p0:%02x\n"), p_u8Depth, m_pUDPContext->tell(), m_pUDPContext->peek());); _udpRead8(u8Len); - u16Offset |= u8Len; - if (m_pUDPContext->isValidOffset(u16Offset)) + if (u8Len & MDNS_DOMAIN_COMPRESS_MARK) { - size_t stCurrentPosition = m_pUDPContext->tell(); // Prepare return from recursion + // Compressed label(s) + uint16_t u16Offset = ((u8Len & ~MDNS_DOMAIN_COMPRESS_MARK) << 8); // Implicit BE to LE conversion! + _udpRead8(u8Len); + u16Offset |= u8Len; - //DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain_Loop(%u): Redirecting from %u to %u!\n"), p_u8Depth, stCurrentPosition, u16Offset);); - m_pUDPContext->seek(u16Offset); - if (_readRRDomain_Loop(p_rRRDomain, p_u8Depth + 1)) // Do recursion + if (m_pUDPContext->isValidOffset(u16Offset)) { - //DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain_Loop(%u): Succeeded to read redirected label! Returning to %u\n"), p_u8Depth, stCurrentPosition);); - m_pUDPContext->seek(stCurrentPosition); // Restore after recursion + size_t stCurrentPosition = m_pUDPContext->tell(); // Prepare return from recursion + + //DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain_Loop(%u): Redirecting from %u to %u!\n"), p_u8Depth, stCurrentPosition, u16Offset);); + m_pUDPContext->seek(u16Offset); + if (_readRRDomain_Loop(p_rRRDomain, p_u8Depth + 1)) // Do recursion + { + //DEBUG_EX_RX(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain_Loop(%u): Succeeded to read redirected label! Returning to %u\n"), p_u8Depth, stCurrentPosition);); + m_pUDPContext->seek(stCurrentPosition); // Restore after recursion + } + else + { + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain_Loop(%u): FAILED to read redirected label!\n"), p_u8Depth);); + bResult = false; + } } else { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain_Loop(%u): FAILED to read redirected label!\n"), p_u8Depth);); + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain_Loop(%u): INVALID offset in redirection!\n"), p_u8Depth);); bResult = false; } + break; } else { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain_Loop(%u): INVALID offset in redirection!\n"), p_u8Depth);); - bResult = false; - } - break; - } - else - { - // Normal (uncompressed) label (maybe '\0' only) - if (MDNS_DOMAIN_MAXLENGTH > (p_rRRDomain.m_u16NameLength + u8Len)) - { - // Add length byte - p_rRRDomain.m_acName[p_rRRDomain.m_u16NameLength] = u8Len; - ++(p_rRRDomain.m_u16NameLength); - if (u8Len) // Add name + // Normal (uncompressed) label (maybe '\0' only) + if (MDNS_DOMAIN_MAXLENGTH > (p_rRRDomain.m_u16NameLength + u8Len)) { - if ((bResult = _udpReadBuffer((unsigned char*)&(p_rRRDomain.m_acName[p_rRRDomain.m_u16NameLength]), u8Len))) + // Add length byte + p_rRRDomain.m_acName[p_rRRDomain.m_u16NameLength] = u8Len; + ++(p_rRRDomain.m_u16NameLength); + if (u8Len) // Add name { - /* DEBUG_EX_INFO( + if ((bResult = _udpReadBuffer((unsigned char*)&(p_rRRDomain.m_acName[p_rRRDomain.m_u16NameLength]), u8Len))) + { + /* DEBUG_EX_INFO( p_rRRDomain.m_acName[p_rRRDomain.m_u16NameLength + u8Len] = 0; // Closing '\0' for printing DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain_Loop(%u): Domain label (%u): %s\n"), p_u8Depth, (unsigned)(p_rRRDomain.m_acName[p_rRRDomain.m_u16NameLength - 1]), &(p_rRRDomain.m_acName[p_rRRDomain.m_u16NameLength])); );*/ - p_rRRDomain.m_u16NameLength += u8Len; + p_rRRDomain.m_u16NameLength += u8Len; + } } + //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain_Loop(2) offset:%u p0:%x\n"), m_pUDPContext->tell(), m_pUDPContext->peek());); + } + else + { + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain_Loop(%u): ERROR! Domain name too long (%u + %u)!\n"), p_u8Depth, p_rRRDomain.m_u16NameLength, u8Len);); + bResult = false; + break; } - //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain_Loop(2) offset:%u p0:%x\n"), m_pUDPContext->tell(), m_pUDPContext->peek());); - } - else - { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain_Loop(%u): ERROR! Domain name too long (%u + %u)!\n"), p_u8Depth, p_rRRDomain.m_u16NameLength, u8Len);); - bResult = false; - break; } - } - } while ((bResult) && - (0 != u8Len)); - } - else - { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain_Loop(%u): ERROR! Too many redirections!\n"), p_u8Depth);); + } while ((bResult) && (0 != u8Len)); + } + else + { + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain_Loop(%u): ERROR! Too many redirections!\n"), p_u8Depth);); + } + return bResult; } - return bResult; -} -/* + /* MDNSResponder::_readRRAttributes */ -bool MDNSResponder::_readRRAttributes(MDNSResponder::stcMDNS_RRAttributes& p_rRRAttributes) -{ - //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAttributes\n"));); + bool MDNSResponder::_readRRAttributes(MDNSResponder::stcMDNS_RRAttributes& p_rRRAttributes) + { + //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAttributes\n"));); - bool bResult = ((_udpRead16(p_rRRAttributes.m_u16Type)) && - (_udpRead16(p_rRRAttributes.m_u16Class))); - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAttributes: FAILED!\n"));); - return bResult; -} + bool bResult = ((_udpRead16(p_rRRAttributes.m_u16Type)) && (_udpRead16(p_rRRAttributes.m_u16Class))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAttributes: FAILED!\n"));); + return bResult; + } -/* + /* DOMAIN NAMES */ -/* + /* MDNSResponder::_buildDomainForHost Builds a MDNS host domain (eg. esp8266.local) for the given hostname. */ -bool MDNSResponder::_buildDomainForHost(const char* p_pcHostname, - MDNSResponder::stcMDNS_RRDomain& p_rHostDomain) const -{ - p_rHostDomain.clear(); - bool bResult = ((p_pcHostname) && - (*p_pcHostname) && - (p_rHostDomain.addLabel(p_pcHostname)) && - (p_rHostDomain.addLabel(scpcLocal)) && - (p_rHostDomain.addLabel(0))); - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _buildDomainForHost: FAILED!\n"));); - return bResult; -} + bool MDNSResponder::_buildDomainForHost(const char* p_pcHostname, + MDNSResponder::stcMDNS_RRDomain& p_rHostDomain) const + { + p_rHostDomain.clear(); + bool bResult = ((p_pcHostname) && (*p_pcHostname) && (p_rHostDomain.addLabel(p_pcHostname)) && (p_rHostDomain.addLabel(scpcLocal)) && (p_rHostDomain.addLabel(0))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _buildDomainForHost: FAILED!\n"));); + return bResult; + } -/* + /* MDNSResponder::_buildDomainForDNSSD Builds the '_services._dns-sd._udp.local' domain. Used while detecting generic service enum question (DNS-SD) and answering these questions. */ -bool MDNSResponder::_buildDomainForDNSSD(MDNSResponder::stcMDNS_RRDomain& p_rDNSSDDomain) const -{ - p_rDNSSDDomain.clear(); - bool bResult = ((p_rDNSSDDomain.addLabel(scpcServices, true)) && - (p_rDNSSDDomain.addLabel(scpcDNSSD, true)) && - (p_rDNSSDDomain.addLabel(scpcUDP, true)) && - (p_rDNSSDDomain.addLabel(scpcLocal)) && - (p_rDNSSDDomain.addLabel(0))); - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _buildDomainForDNSSD: FAILED!\n"));); - return bResult; -} + bool MDNSResponder::_buildDomainForDNSSD(MDNSResponder::stcMDNS_RRDomain& p_rDNSSDDomain) const + { + p_rDNSSDDomain.clear(); + bool bResult = ((p_rDNSSDDomain.addLabel(scpcServices, true)) && (p_rDNSSDDomain.addLabel(scpcDNSSD, true)) && (p_rDNSSDDomain.addLabel(scpcUDP, true)) && (p_rDNSSDDomain.addLabel(scpcLocal)) && (p_rDNSSDDomain.addLabel(0))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _buildDomainForDNSSD: FAILED!\n"));); + return bResult; + } -/* + /* MDNSResponder::_buildDomainForService Builds the domain for the given service (eg. _http._tcp.local or MyESP._http._tcp.local (if p_bIncludeName is set)). */ -bool MDNSResponder::_buildDomainForService(const MDNSResponder::stcMDNSService& p_Service, - bool p_bIncludeName, - MDNSResponder::stcMDNS_RRDomain& p_rServiceDomain) const -{ - p_rServiceDomain.clear(); - bool bResult = (((!p_bIncludeName) || - (p_rServiceDomain.addLabel(p_Service.m_pcName))) && - (p_rServiceDomain.addLabel(p_Service.m_pcService, true)) && - (p_rServiceDomain.addLabel(p_Service.m_pcProtocol, true)) && - (p_rServiceDomain.addLabel(scpcLocal)) && - (p_rServiceDomain.addLabel(0))); - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _buildDomainForService: FAILED!\n"));); - return bResult; -} + bool MDNSResponder::_buildDomainForService(const MDNSResponder::stcMDNSService& p_Service, + bool p_bIncludeName, + MDNSResponder::stcMDNS_RRDomain& p_rServiceDomain) const + { + p_rServiceDomain.clear(); + bool bResult = (((!p_bIncludeName) || (p_rServiceDomain.addLabel(p_Service.m_pcName))) && (p_rServiceDomain.addLabel(p_Service.m_pcService, true)) && (p_rServiceDomain.addLabel(p_Service.m_pcProtocol, true)) && (p_rServiceDomain.addLabel(scpcLocal)) && (p_rServiceDomain.addLabel(0))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _buildDomainForService: FAILED!\n"));); + return bResult; + } -/* + /* MDNSResponder::_buildDomainForService Builds the domain for the given service properties (eg. _http._tcp.local). The usual prepended '_' are added, if missing in the input strings. */ -bool MDNSResponder::_buildDomainForService(const char* p_pcService, - const char* p_pcProtocol, - MDNSResponder::stcMDNS_RRDomain& p_rServiceDomain) const -{ - p_rServiceDomain.clear(); - bool bResult = ((p_pcService) && - (p_pcProtocol) && - (p_rServiceDomain.addLabel(p_pcService, ('_' != *p_pcService))) && - (p_rServiceDomain.addLabel(p_pcProtocol, ('_' != *p_pcProtocol))) && - (p_rServiceDomain.addLabel(scpcLocal)) && - (p_rServiceDomain.addLabel(0))); - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _buildDomainForService: FAILED for (%s.%s)!\n"), (p_pcService ?: "-"), (p_pcProtocol ?: "-"));); - return bResult; -} + bool MDNSResponder::_buildDomainForService(const char* p_pcService, + const char* p_pcProtocol, + MDNSResponder::stcMDNS_RRDomain& p_rServiceDomain) const + { + p_rServiceDomain.clear(); + bool bResult = ((p_pcService) && (p_pcProtocol) && (p_rServiceDomain.addLabel(p_pcService, ('_' != *p_pcService))) && (p_rServiceDomain.addLabel(p_pcProtocol, ('_' != *p_pcProtocol))) && (p_rServiceDomain.addLabel(scpcLocal)) && (p_rServiceDomain.addLabel(0))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _buildDomainForService: FAILED for (%s.%s)!\n"), (p_pcService ?: "-"), (p_pcProtocol ?: "-"));); + return bResult; + } #ifdef MDNS_IP4_SUPPORT -/* + /* MDNSResponder::_buildDomainForReverseIP4 The IP4 address is stringized by printing the four address bytes into a char buffer in reverse order and adding 'in-addr.arpa' (eg. 012.789.456.123.in-addr.arpa). Used while detecting reverse IP4 questions and answering these */ -bool MDNSResponder::_buildDomainForReverseIP4(IPAddress p_IP4Address, - MDNSResponder::stcMDNS_RRDomain& p_rReverseIP4Domain) const -{ - bool bResult = true; + bool MDNSResponder::_buildDomainForReverseIP4(IPAddress p_IP4Address, + MDNSResponder::stcMDNS_RRDomain& p_rReverseIP4Domain) const + { + bool bResult = true; - p_rReverseIP4Domain.clear(); + p_rReverseIP4Domain.clear(); - char acBuffer[32]; - for (int i = MDNS_IP4_SIZE; ((bResult) && (i >= 1)); --i) - { - itoa(p_IP4Address[i - 1], acBuffer, 10); - bResult = p_rReverseIP4Domain.addLabel(acBuffer); + char acBuffer[32]; + for (int i = MDNS_IP4_SIZE; ((bResult) && (i >= 1)); --i) + { + itoa(p_IP4Address[i - 1], acBuffer, 10); + bResult = p_rReverseIP4Domain.addLabel(acBuffer); + } + bResult = ((bResult) && (p_rReverseIP4Domain.addLabel(scpcReverseIP4Domain)) && (p_rReverseIP4Domain.addLabel(scpcReverseTopDomain)) && (p_rReverseIP4Domain.addLabel(0))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _buildDomainForReverseIP4: FAILED!\n"));); + return bResult; } - bResult = ((bResult) && - (p_rReverseIP4Domain.addLabel(scpcReverseIP4Domain)) && - (p_rReverseIP4Domain.addLabel(scpcReverseTopDomain)) && - (p_rReverseIP4Domain.addLabel(0))); - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _buildDomainForReverseIP4: FAILED!\n"));); - return bResult; -} #endif #ifdef MDNS_IP6_SUPPORT -/* + /* MDNSResponder::_buildDomainForReverseIP6 Used while detecting reverse IP6 questions and answering these */ -bool MDNSResponder::_buildDomainForReverseIP6(IPAddress p_IP4Address, - MDNSResponder::stcMDNS_RRDomain& p_rReverseIP6Domain) const -{ - // TODO: Implement - return false; -} + bool MDNSResponder::_buildDomainForReverseIP6(IPAddress p_IP4Address, + MDNSResponder::stcMDNS_RRDomain& p_rReverseIP6Domain) const + { + // TODO: Implement + return false; + } #endif -/* + /* UDP */ -/* + /* MDNSResponder::_udpReadBuffer */ -bool MDNSResponder::_udpReadBuffer(unsigned char* p_pBuffer, - size_t p_stLength) -{ - bool bResult = ((m_pUDPContext) && - (true /*m_pUDPContext->getSize() > p_stLength*/) && - (p_pBuffer) && - (p_stLength) && - ((p_stLength == m_pUDPContext->read((char*)p_pBuffer, p_stLength)))); - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _udpReadBuffer: FAILED!\n")); - }); - return bResult; -} + bool MDNSResponder::_udpReadBuffer(unsigned char* p_pBuffer, + size_t p_stLength) + { + bool bResult = ((m_pUDPContext) && (true /*m_pUDPContext->getSize() > p_stLength*/) && (p_pBuffer) && (p_stLength) && ((p_stLength == m_pUDPContext->read((char*)p_pBuffer, p_stLength)))); + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _udpReadBuffer: FAILED!\n")); + }); + return bResult; + } -/* + /* MDNSResponder::_udpRead8 */ -bool MDNSResponder::_udpRead8(uint8_t& p_ru8Value) -{ - return _udpReadBuffer((unsigned char*)&p_ru8Value, sizeof(p_ru8Value)); -} + bool MDNSResponder::_udpRead8(uint8_t& p_ru8Value) + { + return _udpReadBuffer((unsigned char*)&p_ru8Value, sizeof(p_ru8Value)); + } -/* + /* MDNSResponder::_udpRead16 */ -bool MDNSResponder::_udpRead16(uint16_t& p_ru16Value) -{ - bool bResult = false; - - if (_udpReadBuffer((unsigned char*)&p_ru16Value, sizeof(p_ru16Value))) + bool MDNSResponder::_udpRead16(uint16_t& p_ru16Value) { - p_ru16Value = lwip_ntohs(p_ru16Value); - bResult = true; + bool bResult = false; + + if (_udpReadBuffer((unsigned char*)&p_ru16Value, sizeof(p_ru16Value))) + { + p_ru16Value = lwip_ntohs(p_ru16Value); + bResult = true; + } + return bResult; } - return bResult; -} -/* + /* MDNSResponder::_udpRead32 */ -bool MDNSResponder::_udpRead32(uint32_t& p_ru32Value) -{ - bool bResult = false; - - if (_udpReadBuffer((unsigned char*)&p_ru32Value, sizeof(p_ru32Value))) + bool MDNSResponder::_udpRead32(uint32_t& p_ru32Value) { - p_ru32Value = lwip_ntohl(p_ru32Value); - bResult = true; + bool bResult = false; + + if (_udpReadBuffer((unsigned char*)&p_ru32Value, sizeof(p_ru32Value))) + { + p_ru32Value = lwip_ntohl(p_ru32Value); + bResult = true; + } + return bResult; } - return bResult; -} -/* + /* MDNSResponder::_udpAppendBuffer */ -bool MDNSResponder::_udpAppendBuffer(const unsigned char* p_pcBuffer, - size_t p_stLength) -{ - bool bResult = ((m_pUDPContext) && - (p_pcBuffer) && - (p_stLength) && - (p_stLength == m_pUDPContext->append((const char*)p_pcBuffer, p_stLength))); - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _udpAppendBuffer: FAILED!\n")); - }); - return bResult; -} + bool MDNSResponder::_udpAppendBuffer(const unsigned char* p_pcBuffer, + size_t p_stLength) + { + bool bResult = ((m_pUDPContext) && (p_pcBuffer) && (p_stLength) && (p_stLength == m_pUDPContext->append((const char*)p_pcBuffer, p_stLength))); + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _udpAppendBuffer: FAILED!\n")); + }); + return bResult; + } -/* + /* MDNSResponder::_udpAppend8 */ -bool MDNSResponder::_udpAppend8(uint8_t p_u8Value) -{ - return (_udpAppendBuffer((unsigned char*)&p_u8Value, sizeof(p_u8Value))); -} + bool MDNSResponder::_udpAppend8(uint8_t p_u8Value) + { + return (_udpAppendBuffer((unsigned char*)&p_u8Value, sizeof(p_u8Value))); + } -/* + /* MDNSResponder::_udpAppend16 */ -bool MDNSResponder::_udpAppend16(uint16_t p_u16Value) -{ - p_u16Value = lwip_htons(p_u16Value); - return (_udpAppendBuffer((unsigned char*)&p_u16Value, sizeof(p_u16Value))); -} + bool MDNSResponder::_udpAppend16(uint16_t p_u16Value) + { + p_u16Value = lwip_htons(p_u16Value); + return (_udpAppendBuffer((unsigned char*)&p_u16Value, sizeof(p_u16Value))); + } -/* + /* MDNSResponder::_udpAppend32 */ -bool MDNSResponder::_udpAppend32(uint32_t p_u32Value) -{ - p_u32Value = lwip_htonl(p_u32Value); - return (_udpAppendBuffer((unsigned char*)&p_u32Value, sizeof(p_u32Value))); -} + bool MDNSResponder::_udpAppend32(uint32_t p_u32Value) + { + p_u32Value = lwip_htonl(p_u32Value); + return (_udpAppendBuffer((unsigned char*)&p_u32Value, sizeof(p_u32Value))); + } #ifdef DEBUG_ESP_MDNS_RESPONDER -/* + /* MDNSResponder::_udpDump */ -bool MDNSResponder::_udpDump(bool p_bMovePointer /*= false*/) -{ - const uint8_t cu8BytesPerLine = 16; + bool MDNSResponder::_udpDump(bool p_bMovePointer /*= false*/) + { + const uint8_t cu8BytesPerLine = 16; - uint32_t u32StartPosition = m_pUDPContext->tell(); - DEBUG_OUTPUT.println("UDP Context Dump:"); - uint32_t u32Counter = 0; - uint8_t u8Byte = 0; + uint32_t u32StartPosition = m_pUDPContext->tell(); + DEBUG_OUTPUT.println("UDP Context Dump:"); + uint32_t u32Counter = 0; + uint8_t u8Byte = 0; - while (_udpRead8(u8Byte)) - { - DEBUG_OUTPUT.printf_P(PSTR("%02x %s"), u8Byte, ((++u32Counter % cu8BytesPerLine) ? "" : "\n")); - } - DEBUG_OUTPUT.printf_P(PSTR("%sDone: %u bytes\n"), (((u32Counter) && (u32Counter % cu8BytesPerLine)) ? "\n" : ""), u32Counter); + while (_udpRead8(u8Byte)) + { + DEBUG_OUTPUT.printf_P(PSTR("%02x %s"), u8Byte, ((++u32Counter % cu8BytesPerLine) ? "" : "\n")); + } + DEBUG_OUTPUT.printf_P(PSTR("%sDone: %u bytes\n"), (((u32Counter) && (u32Counter % cu8BytesPerLine)) ? "\n" : ""), u32Counter); - if (!p_bMovePointer) // Restore - { - m_pUDPContext->seek(u32StartPosition); + if (!p_bMovePointer) // Restore + { + m_pUDPContext->seek(u32StartPosition); + } + return true; } - return true; -} -/* + /* MDNSResponder::_udpDump */ -bool MDNSResponder::_udpDump(unsigned p_uOffset, - unsigned p_uLength) -{ - if ((m_pUDPContext) && - (m_pUDPContext->isValidOffset(p_uOffset))) + bool MDNSResponder::_udpDump(unsigned p_uOffset, + unsigned p_uLength) { - unsigned uCurrentPosition = m_pUDPContext->tell(); // Remember start position - - m_pUDPContext->seek(p_uOffset); - uint8_t u8Byte; - for (unsigned u = 0; ((u < p_uLength) && (_udpRead8(u8Byte))); ++u) + if ((m_pUDPContext) && (m_pUDPContext->isValidOffset(p_uOffset))) { - DEBUG_OUTPUT.printf_P(PSTR("%02x "), u8Byte); + unsigned uCurrentPosition = m_pUDPContext->tell(); // Remember start position + + m_pUDPContext->seek(p_uOffset); + uint8_t u8Byte; + for (unsigned u = 0; ((u < p_uLength) && (_udpRead8(u8Byte))); ++u) + { + DEBUG_OUTPUT.printf_P(PSTR("%02x "), u8Byte); + } + // Return to start position + m_pUDPContext->seek(uCurrentPosition); } - // Return to start position - m_pUDPContext->seek(uCurrentPosition); + return true; } - return true; -} #endif -/** + /** READ/WRITE MDNS STRUCTS */ -/* + /* MDNSResponder::_readMDNSMsgHeader Read a MDNS header from the UDP input buffer. @@ -1173,31 +1107,25 @@ bool MDNSResponder::_udpDump(unsigned p_uOffset, In addition, bitfield memory order is undefined in C standard (GCC doesn't order them in the coded direction...), so they need some mapping here */ -bool MDNSResponder::_readMDNSMsgHeader(MDNSResponder::stcMDNS_MsgHeader& p_rMsgHeader) -{ - bool bResult = false; - - uint8_t u8B1; - uint8_t u8B2; - if ((_udpRead16(p_rMsgHeader.m_u16ID)) && - (_udpRead8(u8B1)) && - (_udpRead8(u8B2)) && - (_udpRead16(p_rMsgHeader.m_u16QDCount)) && - (_udpRead16(p_rMsgHeader.m_u16ANCount)) && - (_udpRead16(p_rMsgHeader.m_u16NSCount)) && - (_udpRead16(p_rMsgHeader.m_u16ARCount))) + bool MDNSResponder::_readMDNSMsgHeader(MDNSResponder::stcMDNS_MsgHeader& p_rMsgHeader) { - p_rMsgHeader.m_1bQR = (u8B1 & 0x80); // Query/Respond flag - p_rMsgHeader.m_4bOpcode = (u8B1 & 0x78); // Operation code (0: Standard query, others ignored) - p_rMsgHeader.m_1bAA = (u8B1 & 0x04); // Authoritative answer - p_rMsgHeader.m_1bTC = (u8B1 & 0x02); // Truncation flag - p_rMsgHeader.m_1bRD = (u8B1 & 0x01); // Recursion desired + bool bResult = false; - p_rMsgHeader.m_1bRA = (u8B2 & 0x80); // Recursion available - p_rMsgHeader.m_3bZ = (u8B2 & 0x70); // Zero - p_rMsgHeader.m_4bRCode = (u8B2 & 0x0F); // Response code + uint8_t u8B1; + uint8_t u8B2; + if ((_udpRead16(p_rMsgHeader.m_u16ID)) && (_udpRead8(u8B1)) && (_udpRead8(u8B2)) && (_udpRead16(p_rMsgHeader.m_u16QDCount)) && (_udpRead16(p_rMsgHeader.m_u16ANCount)) && (_udpRead16(p_rMsgHeader.m_u16NSCount)) && (_udpRead16(p_rMsgHeader.m_u16ARCount))) + { + p_rMsgHeader.m_1bQR = (u8B1 & 0x80); // Query/Respond flag + p_rMsgHeader.m_4bOpcode = (u8B1 & 0x78); // Operation code (0: Standard query, others ignored) + p_rMsgHeader.m_1bAA = (u8B1 & 0x04); // Authoritative answer + p_rMsgHeader.m_1bTC = (u8B1 & 0x02); // Truncation flag + p_rMsgHeader.m_1bRD = (u8B1 & 0x01); // Recursion desired + + p_rMsgHeader.m_1bRA = (u8B2 & 0x80); // Recursion available + p_rMsgHeader.m_3bZ = (u8B2 & 0x70); // Zero + p_rMsgHeader.m_4bRCode = (u8B2 & 0x0F); // Response code - /* DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readMDNSMsgHeader: ID:%u QR:%u OP:%u AA:%u TC:%u RD:%u RA:%u R:%u QD:%u AN:%u NS:%u AR:%u\n"), + /* DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readMDNSMsgHeader: ID:%u QR:%u OP:%u AA:%u TC:%u RD:%u RA:%u R:%u QD:%u AN:%u NS:%u AR:%u\n"), (unsigned)p_rMsgHeader.m_u16ID, (unsigned)p_rMsgHeader.m_1bQR, (unsigned)p_rMsgHeader.m_4bOpcode, (unsigned)p_rMsgHeader.m_1bAA, (unsigned)p_rMsgHeader.m_1bTC, (unsigned)p_rMsgHeader.m_1bRD, (unsigned)p_rMsgHeader.m_1bRA, (unsigned)p_rMsgHeader.m_4bRCode, @@ -1205,46 +1133,43 @@ bool MDNSResponder::_readMDNSMsgHeader(MDNSResponder::stcMDNS_MsgHeader& p_rMsgH (unsigned)p_rMsgHeader.m_u16ANCount, (unsigned)p_rMsgHeader.m_u16NSCount, (unsigned)p_rMsgHeader.m_u16ARCount););*/ - bResult = true; + bResult = true; + } + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readMDNSMsgHeader: FAILED!\n")); + }); + return bResult; } - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readMDNSMsgHeader: FAILED!\n")); - }); - return bResult; -} -/* + /* MDNSResponder::_write8 */ -bool MDNSResponder::_write8(uint8_t p_u8Value, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) -{ - return ((_udpAppend8(p_u8Value)) && - (p_rSendParameter.shiftOffset(sizeof(p_u8Value)))); -} + bool MDNSResponder::_write8(uint8_t p_u8Value, + MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + { + return ((_udpAppend8(p_u8Value)) && (p_rSendParameter.shiftOffset(sizeof(p_u8Value)))); + } -/* + /* MDNSResponder::_write16 */ -bool MDNSResponder::_write16(uint16_t p_u16Value, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) -{ - return ((_udpAppend16(p_u16Value)) && - (p_rSendParameter.shiftOffset(sizeof(p_u16Value)))); -} + bool MDNSResponder::_write16(uint16_t p_u16Value, + MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + { + return ((_udpAppend16(p_u16Value)) && (p_rSendParameter.shiftOffset(sizeof(p_u16Value)))); + } -/* + /* MDNSResponder::_write32 */ -bool MDNSResponder::_write32(uint32_t p_u32Value, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) -{ - return ((_udpAppend32(p_u32Value)) && - (p_rSendParameter.shiftOffset(sizeof(p_u32Value)))); -} + bool MDNSResponder::_write32(uint32_t p_u32Value, + MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + { + return ((_udpAppend32(p_u32Value)) && (p_rSendParameter.shiftOffset(sizeof(p_u32Value)))); + } -/* + /* MDNSResponder::_writeMDNSMsgHeader Write MDNS header to the UDP output buffer. @@ -1253,10 +1178,10 @@ bool MDNSResponder::_write32(uint32_t p_u32Value, In addition, bitfield memory order is undefined in C standard (GCC doesn't order them in the coded direction...), so they need some mapping here */ -bool MDNSResponder::_writeMDNSMsgHeader(const MDNSResponder::stcMDNS_MsgHeader& p_MsgHeader, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) -{ - /* DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSMsgHeader: ID:%u QR:%u OP:%u AA:%u TC:%u RD:%u RA:%u R:%u QD:%u AN:%u NS:%u AR:%u\n"), + bool MDNSResponder::_writeMDNSMsgHeader(const MDNSResponder::stcMDNS_MsgHeader& p_MsgHeader, + MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + { + /* DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSMsgHeader: ID:%u QR:%u OP:%u AA:%u TC:%u RD:%u RA:%u R:%u QD:%u AN:%u NS:%u AR:%u\n"), (unsigned)p_MsgHeader.m_u16ID, (unsigned)p_MsgHeader.m_1bQR, (unsigned)p_MsgHeader.m_4bOpcode, (unsigned)p_MsgHeader.m_1bAA, (unsigned)p_MsgHeader.m_1bTC, (unsigned)p_MsgHeader.m_1bRD, (unsigned)p_MsgHeader.m_1bRA, (unsigned)p_MsgHeader.m_4bRCode, @@ -1265,56 +1190,48 @@ bool MDNSResponder::_writeMDNSMsgHeader(const MDNSResponder::stcMDNS_MsgHeader& (unsigned)p_MsgHeader.m_u16NSCount, (unsigned)p_MsgHeader.m_u16ARCount););*/ - uint8_t u8B1((p_MsgHeader.m_1bQR << 7) | (p_MsgHeader.m_4bOpcode << 3) | (p_MsgHeader.m_1bAA << 2) | (p_MsgHeader.m_1bTC << 1) | (p_MsgHeader.m_1bRD)); - uint8_t u8B2((p_MsgHeader.m_1bRA << 7) | (p_MsgHeader.m_3bZ << 4) | (p_MsgHeader.m_4bRCode)); - bool bResult = ((_write16(p_MsgHeader.m_u16ID, p_rSendParameter)) && - (_write8(u8B1, p_rSendParameter)) && - (_write8(u8B2, p_rSendParameter)) && - (_write16(p_MsgHeader.m_u16QDCount, p_rSendParameter)) && - (_write16(p_MsgHeader.m_u16ANCount, p_rSendParameter)) && - (_write16(p_MsgHeader.m_u16NSCount, p_rSendParameter)) && - (_write16(p_MsgHeader.m_u16ARCount, p_rSendParameter))); - - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSMsgHeader: FAILED!\n")); - }); - return bResult; -} + uint8_t u8B1((p_MsgHeader.m_1bQR << 7) | (p_MsgHeader.m_4bOpcode << 3) | (p_MsgHeader.m_1bAA << 2) | (p_MsgHeader.m_1bTC << 1) | (p_MsgHeader.m_1bRD)); + uint8_t u8B2((p_MsgHeader.m_1bRA << 7) | (p_MsgHeader.m_3bZ << 4) | (p_MsgHeader.m_4bRCode)); + bool bResult = ((_write16(p_MsgHeader.m_u16ID, p_rSendParameter)) && (_write8(u8B1, p_rSendParameter)) && (_write8(u8B2, p_rSendParameter)) && (_write16(p_MsgHeader.m_u16QDCount, p_rSendParameter)) && (_write16(p_MsgHeader.m_u16ANCount, p_rSendParameter)) && (_write16(p_MsgHeader.m_u16NSCount, p_rSendParameter)) && (_write16(p_MsgHeader.m_u16ARCount, p_rSendParameter))); -/* + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSMsgHeader: FAILED!\n")); + }); + return bResult; + } + + /* MDNSResponder::_writeRRAttributes */ -bool MDNSResponder::_writeMDNSRRAttributes(const MDNSResponder::stcMDNS_RRAttributes& p_Attributes, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) -{ - bool bResult = ((_write16(p_Attributes.m_u16Type, p_rSendParameter)) && - (_write16(p_Attributes.m_u16Class, p_rSendParameter))); - - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSRRAttributes: FAILED!\n")); - }); - return bResult; -} + bool MDNSResponder::_writeMDNSRRAttributes(const MDNSResponder::stcMDNS_RRAttributes& p_Attributes, + MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + { + bool bResult = ((_write16(p_Attributes.m_u16Type, p_rSendParameter)) && (_write16(p_Attributes.m_u16Class, p_rSendParameter))); -/* + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSRRAttributes: FAILED!\n")); + }); + return bResult; + } + + /* MDNSResponder::_writeMDNSRRDomain */ -bool MDNSResponder::_writeMDNSRRDomain(const MDNSResponder::stcMDNS_RRDomain& p_Domain, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) -{ - bool bResult = ((_udpAppendBuffer((const unsigned char*)p_Domain.m_acName, p_Domain.m_u16NameLength)) && - (p_rSendParameter.shiftOffset(p_Domain.m_u16NameLength))); - - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSRRDomain: FAILED!\n")); - }); - return bResult; -} + bool MDNSResponder::_writeMDNSRRDomain(const MDNSResponder::stcMDNS_RRDomain& p_Domain, + MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + { + bool bResult = ((_udpAppendBuffer((const unsigned char*)p_Domain.m_acName, p_Domain.m_u16NameLength)) && (p_rSendParameter.shiftOffset(p_Domain.m_u16NameLength))); -/* + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSRRDomain: FAILED!\n")); + }); + return bResult; + } + + /* MDNSResponder::_writeMDNSHostDomain Write a host domain to the UDP output buffer. @@ -1329,36 +1246,33 @@ bool MDNSResponder::_writeMDNSRRDomain(const MDNSResponder::stcMDNS_RRDomain& p_ and written to the output buffer. */ -bool MDNSResponder::_writeMDNSHostDomain(const char* p_pcHostname, - bool p_bPrependRDLength, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) -{ - // The 'skip-compression' version is handled in '_writeMDNSAnswer_SRV' - uint16_t u16CachedDomainOffset = p_rSendParameter.findCachedDomainOffset((const void*)p_pcHostname, false); - - stcMDNS_RRDomain hostDomain; - bool bResult = (u16CachedDomainOffset - // Found cached domain -> mark as compressed domain - ? ((MDNS_DOMAIN_COMPRESS_MARK > ((u16CachedDomainOffset >> 8) & ~MDNS_DOMAIN_COMPRESS_MARK)) && // Valid offset - ((!p_bPrependRDLength) || - (_write16(2, p_rSendParameter))) && // Length of 'Cxxx' - (_write8(((u16CachedDomainOffset >> 8) | MDNS_DOMAIN_COMPRESS_MARK), p_rSendParameter)) && // Compression mark (and offset) - (_write8((uint8_t)(u16CachedDomainOffset & 0xFF), p_rSendParameter))) - // No cached domain -> add this domain to cache and write full domain name - : ((_buildDomainForHost(p_pcHostname, hostDomain)) && // eg. esp8266.local - ((!p_bPrependRDLength) || - (_write16(hostDomain.m_u16NameLength, p_rSendParameter))) && // RDLength (if needed) - (p_rSendParameter.addDomainCacheItem((const void*)p_pcHostname, false, p_rSendParameter.m_u16Offset)) && - (_writeMDNSRRDomain(hostDomain, p_rSendParameter)))); - - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSHostDomain: FAILED!\n")); - }); - return bResult; -} + bool MDNSResponder::_writeMDNSHostDomain(const char* p_pcHostname, + bool p_bPrependRDLength, + MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + { + // The 'skip-compression' version is handled in '_writeMDNSAnswer_SRV' + uint16_t u16CachedDomainOffset = p_rSendParameter.findCachedDomainOffset((const void*)p_pcHostname, false); + + stcMDNS_RRDomain hostDomain; + bool bResult = (u16CachedDomainOffset + // Found cached domain -> mark as compressed domain + ? ((MDNS_DOMAIN_COMPRESS_MARK > ((u16CachedDomainOffset >> 8) & ~MDNS_DOMAIN_COMPRESS_MARK)) && // Valid offset + ((!p_bPrependRDLength) || (_write16(2, p_rSendParameter))) && // Length of 'Cxxx' + (_write8(((u16CachedDomainOffset >> 8) | MDNS_DOMAIN_COMPRESS_MARK), p_rSendParameter)) && // Compression mark (and offset) + (_write8((uint8_t)(u16CachedDomainOffset & 0xFF), p_rSendParameter))) + // No cached domain -> add this domain to cache and write full domain name + : ((_buildDomainForHost(p_pcHostname, hostDomain)) && // eg. esp8266.local + ((!p_bPrependRDLength) || (_write16(hostDomain.m_u16NameLength, p_rSendParameter))) && // RDLength (if needed) + (p_rSendParameter.addDomainCacheItem((const void*)p_pcHostname, false, p_rSendParameter.m_u16Offset)) && (_writeMDNSRRDomain(hostDomain, p_rSendParameter)))); + + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSHostDomain: FAILED!\n")); + }); + return bResult; + } -/* + /* MDNSResponder::_writeMDNSServiceDomain Write a service domain to the UDP output buffer. @@ -1370,37 +1284,34 @@ bool MDNSResponder::_writeMDNSHostDomain(const char* p_pcHostname, the instance name (p_bIncludeName is set) and thoose who don't. */ -bool MDNSResponder::_writeMDNSServiceDomain(const MDNSResponder::stcMDNSService& p_Service, - bool p_bIncludeName, - bool p_bPrependRDLength, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) -{ - // The 'skip-compression' version is handled in '_writeMDNSAnswer_SRV' - uint16_t u16CachedDomainOffset = p_rSendParameter.findCachedDomainOffset((const void*)&p_Service, p_bIncludeName); - - stcMDNS_RRDomain serviceDomain; - bool bResult = (u16CachedDomainOffset - // Found cached domain -> mark as compressed domain - ? ((MDNS_DOMAIN_COMPRESS_MARK > ((u16CachedDomainOffset >> 8) & ~MDNS_DOMAIN_COMPRESS_MARK)) && // Valid offset - ((!p_bPrependRDLength) || - (_write16(2, p_rSendParameter))) && // Length of 'Cxxx' - (_write8(((u16CachedDomainOffset >> 8) | MDNS_DOMAIN_COMPRESS_MARK), p_rSendParameter)) && // Compression mark (and offset) - (_write8((uint8_t)(u16CachedDomainOffset & 0xFF), p_rSendParameter))) - // No cached domain -> add this domain to cache and write full domain name - : ((_buildDomainForService(p_Service, p_bIncludeName, serviceDomain)) && // eg. MyESP._http._tcp.local - ((!p_bPrependRDLength) || - (_write16(serviceDomain.m_u16NameLength, p_rSendParameter))) && // RDLength (if needed) - (p_rSendParameter.addDomainCacheItem((const void*)&p_Service, p_bIncludeName, p_rSendParameter.m_u16Offset)) && - (_writeMDNSRRDomain(serviceDomain, p_rSendParameter)))); - - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSServiceDomain: FAILED!\n")); - }); - return bResult; -} + bool MDNSResponder::_writeMDNSServiceDomain(const MDNSResponder::stcMDNSService& p_Service, + bool p_bIncludeName, + bool p_bPrependRDLength, + MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + { + // The 'skip-compression' version is handled in '_writeMDNSAnswer_SRV' + uint16_t u16CachedDomainOffset = p_rSendParameter.findCachedDomainOffset((const void*)&p_Service, p_bIncludeName); + + stcMDNS_RRDomain serviceDomain; + bool bResult = (u16CachedDomainOffset + // Found cached domain -> mark as compressed domain + ? ((MDNS_DOMAIN_COMPRESS_MARK > ((u16CachedDomainOffset >> 8) & ~MDNS_DOMAIN_COMPRESS_MARK)) && // Valid offset + ((!p_bPrependRDLength) || (_write16(2, p_rSendParameter))) && // Length of 'Cxxx' + (_write8(((u16CachedDomainOffset >> 8) | MDNS_DOMAIN_COMPRESS_MARK), p_rSendParameter)) && // Compression mark (and offset) + (_write8((uint8_t)(u16CachedDomainOffset & 0xFF), p_rSendParameter))) + // No cached domain -> add this domain to cache and write full domain name + : ((_buildDomainForService(p_Service, p_bIncludeName, serviceDomain)) && // eg. MyESP._http._tcp.local + ((!p_bPrependRDLength) || (_write16(serviceDomain.m_u16NameLength, p_rSendParameter))) && // RDLength (if needed) + (p_rSendParameter.addDomainCacheItem((const void*)&p_Service, p_bIncludeName, p_rSendParameter.m_u16Offset)) && (_writeMDNSRRDomain(serviceDomain, p_rSendParameter)))); + + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSServiceDomain: FAILED!\n")); + }); + return bResult; + } -/* + /* MDNSResponder::_writeMDNSQuestion Write a MDNS question to the UDP output buffer @@ -1410,23 +1321,22 @@ bool MDNSResponder::_writeMDNSServiceDomain(const MDNSResponder::stcMDNSService& QCLASS (16bit, eg. IN) */ -bool MDNSResponder::_writeMDNSQuestion(MDNSResponder::stcMDNS_RRQuestion& p_Question, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) -{ - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSQuestion\n"));); + bool MDNSResponder::_writeMDNSQuestion(MDNSResponder::stcMDNS_RRQuestion& p_Question, + MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + { + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSQuestion\n"));); - bool bResult = ((_writeMDNSRRDomain(p_Question.m_Header.m_Domain, p_rSendParameter)) && - (_writeMDNSRRAttributes(p_Question.m_Header.m_Attributes, p_rSendParameter))); + bool bResult = ((_writeMDNSRRDomain(p_Question.m_Header.m_Domain, p_rSendParameter)) && (_writeMDNSRRAttributes(p_Question.m_Header.m_Attributes, p_rSendParameter))); - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSQuestion: FAILED!\n")); - }); - return bResult; -} + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSQuestion: FAILED!\n")); + }); + return bResult; + } #ifdef MDNS_IP4_SUPPORT -/* + /* MDNSResponder::_writeMDNSAnswer_A Write a MDNS A answer to the UDP output buffer. @@ -1441,29 +1351,28 @@ bool MDNSResponder::_writeMDNSQuestion(MDNSResponder::stcMDNS_RRQuestion& p_Ques eg. esp8266.local A 0x8001 120 4 123.456.789.012 Ref: http://www.zytrax.com/books/dns/ch8/a.html */ -bool MDNSResponder::_writeMDNSAnswer_A(IPAddress p_IPAddress, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) -{ - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_A (%s)\n"), p_IPAddress.toString().c_str());); - - stcMDNS_RRAttributes attributes(DNS_RRTYPE_A, - ((p_rSendParameter.m_bCacheFlush ? 0x8000 : 0) | DNS_RRCLASS_IN)); // Cache flush? & INternet - const unsigned char aucIPAddress[MDNS_IP4_SIZE] = {p_IPAddress[0], p_IPAddress[1], p_IPAddress[2], p_IPAddress[3]}; - bool bResult = ((_writeMDNSHostDomain(m_pcHostname, false, p_rSendParameter)) && - (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS - (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_HOST_TTL), p_rSendParameter)) && // TTL - (_write16(MDNS_IP4_SIZE, p_rSendParameter)) && // RDLength - (_udpAppendBuffer(aucIPAddress, MDNS_IP4_SIZE)) && // RData - (p_rSendParameter.shiftOffset(MDNS_IP4_SIZE))); - - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_A: FAILED!\n")); - }); - return bResult; -} + bool MDNSResponder::_writeMDNSAnswer_A(IPAddress p_IPAddress, + MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + { + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_A (%s)\n"), p_IPAddress.toString().c_str());); + + stcMDNS_RRAttributes attributes(DNS_RRTYPE_A, + ((p_rSendParameter.m_bCacheFlush ? 0x8000 : 0) | DNS_RRCLASS_IN)); // Cache flush? & INternet + const unsigned char aucIPAddress[MDNS_IP4_SIZE] = { p_IPAddress[0], p_IPAddress[1], p_IPAddress[2], p_IPAddress[3] }; + bool bResult = ((_writeMDNSHostDomain(m_pcHostname, false, p_rSendParameter)) && (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS + (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_HOST_TTL), p_rSendParameter)) && // TTL + (_write16(MDNS_IP4_SIZE, p_rSendParameter)) && // RDLength + (_udpAppendBuffer(aucIPAddress, MDNS_IP4_SIZE)) && // RData + (p_rSendParameter.shiftOffset(MDNS_IP4_SIZE))); + + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_A: FAILED!\n")); + }); + return bResult; + } -/* + /* MDNSResponder::_writeMDNSAnswer_PTR_IP4 Write a MDNS reverse IP4 PTR answer to the UDP output buffer. @@ -1472,30 +1381,29 @@ bool MDNSResponder::_writeMDNSAnswer_A(IPAddress p_IPAddress, eg. 012.789.456.123.in-addr.arpa PTR 0x8001 120 15 esp8266.local Used while answering reverse IP4 questions */ -bool MDNSResponder::_writeMDNSAnswer_PTR_IP4(IPAddress p_IPAddress, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) -{ - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_IP4 (%s)\n"), p_IPAddress.toString().c_str());); - - stcMDNS_RRDomain reverseIP4Domain; - stcMDNS_RRAttributes attributes(DNS_RRTYPE_PTR, - ((p_rSendParameter.m_bCacheFlush ? 0x8000 : 0) | DNS_RRCLASS_IN)); // Cache flush? & INternet - stcMDNS_RRDomain hostDomain; - bool bResult = ((_buildDomainForReverseIP4(p_IPAddress, reverseIP4Domain)) && // 012.789.456.123.in-addr.arpa - (_writeMDNSRRDomain(reverseIP4Domain, p_rSendParameter)) && - (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS - (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_HOST_TTL), p_rSendParameter)) && // TTL - (_writeMDNSHostDomain(m_pcHostname, true, p_rSendParameter))); // RDLength & RData (host domain, eg. esp8266.local) - - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_IP4: FAILED!\n")); - }); - return bResult; -} + bool MDNSResponder::_writeMDNSAnswer_PTR_IP4(IPAddress p_IPAddress, + MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + { + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_IP4 (%s)\n"), p_IPAddress.toString().c_str());); + + stcMDNS_RRDomain reverseIP4Domain; + stcMDNS_RRAttributes attributes(DNS_RRTYPE_PTR, + ((p_rSendParameter.m_bCacheFlush ? 0x8000 : 0) | DNS_RRCLASS_IN)); // Cache flush? & INternet + stcMDNS_RRDomain hostDomain; + bool bResult = ((_buildDomainForReverseIP4(p_IPAddress, reverseIP4Domain)) && // 012.789.456.123.in-addr.arpa + (_writeMDNSRRDomain(reverseIP4Domain, p_rSendParameter)) && (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS + (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_HOST_TTL), p_rSendParameter)) && // TTL + (_writeMDNSHostDomain(m_pcHostname, true, p_rSendParameter))); // RDLength & RData (host domain, eg. esp8266.local) + + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_IP4: FAILED!\n")); + }); + return bResult; + } #endif -/* + /* MDNSResponder::_writeMDNSAnswer_PTR_TYPE Write a MDNS PTR answer to the UDP output buffer. @@ -1505,28 +1413,27 @@ bool MDNSResponder::_writeMDNSAnswer_PTR_IP4(IPAddress p_IPAddress, eg. _services._dns-sd._udp.local PTR 0x8001 5400 xx _http._tcp.local http://www.zytrax.com/books/dns/ch8/ptr.html */ -bool MDNSResponder::_writeMDNSAnswer_PTR_TYPE(MDNSResponder::stcMDNSService& p_rService, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) -{ - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_TYPE\n"));); - - stcMDNS_RRDomain dnssdDomain; - stcMDNS_RRDomain serviceDomain; - stcMDNS_RRAttributes attributes(DNS_RRTYPE_PTR, DNS_RRCLASS_IN); // No cache flush! only INternet - bool bResult = ((_buildDomainForDNSSD(dnssdDomain)) && // _services._dns-sd._udp.local - (_writeMDNSRRDomain(dnssdDomain, p_rSendParameter)) && - (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS - (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_SERVICE_TTL), p_rSendParameter)) && // TTL - (_writeMDNSServiceDomain(p_rService, false, true, p_rSendParameter))); // RDLength & RData (service domain, eg. _http._tcp.local) - - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_TYPE: FAILED!\n")); - }); - return bResult; -} + bool MDNSResponder::_writeMDNSAnswer_PTR_TYPE(MDNSResponder::stcMDNSService& p_rService, + MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + { + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_TYPE\n"));); -/* + stcMDNS_RRDomain dnssdDomain; + stcMDNS_RRDomain serviceDomain; + stcMDNS_RRAttributes attributes(DNS_RRTYPE_PTR, DNS_RRCLASS_IN); // No cache flush! only INternet + bool bResult = ((_buildDomainForDNSSD(dnssdDomain)) && // _services._dns-sd._udp.local + (_writeMDNSRRDomain(dnssdDomain, p_rSendParameter)) && (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS + (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_SERVICE_TTL), p_rSendParameter)) && // TTL + (_writeMDNSServiceDomain(p_rService, false, true, p_rSendParameter))); // RDLength & RData (service domain, eg. _http._tcp.local) + + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_TYPE: FAILED!\n")); + }); + return bResult; + } + + /* MDNSResponder::_writeMDNSAnswer_PTR_NAME Write a MDNS PTR answer to the UDP output buffer. @@ -1536,25 +1443,25 @@ bool MDNSResponder::_writeMDNSAnswer_PTR_TYPE(MDNSResponder::stcMDNSService& p_r eg. _http.tcp.local PTR 0x8001 120 xx myESP._http._tcp.local http://www.zytrax.com/books/dns/ch8/ptr.html */ -bool MDNSResponder::_writeMDNSAnswer_PTR_NAME(MDNSResponder::stcMDNSService& p_rService, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) -{ - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_NAME\n"));); - - stcMDNS_RRAttributes attributes(DNS_RRTYPE_PTR, DNS_RRCLASS_IN); // No cache flush! only INternet - bool bResult = ((_writeMDNSServiceDomain(p_rService, false, false, p_rSendParameter)) && // _http._tcp.local - (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS - (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_SERVICE_TTL), p_rSendParameter)) && // TTL - (_writeMDNSServiceDomain(p_rService, true, true, p_rSendParameter))); // RDLength & RData (service domain, eg. MyESP._http._tcp.local) - - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_NAME: FAILED!\n")); - }); - return bResult; -} + bool MDNSResponder::_writeMDNSAnswer_PTR_NAME(MDNSResponder::stcMDNSService& p_rService, + MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + { + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_NAME\n"));); -/* + stcMDNS_RRAttributes attributes(DNS_RRTYPE_PTR, DNS_RRCLASS_IN); // No cache flush! only INternet + bool bResult = ((_writeMDNSServiceDomain(p_rService, false, false, p_rSendParameter)) && // _http._tcp.local + (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS + (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_SERVICE_TTL), p_rSendParameter)) && // TTL + (_writeMDNSServiceDomain(p_rService, true, true, p_rSendParameter))); // RDLength & RData (service domain, eg. MyESP._http._tcp.local) + + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_NAME: FAILED!\n")); + }); + return bResult; + } + + /* MDNSResponder::_writeMDNSAnswer_TXT Write a MDNS TXT answer to the UDP output buffer. @@ -1565,54 +1472,49 @@ bool MDNSResponder::_writeMDNSAnswer_PTR_NAME(MDNSResponder::stcMDNSService& p_r eg. myESP._http._tcp.local TXT 0x8001 120 4 c#=1 http://www.zytrax.com/books/dns/ch8/txt.html */ -bool MDNSResponder::_writeMDNSAnswer_TXT(MDNSResponder::stcMDNSService& p_rService, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) -{ - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_TXT\n"));); + bool MDNSResponder::_writeMDNSAnswer_TXT(MDNSResponder::stcMDNSService& p_rService, + MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + { + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_TXT\n"));); - bool bResult = false; + bool bResult = false; - stcMDNS_RRAttributes attributes(DNS_RRTYPE_TXT, - ((p_rSendParameter.m_bCacheFlush ? 0x8000 : 0) | DNS_RRCLASS_IN)); // Cache flush? & INternet + stcMDNS_RRAttributes attributes(DNS_RRTYPE_TXT, + ((p_rSendParameter.m_bCacheFlush ? 0x8000 : 0) | DNS_RRCLASS_IN)); // Cache flush? & INternet - if ((_collectServiceTxts(p_rService)) && - (_writeMDNSServiceDomain(p_rService, true, false, p_rSendParameter)) && // MyESP._http._tcp.local - (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS - (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_SERVICE_TTL), p_rSendParameter)) && // TTL - (_write16(p_rService.m_Txts.length(), p_rSendParameter))) // RDLength - { - bResult = true; - // RData Txts - for (stcMDNSServiceTxt* pTxt = p_rService.m_Txts.m_pTxts; ((bResult) && (pTxt)); pTxt = pTxt->m_pNext) + if ((_collectServiceTxts(p_rService)) && (_writeMDNSServiceDomain(p_rService, true, false, p_rSendParameter)) && // MyESP._http._tcp.local + (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS + (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_SERVICE_TTL), p_rSendParameter)) && // TTL + (_write16(p_rService.m_Txts.length(), p_rSendParameter))) // RDLength { - unsigned char ucLengthByte = pTxt->length(); - bResult = ((_udpAppendBuffer((unsigned char*)&ucLengthByte, sizeof(ucLengthByte))) && // Length - (p_rSendParameter.shiftOffset(sizeof(ucLengthByte))) && - ((size_t)os_strlen(pTxt->m_pcKey) == m_pUDPContext->append(pTxt->m_pcKey, os_strlen(pTxt->m_pcKey))) && // Key - (p_rSendParameter.shiftOffset((size_t)os_strlen(pTxt->m_pcKey))) && - (1 == m_pUDPContext->append("=", 1)) && // = - (p_rSendParameter.shiftOffset(1)) && - ((!pTxt->m_pcValue) || - (((size_t)os_strlen(pTxt->m_pcValue) == m_pUDPContext->append(pTxt->m_pcValue, os_strlen(pTxt->m_pcValue))) && // Value - (p_rSendParameter.shiftOffset((size_t)os_strlen(pTxt->m_pcValue)))))); - - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_TXT: FAILED to write %sTxt %s=%s!\n"), (pTxt->m_bTemp ? "temp. " : ""), (pTxt->m_pcKey ?: "?"), (pTxt->m_pcValue ?: "?")); - }); + bResult = true; + // RData Txts + for (stcMDNSServiceTxt* pTxt = p_rService.m_Txts.m_pTxts; ((bResult) && (pTxt)); pTxt = pTxt->m_pNext) + { + unsigned char ucLengthByte = pTxt->length(); + bResult = ((_udpAppendBuffer((unsigned char*)&ucLengthByte, sizeof(ucLengthByte))) && // Length + (p_rSendParameter.shiftOffset(sizeof(ucLengthByte))) && ((size_t)os_strlen(pTxt->m_pcKey) == m_pUDPContext->append(pTxt->m_pcKey, os_strlen(pTxt->m_pcKey))) && // Key + (p_rSendParameter.shiftOffset((size_t)os_strlen(pTxt->m_pcKey))) && (1 == m_pUDPContext->append("=", 1)) && // = + (p_rSendParameter.shiftOffset(1)) && ((!pTxt->m_pcValue) || (((size_t)os_strlen(pTxt->m_pcValue) == m_pUDPContext->append(pTxt->m_pcValue, os_strlen(pTxt->m_pcValue))) && // Value + (p_rSendParameter.shiftOffset((size_t)os_strlen(pTxt->m_pcValue)))))); + + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_TXT: FAILED to write %sTxt %s=%s!\n"), (pTxt->m_bTemp ? "temp. " : ""), (pTxt->m_pcKey ?: "?"), (pTxt->m_pcValue ?: "?")); + }); + } } - } - _releaseTempServiceTxts(p_rService); + _releaseTempServiceTxts(p_rService); - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_TXT: FAILED!\n")); - }); - return bResult; -} + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_TXT: FAILED!\n")); + }); + return bResult; + } #ifdef MDNS_IP6_SUPPORT -/* + /* MDNSResponder::_writeMDNSAnswer_AAAA Write a MDNS AAAA answer to the UDP output buffer. @@ -1621,27 +1523,27 @@ bool MDNSResponder::_writeMDNSAnswer_TXT(MDNSResponder::stcMDNSService& p_rServi eg. esp8266.local AAAA 0x8001 120 16 xxxx::xx http://www.zytrax.com/books/dns/ch8/aaaa.html */ -bool MDNSResponder::_writeMDNSAnswer_AAAA(IPAddress p_IPAddress, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) -{ - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_AAAA\n"));); - - stcMDNS_RRAttributes attributes(DNS_RRTYPE_AAAA, - ((p_rSendParameter.m_bCacheFlush ? 0x8000 : 0) | DNS_RRCLASS_IN)); // Cache flush? & INternet - bool bResult = ((_writeMDNSHostDomain(m_pcHostname, false, p_rSendParameter)) && // esp8266.local - (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS - (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_HOST_TTL), p_rSendParameter)) && // TTL - (_write16(MDNS_IP6_SIZE, p_rSendParameter)) && // RDLength - (false /*TODO: IP6 version of: _udpAppendBuffer((uint32_t)p_IPAddress, MDNS_IP4_SIZE)*/)); // RData - - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_AAAA: FAILED!\n")); - }); - return bResult; -} + bool MDNSResponder::_writeMDNSAnswer_AAAA(IPAddress p_IPAddress, + MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + { + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_AAAA\n"));); -/* + stcMDNS_RRAttributes attributes(DNS_RRTYPE_AAAA, + ((p_rSendParameter.m_bCacheFlush ? 0x8000 : 0) | DNS_RRCLASS_IN)); // Cache flush? & INternet + bool bResult = ((_writeMDNSHostDomain(m_pcHostname, false, p_rSendParameter)) && // esp8266.local + (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS + (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_HOST_TTL), p_rSendParameter)) && // TTL + (_write16(MDNS_IP6_SIZE, p_rSendParameter)) && // RDLength + (false /*TODO: IP6 version of: _udpAppendBuffer((uint32_t)p_IPAddress, MDNS_IP4_SIZE)*/)); // RData + + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_AAAA: FAILED!\n")); + }); + return bResult; + } + + /* MDNSResponder::_writeMDNSAnswer_PTR_IP6 Write a MDNS reverse IP6 PTR answer to the UDP output buffer. @@ -1650,81 +1552,76 @@ bool MDNSResponder::_writeMDNSAnswer_AAAA(IPAddress p_IPAddress, eg. xxxx::xx.in6.arpa PTR 0x8001 120 15 esp8266.local Used while answering reverse IP6 questions */ -bool MDNSResponder::_writeMDNSAnswer_PTR_IP6(IPAddress p_IPAddress, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) -{ - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_IP6\n"));); - - stcMDNS_RRDomain reverseIP6Domain; - stcMDNS_RRAttributes attributes(DNS_RRTYPE_PTR, - ((p_rSendParameter.m_bCacheFlush ? 0x8000 : 0) | DNS_RRCLASS_IN)); // Cache flush? & INternet - bool bResult = ((_buildDomainForReverseIP6(p_IPAddress, reverseIP6Domain)) && // xxxx::xx.ip6.arpa - (_writeMDNSRRDomain(reverseIP6Domain, p_rSendParameter)) && - (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS - (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_HOST_TTL), p_rSendParameter)) && // TTL - (_writeMDNSHostDomain(m_pcHostname, true, p_rSendParameter))); // RDLength & RData (host domain, eg. esp8266.local) - - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_IP6: FAILED!\n")); - }); - return bResult; -} + bool MDNSResponder::_writeMDNSAnswer_PTR_IP6(IPAddress p_IPAddress, + MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + { + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_IP6\n"));); + + stcMDNS_RRDomain reverseIP6Domain; + stcMDNS_RRAttributes attributes(DNS_RRTYPE_PTR, + ((p_rSendParameter.m_bCacheFlush ? 0x8000 : 0) | DNS_RRCLASS_IN)); // Cache flush? & INternet + bool bResult = ((_buildDomainForReverseIP6(p_IPAddress, reverseIP6Domain)) && // xxxx::xx.ip6.arpa + (_writeMDNSRRDomain(reverseIP6Domain, p_rSendParameter)) && (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS + (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_HOST_TTL), p_rSendParameter)) && // TTL + (_writeMDNSHostDomain(m_pcHostname, true, p_rSendParameter))); // RDLength & RData (host domain, eg. esp8266.local) + + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_IP6: FAILED!\n")); + }); + return bResult; + } #endif -/* + /* MDNSResponder::_writeMDNSAnswer_SRV eg. MyESP._http.tcp.local SRV 0x8001 120 0 0 60068 esp8266.local http://www.zytrax.com/books/dns/ch8/srv.html ???? Include instance name ???? */ -bool MDNSResponder::_writeMDNSAnswer_SRV(MDNSResponder::stcMDNSService& p_rService, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) -{ - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_SRV\n"));); - - uint16_t u16CachedDomainOffset = (p_rSendParameter.m_bLegacyQuery - ? 0 - : p_rSendParameter.findCachedDomainOffset((const void*)m_pcHostname, false)); - - stcMDNS_RRAttributes attributes(DNS_RRTYPE_SRV, - ((p_rSendParameter.m_bCacheFlush ? 0x8000 : 0) | DNS_RRCLASS_IN)); // Cache flush? & INternet - stcMDNS_RRDomain hostDomain; - bool bResult = ((_writeMDNSServiceDomain(p_rService, true, false, p_rSendParameter)) && // MyESP._http._tcp.local - (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS - (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_SERVICE_TTL), p_rSendParameter)) && // TTL - (!u16CachedDomainOffset - // No cache for domain name (or no compression allowed) - ? ((_buildDomainForHost(m_pcHostname, hostDomain)) && - (_write16((sizeof(uint16_t /*Prio*/) + // RDLength - sizeof(uint16_t /*Weight*/) + - sizeof(uint16_t /*Port*/) + - hostDomain.m_u16NameLength), - p_rSendParameter)) && // Domain length - (_write16(MDNS_SRV_PRIORITY, p_rSendParameter)) && // Priority - (_write16(MDNS_SRV_WEIGHT, p_rSendParameter)) && // Weight - (_write16(p_rService.m_u16Port, p_rSendParameter)) && // Port - (p_rSendParameter.addDomainCacheItem((const void*)m_pcHostname, false, p_rSendParameter.m_u16Offset)) && - (_writeMDNSRRDomain(hostDomain, p_rSendParameter))) // Host, eg. esp8266.local - // Cache available for domain - : ((MDNS_DOMAIN_COMPRESS_MARK > ((u16CachedDomainOffset >> 8) & ~MDNS_DOMAIN_COMPRESS_MARK)) && // Valid offset - (_write16((sizeof(uint16_t /*Prio*/) + // RDLength - sizeof(uint16_t /*Weight*/) + - sizeof(uint16_t /*Port*/) + - 2), - p_rSendParameter)) && // Length of 'C0xx' - (_write16(MDNS_SRV_PRIORITY, p_rSendParameter)) && // Priority - (_write16(MDNS_SRV_WEIGHT, p_rSendParameter)) && // Weight - (_write16(p_rService.m_u16Port, p_rSendParameter)) && // Port - (_write8(((u16CachedDomainOffset >> 8) | MDNS_DOMAIN_COMPRESS_MARK), p_rSendParameter)) && // Compression mark (and offset) - (_write8((uint8_t)u16CachedDomainOffset, p_rSendParameter))))); // Offset - - DEBUG_EX_ERR(if (!bResult) - { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_SRV: FAILED!\n")); - }); - return bResult; -} + bool MDNSResponder::_writeMDNSAnswer_SRV(MDNSResponder::stcMDNSService& p_rService, + MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + { + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_SRV\n"));); + + uint16_t u16CachedDomainOffset = (p_rSendParameter.m_bLegacyQuery + ? 0 + : p_rSendParameter.findCachedDomainOffset((const void*)m_pcHostname, false)); + + stcMDNS_RRAttributes attributes(DNS_RRTYPE_SRV, + ((p_rSendParameter.m_bCacheFlush ? 0x8000 : 0) | DNS_RRCLASS_IN)); // Cache flush? & INternet + stcMDNS_RRDomain hostDomain; + bool bResult = ((_writeMDNSServiceDomain(p_rService, true, false, p_rSendParameter)) && // MyESP._http._tcp.local + (_writeMDNSRRAttributes(attributes, p_rSendParameter)) && // TYPE & CLASS + (_write32((p_rSendParameter.m_bUnannounce ? 0 : MDNS_SERVICE_TTL), p_rSendParameter)) && // TTL + (!u16CachedDomainOffset + // No cache for domain name (or no compression allowed) + ? ((_buildDomainForHost(m_pcHostname, hostDomain)) && (_write16((sizeof(uint16_t /*Prio*/) + // RDLength + sizeof(uint16_t /*Weight*/) + sizeof(uint16_t /*Port*/) + hostDomain.m_u16NameLength), + p_rSendParameter)) + && // Domain length + (_write16(MDNS_SRV_PRIORITY, p_rSendParameter)) && // Priority + (_write16(MDNS_SRV_WEIGHT, p_rSendParameter)) && // Weight + (_write16(p_rService.m_u16Port, p_rSendParameter)) && // Port + (p_rSendParameter.addDomainCacheItem((const void*)m_pcHostname, false, p_rSendParameter.m_u16Offset)) && (_writeMDNSRRDomain(hostDomain, p_rSendParameter))) // Host, eg. esp8266.local + // Cache available for domain + : ((MDNS_DOMAIN_COMPRESS_MARK > ((u16CachedDomainOffset >> 8) & ~MDNS_DOMAIN_COMPRESS_MARK)) && // Valid offset + (_write16((sizeof(uint16_t /*Prio*/) + // RDLength + sizeof(uint16_t /*Weight*/) + sizeof(uint16_t /*Port*/) + 2), + p_rSendParameter)) + && // Length of 'C0xx' + (_write16(MDNS_SRV_PRIORITY, p_rSendParameter)) && // Priority + (_write16(MDNS_SRV_WEIGHT, p_rSendParameter)) && // Weight + (_write16(p_rService.m_u16Port, p_rSendParameter)) && // Port + (_write8(((u16CachedDomainOffset >> 8) | MDNS_DOMAIN_COMPRESS_MARK), p_rSendParameter)) && // Compression mark (and offset) + (_write8((uint8_t)u16CachedDomainOffset, p_rSendParameter))))); // Offset + + DEBUG_EX_ERR(if (!bResult) + { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_SRV: FAILED!\n")); + }); + return bResult; + } } // namespace MDNSImplementation diff --git a/libraries/I2S/examples/InputSerialPlotter/InputSerialPlotter.ino b/libraries/I2S/examples/InputSerialPlotter/InputSerialPlotter.ino index 713440d73f..16139c5d22 100644 --- a/libraries/I2S/examples/InputSerialPlotter/InputSerialPlotter.ino +++ b/libraries/I2S/examples/InputSerialPlotter/InputSerialPlotter.ino @@ -21,7 +21,8 @@ void setup() { // start I2S at 8 kHz with 24-bits per sample if (!I2S.begin(I2S_PHILIPS_MODE, 8000, 24)) { Serial.println("Failed to initialize I2S!"); - while (1); // do nothing + while (1) + ; // do nothing } } diff --git a/libraries/I2S/examples/SimpleTone/SimpleTone.ino b/libraries/I2S/examples/SimpleTone/SimpleTone.ino index 6959ae74ba..5825ba12ca 100644 --- a/libraries/I2S/examples/SimpleTone/SimpleTone.ino +++ b/libraries/I2S/examples/SimpleTone/SimpleTone.ino @@ -26,7 +26,8 @@ void setup() { // start I2S at the sample rate with 16-bits per sample if (!I2S.begin(I2S_PHILIPS_MODE, sampleRate, 16)) { Serial.println("Failed to initialize I2S!"); - while (1); // do nothing + while (1) + ; // do nothing } } @@ -43,4 +44,3 @@ void loop() { // increment the counter for the next sample count++; } - diff --git a/libraries/LittleFS/examples/LittleFS_Timestamp/LittleFS_Timestamp.ino b/libraries/LittleFS/examples/LittleFS_Timestamp/LittleFS_Timestamp.ino index 40e02087dc..b7a2f0c5e4 100644 --- a/libraries/LittleFS/examples/LittleFS_Timestamp/LittleFS_Timestamp.ino +++ b/libraries/LittleFS/examples/LittleFS_Timestamp/LittleFS_Timestamp.ino @@ -9,17 +9,16 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char *ssid = STASSID; -const char *pass = STAPSK; +const char* ssid = STASSID; +const char* pass = STAPSK; long timezone = 2; byte daysavetime = 1; - -void listDir(const char * dirname) { +void listDir(const char* dirname) { Serial.printf("Listing directory: %s\n", dirname); Dir root = LittleFS.openDir(dirname); @@ -33,15 +32,14 @@ void listDir(const char * dirname) { time_t cr = file.getCreationTime(); time_t lw = file.getLastWrite(); file.close(); - struct tm * tmstruct = localtime(&cr); + struct tm* tmstruct = localtime(&cr); Serial.printf(" CREATION: %d-%02d-%02d %02d:%02d:%02d\n", (tmstruct->tm_year) + 1900, (tmstruct->tm_mon) + 1, tmstruct->tm_mday, tmstruct->tm_hour, tmstruct->tm_min, tmstruct->tm_sec); tmstruct = localtime(&lw); Serial.printf(" LAST WRITE: %d-%02d-%02d %02d:%02d:%02d\n", (tmstruct->tm_year) + 1900, (tmstruct->tm_mon) + 1, tmstruct->tm_mday, tmstruct->tm_hour, tmstruct->tm_min, tmstruct->tm_sec); } } - -void readFile(const char * path) { +void readFile(const char* path) { Serial.printf("Reading file: %s\n", path); File file = LittleFS.open(path, "r"); @@ -57,7 +55,7 @@ void readFile(const char * path) { file.close(); } -void writeFile(const char * path, const char * message) { +void writeFile(const char* path, const char* message) { Serial.printf("Writing file: %s\n", path); File file = LittleFS.open(path, "w"); @@ -74,7 +72,7 @@ void writeFile(const char * path, const char * message) { file.close(); } -void appendFile(const char * path, const char * message) { +void appendFile(const char* path, const char* message) { Serial.printf("Appending to file: %s\n", path); File file = LittleFS.open(path, "a"); @@ -90,7 +88,7 @@ void appendFile(const char * path, const char * message) { file.close(); } -void renameFile(const char * path1, const char * path2) { +void renameFile(const char* path1, const char* path2) { Serial.printf("Renaming file %s to %s\n", path1, path2); if (LittleFS.rename(path1, path2)) { Serial.println("File renamed"); @@ -99,7 +97,7 @@ void renameFile(const char * path1, const char * path2) { } } -void deleteFile(const char * path) { +void deleteFile(const char* path) { Serial.printf("Deleting file: %s\n", path); if (LittleFS.remove(path)) { Serial.println("File deleted"); @@ -127,7 +125,7 @@ void setup() { Serial.println(WiFi.localIP()); Serial.println("Contacting Time Server"); configTime(3600 * timezone, daysavetime * 3600, "time.nist.gov", "0.pool.ntp.org", "1.pool.ntp.org"); - struct tm tmstruct ; + struct tm tmstruct; delay(2000); tmstruct.tm_year = 0; getLocalTime(&tmstruct, 5000); @@ -158,9 +156,6 @@ void setup() { } readFile("/hello.txt"); listDir("/"); - - } void loop() { } - diff --git a/libraries/LittleFS/examples/SpeedTest/SpeedTest.ino b/libraries/LittleFS/examples/SpeedTest/SpeedTest.ino index 35e0ac66e6..1c631e309c 100644 --- a/libraries/LittleFS/examples/SpeedTest/SpeedTest.ino +++ b/libraries/LittleFS/examples/SpeedTest/SpeedTest.ino @@ -15,7 +15,7 @@ #define TESTSIZEKB 512 // Format speed in bytes/second. Static buffer so not re-entrant safe -const char *rate(unsigned long start, unsigned long stop, unsigned long bytes) { +const char* rate(unsigned long start, unsigned long stop, unsigned long bytes) { static char buff[64]; if (stop == start) { strcpy_P(buff, PSTR("Inf b/s")); @@ -33,7 +33,7 @@ const char *rate(unsigned long start, unsigned long stop, unsigned long bytes) { return buff; } -void DoTest(FS *fs) { +void DoTest(FS* fs) { if (!fs->format()) { Serial.printf("Unable to format(), aborting\n"); return; @@ -45,7 +45,7 @@ void DoTest(FS *fs) { uint8_t data[256]; for (int i = 0; i < 256; i++) { - data[i] = (uint8_t) i; + data[i] = (uint8_t)i; } Serial.printf("Creating %dKB file, may take a while...\n", TESTSIZEKB); @@ -133,7 +133,6 @@ void DoTest(FS *fs) { stop = millis(); Serial.printf("==> Time to read 64KB in 1b chunks = %lu milliseconds = %s\n", stop - start, rate(start, stop, 65536)); - start = millis(); auto dest = fs->open("/test1bw.bin", "w"); f = fs->open("/test1b.bin", "r"); diff --git a/libraries/Netdump/examples/Netdump/Netdump.ino b/libraries/Netdump/examples/Netdump/Netdump.ino index dbba63869b..0251fe2fd1 100644 --- a/libraries/Netdump/examples/Netdump/Netdump.ino +++ b/libraries/Netdump/examples/Netdump/Netdump.ino @@ -12,7 +12,7 @@ using namespace NetCapture; #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* ssid = STASSID; @@ -23,9 +23,9 @@ Netdump nd; //FS* filesystem = &SPIFFS; FS* filesystem = &LittleFS; -ESP8266WebServer webServer(80); // Used for sending commands -WiFiServer tcpServer(8000); // Used to show netcat option. -File tracefile; +ESP8266WebServer webServer(80); // Used for sending commands +WiFiServer tcpServer(8000); // Used to show netcat option. +File tracefile; std::map packetCount; @@ -37,25 +37,23 @@ enum class SerialOption : uint8_t { void startSerial(SerialOption option) { switch (option) { - case SerialOption::AllFull : //All Packets, show packet summary. + case SerialOption::AllFull: //All Packets, show packet summary. nd.printDump(Serial, Packet::PacketDetail::FULL); break; - case SerialOption::LocalNone : // Only local IP traffic, full details + case SerialOption::LocalNone: // Only local IP traffic, full details nd.printDump(Serial, Packet::PacketDetail::NONE, - [](Packet n) { - return (n.hasIP(WiFi.localIP())); - } - ); + [](Packet n) { + return (n.hasIP(WiFi.localIP())); + }); break; - case SerialOption::HTTPChar : // Only HTTP traffic, show packet content as chars + case SerialOption::HTTPChar: // Only HTTP traffic, show packet content as chars nd.printDump(Serial, Packet::PacketDetail::CHAR, - [](Packet n) { - return (n.isHTTP()); - } - ); + [](Packet n) { + return (n.isHTTP()); + }); break; - default : + default: Serial.printf("No valid SerialOption provided\r\n"); }; } @@ -92,32 +90,29 @@ void setup(void) { filesystem->begin(); webServer.on("/list", - []() { - Dir dir = filesystem->openDir("/"); - String d = "

      File list

      "; - while (dir.next()) { - d.concat("
    2. " + dir.fileName() + "
    3. "); - } - webServer.send(200, "text.html", d); - } - ); + []() { + Dir dir = filesystem->openDir("/"); + String d = "

      File list

      "; + while (dir.next()) { + d.concat("
    4. " + dir.fileName() + "
    5. "); + } + webServer.send(200, "text.html", d); + }); webServer.on("/req", - []() { - static int rq = 0; - String a = "

      You are connected, Number of requests = " + String(rq++) + "

      "; - webServer.send(200, "text/html", a); - } - ); + []() { + static int rq = 0; + String a = "

      You are connected, Number of requests = " + String(rq++) + "

      "; + webServer.send(200, "text/html", a); + }); webServer.on("/reset", - []() { - nd.reset(); - tracefile.close(); - tcpServer.close(); - webServer.send(200, "text.html", "

      Netdump session reset

      "); - } - ); + []() { + nd.reset(); + tracefile.close(); + tcpServer.close(); + webServer.send(200, "text.html", "

      Netdump session reset

      "); + }); webServer.serveStatic("/", *filesystem, "/"); webServer.begin(); @@ -153,4 +148,3 @@ void loop(void) { webServer.handleClient(); MDNS.update(); } - diff --git a/libraries/Netdump/src/Netdump.cpp b/libraries/Netdump/src/Netdump.cpp index 9e688f3ca7..57898f0ee1 100644 --- a/libraries/Netdump/src/Netdump.cpp +++ b/libraries/Netdump/src/Netdump.cpp @@ -68,16 +68,16 @@ void Netdump::printDump(Print& out, Packet::PacketDetail ndd, const Filter nf) { out.printf_P(PSTR("netDump starting\r\n")); setCallback([&out, ndd, this](const Packet& ndp) - { printDumpProcess(out, ndd, ndp); }, - nf); + { printDumpProcess(out, ndd, ndp); }, + nf); } void Netdump::fileDump(File& outfile, const Filter nf) { writePcapHeader(outfile); setCallback([&outfile, this](const Packet& ndp) - { fileDumpProcess(outfile, ndp); }, - nf); + { fileDumpProcess(outfile, ndp); }, + nf); } bool Netdump::tcpDump(WiFiServer& tcpDumpServer, const Filter nf) { @@ -93,7 +93,7 @@ bool Netdump::tcpDump(WiFiServer& tcpDumpServer, const Filter nf) bufferIndex = 0; schedule_function([&tcpDumpServer, this, nf]() - { tcpDumpLoop(tcpDumpServer, nf); }); + { tcpDumpLoop(tcpDumpServer, nf); }); return true; } @@ -192,8 +192,8 @@ void Netdump::tcpDumpLoop(WiFiServer& tcpDumpServer, const Filter nf) writePcapHeader(tcpDumpClient); setCallback([this](const Packet& ndp) - { tcpDumpProcess(ndp); }, - nf); + { tcpDumpProcess(ndp); }, + nf); } if (!tcpDumpClient || !tcpDumpClient.connected()) { @@ -208,7 +208,7 @@ void Netdump::tcpDumpLoop(WiFiServer& tcpDumpServer, const Filter nf) if (tcpDumpServer.status() != CLOSED) { schedule_function([&tcpDumpServer, this, nf]() - { tcpDumpLoop(tcpDumpServer, nf); }); + { tcpDumpLoop(tcpDumpServer, nf); }); } } diff --git a/libraries/Netdump/src/Netdump.h b/libraries/Netdump/src/Netdump.h index 2dead84551..34457b6e9b 100644 --- a/libraries/Netdump/src/Netdump.h +++ b/libraries/Netdump/src/Netdump.h @@ -36,7 +36,7 @@ using namespace experimental::CBListImplentation; class Netdump { - public: +public: using Filter = std::function; using Callback = std::function; using LwipCallback = std::function; @@ -53,7 +53,7 @@ class Netdump void fileDump(File& outfile, const Filter nf = nullptr); bool tcpDump(WiFiServer& tcpDumpServer, const Filter nf = nullptr); - private: +private: Callback netDumpCallback = nullptr; Filter netDumpFilter = nullptr; diff --git a/libraries/Netdump/src/NetdumpIP.cpp b/libraries/Netdump/src/NetdumpIP.cpp index f90113f47b..dd8c657111 100644 --- a/libraries/Netdump/src/NetdumpIP.cpp +++ b/libraries/Netdump/src/NetdumpIP.cpp @@ -294,39 +294,39 @@ bool NetdumpIP::compareIP(const IPAddress& ip) const { switch (ipv) { - case IPversion::UNSET: - if (ip.isSet()) - { - return false; - } - else - { - return true; - } - break; - case IPversion::IPV4: - if (ip.isV6() || !ip.isSet()) - { - return false; - } - else - { - return compareRaw(IPversion::IPV4, rawip, reinterpret_cast(&ip.v4())); - } - break; - case IPversion::IPV6: - if (ip.isV4() || !ip.isSet()) - { - return false; - } - else - { - return compareRaw(IPversion::IPV6, rawip, reinterpret_cast(ip.raw6())); - } - break; - default: + case IPversion::UNSET: + if (ip.isSet()) + { + return false; + } + else + { + return true; + } + break; + case IPversion::IPV4: + if (ip.isV6() || !ip.isSet()) + { + return false; + } + else + { + return compareRaw(IPversion::IPV4, rawip, reinterpret_cast(&ip.v4())); + } + break; + case IPversion::IPV6: + if (ip.isV4() || !ip.isSet()) + { return false; - break; + } + else + { + return compareRaw(IPversion::IPV6, rawip, reinterpret_cast(ip.raw6())); + } + break; + default: + return false; + break; } } @@ -334,39 +334,39 @@ bool NetdumpIP::compareIP(const NetdumpIP& nip) const { switch (ipv) { - case IPversion::UNSET: - if (nip.isSet()) - { - return false; - } - else - { - return true; - } - break; - case IPversion::IPV4: - if (nip.isV6() || !nip.isSet()) - { - return false; - } - else - { - return compareRaw(IPversion::IPV4, rawip, nip.rawip); - } - break; - case IPversion::IPV6: - if (nip.isV4() || !nip.isSet()) - { - return false; - } - else - { - return compareRaw(IPversion::IPV6, rawip, nip.rawip); - } - break; - default: + case IPversion::UNSET: + if (nip.isSet()) + { + return false; + } + else + { + return true; + } + break; + case IPversion::IPV4: + if (nip.isV6() || !nip.isSet()) + { + return false; + } + else + { + return compareRaw(IPversion::IPV4, rawip, nip.rawip); + } + break; + case IPversion::IPV6: + if (nip.isV4() || !nip.isSet()) + { return false; - break; + } + else + { + return compareRaw(IPversion::IPV6, rawip, nip.rawip); + } + break; + default: + return false; + break; } } diff --git a/libraries/Netdump/src/NetdumpIP.h b/libraries/Netdump/src/NetdumpIP.h index bf93c7c940..41b1677869 100644 --- a/libraries/Netdump/src/NetdumpIP.h +++ b/libraries/Netdump/src/NetdumpIP.h @@ -17,7 +17,7 @@ namespace NetCapture { class NetdumpIP { - public: +public: NetdumpIP(); NetdumpIP(uint8_t first_octet, uint8_t second_octet, uint8_t third_octet, uint8_t fourth_octet); @@ -34,7 +34,7 @@ class NetdumpIP String toString(); - private: +private: enum class IPversion { UNSET, @@ -43,7 +43,7 @@ class NetdumpIP }; IPversion ipv = IPversion::UNSET; - uint8_t rawip[16] = {0}; + uint8_t rawip[16] = { 0 }; void setV4() { @@ -83,7 +83,7 @@ class NetdumpIP size_t printTo(Print& p); - public: +public: bool operator==(const IPAddress& addr) const { return compareIP(addr); diff --git a/libraries/Netdump/src/NetdumpPacket.cpp b/libraries/Netdump/src/NetdumpPacket.cpp index 0af8292bb2..e3243cc887 100644 --- a/libraries/Netdump/src/NetdumpPacket.cpp +++ b/libraries/Netdump/src/NetdumpPacket.cpp @@ -164,13 +164,13 @@ void Packet::ARPtoString(PacketDetail netdumpDetail, StreamString& sstr) const { switch (getARPType()) { - case 1: - sstr.printf_P(PSTR("who has %s tell %s"), getIP(ETH_HDR_LEN + 24).toString().c_str(), getIP(ETH_HDR_LEN + 14).toString().c_str()); - break; - case 2: - sstr.printf_P(PSTR("%s is at "), getIP(ETH_HDR_LEN + 14).toString().c_str()); - MACtoString(ETH_HDR_LEN + 8, sstr); - break; + case 1: + sstr.printf_P(PSTR("who has %s tell %s"), getIP(ETH_HDR_LEN + 24).toString().c_str(), getIP(ETH_HDR_LEN + 14).toString().c_str()); + break; + case 2: + sstr.printf_P(PSTR("%s is at "), getIP(ETH_HDR_LEN + 14).toString().c_str()); + MACtoString(ETH_HDR_LEN + 8, sstr); + break; } sstr.printf("\r\n"); printDetail(sstr, PSTR(" D "), &data[ETH_HDR_LEN], packetLength - ETH_HDR_LEN, netdumpDetail); @@ -237,36 +237,36 @@ void Packet::ICMPtoString(PacketDetail, StreamString& sstr) const { switch (getIcmpType()) { - case 0: - sstr.printf_P(PSTR("ping reply")); - break; - case 8: - sstr.printf_P(PSTR("ping request")); - break; - default: - sstr.printf_P(PSTR("type(0x%02x)"), getIcmpType()); - break; + case 0: + sstr.printf_P(PSTR("ping reply")); + break; + case 8: + sstr.printf_P(PSTR("ping request")); + break; + default: + sstr.printf_P(PSTR("type(0x%02x)"), getIcmpType()); + break; } } if (isIPv6()) { switch (getIcmpType()) { - case 129: - sstr.printf_P(PSTR("ping reply")); - break; - case 128: - sstr.printf_P(PSTR("ping request")); - break; - case 135: - sstr.printf_P(PSTR("Neighbour solicitation")); - break; - case 136: - sstr.printf_P(PSTR("Neighbour advertisement")); - break; - default: - sstr.printf_P(PSTR("type(0x%02x)"), getIcmpType()); - break; + case 129: + sstr.printf_P(PSTR("ping reply")); + break; + case 128: + sstr.printf_P(PSTR("ping request")); + break; + case 135: + sstr.printf_P(PSTR("Neighbour solicitation")); + break; + case 136: + sstr.printf_P(PSTR("Neighbour advertisement")); + break; + default: + sstr.printf_P(PSTR("type(0x%02x)"), getIcmpType()); + break; } } sstr.printf_P(PSTR("\r\n")); @@ -276,42 +276,42 @@ void Packet::IGMPtoString(PacketDetail, StreamString& sstr) const { switch (getIgmpType()) { - case 1: - sstr.printf_P(PSTR("Create Group Request")); - break; - case 2: - sstr.printf_P(PSTR("Create Group Reply")); - break; - case 3: - sstr.printf_P(PSTR("Join Group Request")); - break; - case 4: - sstr.printf_P(PSTR("Join Group Reply")); - break; - case 5: - sstr.printf_P(PSTR("Leave Group Request")); - break; - case 6: - sstr.printf_P(PSTR("Leave Group Reply")); - break; - case 7: - sstr.printf_P(PSTR("Confirm Group Request")); - break; - case 8: - sstr.printf_P(PSTR("Confirm Group Reply")); - break; - case 0x11: - sstr.printf_P(PSTR("Group Membership Query")); - break; - case 0x12: - sstr.printf_P(PSTR("IGMPv1 Membership Report")); - break; - case 0x22: - sstr.printf_P(PSTR("IGMPv3 Membership Report")); - break; - default: - sstr.printf_P(PSTR("type(0x%02x)"), getIgmpType()); - break; + case 1: + sstr.printf_P(PSTR("Create Group Request")); + break; + case 2: + sstr.printf_P(PSTR("Create Group Reply")); + break; + case 3: + sstr.printf_P(PSTR("Join Group Request")); + break; + case 4: + sstr.printf_P(PSTR("Join Group Reply")); + break; + case 5: + sstr.printf_P(PSTR("Leave Group Request")); + break; + case 6: + sstr.printf_P(PSTR("Leave Group Reply")); + break; + case 7: + sstr.printf_P(PSTR("Confirm Group Request")); + break; + case 8: + sstr.printf_P(PSTR("Confirm Group Reply")); + break; + case 0x11: + sstr.printf_P(PSTR("Group Membership Query")); + break; + case 0x12: + sstr.printf_P(PSTR("IGMPv1 Membership Report")); + break; + case 0x22: + sstr.printf_P(PSTR("IGMPv3 Membership Report")); + break; + default: + sstr.printf_P(PSTR("type(0x%02x)"), getIgmpType()); + break; } sstr.printf_P(PSTR("\r\n")); } @@ -359,60 +359,60 @@ const String Packet::toString(PacketDetail netdumpDetail) const switch (thisPacketType) { - case PacketType::ARP: - { - ARPtoString(netdumpDetail, sstr); - break; - } - case PacketType::MDNS: - case PacketType::DNS: - { - DNStoString(netdumpDetail, sstr); - break; - } - case PacketType::SSDP: - case PacketType::DHCP: - case PacketType::WSDD: - case PacketType::NETBIOS: - case PacketType::SMB: - case PacketType::OTA: - case PacketType::UDP: - { - UDPtoString(netdumpDetail, sstr); - break; - } - case PacketType::TCP: - case PacketType::HTTP: - { - TCPtoString(netdumpDetail, sstr); - break; - } - case PacketType::ICMP: - { - ICMPtoString(netdumpDetail, sstr); - break; - } - case PacketType::IGMP: - { - IGMPtoString(netdumpDetail, sstr); - break; - } - case PacketType::IPv4: - case PacketType::IPv6: - { - IPtoString(netdumpDetail, sstr); - break; - } - case PacketType::UKNW: - { - UKNWtoString(netdumpDetail, sstr); - break; - } - default: - { - sstr.printf_P(PSTR("Non identified packet\r\n")); - break; - } + case PacketType::ARP: + { + ARPtoString(netdumpDetail, sstr); + break; + } + case PacketType::MDNS: + case PacketType::DNS: + { + DNStoString(netdumpDetail, sstr); + break; + } + case PacketType::SSDP: + case PacketType::DHCP: + case PacketType::WSDD: + case PacketType::NETBIOS: + case PacketType::SMB: + case PacketType::OTA: + case PacketType::UDP: + { + UDPtoString(netdumpDetail, sstr); + break; + } + case PacketType::TCP: + case PacketType::HTTP: + { + TCPtoString(netdumpDetail, sstr); + break; + } + case PacketType::ICMP: + { + ICMPtoString(netdumpDetail, sstr); + break; + } + case PacketType::IGMP: + { + IGMPtoString(netdumpDetail, sstr); + break; + } + case PacketType::IPv4: + case PacketType::IPv6: + { + IPtoString(netdumpDetail, sstr); + break; + } + case PacketType::UKNW: + { + UKNWtoString(netdumpDetail, sstr); + break; + } + default: + { + sstr.printf_P(PSTR("Non identified packet\r\n")); + break; + } } return sstr; } diff --git a/libraries/Netdump/src/NetdumpPacket.h b/libraries/Netdump/src/NetdumpPacket.h index f143ea832e..7d4aabf4dc 100644 --- a/libraries/Netdump/src/NetdumpPacket.h +++ b/libraries/Netdump/src/NetdumpPacket.h @@ -35,9 +35,14 @@ int constexpr ETH_HDR_LEN = 14; class Packet { - public: +public: Packet(unsigned long msec, int n, const char* d, size_t l, int o, int s) - : packetTime(msec), netif_idx(n), data(d), packetLength(l), out(o), success(s) + : packetTime(msec) + , netif_idx(n) + , data(d) + , packetLength(l) + , out(o) + , success(s) { setPacketTypes(); }; @@ -281,7 +286,7 @@ class Packet const PacketType packetType() const; const std::vector& allPacketTypes() const; - private: +private: void setPacketType(PacketType); void setPacketTypes(); diff --git a/libraries/Netdump/src/PacketType.cpp b/libraries/Netdump/src/PacketType.cpp index 05bf35a9f6..b2d6f84e75 100644 --- a/libraries/Netdump/src/PacketType.cpp +++ b/libraries/Netdump/src/PacketType.cpp @@ -17,44 +17,44 @@ String PacketType::toString() const { switch (ptype) { - case PType::ARP: - return PSTR("ARP"); - case PType::IP: - return PSTR("IP"); - case PType::UDP: - return PSTR("UDP"); - case PType::MDNS: - return PSTR("MDNS"); - case PType::DNS: - return PSTR("DNS"); - case PType::SSDP: - return PSTR("SSDP"); - case PType::DHCP: - return PSTR("DHCP"); - case PType::WSDD: - return PSTR("WSDD"); - case PType::NETBIOS: - return PSTR("NBIO"); - case PType::SMB: - return PSTR("SMB"); - case PType::OTA: - return PSTR("OTA"); - case PType::TCP: - return PSTR("TCP"); - case PType::HTTP: - return PSTR("HTTP"); - case PType::ICMP: - return PSTR("ICMP"); - case PType::IGMP: - return PSTR("IGMP"); - case PType::IPv4: - return PSTR("IPv4"); - case PType::IPv6: - return PSTR("IPv6"); - case PType::UKNW: - return PSTR("UKNW"); - default: - return PSTR("ERR"); + case PType::ARP: + return PSTR("ARP"); + case PType::IP: + return PSTR("IP"); + case PType::UDP: + return PSTR("UDP"); + case PType::MDNS: + return PSTR("MDNS"); + case PType::DNS: + return PSTR("DNS"); + case PType::SSDP: + return PSTR("SSDP"); + case PType::DHCP: + return PSTR("DHCP"); + case PType::WSDD: + return PSTR("WSDD"); + case PType::NETBIOS: + return PSTR("NBIO"); + case PType::SMB: + return PSTR("SMB"); + case PType::OTA: + return PSTR("OTA"); + case PType::TCP: + return PSTR("TCP"); + case PType::HTTP: + return PSTR("HTTP"); + case PType::ICMP: + return PSTR("ICMP"); + case PType::IGMP: + return PSTR("IGMP"); + case PType::IPv4: + return PSTR("IPv4"); + case PType::IPv6: + return PSTR("IPv6"); + case PType::UKNW: + return PSTR("UKNW"); + default: + return PSTR("ERR"); }; } diff --git a/libraries/Netdump/src/PacketType.h b/libraries/Netdump/src/PacketType.h index c819f15511..36a5593ead 100644 --- a/libraries/Netdump/src/PacketType.h +++ b/libraries/Netdump/src/PacketType.h @@ -13,7 +13,7 @@ namespace NetCapture { class PacketType { - public: +public: enum PType : int { ARP, @@ -38,7 +38,7 @@ class PacketType PacketType(); PacketType(PType pt) - : ptype(pt){}; + : ptype(pt) {}; operator PType() const { @@ -51,7 +51,7 @@ class PacketType String toString() const; - private: +private: PType ptype; }; diff --git a/libraries/SD/examples/Datalogger/Datalogger.ino b/libraries/SD/examples/Datalogger/Datalogger.ino index a023b63821..d75a2e1c8e 100644 --- a/libraries/SD/examples/Datalogger/Datalogger.ino +++ b/libraries/SD/examples/Datalogger/Datalogger.ino @@ -69,12 +69,3 @@ void loop() { Serial.println("error opening datalog.txt"); } } - - - - - - - - - diff --git a/libraries/SD/examples/DumpFile/DumpFile.ino b/libraries/SD/examples/DumpFile/DumpFile.ino index 3574652890..038cfc1c01 100644 --- a/libraries/SD/examples/DumpFile/DumpFile.ino +++ b/libraries/SD/examples/DumpFile/DumpFile.ino @@ -58,4 +58,3 @@ void setup() { void loop() { } - diff --git a/libraries/SD/examples/Files/Files.ino b/libraries/SD/examples/Files/Files.ino index 1c1b83ec20..f162837dcf 100644 --- a/libraries/SD/examples/Files/Files.ino +++ b/libraries/SD/examples/Files/Files.ino @@ -66,6 +66,3 @@ void setup() { void loop() { // nothing happens after setup finishes. } - - - diff --git a/libraries/SD/examples/ReadWrite/ReadWrite.ino b/libraries/SD/examples/ReadWrite/ReadWrite.ino index 7aa9a40c4b..680bb33296 100644 --- a/libraries/SD/examples/ReadWrite/ReadWrite.ino +++ b/libraries/SD/examples/ReadWrite/ReadWrite.ino @@ -71,5 +71,3 @@ void setup() { void loop() { // nothing happens after setup } - - diff --git a/libraries/SD/examples/listfiles/listfiles.ino b/libraries/SD/examples/listfiles/listfiles.ino index 55478d7080..a1de460672 100644 --- a/libraries/SD/examples/listfiles/listfiles.ino +++ b/libraries/SD/examples/listfiles/listfiles.ino @@ -52,8 +52,8 @@ void loop() { void printDirectory(File dir, int numTabs) { while (true) { - File entry = dir.openNextFile(); - if (! entry) { + File entry = dir.openNextFile(); + if (!entry) { // no more files break; } @@ -70,7 +70,7 @@ void printDirectory(File dir, int numTabs) { Serial.print(entry.size(), DEC); time_t cr = entry.getCreationTime(); time_t lw = entry.getLastWrite(); - struct tm * tmstruct = localtime(&cr); + struct tm* tmstruct = localtime(&cr); Serial.printf("\tCREATION: %d-%02d-%02d %02d:%02d:%02d", (tmstruct->tm_year) + 1900, (tmstruct->tm_mon) + 1, tmstruct->tm_mday, tmstruct->tm_hour, tmstruct->tm_min, tmstruct->tm_sec); tmstruct = localtime(&lw); Serial.printf("\tLAST WRITE: %d-%02d-%02d %02d:%02d:%02d\n", (tmstruct->tm_year) + 1900, (tmstruct->tm_mon) + 1, tmstruct->tm_mday, tmstruct->tm_hour, tmstruct->tm_min, tmstruct->tm_sec); diff --git a/libraries/SPISlave/examples/SPISlave_Master/SPISlave_Master.ino b/libraries/SPISlave/examples/SPISlave_Master/SPISlave_Master.ino index 528e52ed81..a564b3c027 100644 --- a/libraries/SPISlave/examples/SPISlave_Master/SPISlave_Master.ino +++ b/libraries/SPISlave/examples/SPISlave_Master/SPISlave_Master.ino @@ -18,72 +18,74 @@ class ESPMaster { private: - uint8_t _ss_pin; + uint8_t _ss_pin; public: - ESPMaster(uint8_t pin): _ss_pin(pin) {} - void begin() { - pinMode(_ss_pin, OUTPUT); - digitalWrite(_ss_pin, HIGH); - } + ESPMaster(uint8_t pin) + : _ss_pin(pin) { + } + void begin() { + pinMode(_ss_pin, OUTPUT); + digitalWrite(_ss_pin, HIGH); + } - uint32_t readStatus() { - digitalWrite(_ss_pin, LOW); - SPI.transfer(0x04); - uint32_t status = (SPI.transfer(0) | ((uint32_t)(SPI.transfer(0)) << 8) | ((uint32_t)(SPI.transfer(0)) << 16) | ((uint32_t)(SPI.transfer(0)) << 24)); - digitalWrite(_ss_pin, HIGH); - return status; - } + uint32_t readStatus() { + digitalWrite(_ss_pin, LOW); + SPI.transfer(0x04); + uint32_t status = (SPI.transfer(0) | ((uint32_t)(SPI.transfer(0)) << 8) | ((uint32_t)(SPI.transfer(0)) << 16) | ((uint32_t)(SPI.transfer(0)) << 24)); + digitalWrite(_ss_pin, HIGH); + return status; + } - void writeStatus(uint32_t status) { - digitalWrite(_ss_pin, LOW); - SPI.transfer(0x01); - SPI.transfer(status & 0xFF); - SPI.transfer((status >> 8) & 0xFF); - SPI.transfer((status >> 16) & 0xFF); - SPI.transfer((status >> 24) & 0xFF); - digitalWrite(_ss_pin, HIGH); - } + void writeStatus(uint32_t status) { + digitalWrite(_ss_pin, LOW); + SPI.transfer(0x01); + SPI.transfer(status & 0xFF); + SPI.transfer((status >> 8) & 0xFF); + SPI.transfer((status >> 16) & 0xFF); + SPI.transfer((status >> 24) & 0xFF); + digitalWrite(_ss_pin, HIGH); + } - void readData(uint8_t * data) { - digitalWrite(_ss_pin, LOW); - SPI.transfer(0x03); - SPI.transfer(0x00); - for (uint8_t i = 0; i < 32; i++) { - data[i] = SPI.transfer(0); - } - digitalWrite(_ss_pin, HIGH); + void readData(uint8_t* data) { + digitalWrite(_ss_pin, LOW); + SPI.transfer(0x03); + SPI.transfer(0x00); + for (uint8_t i = 0; i < 32; i++) { + data[i] = SPI.transfer(0); } + digitalWrite(_ss_pin, HIGH); + } - void writeData(uint8_t * data, size_t len) { - uint8_t i = 0; - digitalWrite(_ss_pin, LOW); - SPI.transfer(0x02); - SPI.transfer(0x00); - while (len-- && i < 32) { - SPI.transfer(data[i++]); - } - while (i++ < 32) { - SPI.transfer(0); - } - digitalWrite(_ss_pin, HIGH); + void writeData(uint8_t* data, size_t len) { + uint8_t i = 0; + digitalWrite(_ss_pin, LOW); + SPI.transfer(0x02); + SPI.transfer(0x00); + while (len-- && i < 32) { + SPI.transfer(data[i++]); } - - String readData() { - char data[33]; - data[32] = 0; - readData((uint8_t *)data); - return String(data); + while (i++ < 32) { + SPI.transfer(0); } + digitalWrite(_ss_pin, HIGH); + } - void writeData(const char * data) { - writeData((uint8_t *)data, strlen(data)); - } + String readData() { + char data[33]; + data[32] = 0; + readData((uint8_t*)data); + return String(data); + } + + void writeData(const char* data) { + writeData((uint8_t*)data, strlen(data)); + } }; ESPMaster esp(SS); -void send(const char * message) { +void send(const char* message) { Serial.print("Master: "); Serial.println(message); esp.writeData(message); diff --git a/libraries/SPISlave/examples/SPISlave_SafeMaster/SPISlave_SafeMaster.ino b/libraries/SPISlave/examples/SPISlave_SafeMaster/SPISlave_SafeMaster.ino index 04c23c4502..6019e5fb54 100644 --- a/libraries/SPISlave/examples/SPISlave_SafeMaster/SPISlave_SafeMaster.ino +++ b/libraries/SPISlave/examples/SPISlave_SafeMaster/SPISlave_SafeMaster.ino @@ -19,76 +19,79 @@ class ESPSafeMaster { private: - uint8_t _ss_pin; - void _pulseSS() { - digitalWrite(_ss_pin, HIGH); - delayMicroseconds(5); - digitalWrite(_ss_pin, LOW); - } + uint8_t _ss_pin; + void _pulseSS() { + digitalWrite(_ss_pin, HIGH); + delayMicroseconds(5); + digitalWrite(_ss_pin, LOW); + } + public: - ESPSafeMaster(uint8_t pin): _ss_pin(pin) {} - void begin() { - pinMode(_ss_pin, OUTPUT); - _pulseSS(); - } + ESPSafeMaster(uint8_t pin) + : _ss_pin(pin) { + } + void begin() { + pinMode(_ss_pin, OUTPUT); + _pulseSS(); + } - uint32_t readStatus() { - _pulseSS(); - SPI.transfer(0x04); - uint32_t status = (SPI.transfer(0) | ((uint32_t)(SPI.transfer(0)) << 8) | ((uint32_t)(SPI.transfer(0)) << 16) | ((uint32_t)(SPI.transfer(0)) << 24)); - _pulseSS(); - return status; - } + uint32_t readStatus() { + _pulseSS(); + SPI.transfer(0x04); + uint32_t status = (SPI.transfer(0) | ((uint32_t)(SPI.transfer(0)) << 8) | ((uint32_t)(SPI.transfer(0)) << 16) | ((uint32_t)(SPI.transfer(0)) << 24)); + _pulseSS(); + return status; + } - void writeStatus(uint32_t status) { - _pulseSS(); - SPI.transfer(0x01); - SPI.transfer(status & 0xFF); - SPI.transfer((status >> 8) & 0xFF); - SPI.transfer((status >> 16) & 0xFF); - SPI.transfer((status >> 24) & 0xFF); - _pulseSS(); - } + void writeStatus(uint32_t status) { + _pulseSS(); + SPI.transfer(0x01); + SPI.transfer(status & 0xFF); + SPI.transfer((status >> 8) & 0xFF); + SPI.transfer((status >> 16) & 0xFF); + SPI.transfer((status >> 24) & 0xFF); + _pulseSS(); + } - void readData(uint8_t * data) { - _pulseSS(); - SPI.transfer(0x03); - SPI.transfer(0x00); - for (uint8_t i = 0; i < 32; i++) { - data[i] = SPI.transfer(0); - } - _pulseSS(); + void readData(uint8_t* data) { + _pulseSS(); + SPI.transfer(0x03); + SPI.transfer(0x00); + for (uint8_t i = 0; i < 32; i++) { + data[i] = SPI.transfer(0); } + _pulseSS(); + } - void writeData(uint8_t * data, size_t len) { - uint8_t i = 0; - _pulseSS(); - SPI.transfer(0x02); - SPI.transfer(0x00); - while (len-- && i < 32) { - SPI.transfer(data[i++]); - } - while (i++ < 32) { - SPI.transfer(0); - } - _pulseSS(); + void writeData(uint8_t* data, size_t len) { + uint8_t i = 0; + _pulseSS(); + SPI.transfer(0x02); + SPI.transfer(0x00); + while (len-- && i < 32) { + SPI.transfer(data[i++]); } - - String readData() { - char data[33]; - data[32] = 0; - readData((uint8_t *)data); - return String(data); + while (i++ < 32) { + SPI.transfer(0); } + _pulseSS(); + } - void writeData(const char * data) { - writeData((uint8_t *)data, strlen(data)); - } + String readData() { + char data[33]; + data[32] = 0; + readData((uint8_t*)data); + return String(data); + } + + void writeData(const char* data) { + writeData((uint8_t*)data, strlen(data)); + } }; ESPSafeMaster esp(SS); -void send(const char * message) { +void send(const char* message) { Serial.print("Master: "); Serial.println(message); esp.writeData(message); diff --git a/libraries/SPISlave/examples/SPISlave_Test/SPISlave_Test.ino b/libraries/SPISlave/examples/SPISlave_Test/SPISlave_Test.ino index 0be83fd298..f8b29a220d 100644 --- a/libraries/SPISlave/examples/SPISlave_Test/SPISlave_Test.ino +++ b/libraries/SPISlave/examples/SPISlave_Test/SPISlave_Test.ino @@ -24,9 +24,9 @@ void setup() { // data has been received from the master. Beware that len is always 32 // and the buffer is autofilled with zeroes if data is less than 32 bytes long // It's up to the user to implement protocol for handling data length - SPISlave.onData([](uint8_t * data, size_t len) { - String message = String((char *)data); - (void) len; + SPISlave.onData([](uint8_t* data, size_t len) { + String message = String((char*)data); + (void)len; if (message.equals("Hello Slave!")) { SPISlave.setData("Hello Master!"); } else if (message.equals("Are you alive?")) { @@ -36,7 +36,7 @@ void setup() { } else { SPISlave.setData("Say what?"); } - Serial.printf("Question: %s\n", (char *)data); + Serial.printf("Question: %s\n", (char*)data); }); // The master has read out outgoing data buffer @@ -69,4 +69,4 @@ void setup() { SPISlave.setData("Ask me a question!"); } -void loop() {} +void loop() { } diff --git a/libraries/Servo/examples/Sweep/Sweep.ino b/libraries/Servo/examples/Sweep/Sweep.ino index 5a6bd6ef40..dd5453e647 100644 --- a/libraries/Servo/examples/Sweep/Sweep.ino +++ b/libraries/Servo/examples/Sweep/Sweep.ino @@ -12,12 +12,11 @@ #include -Servo myservo; // create servo object to control a servo +Servo myservo; // create servo object to control a servo // twelve servo objects can be created on most boards - void setup() { - myservo.attach(2); // attaches the servo on GIO2 to the servo object + myservo.attach(2); // attaches the servo on GIO2 to the servo object } void loop() { @@ -25,12 +24,11 @@ void loop() { for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees // in steps of 1 degree - myservo.write(pos); // tell servo to go to position in variable 'pos' - delay(15); // waits 15ms for the servo to reach the position + myservo.write(pos); // tell servo to go to position in variable 'pos' + delay(15); // waits 15ms for the servo to reach the position } for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees - myservo.write(pos); // tell servo to go to position in variable 'pos' - delay(15); // waits 15ms for the servo to reach the position + myservo.write(pos); // tell servo to go to position in variable 'pos' + delay(15); // waits 15ms for the servo to reach the position } } - diff --git a/libraries/TFT_Touch_Shield_V2/examples/drawCircle/drawCircle.ino b/libraries/TFT_Touch_Shield_V2/examples/drawCircle/drawCircle.ino index fbc22a861c..68b44cdd50 100644 --- a/libraries/TFT_Touch_Shield_V2/examples/drawCircle/drawCircle.ino +++ b/libraries/TFT_Touch_Shield_V2/examples/drawCircle/drawCircle.ino @@ -8,21 +8,20 @@ #include void setup() { - TFT_BL_ON; //turn on the background light + TFT_BL_ON; //turn on the background light - Tft.TFTinit(); //init TFT library + Tft.TFTinit(); //init TFT library - Tft.drawCircle(100, 100, 30, YELLOW); //center: (100, 100), r = 30 ,color : YELLOW + Tft.drawCircle(100, 100, 30, YELLOW); //center: (100, 100), r = 30 ,color : YELLOW - Tft.drawCircle(100, 200, 40, CYAN); // center: (100, 200), r = 10 ,color : CYAN + Tft.drawCircle(100, 200, 40, CYAN); // center: (100, 200), r = 10 ,color : CYAN - Tft.fillCircle(200, 100, 30, RED); //center: (200, 100), r = 30 ,color : RED + Tft.fillCircle(200, 100, 30, RED); //center: (200, 100), r = 30 ,color : RED - Tft.fillCircle(200, 200, 30, BLUE); //center: (200, 200), r = 30 ,color : BLUE + Tft.fillCircle(200, 200, 30, BLUE); //center: (200, 200), r = 30 ,color : BLUE } void loop() { - } /********************************************************************************************************* diff --git a/libraries/TFT_Touch_Shield_V2/examples/drawLines/drawLines.ino b/libraries/TFT_Touch_Shield_V2/examples/drawLines/drawLines.ino index a777044d3e..b89aa5a09a 100644 --- a/libraries/TFT_Touch_Shield_V2/examples/drawLines/drawLines.ino +++ b/libraries/TFT_Touch_Shield_V2/examples/drawLines/drawLines.ino @@ -8,20 +8,19 @@ #include #include void setup() { - TFT_BL_ON; // turn on the background light - Tft.TFTinit(); //init TFT library + TFT_BL_ON; // turn on the background light + Tft.TFTinit(); //init TFT library - Tft.drawLine(0, 0, 239, 319, RED); //start: (0, 0) end: (239, 319), color : RED + Tft.drawLine(0, 0, 239, 319, RED); //start: (0, 0) end: (239, 319), color : RED - Tft.drawVerticalLine(60, 100, 100, GREEN); // Draw a vertical line + Tft.drawVerticalLine(60, 100, 100, GREEN); // Draw a vertical line // start: (60, 100) length: 100 color: green - Tft.drawHorizontalLine(30, 60, 150, BLUE); //Draw a horizontal line + Tft.drawHorizontalLine(30, 60, 150, BLUE); //Draw a horizontal line //start: (30, 60), high: 150, color: blue } void loop() { - } /********************************************************************************************************* diff --git a/libraries/TFT_Touch_Shield_V2/examples/drawNumber/drawNumber.ino b/libraries/TFT_Touch_Shield_V2/examples/drawNumber/drawNumber.ino index ed62233796..ff94d9c587 100644 --- a/libraries/TFT_Touch_Shield_V2/examples/drawNumber/drawNumber.ino +++ b/libraries/TFT_Touch_Shield_V2/examples/drawNumber/drawNumber.ino @@ -9,28 +9,26 @@ #include void setup() { - TFT_BL_ON; // turn on the background light + TFT_BL_ON; // turn on the background light - Tft.TFTinit(); // init TFT library + Tft.TFTinit(); // init TFT library - Tft.drawNumber(1024, 0, 0, 1, RED); // draw a integer: 1024, Location: (0, 0), size: 1, color: RED + Tft.drawNumber(1024, 0, 0, 1, RED); // draw a integer: 1024, Location: (0, 0), size: 1, color: RED - Tft.drawNumber(1024, 0, 20, 2, BLUE); // draw a integer: 1024, Location: (0, 20), size: 2, color: BLUE + Tft.drawNumber(1024, 0, 20, 2, BLUE); // draw a integer: 1024, Location: (0, 20), size: 2, color: BLUE - Tft.drawNumber(1024, 0, 50, 3, GREEN); // draw a integer: 1024, Location: (0, 50), size: 3, color: GREEN + Tft.drawNumber(1024, 0, 50, 3, GREEN); // draw a integer: 1024, Location: (0, 50), size: 3, color: GREEN - Tft.drawNumber(1024, 0, 90, 4, BLUE); // draw a integer: 1024, Location: (0, 90), size:4, color: BLUE + Tft.drawNumber(1024, 0, 90, 4, BLUE); // draw a integer: 1024, Location: (0, 90), size:4, color: BLUE - Tft.drawFloat(1.2345, 0, 150, 4, YELLOW); // draw a float number: 1.2345, Location: (0, 150), size: 4, color: YELLOW + Tft.drawFloat(1.2345, 0, 150, 4, YELLOW); // draw a float number: 1.2345, Location: (0, 150), size: 4, color: YELLOW - Tft.drawFloat(1.2345, 2, 0, 200, 4, BLUE); // draw a float number: 1.2345: Location: (0, 200), size: 4, decimal: 2, color: BLUE - - Tft.drawFloat(1.2345, 4, 0, 250, 4, RED); // draw a float number: 1.2345 Location: (0, 250), size: 4, decimal: 4, color: RED + Tft.drawFloat(1.2345, 2, 0, 200, 4, BLUE); // draw a float number: 1.2345: Location: (0, 200), size: 4, decimal: 2, color: BLUE + Tft.drawFloat(1.2345, 4, 0, 250, 4, RED); // draw a float number: 1.2345 Location: (0, 250), size: 4, decimal: 4, color: RED } void loop() { - } /********************************************************************************************************* diff --git a/libraries/TFT_Touch_Shield_V2/examples/drawRectangle/drawRectangle.ino b/libraries/TFT_Touch_Shield_V2/examples/drawRectangle/drawRectangle.ino index a2d7af8709..f7d7c91b8d 100644 --- a/libraries/TFT_Touch_Shield_V2/examples/drawRectangle/drawRectangle.ino +++ b/libraries/TFT_Touch_Shield_V2/examples/drawRectangle/drawRectangle.ino @@ -8,8 +8,8 @@ #include void setup() { - TFT_BL_ON; // turn on the background light - Tft.TFTinit(); // init TFT library + TFT_BL_ON; // turn on the background light + Tft.TFTinit(); // init TFT library Tft.fillScreen(80, 160, 50, 150, RED); Tft.fillRectangle(30, 120, 100, 65, YELLOW); @@ -17,7 +17,6 @@ void setup() { } void loop() { - } /********************************************************************************************************* END FILE diff --git a/libraries/TFT_Touch_Shield_V2/examples/paint/paint.ino b/libraries/TFT_Touch_Shield_V2/examples/paint/paint.ino index dc13088b9f..4774becf60 100644 --- a/libraries/TFT_Touch_Shield_V2/examples/paint/paint.ino +++ b/libraries/TFT_Touch_Shield_V2/examples/paint/paint.ino @@ -5,8 +5,8 @@ #include int ColorPaletteHigh = 30; -int color = WHITE; //Paint brush color -unsigned int colors[8] = {BLACK, RED, GREEN, BLUE, CYAN, YELLOW, WHITE, GRAY1}; +int color = WHITE; //Paint brush color +unsigned int colors[8] = { BLACK, RED, GREEN, BLUE, CYAN, YELLOW, WHITE, GRAY1 }; // For better pressure precision, we need to know the resistance // between X+ and X- Use any multimeter to read it @@ -15,7 +15,7 @@ unsigned int colors[8] = {BLACK, RED, GREEN, BLUE, CYAN, YELLOW, WHITE, GRAY1}; TouchScreen ts = TouchScreen(XP, YP, XM, YM); //init TouchScreen port pins void setup() { - Tft.TFTinit(); //init TFT library + Tft.TFTinit(); //init TFT library Serial.begin(115200); //Draw the pallet for (int i = 0; i < 8; i++) { diff --git a/libraries/TFT_Touch_Shield_V2/examples/shapes/shapes.ino b/libraries/TFT_Touch_Shield_V2/examples/shapes/shapes.ino index 6607a01cff..f6b2eee5b4 100644 --- a/libraries/TFT_Touch_Shield_V2/examples/shapes/shapes.ino +++ b/libraries/TFT_Touch_Shield_V2/examples/shapes/shapes.ino @@ -5,13 +5,13 @@ #include void setup() { - TFT_BL_ON; // turn on the background light - Tft.TFTinit(); // init TFT library + TFT_BL_ON; // turn on the background light + Tft.TFTinit(); // init TFT library } void loop() { - for (int r = 0; r < 115; r = r + 2) { //set r : 0--115 - Tft.drawCircle(119, 160, r, random(0xFFFF)); //draw circle, center:(119, 160), color: random + for (int r = 0; r < 115; r = r + 2) { //set r : 0--115 + Tft.drawCircle(119, 160, r, random(0xFFFF)); //draw circle, center:(119, 160), color: random } delay(10); } diff --git a/libraries/TFT_Touch_Shield_V2/examples/text/text.ino b/libraries/TFT_Touch_Shield_V2/examples/text/text.ino index 03308f6891..d35f100d5c 100644 --- a/libraries/TFT_Touch_Shield_V2/examples/text/text.ino +++ b/libraries/TFT_Touch_Shield_V2/examples/text/text.ino @@ -8,26 +8,23 @@ #include void setup() { - TFT_BL_ON; // turn on the background light - Tft.TFTinit(); // init TFT library + TFT_BL_ON; // turn on the background light + Tft.TFTinit(); // init TFT library - Tft.drawChar('S', 0, 0, 1, RED); // draw char: 'S', (0, 0), size: 1, color: RED + Tft.drawChar('S', 0, 0, 1, RED); // draw char: 'S', (0, 0), size: 1, color: RED - Tft.drawChar('E', 10, 10, 2, BLUE); // draw char: 'E', (10, 10), size: 2, color: BLUE + Tft.drawChar('E', 10, 10, 2, BLUE); // draw char: 'E', (10, 10), size: 2, color: BLUE - Tft.drawChar('E', 20, 40, 3, GREEN); // draw char: 'E', (20, 40), size: 3, color: GREEN + Tft.drawChar('E', 20, 40, 3, GREEN); // draw char: 'E', (20, 40), size: 3, color: GREEN - Tft.drawChar('E', 30, 80, 4, YELLOW); // draw char: 'E', (30, 80), size: 4, color: YELLOW + Tft.drawChar('E', 30, 80, 4, YELLOW); // draw char: 'E', (30, 80), size: 4, color: YELLOW - Tft.drawChar('D', 40, 120, 4, YELLOW); // draw char: 'D', (40, 120), size: 4, color: YELLOW + Tft.drawChar('D', 40, 120, 4, YELLOW); // draw char: 'D', (40, 120), size: 4, color: YELLOW - Tft.drawString("Hello", 0, 180, 3, CYAN); // draw string: "hello", (0, 180), size: 3, color: CYAN + Tft.drawString("Hello", 0, 180, 3, CYAN); // draw string: "hello", (0, 180), size: 3, color: CYAN Tft.drawString("World!!", 60, 220, 4, WHITE); // draw string: "world!!", (80, 230), size: 4, color: WHITE - - } void loop() { - } diff --git a/libraries/TFT_Touch_Shield_V2/examples/tftbmp/tftbmp.ino b/libraries/TFT_Touch_Shield_V2/examples/tftbmp/tftbmp.ino index 49d39fee3b..6ee5238abd 100644 --- a/libraries/TFT_Touch_Shield_V2/examples/tftbmp/tftbmp.ino +++ b/libraries/TFT_Touch_Shield_V2/examples/tftbmp/tftbmp.ino @@ -16,30 +16,27 @@ #include "TFTv2.h" -#define MAX_BMP 10 // bmp file num -#define FILENAME_LEN 20 // max file name length +#define MAX_BMP 10 // bmp file num +#define FILENAME_LEN 20 // max file name length +const int PIN_SD_CS = 4; // pin of sd card -const int PIN_SD_CS = 4; // pin of sd card +const int __Gnbmp_height = 320; // bmp height +const int __Gnbmp_width = 240; // bmp width -const int __Gnbmp_height = 320; // bmp height -const int __Gnbmp_width = 240; // bmp width +unsigned char __Gnbmp_image_offset = 0; // offset -unsigned char __Gnbmp_image_offset = 0; // offset +int __Gnfile_num = 3; // num of file - -int __Gnfile_num = 3; // num of file - -char __Gsbmp_files[3][FILENAME_LEN] = { // add file name here +char __Gsbmp_files[3][FILENAME_LEN] = { + // add file name here "flower.BMP", "hibiscus.bmp", "test.bmp", }; - File bmpFile; - void setup() { Serial.begin(115200); @@ -54,7 +51,8 @@ void setup() { if (!SD.begin(PIN_SD_CS)) { Serial.println("failed!"); - while (1); // init fail, die here + while (1) + ; // init fail, die here } Serial.println("SD OK!"); @@ -65,12 +63,13 @@ void setup() { void loop() { for (unsigned char i = 0; i < __Gnfile_num; i++) { bmpFile = SD.open(__Gsbmp_files[i]); - if (! bmpFile) { + if (!bmpFile) { Serial.println("didn't find image"); - while (1); + while (1) + ; } - if (! bmpReadHeader(bmpFile)) { + if (!bmpReadHeader(bmpFile)) { Serial.println("bad bmp"); return; } @@ -80,7 +79,6 @@ void loop() { delay(1000); } - } /*********************************************/ @@ -90,15 +88,15 @@ void loop() { // more RAM but makes the drawing a little faster. 20 pixels' worth // is probably a good place -#define BUFFPIXEL 60 // must be a divisor of 240 -#define BUFFPIXEL_X3 180 // BUFFPIXELx3 +#define BUFFPIXEL 60 // must be a divisor of 240 +#define BUFFPIXEL_X3 180 // BUFFPIXELx3 void bmpdraw(File f, int x, int y) { bmpFile.seek(__Gnbmp_image_offset); uint32_t time = millis(); - uint8_t sdbuffer[BUFFPIXEL_X3]; // 3 * pixels to buffer + uint8_t sdbuffer[BUFFPIXEL_X3]; // 3 * pixels to buffer for (int i = 0; i < __Gnbmp_height; i++) { @@ -110,7 +108,7 @@ void bmpdraw(File f, int x, int y) { unsigned int __color[BUFFPIXEL]; for (int k = 0; k < BUFFPIXEL; k++) { - __color[k] = sdbuffer[buffidx + 2] >> 3; // read + __color[k] = sdbuffer[buffidx + 2] >> 3; // read __color[k] = __color[k] << 6 | (sdbuffer[buffidx + 1] >> 2); // green __color[k] = __color[k] << 5 | (sdbuffer[buffidx + 0] >> 3); // blue @@ -131,7 +129,6 @@ void bmpdraw(File f, int x, int y) { TFT_CS_HIGH; } - } Serial.print(millis() - time, DEC); @@ -165,11 +162,10 @@ boolean bmpReadHeader(File f) { Serial.print("header size "); Serial.println(tmp, DEC); - int bmp_width = read32(f); int bmp_height = read32(f); - if (bmp_width != __Gnbmp_width || bmp_height != __Gnbmp_height) { // if image is not 320x240, return false + if (bmp_width != __Gnbmp_width || bmp_height != __Gnbmp_height) { // if image is not 320x240, return false return false; } diff --git a/libraries/TFT_Touch_Shield_V2/examples/tftbmp2/tftbmp2.ino b/libraries/TFT_Touch_Shield_V2/examples/tftbmp2/tftbmp2.ino index 03423a4ef5..0e91c67ce4 100644 --- a/libraries/TFT_Touch_Shield_V2/examples/tftbmp2/tftbmp2.ino +++ b/libraries/TFT_Touch_Shield_V2/examples/tftbmp2/tftbmp2.ino @@ -18,23 +18,24 @@ #include "TFTv2.h" -#define MAX_BMP 10 // bmp file num -#define FILENAME_LEN 20 // max file name length +#define MAX_BMP 10 // bmp file num +#define FILENAME_LEN 20 // max file name length -const int PIN_SD_CS = 4; // pin of sd card +const int PIN_SD_CS = 4; // pin of sd card -const long __Gnbmp_height = 320; // bmp height -const long __Gnbmp_width = 240; // bmp width +const long __Gnbmp_height = 320; // bmp height +const long __Gnbmp_width = 240; // bmp width -long __Gnbmp_image_offset = 0;; +long __Gnbmp_image_offset = 0; +; -int __Gnfile_num = 0; // num of file -char __Gsbmp_files[MAX_BMP][FILENAME_LEN]; // file name +int __Gnfile_num = 0; // num of file +char __Gsbmp_files[MAX_BMP][FILENAME_LEN]; // file name File bmpFile; // if bmp file return 1, else return 0 -bool checkBMP(char *_name, char r_name[]) { +bool checkBMP(char* _name, char r_name[]) { int len = 0; if (NULL == _name) { @@ -55,29 +56,28 @@ bool checkBMP(char *_name, char r_name[]) { } // if xxx.bmp or xxx.BMP - if (r_name[len - 4] == '.' \ - && (r_name[len - 3] == 'b' || (r_name[len - 3] == 'B')) \ - && (r_name[len - 2] == 'm' || (r_name[len - 2] == 'M')) \ + if (r_name[len - 4] == '.' + && (r_name[len - 3] == 'b' || (r_name[len - 3] == 'B')) + && (r_name[len - 2] == 'm' || (r_name[len - 2] == 'M')) && (r_name[len - 1] == 'p' || (r_name[len - 1] == 'P'))) { return true; } return false; - } // search root to find bmp file void searchDirectory() { - File root = SD.open("/"); // root + File root = SD.open("/"); // root while (true) { - File entry = root.openNextFile(); + File entry = root.openNextFile(); - if (! entry) { + if (!entry) { break; } if (!entry.isDirectory()) { - char *ptmp = entry.name(); + char* ptmp = entry.name(); char __Name[20]; @@ -99,7 +99,6 @@ void searchDirectory() { } } - void setup() { Serial.begin(115200); @@ -114,7 +113,8 @@ void setup() { if (!SD.begin(PIN_SD_CS)) { Serial.println("failed!"); - while (1); // init fail, die here + while (1) + ; // init fail, die here } Serial.println("SD OK!"); @@ -150,15 +150,15 @@ void loop() { } */ - bmpFile = SD.open("pfvm_1.bmp"); - if (! bmpFile) { + if (!bmpFile) { Serial.println("didn't find image"); - while (1); + while (1) + ; } - if (! bmpReadHeader(bmpFile)) { + if (!bmpReadHeader(bmpFile)) { Serial.println("bad bmp"); return; } @@ -166,7 +166,8 @@ void loop() { bmpdraw(bmpFile, 0, 0, 1); bmpFile.close(); - while (1); + while (1) + ; } /*********************************************/ @@ -176,12 +177,11 @@ void loop() { // more RAM but makes the drawing a little faster. 20 pixels' worth // is probably a good place -#define BUFFPIXEL 60 // must be a divisor of 240 -#define BUFFPIXEL_X3 180 // BUFFPIXELx3 +#define BUFFPIXEL 60 // must be a divisor of 240 +#define BUFFPIXEL_X3 180 // BUFFPIXELx3 - -#define UP_DOWN 1 -#define DOWN_UP 0 +#define UP_DOWN 1 +#define DOWN_UP 0 // dir - 1: up to down // dir - 2: down to up @@ -194,7 +194,7 @@ void bmpdraw(File f, int x, int y, int dir) { uint32_t time = millis(); - uint8_t sdbuffer[BUFFPIXEL_X3]; // 3 * pixels to buffer + uint8_t sdbuffer[BUFFPIXEL_X3]; // 3 * pixels to buffer for (int i = 0; i < __Gnbmp_height; i++) { if (dir) { @@ -210,7 +210,7 @@ void bmpdraw(File f, int x, int y, int dir) { unsigned int __color[BUFFPIXEL]; for (int k = 0; k < BUFFPIXEL; k++) { - __color[k] = sdbuffer[buffidx + 2] >> 3; // read + __color[k] = sdbuffer[buffidx + 2] >> 3; // read __color[k] = __color[k] << 6 | (sdbuffer[buffidx + 1] >> 2); // green __color[k] = __color[k] << 5 | (sdbuffer[buffidx + 0] >> 3); // blue @@ -239,7 +239,6 @@ void bmpdraw(File f, int x, int y, int dir) { TFT_CS_HIGH; } - } Serial.print(millis() - time, DEC); @@ -276,7 +275,7 @@ boolean bmpReadHeader(File f) { int bmp_width = read32(f); int bmp_height = read32(f); - if (bmp_width != __Gnbmp_width || bmp_height != __Gnbmp_height) { // if image is not 320x240, return false + if (bmp_width != __Gnbmp_width || bmp_height != __Gnbmp_height) { // if image is not 320x240, return false return false; } diff --git a/libraries/Ticker/examples/TickerBasic/TickerBasic.ino b/libraries/Ticker/examples/TickerBasic/TickerBasic.ino index 2fabd98315..0eed169ee2 100644 --- a/libraries/Ticker/examples/TickerBasic/TickerBasic.ino +++ b/libraries/Ticker/examples/TickerBasic/TickerBasic.ino @@ -19,8 +19,8 @@ Ticker flipper; int count = 0; void flip() { - int state = digitalRead(LED_BUILTIN); // get the current state of GPIO1 pin - digitalWrite(LED_BUILTIN, !state); // set pin to the opposite state + int state = digitalRead(LED_BUILTIN); // get the current state of GPIO1 pin + digitalWrite(LED_BUILTIN, !state); // set pin to the opposite state ++count; // when the counter reaches a certain value, start blinking like crazy diff --git a/libraries/Ticker/examples/TickerFunctional/TickerFunctional.ino b/libraries/Ticker/examples/TickerFunctional/TickerFunctional.ino index 33c9435982..970bf7235a 100644 --- a/libraries/Ticker/examples/TickerFunctional/TickerFunctional.ino +++ b/libraries/Ticker/examples/TickerFunctional/TickerFunctional.ino @@ -1,27 +1,28 @@ #include "Arduino.h" #include "Ticker.h" -#define LED1 2 -#define LED2 4 -#define LED3 12 -#define LED4 14 -#define LED5 15 - +#define LED1 2 +#define LED2 4 +#define LED3 12 +#define LED4 14 +#define LED5 15 class ExampleClass { public: - ExampleClass(int pin, int duration) : _pin(pin), _duration(duration) { - pinMode(_pin, OUTPUT); - _myTicker.attach_ms(_duration, std::bind(&ExampleClass::classBlink, this)); - } - ~ExampleClass() {}; - - int _pin, _duration; - Ticker _myTicker; - - void classBlink() { - digitalWrite(_pin, !digitalRead(_pin)); - } + ExampleClass(int pin, int duration) + : _pin(pin) + , _duration(duration) { + pinMode(_pin, OUTPUT); + _myTicker.attach_ms(_duration, std::bind(&ExampleClass::classBlink, this)); + } + ~ExampleClass() {}; + + int _pin, _duration; + Ticker _myTicker; + + void classBlink() { + digitalWrite(_pin, !digitalRead(_pin)); + } }; void staticBlink() { @@ -43,7 +44,6 @@ Ticker lambdaTicker; ExampleClass example(LED1, 100); - void setup() { pinMode(LED2, OUTPUT); staticTicker.attach_ms(100, staticBlink); diff --git a/libraries/Wire/Wire.cpp b/libraries/Wire/Wire.cpp index 495978b421..592bbb08c4 100644 --- a/libraries/Wire/Wire.cpp +++ b/libraries/Wire/Wire.cpp @@ -58,7 +58,7 @@ static int default_scl_pin = SCL; // Constructors //////////////////////////////////////////////////////////////// -TwoWire::TwoWire() {} +TwoWire::TwoWire() { } // Public Methods ////////////////////////////////////////////////////////////// diff --git a/libraries/Wire/Wire.h b/libraries/Wire/Wire.h index 626087a4b2..1b2a00b908 100644 --- a/libraries/Wire/Wire.h +++ b/libraries/Wire/Wire.h @@ -35,7 +35,7 @@ class TwoWire : public Stream { - private: +private: static uint8_t rxBuffer[]; static size_t rxBufferIndex; static size_t rxBufferLength; @@ -51,7 +51,7 @@ class TwoWire : public Stream static void onRequestService(void); static void onReceiveService(uint8_t*, size_t); - public: +public: TwoWire(); void begin(int sda, int scl); void begin(int sda, int scl, uint8_t address); diff --git a/libraries/Wire/examples/master_reader/master_reader.ino b/libraries/Wire/examples/master_reader/master_reader.ino index 323830f847..bc464d529a 100644 --- a/libraries/Wire/examples/master_reader/master_reader.ino +++ b/libraries/Wire/examples/master_reader/master_reader.ino @@ -8,7 +8,6 @@ // This example code is in the public domain. - #include #include @@ -18,8 +17,8 @@ const int16_t I2C_MASTER = 0x42; const int16_t I2C_SLAVE = 0x08; void setup() { - Serial.begin(115200); // start serial for output - Wire.begin(SDA_PIN, SCL_PIN, I2C_MASTER); // join i2c bus (address optional for master) + Serial.begin(115200); // start serial for output + Wire.begin(SDA_PIN, SCL_PIN, I2C_MASTER); // join i2c bus (address optional for master) } void loop() { @@ -27,11 +26,11 @@ void loop() { static periodic nextPing(1000); if (nextPing) { - Wire.requestFrom(I2C_SLAVE, 6); // request 6 bytes from slave device #8 + Wire.requestFrom(I2C_SLAVE, 6); // request 6 bytes from slave device #8 while (Wire.available()) { // slave may send less than requested char c = Wire.read(); // receive a byte as character - Serial.print(c); // print the character + Serial.print(c); // print the character } } } diff --git a/libraries/Wire/examples/master_writer/master_writer.ino b/libraries/Wire/examples/master_writer/master_writer.ino index 1e9719e23c..d19edbd27a 100644 --- a/libraries/Wire/examples/master_writer/master_writer.ino +++ b/libraries/Wire/examples/master_writer/master_writer.ino @@ -8,7 +8,6 @@ // This example code is in the public domain. - #include #include @@ -29,9 +28,9 @@ void loop() { if (nextPing) { Wire.beginTransmission(I2C_SLAVE); // transmit to device #8 - Wire.write("x is "); // sends five bytes - Wire.write(x); // sends one byte - Wire.endTransmission(); // stop transmitting + Wire.write("x is "); // sends five bytes + Wire.write(x); // sends one byte + Wire.endTransmission(); // stop transmitting x++; } diff --git a/libraries/Wire/examples/slave_receiver/slave_receiver.ino b/libraries/Wire/examples/slave_receiver/slave_receiver.ino index 270cc43129..812ed0e385 100644 --- a/libraries/Wire/examples/slave_receiver/slave_receiver.ino +++ b/libraries/Wire/examples/slave_receiver/slave_receiver.ino @@ -8,7 +8,6 @@ // This example code is in the public domain. - #include #define SDA_PIN 4 @@ -18,7 +17,7 @@ const int16_t I2C_MASTER = 0x42; const int16_t I2C_SLAVE = 0x08; void setup() { - Serial.begin(115200); // start serial for output + Serial.begin(115200); // start serial for output Wire.begin(SDA_PIN, SCL_PIN, I2C_SLAVE); // new syntax: join i2c bus (address required for slave) Wire.onReceive(receiveEvent); // register event @@ -31,11 +30,11 @@ void loop() { // this function is registered as an event, see setup() void receiveEvent(size_t howMany) { - (void) howMany; + (void)howMany; while (1 < Wire.available()) { // loop through all but the last char c = Wire.read(); // receive byte as a character - Serial.print(c); // print the character + Serial.print(c); // print the character } - int x = Wire.read(); // receive byte as an integer - Serial.println(x); // print the integer + int x = Wire.read(); // receive byte as an integer + Serial.println(x); // print the integer } diff --git a/libraries/Wire/examples/slave_sender/slave_sender.ino b/libraries/Wire/examples/slave_sender/slave_sender.ino index e177be8538..31bfbc40e3 100644 --- a/libraries/Wire/examples/slave_sender/slave_sender.ino +++ b/libraries/Wire/examples/slave_sender/slave_sender.ino @@ -8,7 +8,6 @@ // This example code is in the public domain. - #include #define SDA_PIN 4 @@ -17,7 +16,7 @@ const int16_t I2C_MASTER = 0x42; const int16_t I2C_SLAVE = 0x08; void setup() { - Wire.begin(SDA_PIN, SCL_PIN, I2C_SLAVE); // join i2c bus with address #8 + Wire.begin(SDA_PIN, SCL_PIN, I2C_SLAVE); // join i2c bus with address #8 Wire.onRequest(requestEvent); // register event } diff --git a/libraries/esp8266/examples/Blink/Blink.ino b/libraries/esp8266/examples/Blink/Blink.ino index de23fb519f..cf7d4c55e4 100644 --- a/libraries/esp8266/examples/Blink/Blink.ino +++ b/libraries/esp8266/examples/Blink/Blink.ino @@ -10,15 +10,15 @@ */ void setup() { - pinMode(LED_BUILTIN, OUTPUT); // Initialize the LED_BUILTIN pin as an output + pinMode(LED_BUILTIN, OUTPUT); // Initialize the LED_BUILTIN pin as an output } // the loop function runs over and over again forever void loop() { - digitalWrite(LED_BUILTIN, LOW); // Turn the LED on (Note that LOW is the voltage level + digitalWrite(LED_BUILTIN, LOW); // Turn the LED on (Note that LOW is the voltage level // but actually the LED is on; this is because // it is active low on the ESP-01) - delay(1000); // Wait for a second - digitalWrite(LED_BUILTIN, HIGH); // Turn the LED off by making the voltage HIGH - delay(2000); // Wait for two seconds (to demonstrate the active low LED) + delay(1000); // Wait for a second + digitalWrite(LED_BUILTIN, HIGH); // Turn the LED off by making the voltage HIGH + delay(2000); // Wait for two seconds (to demonstrate the active low LED) } diff --git a/libraries/esp8266/examples/BlinkPolledTimeout/BlinkPolledTimeout.ino b/libraries/esp8266/examples/BlinkPolledTimeout/BlinkPolledTimeout.ino index 11e2aff482..304c27d384 100644 --- a/libraries/esp8266/examples/BlinkPolledTimeout/BlinkPolledTimeout.ino +++ b/libraries/esp8266/examples/BlinkPolledTimeout/BlinkPolledTimeout.ino @@ -22,22 +22,20 @@ Note that this sketch uses LED_BUILTIN to find the pin with the internal LED */ - #include void ledOn() { - digitalWrite(LED_BUILTIN, LOW); // Turn the LED on (Note that LOW is the voltage level + digitalWrite(LED_BUILTIN, LOW); // Turn the LED on (Note that LOW is the voltage level } void ledOff() { - digitalWrite(LED_BUILTIN, HIGH); // Turn the LED off by making the voltage HIGH + digitalWrite(LED_BUILTIN, HIGH); // Turn the LED off by making the voltage HIGH } void ledToggle() { - digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); // Change the state of the LED + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); // Change the state of the LED } - esp8266::polledTimeout::periodicFastUs halfPeriod(500000); //use fully qualified type and avoid importing all ::esp8266 namespace to the global namespace // the setup function runs only once at start @@ -57,7 +55,7 @@ void setup() { Serial.printf("periodic/oneShotFastNs::rangeCompensate = %u\n", (uint32_t)esp8266::polledTimeout::periodicFastNs::rangeCompensate); #endif - pinMode(LED_BUILTIN, OUTPUT); // Initialize the LED_BUILTIN pin as an output + pinMode(LED_BUILTIN, OUTPUT); // Initialize the LED_BUILTIN pin as an output using esp8266::polledTimeout::oneShotMs; //import the type to the local namespace @@ -83,7 +81,6 @@ void setup() { halfPeriod.reset(); //halfPeriod is global, so it gets inited on sketch start. Clear it here to make it ready for loop, where it's actually used. } - // the loop function runs over and over again forever void loop() { if (halfPeriod) { diff --git a/libraries/esp8266/examples/BlinkWithoutDelay/BlinkWithoutDelay.ino b/libraries/esp8266/examples/BlinkWithoutDelay/BlinkWithoutDelay.ino index 24689f3a44..a1af7aab53 100644 --- a/libraries/esp8266/examples/BlinkWithoutDelay/BlinkWithoutDelay.ino +++ b/libraries/esp8266/examples/BlinkWithoutDelay/BlinkWithoutDelay.ino @@ -24,9 +24,9 @@ void loop() { if (currentMillis - previousMillis >= interval) { previousMillis = currentMillis; if (ledState == LOW) { - ledState = HIGH; // Note that this switches the LED *off* + ledState = HIGH; // Note that this switches the LED *off* } else { - ledState = LOW; // Note that this switches the LED *on* + ledState = LOW; // Note that this switches the LED *on* } digitalWrite(LED_BUILTIN, ledState); } diff --git a/libraries/esp8266/examples/CallBackList/CallBackGeneric.ino b/libraries/esp8266/examples/CallBackList/CallBackGeneric.ino index ce4dac2470..b4aff127fb 100644 --- a/libraries/esp8266/examples/CallBackList/CallBackGeneric.ino +++ b/libraries/esp8266/examples/CallBackList/CallBackGeneric.ino @@ -6,24 +6,24 @@ using namespace experimental::CBListImplentation; class exampleClass { public: - exampleClass() {}; + exampleClass() {}; - using exCallBack = std::function; - using exHandler = CallBackList::CallBackHandler; + using exCallBack = std::function; + using exHandler = CallBackList::CallBackHandler; - CallBackList myHandlers; + CallBackList myHandlers; - exHandler setHandler(exCallBack cb) { - return myHandlers.add(cb); - } + exHandler setHandler(exCallBack cb) { + return myHandlers.add(cb); + } - void removeHandler(exHandler hnd) { - myHandlers.remove(hnd); - } + void removeHandler(exHandler hnd) { + myHandlers.remove(hnd); + } - void trigger(int t) { - myHandlers.execute(t); - } + void trigger(int t) { + myHandlers.execute(t); + } }; exampleClass myExample; diff --git a/libraries/esp8266/examples/CheckFlashCRC/CheckFlashCRC.ino b/libraries/esp8266/examples/CheckFlashCRC/CheckFlashCRC.ino index fa520722f6..95a92c9ca2 100644 --- a/libraries/esp8266/examples/CheckFlashCRC/CheckFlashCRC.ino +++ b/libraries/esp8266/examples/CheckFlashCRC/CheckFlashCRC.ino @@ -25,7 +25,7 @@ void setup() { uint32_t sector = ((((uint32_t)ptr - 0x40200000) / SPI_FLASH_SEC_SIZE)); // Create a sector with 1 bit set (i.e. fake corruption) - uint32_t *space = (uint32_t*)calloc(SPI_FLASH_SEC_SIZE, 1); + uint32_t* space = (uint32_t*)calloc(SPI_FLASH_SEC_SIZE, 1); space[42] = 64; // Write it into flash at the spot in question @@ -40,6 +40,5 @@ void setup() { Serial.printf("CRC check: %s\n", ESP.checkFlashCRC() ? "OK" : "ERROR"); } - void loop() { } diff --git a/libraries/esp8266/examples/CheckFlashConfig/CheckFlashConfig.ino b/libraries/esp8266/examples/CheckFlashConfig/CheckFlashConfig.ino index 9c3a54d7da..f5ac22f10b 100644 --- a/libraries/esp8266/examples/CheckFlashConfig/CheckFlashConfig.ino +++ b/libraries/esp8266/examples/CheckFlashConfig/CheckFlashConfig.ino @@ -20,7 +20,10 @@ void loop() { Serial.printf("Flash ide size: %u bytes\n", ideSize); Serial.printf("Flash ide speed: %u Hz\n", ESP.getFlashChipSpeed()); - Serial.printf("Flash ide mode: %s\n", (ideMode == FM_QIO ? "QIO" : ideMode == FM_QOUT ? "QOUT" : ideMode == FM_DIO ? "DIO" : ideMode == FM_DOUT ? "DOUT" : "UNKNOWN")); + Serial.printf("Flash ide mode: %s\n", (ideMode == FM_QIO ? "QIO" : ideMode == FM_QOUT ? "QOUT" + : ideMode == FM_DIO ? "DIO" + : ideMode == FM_DOUT ? "DOUT" + : "UNKNOWN")); if (ideSize != realSize) { Serial.println("Flash Chip configuration wrong!\n"); diff --git a/libraries/esp8266/examples/ConfigFile/ConfigFile.ino b/libraries/esp8266/examples/ConfigFile/ConfigFile.ino index 59693edb31..964b2dc7e0 100644 --- a/libraries/esp8266/examples/ConfigFile/ConfigFile.ino +++ b/libraries/esp8266/examples/ConfigFile/ConfigFile.ino @@ -67,7 +67,6 @@ void setup() { return; } - if (!saveConfig()) { Serial.println("Failed to save config"); } else { diff --git a/libraries/esp8266/examples/FadePolledTimeout/FadePolledTimeout.ino b/libraries/esp8266/examples/FadePolledTimeout/FadePolledTimeout.ino index 1f192dd01c..e2ecb41bf6 100644 --- a/libraries/esp8266/examples/FadePolledTimeout/FadePolledTimeout.ino +++ b/libraries/esp8266/examples/FadePolledTimeout/FadePolledTimeout.ino @@ -39,12 +39,12 @@ void setup() { // PWM-Locked generator: https://github.com/esp8266/Arduino/pull/7231 enablePhaseLockedWaveform(); - pinMode(LED_BUILTIN, OUTPUT); // Initialize the LED_BUILTIN pin as an output + pinMode(LED_BUILTIN, OUTPUT); // Initialize the LED_BUILTIN pin as an output analogWriteRange(1000); using esp8266::polledTimeout::oneShotMs; //import the type to the local namespace - digitalWrite(LED_BUILTIN, LOW); // Turn the LED on (Note that LOW is the voltage level + digitalWrite(LED_BUILTIN, LOW); // Turn the LED on (Note that LOW is the voltage level oneShotMs timeoutOn(2000); while (!timeoutOn) { @@ -54,7 +54,6 @@ void setup() { stepPeriod.reset(); } - void loop() { static int val = 0; static int delta = 100; diff --git a/libraries/esp8266/examples/HeapMetric/HeapMetric.ino b/libraries/esp8266/examples/HeapMetric/HeapMetric.ino index 5c7a27dbbe..387ac5624a 100644 --- a/libraries/esp8266/examples/HeapMetric/HeapMetric.ino +++ b/libraries/esp8266/examples/HeapMetric/HeapMetric.ino @@ -52,21 +52,18 @@ void tryit(int blocksize) { calculation of multiple elements combined with the rounding up for the 8-byte alignment of each allocation can make for some tricky calculations. */ - int rawMemoryMaxFreeBlockSize = ESP.getMaxFreeBlockSize(); + int rawMemoryMaxFreeBlockSize = ESP.getMaxFreeBlockSize(); // Remove the space for overhead component of the blocks*sizeof(void*) array. int maxFreeBlockSize = rawMemoryMaxFreeBlockSize - UMM_OVERHEAD_ADJUST; // Initial estimate to use all of the MaxFreeBlock with multiples of 8 rounding up. - blocks = maxFreeBlockSize / - (((blocksize + UMM_OVERHEAD_ADJUST + 7) & ~7) + sizeof(void*)); + blocks = maxFreeBlockSize / (((blocksize + UMM_OVERHEAD_ADJUST + 7) & ~7) + sizeof(void*)); /* While we allowed for the 8-byte alignment overhead for blocks*blocksize we were unable to compensate in advance for the later 8-byte aligning needed for the blocks*sizeof(void*) allocation. Thus blocks may be off by one count. We now validate the estimate and adjust as needed. */ - int rawMemoryEstimate = - blocks * ((blocksize + UMM_OVERHEAD_ADJUST + 7) & ~7) + - ((blocks * sizeof(void*) + UMM_OVERHEAD_ADJUST + 7) & ~7); + int rawMemoryEstimate = blocks * ((blocksize + UMM_OVERHEAD_ADJUST + 7) & ~7) + ((blocks * sizeof(void*) + UMM_OVERHEAD_ADJUST + 7) & ~7); if (rawMemoryMaxFreeBlockSize < rawMemoryEstimate) { --blocks; } diff --git a/libraries/esp8266/examples/HelloCrypto/HelloCrypto.ino b/libraries/esp8266/examples/HelloCrypto/HelloCrypto.ino index 1fb90134c2..c7c3249888 100644 --- a/libraries/esp8266/examples/HelloCrypto/HelloCrypto.ino +++ b/libraries/esp8266/examples/HelloCrypto/HelloCrypto.ino @@ -47,7 +47,6 @@ void loop() { static uint32_t encryptionCounter = 0; - // Generate the salt to use for HKDF uint8_t hkdfSalt[16] { 0 }; getNonceGenerator()(hkdfSalt, sizeof hkdfSalt); @@ -61,14 +60,12 @@ void loop() { Serial.println(String(F("\nThis is the SHA256 hash of our example data, in HEX format:\n")) + TypeCast::uint8ArrayToHexString(resultArray, sizeof resultArray)); Serial.println(String(F("This is the SHA256 hash of our example data, in HEX format, using String output:\n")) + SHA256::hash(exampleData)); - // HMAC // Note that HMAC output length is limited SHA256::hmac(exampleData.c_str(), exampleData.length(), derivedKey, sizeof derivedKey, resultArray, sizeof resultArray); Serial.println(String(F("\nThis is the SHA256 HMAC of our example data, in HEX format:\n")) + TypeCast::uint8ArrayToHexString(resultArray, sizeof resultArray)); Serial.println(String(F("This is the SHA256 HMAC of our example data, in HEX format, using String output:\n")) + SHA256::hmac(exampleData, derivedKey, sizeof derivedKey, SHA256::NATURAL_LENGTH)); - // Authenticated Encryption with Associated Data (AEAD) String dataToEncrypt = F("This data is not encrypted."); uint8_t resultingNonce[12] { 0 }; // The nonce is always 12 bytes @@ -91,7 +88,6 @@ void loop() { Serial.println(dataToEncrypt); - Serial.println(F("\n##########################################################################################################\n")); delay(10000); diff --git a/libraries/esp8266/examples/HwdtStackDump/HwdtStackDump.ino b/libraries/esp8266/examples/HwdtStackDump/HwdtStackDump.ino index ff1c41e93b..0d57aa78c8 100644 --- a/libraries/esp8266/examples/HwdtStackDump/HwdtStackDump.ino +++ b/libraries/esp8266/examples/HwdtStackDump/HwdtStackDump.ino @@ -24,7 +24,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* ssid = STASSID; @@ -39,9 +39,9 @@ extern "C" { #define thunk_ets_uart_printf ets_uart_printf #else - int thunk_ets_uart_printf(const char *format, ...) __attribute__((format(printf, 1, 2))); - // Second stack thunked helper - this macro creates the global function thunk_ets_uart_printf - make_stack_thunk(ets_uart_printf); +int thunk_ets_uart_printf(const char* format, ...) __attribute__((format(printf, 1, 2))); +// Second stack thunked helper - this macro creates the global function thunk_ets_uart_printf +make_stack_thunk(ets_uart_printf); #endif }; //////////////////////////////////////////////////////////////////// @@ -50,7 +50,7 @@ void setup(void) { WiFi.persistent(false); // w/o this a flash write occurs at every boot WiFi.mode(WIFI_OFF); Serial.begin(115200); - delay(20); // This delay helps when using the 'Modified Serial monitor' otherwise it is not needed. + delay(20); // This delay helps when using the 'Modified Serial monitor' otherwise it is not needed. Serial.println(); Serial.println(); Serial.println(F("The Hardware Watchdog Timer Demo is starting ...")); @@ -78,8 +78,8 @@ void setup(void) { #endif Serial.printf_P(PSTR("This example was built with%s an extra 4K of heap space (g_pcont == 0x%08lX)\r\n"), - ((uintptr_t)0x3FFFC000 < (uintptr_t)g_pcont) ? "" : "out", - (uintptr_t)g_pcont); + ((uintptr_t)0x3FFFC000 < (uintptr_t)g_pcont) ? "" : "out", + (uintptr_t)g_pcont); #if defined(DEBUG_ESP_HWDT) || defined(DEBUG_ESP_HWDT_NOEXTRA4K) Serial.print(F("and with the HWDT")); #if defined(DEBUG_ESP_HWDT_NOEXTRA4K) @@ -94,7 +94,6 @@ void setup(void) { processKey(Serial, '?'); } - void loop(void) { if (Serial.available() > 0) { int hotKey = Serial.read(); diff --git a/libraries/esp8266/examples/HwdtStackDump/ProcessKey.ino b/libraries/esp8266/examples/HwdtStackDump/ProcessKey.ino index 7d182bf377..195d1fa178 100644 --- a/libraries/esp8266/examples/HwdtStackDump/ProcessKey.ino +++ b/libraries/esp8266/examples/HwdtStackDump/ProcessKey.ino @@ -1,5 +1,5 @@ #include -void crashMeIfYouCan(void)__attribute__((weak)); +void crashMeIfYouCan(void) __attribute__((weak)); int divideA_B(int a, int b); int* nullPointer = NULL; @@ -15,16 +15,15 @@ void processKey(Print& out, int hotKey) { ESP.restart(); break; case 's': { - uint32_t startTime = millis(); - out.printf_P(PSTR("Now crashing with Software WDT. This will take about 3 seconds.\r\n")); - ets_install_putc1(ets_putc); - while (true) { - ets_printf("%9lu\r", (millis() - startTime)); - ets_delay_us(250000); - // stay in an loop blocking other system activity. - } + uint32_t startTime = millis(); + out.printf_P(PSTR("Now crashing with Software WDT. This will take about 3 seconds.\r\n")); + ets_install_putc1(ets_putc); + while (true) { + ets_printf("%9lu\r", (millis() - startTime)); + ets_delay_us(250000); + // stay in an loop blocking other system activity. } - break; + } break; case 'h': out.printf_P(PSTR("Now crashing with Hardware WDT. This will take about 6 seconds.\r\n")); asm volatile("mov.n a2, %0\n\t" @@ -32,7 +31,9 @@ void processKey(Print& out, int hotKey) { "mov.n a4, %2\n\t" "mov.n a5, %3\n\t" "mov.n a6, %4\n\t" - : : "r"(0xaaaaaaaa), "r"(0xaaaaaaaa), "r"(0xaaaaaaaa), "r"(0xaaaaaaaa), "r"(0xaaaaaaaa) : "memory"); + : + : "r"(0xaaaaaaaa), "r"(0xaaaaaaaa), "r"(0xaaaaaaaa), "r"(0xaaaaaaaa), "r"(0xaaaaaaaa) + : "memory"); // Could not find these in the stack dump, unless interrupts were enabled. { uint32_t startTime = millis(); diff --git a/libraries/esp8266/examples/I2STransmit/I2STransmit.ino b/libraries/esp8266/examples/I2STransmit/I2STransmit.ino index 2eaab265d2..9758455b75 100644 --- a/libraries/esp8266/examples/I2STransmit/I2STransmit.ino +++ b/libraries/esp8266/examples/I2STransmit/I2STransmit.ino @@ -14,12 +14,12 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif // Set your network here -const char *SSID = STASSID; -const char *PASS = STAPSK; +const char* SSID = STASSID; +const char* PASS = STAPSK; WiFiUDP udp; // Set your listener PC's IP here: @@ -60,7 +60,6 @@ void setup() { udp.beginPacket(listener, port); udp.write("I2S Receiver\r\n"); udp.endPacket(); - } void loop() { diff --git a/libraries/esp8266/examples/IramReserve/IramReserve.ino b/libraries/esp8266/examples/IramReserve/IramReserve.ino index 96d7479da4..7c354d5a13 100644 --- a/libraries/esp8266/examples/IramReserve/IramReserve.ino +++ b/libraries/esp8266/examples/IramReserve/IramReserve.ino @@ -18,7 +18,7 @@ #if defined(UMM_HEAP_IRAM) #if defined(CORE_MOCK) -#define XCHAL_INSTRAM1_VADDR 0x40100000 +#define XCHAL_INSTRAM1_VADDR 0x40100000 #else #include // For config/core-isa.h #endif @@ -29,7 +29,6 @@ struct durable { uint32_t chksum; }; - // Leave a durable block of IRAM after the 2nd heap. // The block should be in 8-byte increments and fall on an 8-byte alignment. @@ -39,7 +38,7 @@ struct durable { #define IRAM_RESERVE ((uintptr_t)XCHAL_INSTRAM1_VADDR + 0xC000UL - IRAM_RESERVE_SZ) // Define a reference with the right properties to make access easier. -#define DURABLE ((struct durable *)IRAM_RESERVE) +#define DURABLE ((struct durable*)IRAM_RESERVE) #define INCREMENT_BOOTCOUNT() (DURABLE->bootCounter)++ extern struct rst_info resetInfo; @@ -58,11 +57,9 @@ extern struct rst_info resetInfo; XOR sum on the IRAM data (or just a section of the IRAM data). */ inline bool is_iram_valid(void) { - return (REASON_WDT_RST <= resetInfo.reason && - REASON_SOFT_RESTART >= resetInfo.reason); + return (REASON_WDT_RST <= resetInfo.reason && REASON_SOFT_RESTART >= resetInfo.reason); } - void setup() { WiFi.persistent(false); WiFi.mode(WIFI_OFF); @@ -79,7 +76,6 @@ void setup() { Serial.printf("Number of reboots at %u\r\n", DURABLE->bootCounter); Serial.printf("\r\nSome less than direct, ways to restart:\r\n"); processKey(Serial, '?'); - } void loop(void) { @@ -112,7 +108,7 @@ extern "C" void umm_init_iram(void) { sec_heap_sz -= IRAM_RESERVE_SZ; // Shrink IRAM heap if (0xC000UL > sec_heap_sz) { - umm_init_iram_ex((void *)sec_heap, sec_heap_sz, true); + umm_init_iram_ex((void*)sec_heap, sec_heap_sz, true); } } diff --git a/libraries/esp8266/examples/IramReserve/ProcessKey.ino b/libraries/esp8266/examples/IramReserve/ProcessKey.ino index 7d182bf377..195d1fa178 100644 --- a/libraries/esp8266/examples/IramReserve/ProcessKey.ino +++ b/libraries/esp8266/examples/IramReserve/ProcessKey.ino @@ -1,5 +1,5 @@ #include -void crashMeIfYouCan(void)__attribute__((weak)); +void crashMeIfYouCan(void) __attribute__((weak)); int divideA_B(int a, int b); int* nullPointer = NULL; @@ -15,16 +15,15 @@ void processKey(Print& out, int hotKey) { ESP.restart(); break; case 's': { - uint32_t startTime = millis(); - out.printf_P(PSTR("Now crashing with Software WDT. This will take about 3 seconds.\r\n")); - ets_install_putc1(ets_putc); - while (true) { - ets_printf("%9lu\r", (millis() - startTime)); - ets_delay_us(250000); - // stay in an loop blocking other system activity. - } + uint32_t startTime = millis(); + out.printf_P(PSTR("Now crashing with Software WDT. This will take about 3 seconds.\r\n")); + ets_install_putc1(ets_putc); + while (true) { + ets_printf("%9lu\r", (millis() - startTime)); + ets_delay_us(250000); + // stay in an loop blocking other system activity. } - break; + } break; case 'h': out.printf_P(PSTR("Now crashing with Hardware WDT. This will take about 6 seconds.\r\n")); asm volatile("mov.n a2, %0\n\t" @@ -32,7 +31,9 @@ void processKey(Print& out, int hotKey) { "mov.n a4, %2\n\t" "mov.n a5, %3\n\t" "mov.n a6, %4\n\t" - : : "r"(0xaaaaaaaa), "r"(0xaaaaaaaa), "r"(0xaaaaaaaa), "r"(0xaaaaaaaa), "r"(0xaaaaaaaa) : "memory"); + : + : "r"(0xaaaaaaaa), "r"(0xaaaaaaaa), "r"(0xaaaaaaaa), "r"(0xaaaaaaaa), "r"(0xaaaaaaaa) + : "memory"); // Could not find these in the stack dump, unless interrupts were enabled. { uint32_t startTime = millis(); diff --git a/libraries/esp8266/examples/LowPowerDemo/LowPowerDemo.ino b/libraries/esp8266/examples/LowPowerDemo/LowPowerDemo.ino index 2c22416e0d..2dc8b99404 100644 --- a/libraries/esp8266/examples/LowPowerDemo/LowPowerDemo.ino +++ b/libraries/esp8266/examples/LowPowerDemo/LowPowerDemo.ino @@ -38,43 +38,43 @@ 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include -#include // crc32() +#include // crc32() #include #include // WiFiState structure details //#define DEBUG // prints WiFi connection info to serial, uncomment if you want WiFi messages #ifdef DEBUG -#define DEBUG_PRINTLN(x) Serial.println(x) -#define DEBUG_PRINT(x) Serial.print(x) +#define DEBUG_PRINTLN(x) Serial.println(x) +#define DEBUG_PRINT(x) Serial.print(x) #else #define DEBUG_PRINTLN(x) #define DEBUG_PRINT(x) #endif -#define WAKE_UP_PIN 0 // D3/GPIO0, can also force a serial flash upload with RESET +#define WAKE_UP_PIN 0 // D3/GPIO0, can also force a serial flash upload with RESET // you can use any GPIO for WAKE_UP_PIN except for D0/GPIO16 as it doesn't support interrupts // uncomment one of the two lines below for your LED connection (optional) -#define LED 5 // D1/GPIO5 external LED for modules with built-in LEDs so it doesn't add amperage +#define LED 5 // D1/GPIO5 external LED for modules with built-in LEDs so it doesn't add amperage //#define LED 2 // D4/GPIO2 LED for ESP-01,07 modules; D4 is LED_BUILTIN on most other modules // you can use LED_BUILTIN, but it adds to the measured amperage by 0.3mA to 6mA. -ADC_MODE(ADC_VCC); // allows you to monitor the internal VCC level; it varies with WiFi load +ADC_MODE(ADC_VCC); // allows you to monitor the internal VCC level; it varies with WiFi load // don't connect anything to the analog input pin(s)! // enter your WiFi configuration below -const char* AP_SSID = "SSID"; // your router's SSID here -const char* AP_PASS = "password"; // your router's password here +const char* AP_SSID = "SSID"; // your router's SSID here +const char* AP_PASS = "password"; // your router's password here IPAddress staticIP(0, 0, 0, 0); // parameters below are for your static IP address, if used IPAddress gateway(0, 0, 0, 0); IPAddress subnet(0, 0, 0, 0); IPAddress dns1(0, 0, 0, 0); IPAddress dns2(0, 0, 0, 0); -uint32_t timeout = 30E3; // 30 second timeout on the WiFi connection +uint32_t timeout = 30E3; // 30 second timeout on the WiFi connection //#define TESTPOINT // used to track the timing of several test cycles (optional) #ifdef TESTPOINT -#define testPointPin 4 // D2/GPIO4, you can use any pin that supports interrupts +#define testPointPin 4 // D2/GPIO4, you can use any pin that supports interrupts #define testPoint_HIGH digitalWrite(testPointPin, HIGH) #define testPoint_LOW digitalWrite(testPointPin, LOW) #else @@ -89,35 +89,35 @@ struct nv_s { struct { uint32_t crc32; - uint32_t rstCount; // stores the Deep Sleep reset count + uint32_t rstCount; // stores the Deep Sleep reset count // you can add anything else here that you want to save, must be 4-byte aligned } rtcData; }; static nv_s* nv = (nv_s*)RTC_USER_MEM; // user RTC RAM area -uint32_t resetCount = 0; // keeps track of the number of Deep Sleep tests / resets +uint32_t resetCount = 0; // keeps track of the number of Deep Sleep tests / resets const uint32_t blinkDelay = 100; // fast blink rate for the LED when waiting for the user -esp8266::polledTimeout::periodicMs blinkLED(blinkDelay); // LED blink delay without delay() -esp8266::polledTimeout::oneShotMs altDelay(blinkDelay); // tight loop to simulate user code -esp8266::polledTimeout::oneShotMs wifiTimeout(timeout); // 30 second timeout on WiFi connection +esp8266::polledTimeout::periodicMs blinkLED(blinkDelay); // LED blink delay without delay() +esp8266::polledTimeout::oneShotMs altDelay(blinkDelay); // tight loop to simulate user code +esp8266::polledTimeout::oneShotMs wifiTimeout(timeout); // 30 second timeout on WiFi connection // use fully qualified type and avoid importing all ::esp8266 namespace to the global namespace -void wakeupCallback() { // unlike ISRs, you can do a print() from a callback function - testPoint_LOW; // testPoint tracks latency from WAKE_UP_PIN LOW to testPoint LOW - printMillis(); // show time difference across sleep; millis is wrong as the CPU eventually stops +void wakeupCallback() { // unlike ISRs, you can do a print() from a callback function + testPoint_LOW; // testPoint tracks latency from WAKE_UP_PIN LOW to testPoint LOW + printMillis(); // show time difference across sleep; millis is wrong as the CPU eventually stops Serial.println(F("Woke from Light Sleep - this is the callback")); } void setup() { #ifdef TESTPOINT - pinMode(testPointPin, OUTPUT); // test point for Light Sleep and Deep Sleep tests - testPoint_LOW; // Deep Sleep reset doesn't clear GPIOs, testPoint LOW shows boot time + pinMode(testPointPin, OUTPUT); // test point for Light Sleep and Deep Sleep tests + testPoint_LOW; // Deep Sleep reset doesn't clear GPIOs, testPoint LOW shows boot time #endif - pinMode(LED, OUTPUT); // activity and status indicator - digitalWrite(LED, LOW); // turn on the LED - pinMode(WAKE_UP_PIN, INPUT_PULLUP); // polled to advance tests, interrupt for Forced Light Sleep + pinMode(LED, OUTPUT); // activity and status indicator + digitalWrite(LED, LOW); // turn on the LED + pinMode(WAKE_UP_PIN, INPUT_PULLUP); // polled to advance tests, interrupt for Forced Light Sleep Serial.begin(115200); Serial.println(); Serial.print(F("\nReset reason = ")); @@ -129,31 +129,31 @@ void setup() { } // Read previous resets (Deep Sleeps) from RTC memory, if any - uint32_t crcOfData = crc32((uint8_t*) &nv->rtcData.rstCount, sizeof(nv->rtcData.rstCount)); + uint32_t crcOfData = crc32((uint8_t*)&nv->rtcData.rstCount, sizeof(nv->rtcData.rstCount)); if ((crcOfData = nv->rtcData.crc32) && (resetCause == "Deep-Sleep Wake")) { - resetCount = nv->rtcData.rstCount; // read the previous reset count + resetCount = nv->rtcData.rstCount; // read the previous reset count resetCount++; } nv->rtcData.rstCount = resetCount; // update the reset count & CRC updateRTCcrc(); - if (resetCount == 1) { // show that millis() is cleared across the Deep Sleep reset + if (resetCount == 1) { // show that millis() is cleared across the Deep Sleep reset printMillis(); } -} // end of setup() +} // end of setup() void loop() { - if (resetCount == 0) { // if first loop() since power on or external reset + if (resetCount == 0) { // if first loop() since power on or external reset runTest1(); runTest2(); runTest3(); runTest4(); runTest5(); runTest6(); - runTest7(); // first Deep Sleep test, all these end with a RESET + runTest7(); // first Deep Sleep test, all these end with a RESET } if (resetCount < 4) { - initWiFi(); // optional re-init of WiFi for the Deep Sleep tests + initWiFi(); // optional re-init of WiFi for the Deep Sleep tests } if (resetCount == 1) { runTest8(); @@ -168,7 +168,7 @@ void loop() { void runTest1() { Serial.println(F("\n1st test - running with WiFi unconfigured")); - readVoltage(); // read internal VCC + readVoltage(); // read internal VCC Serial.println(F("press the switch to continue")); waitPushbutton(false, blinkDelay); } @@ -177,11 +177,11 @@ void runTest2() { Serial.println(F("\n2nd test - Automatic Modem Sleep")); Serial.println(F("connecting WiFi, please wait until the LED blinks")); initWiFi(); - if (WiFi.localIP()) { // won't go into Automatic Sleep without an active WiFi connection + if (WiFi.localIP()) { // won't go into Automatic Sleep without an active WiFi connection Serial.println(F("The amperage will drop in 7 seconds.")); - readVoltage(); // read internal VCC + readVoltage(); // read internal VCC Serial.println(F("press the switch to continue")); - waitPushbutton(true, 90); /* This is using a special feature: below 100 mS blink delay, + waitPushbutton(true, 90); /* This is using a special feature: below 100 mS blink delay, the LED blink delay is padding 100 mS time with 'program cycles' to fill the 100 mS. At 90 mS delay, 90% of the blink time is delay(), and 10% is 'your program running'. Below 90% you'll see a difference in the average amperage: less delay() = more amperage. @@ -195,13 +195,13 @@ void runTest2() { void runTest3() { Serial.println(F("\n3rd test - Forced Modem Sleep")); - WiFi.shutdown(nv->wss); // shut the modem down and save the WiFi state for faster reconnection + WiFi.shutdown(nv->wss); // shut the modem down and save the WiFi state for faster reconnection // WiFi.forceSleepBegin(delay_in_uS); // alternate method of Forced Modem Sleep for an optional timed shutdown, // with WiFi.forceSleepBegin(0xFFFFFFF); the modem sleeps until you wake it, with values <= 0xFFFFFFE it's timed // delay(10); // it doesn't always go to sleep unless you delay(10); yield() wasn't reliable - readVoltage(); // read internal VCC + readVoltage(); // read internal VCC Serial.println(F("press the switch to continue")); - waitPushbutton(true, 99); /* Using the same < 100 mS feature. If you drop the delay below 100, you + waitPushbutton(true, 99); /* Using the same < 100 mS feature. If you drop the delay below 100, you will see the effect of program time vs. delay() time on minimum amperage. Above ~ 97 (97% of the time in delay) there is little change in amperage, so you need to spend maximum time in delay() to get minimum amperage.*/ @@ -213,10 +213,10 @@ void runTest4() { Serial.println(F("Automatic Light Sleep begins after WiFi connects (LED blinks)")); // on successive loops after power-on, WiFi shows 'connected' several seconds before Sleep happens // and WiFi reconnects after the forceSleepWake more quickly - digitalWrite(LED, LOW); // visual cue that we're reconnecting WiFi + digitalWrite(LED, LOW); // visual cue that we're reconnecting WiFi uint32_t wifiBegin = millis(); - WiFi.forceSleepWake(); // reconnect with previous STA mode and connection settings - WiFi.setSleepMode(WIFI_LIGHT_SLEEP, 3); // Automatic Light Sleep, DTIM listen interval = 3 + WiFi.forceSleepWake(); // reconnect with previous STA mode and connection settings + WiFi.setSleepMode(WIFI_LIGHT_SLEEP, 3); // Automatic Light Sleep, DTIM listen interval = 3 // at higher DTIM intervals you'll have a hard time establishing and maintaining a connection wifiTimeout.reset(timeout); while (((!WiFi.localIP()) || (WiFi.status() != WL_CONNECTED)) && (!wifiTimeout)) { @@ -227,9 +227,9 @@ void runTest4() { float reConn = (millis() - wifiBegin); Serial.print(F("WiFi connect time = ")); Serial.printf("%1.2f seconds\n", reConn / 1000); - readVoltage(); // read internal VCC + readVoltage(); // read internal VCC Serial.println(F("long press of the switch to continue")); - waitPushbutton(true, 350); /* Below 100 mS delay it only goes into 'Automatic Modem Sleep', + waitPushbutton(true, 350); /* Below 100 mS delay it only goes into 'Automatic Modem Sleep', and below ~ 350 mS delay() the 'Automatic Light Sleep' is less frequent. Above 500 mS delay() doesn't make significant improvement in power savings. */ } else { @@ -241,142 +241,142 @@ void runTest5() { Serial.println(F("\n5th test - Timed Light Sleep, wake in 10 seconds")); Serial.println(F("Press the button when you're ready to proceed")); waitPushbutton(true, blinkDelay); - WiFi.mode(WIFI_OFF); // you must turn the modem off; using disconnect won't work - readVoltage(); // read internal VCC - printMillis(); // show millis() across sleep, including Serial.flush() - digitalWrite(LED, HIGH); // turn the LED off so they know the CPU isn't running - testPoint_HIGH; // testPoint LOW in callback tracks delay from testPoint HIGH to LOW - extern os_timer_t *timer_list; - timer_list = nullptr; // stop (but don't disable) the 4 OS timers + WiFi.mode(WIFI_OFF); // you must turn the modem off; using disconnect won't work + readVoltage(); // read internal VCC + printMillis(); // show millis() across sleep, including Serial.flush() + digitalWrite(LED, HIGH); // turn the LED off so they know the CPU isn't running + testPoint_HIGH; // testPoint LOW in callback tracks delay from testPoint HIGH to LOW + extern os_timer_t* timer_list; + timer_list = nullptr; // stop (but don't disable) the 4 OS timers wifi_fpm_set_sleep_type(LIGHT_SLEEP_T); - gpio_pin_wakeup_enable(GPIO_ID_PIN(WAKE_UP_PIN), GPIO_PIN_INTR_LOLEVEL); // GPIO wakeup (optional) + gpio_pin_wakeup_enable(GPIO_ID_PIN(WAKE_UP_PIN), GPIO_PIN_INTR_LOLEVEL); // GPIO wakeup (optional) // only LOLEVEL or HILEVEL interrupts work, no edge, that's an SDK or CPU limitation wifi_fpm_set_wakeup_cb(wakeupCallback); // set wakeup callback // the callback is optional, but without it the modem will wake in 10 seconds then delay(10 seconds) // with the callback the sleep time is only 10 seconds total, no extra delay() afterward wifi_fpm_open(); - wifi_fpm_do_sleep(10E6); // Sleep range = 10000 ~ 268,435,454 uS (0xFFFFFFE, 2^28-1) + wifi_fpm_do_sleep(10E6); // Sleep range = 10000 ~ 268,435,454 uS (0xFFFFFFE, 2^28-1) delay(10e3 + 1); // delay needs to be 1 mS longer than sleep or it only goes into Modem Sleep - Serial.println(F("Woke up!")); // the interrupt callback hits before this is executed + Serial.println(F("Woke up!")); // the interrupt callback hits before this is executed } void runTest6() { Serial.println(F("\n6th test - Forced Light Sleep, wake with GPIO interrupt")); Serial.flush(); - WiFi.mode(WIFI_OFF); // you must turn the modem off; using disconnect won't work - digitalWrite(LED, HIGH); // turn the LED off so they know the CPU isn't running - readVoltage(); // read internal VCC + WiFi.mode(WIFI_OFF); // you must turn the modem off; using disconnect won't work + digitalWrite(LED, HIGH); // turn the LED off so they know the CPU isn't running + readVoltage(); // read internal VCC Serial.println(F("CPU going to sleep, pull WAKE_UP_PIN low to wake it (press the switch)")); - printMillis(); // show millis() across sleep, including Serial.flush() - testPoint_HIGH; // testPoint tracks latency from WAKE_UP_PIN LOW to testPoint LOW in callback + printMillis(); // show millis() across sleep, including Serial.flush() + testPoint_HIGH; // testPoint tracks latency from WAKE_UP_PIN LOW to testPoint LOW in callback wifi_fpm_set_sleep_type(LIGHT_SLEEP_T); gpio_pin_wakeup_enable(GPIO_ID_PIN(WAKE_UP_PIN), GPIO_PIN_INTR_LOLEVEL); // only LOLEVEL or HILEVEL interrupts work, no edge, that's an SDK or CPU limitation wifi_fpm_set_wakeup_cb(wakeupCallback); // Set wakeup callback (optional) wifi_fpm_open(); - wifi_fpm_do_sleep(0xFFFFFFF); // only 0xFFFFFFF, any other value and it won't disconnect the RTC timer - delay(10); // it goes to sleep during this delay() and waits for an interrupt - Serial.println(F("Woke up!")); // the interrupt callback hits before this is executed*/ + wifi_fpm_do_sleep(0xFFFFFFF); // only 0xFFFFFFF, any other value and it won't disconnect the RTC timer + delay(10); // it goes to sleep during this delay() and waits for an interrupt + Serial.println(F("Woke up!")); // the interrupt callback hits before this is executed*/ } void runTest7() { Serial.println(F("\n7th test - Deep Sleep for 10 seconds, reset and wake with RF_DEFAULT")); - initWiFi(); // initialize WiFi since we turned it off in the last test - readVoltage(); // read internal VCC + initWiFi(); // initialize WiFi since we turned it off in the last test + readVoltage(); // read internal VCC Serial.println(F("press the switch to continue")); - while (!digitalRead(WAKE_UP_PIN)) { // wait for them to release the switch from the previous test + while (!digitalRead(WAKE_UP_PIN)) { // wait for them to release the switch from the previous test delay(10); } - delay(50); // debounce time for the switch, pushbutton released - waitPushbutton(false, blinkDelay); // set true if you want to see Automatic Modem Sleep - digitalWrite(LED, LOW); // turn the LED on, at least briefly + delay(50); // debounce time for the switch, pushbutton released + waitPushbutton(false, blinkDelay); // set true if you want to see Automatic Modem Sleep + digitalWrite(LED, LOW); // turn the LED on, at least briefly //WiFi.shutdown(nv->wss); // Forced Modem Sleep for a more Instant Deep Sleep, // and no extended RFCAL as it goes into Deep Sleep Serial.println(F("going into Deep Sleep now...")); - printMillis(); // show time difference across sleep - testPoint_HIGH; // testPoint set HIGH to track Deep Sleep period, cleared at startup() + printMillis(); // show time difference across sleep + testPoint_HIGH; // testPoint set HIGH to track Deep Sleep period, cleared at startup() ESP.deepSleep(10E6, WAKE_RF_DEFAULT); // good night! D0 fires a reset in 10 seconds... // if you do ESP.deepSleep(0, mode); it needs a RESET to come out of sleep (RTC is disconnected) // maximum timed Deep Sleep interval ~ 3 to 4 hours depending on the RTC timer, see the README // the 2 uA GPIO amperage during Deep Sleep can't drive the LED so it's not lit now, although // depending on the LED used, you might see it very dimly lit in a dark room during this test - Serial.println(F("What... I'm not asleep?!?")); // it will never get here + Serial.println(F("What... I'm not asleep?!?")); // it will never get here } void runTest8() { Serial.println(F("\n8th test - in RF_DEFAULT, Deep Sleep for 10 seconds, reset and wake with RFCAL")); - readVoltage(); // read internal VCC + readVoltage(); // read internal VCC Serial.println(F("press the switch to continue")); - waitPushbutton(false, blinkDelay); // set true if you want to see Automatic Modem Sleep + waitPushbutton(false, blinkDelay); // set true if you want to see Automatic Modem Sleep //WiFi.shutdown(nv->wss); // Forced Modem Sleep for a more Instant Deep Sleep, // and no extended RFCAL as it goes into Deep Sleep Serial.println(F("going into Deep Sleep now...")); - Serial.flush(); // needs a delay(10) or Serial.flush() else it doesn't print the whole message - testPoint_HIGH; // testPoint set HIGH to track Deep Sleep period, cleared at startup() + Serial.flush(); // needs a delay(10) or Serial.flush() else it doesn't print the whole message + testPoint_HIGH; // testPoint set HIGH to track Deep Sleep period, cleared at startup() ESP.deepSleep(10E6, WAKE_RFCAL); // good night! D0 fires a reset in 10 seconds... - Serial.println(F("What... I'm not asleep?!?")); // it will never get here + Serial.println(F("What... I'm not asleep?!?")); // it will never get here } void runTest9() { Serial.println(F("\n9th test - in RFCAL, Deep Sleep Instant for 10 seconds, reset and wake with NO_RFCAL")); - readVoltage(); // read internal VCC + readVoltage(); // read internal VCC Serial.println(F("press the switch to continue")); - waitPushbutton(false, blinkDelay); // set true if you want to see Automatic Modem Sleep - WiFi.shutdown(nv->wss); // Forced Modem Sleep for a more Instant Deep Sleep + waitPushbutton(false, blinkDelay); // set true if you want to see Automatic Modem Sleep + WiFi.shutdown(nv->wss); // Forced Modem Sleep for a more Instant Deep Sleep Serial.println(F("going into Deep Sleep now...")); - Serial.flush(); // needs a delay(10) or Serial.flush() else it doesn't print the whole message - testPoint_HIGH; // testPoint set HIGH to track Deep Sleep period, cleared at startup() + Serial.flush(); // needs a delay(10) or Serial.flush() else it doesn't print the whole message + testPoint_HIGH; // testPoint set HIGH to track Deep Sleep period, cleared at startup() ESP.deepSleepInstant(10E6, WAKE_NO_RFCAL); // good night! D0 fires a reset in 10 seconds... - Serial.println(F("What... I'm not asleep?!?")); // it will never get here + Serial.println(F("What... I'm not asleep?!?")); // it will never get here } void runTest10() { Serial.println(F("\n10th test - in NO_RFCAL, Deep Sleep Instant for 10 seconds, reset and wake with RF_DISABLED")); - readVoltage(); // read internal VCC + readVoltage(); // read internal VCC Serial.println(F("press the switch to continue")); - waitPushbutton(false, blinkDelay); // set true if you want to see Automatic Modem Sleep + waitPushbutton(false, blinkDelay); // set true if you want to see Automatic Modem Sleep //WiFi.forceSleepBegin(); // Forced Modem Sleep for a more Instant Deep Sleep Serial.println(F("going into Deep Sleep now...")); - Serial.flush(); // needs a delay(10) or Serial.flush() else it doesn't print the whole message - testPoint_HIGH; // testPoint set HIGH to track Deep Sleep period, cleared at startup() + Serial.flush(); // needs a delay(10) or Serial.flush() else it doesn't print the whole message + testPoint_HIGH; // testPoint set HIGH to track Deep Sleep period, cleared at startup() ESP.deepSleepInstant(10E6, WAKE_RF_DISABLED); // good night! D0 fires a reset in 10 seconds... - Serial.println(F("What... I'm not asleep?!?")); // it will never get here + Serial.println(F("What... I'm not asleep?!?")); // it will never get here } void resetTests() { - readVoltage(); // read internal VCC + readVoltage(); // read internal VCC Serial.println(F("\nTests completed, in RF_DISABLED, press the switch to do an ESP.restart()")); - memset(&nv->wss, 0, sizeof(nv->wss) * 2); // wipe saved WiFi states, comment this if you want to keep them + memset(&nv->wss, 0, sizeof(nv->wss) * 2); // wipe saved WiFi states, comment this if you want to keep them waitPushbutton(false, 1000); ESP.restart(); } -void waitPushbutton(bool usesDelay, unsigned int delayTime) { // loop until they press the switch +void waitPushbutton(bool usesDelay, unsigned int delayTime) { // loop until they press the switch // note: 2 different modes, as 3 of the power saving modes need a delay() to activate fully - if (!usesDelay) { // quick interception of pushbutton press, no delay() used + if (!usesDelay) { // quick interception of pushbutton press, no delay() used blinkLED.reset(delayTime); - while (digitalRead(WAKE_UP_PIN)) { // wait for a pushbutton press + while (digitalRead(WAKE_UP_PIN)) { // wait for a pushbutton press if (blinkLED) { - digitalWrite(LED, !digitalRead(LED)); // toggle the activity LED + digitalWrite(LED, !digitalRead(LED)); // toggle the activity LED } - yield(); // this would be a good place for ArduinoOTA.handle(); + yield(); // this would be a good place for ArduinoOTA.handle(); } - } else { // long delay() for the 3 modes that need it, but it misses quick switch presses - while (digitalRead(WAKE_UP_PIN)) { // wait for a pushbutton press - digitalWrite(LED, !digitalRead(LED)); // toggle the activity LED - delay(delayTime); // another good place for ArduinoOTA.handle(); + } else { // long delay() for the 3 modes that need it, but it misses quick switch presses + while (digitalRead(WAKE_UP_PIN)) { // wait for a pushbutton press + digitalWrite(LED, !digitalRead(LED)); // toggle the activity LED + delay(delayTime); // another good place for ArduinoOTA.handle(); if (delayTime < 100) { - altDelay.reset(100 - delayTime); // pad the time < 100 mS with some real CPU cycles - while (!altDelay) { // this simulates 'your program running', not delay() time + altDelay.reset(100 - delayTime); // pad the time < 100 mS with some real CPU cycles + while (!altDelay) { // this simulates 'your program running', not delay() time } } } } - delay(50); // debounce time for the switch, pushbutton pressed - while (!digitalRead(WAKE_UP_PIN)) { // now wait for them to release the pushbutton + delay(50); // debounce time for the switch, pushbutton pressed + while (!digitalRead(WAKE_UP_PIN)) { // now wait for them to release the pushbutton delay(10); } - delay(50); // debounce time for the switch, pushbutton released + delay(50); // debounce time for the switch, pushbutton released } void readVoltage() { // read internal VCC @@ -385,34 +385,34 @@ void readVoltage() { // read internal VCC } void printMillis() { - Serial.print(F("millis() = ")); // show that millis() isn't correct across most Sleep modes + Serial.print(F("millis() = ")); // show that millis() isn't correct across most Sleep modes Serial.println(millis()); - Serial.flush(); // needs a Serial.flush() else it may not print the whole message before sleeping + Serial.flush(); // needs a Serial.flush() else it may not print the whole message before sleeping } -void updateRTCcrc() { // updates the reset count CRC - nv->rtcData.crc32 = crc32((uint8_t*) &nv->rtcData.rstCount, sizeof(nv->rtcData.rstCount)); +void updateRTCcrc() { // updates the reset count CRC + nv->rtcData.crc32 = crc32((uint8_t*)&nv->rtcData.rstCount, sizeof(nv->rtcData.rstCount)); } void initWiFi() { - digitalWrite(LED, LOW); // give a visual indication that we're alive but busy with WiFi - uint32_t wifiBegin = millis(); // how long does it take to connect - if ((crc32((uint8_t*) &nv->rtcData.rstCount + 1, sizeof(nv->wss)) && !WiFi.shutdownValidCRC(nv->wss))) { + digitalWrite(LED, LOW); // give a visual indication that we're alive but busy with WiFi + uint32_t wifiBegin = millis(); // how long does it take to connect + if ((crc32((uint8_t*)&nv->rtcData.rstCount + 1, sizeof(nv->wss)) && !WiFi.shutdownValidCRC(nv->wss))) { // if good copy of wss, overwrite invalid (primary) copy - memcpy((uint32_t*) &nv->wss, (uint32_t*) &nv->rtcData.rstCount + 1, sizeof(nv->wss)); + memcpy((uint32_t*)&nv->wss, (uint32_t*)&nv->rtcData.rstCount + 1, sizeof(nv->wss)); } - if (WiFi.shutdownValidCRC(nv->wss)) { // if we have a valid WiFi saved state - memcpy((uint32_t*) &nv->rtcData.rstCount + 1, (uint32_t*) &nv->wss, sizeof(nv->wss)); // save a copy of it + if (WiFi.shutdownValidCRC(nv->wss)) { // if we have a valid WiFi saved state + memcpy((uint32_t*)&nv->rtcData.rstCount + 1, (uint32_t*)&nv->wss, sizeof(nv->wss)); // save a copy of it Serial.println(F("resuming WiFi")); } - if (!(WiFi.resumeFromShutdown(nv->wss))) { // couldn't resume, or no valid saved WiFi state yet + if (!(WiFi.resumeFromShutdown(nv->wss))) { // couldn't resume, or no valid saved WiFi state yet /* Explicitly set the ESP8266 as a WiFi-client (STAtion mode), otherwise by default it would try to act as both a client and an access-point and could cause network issues with other WiFi devices on your network. */ - WiFi.persistent(false); // don't store the connection each time to save wear on the flash + WiFi.persistent(false); // don't store the connection each time to save wear on the flash WiFi.mode(WIFI_STA); - WiFi.setOutputPower(10); // reduce RF output power, increase if it won't connect - WiFi.config(staticIP, gateway, subnet); // if using static IP, enter parameters at the top + WiFi.setOutputPower(10); // reduce RF output power, increase if it won't connect + WiFi.config(staticIP, gateway, subnet); // if using static IP, enter parameters at the top WiFi.begin(AP_SSID, AP_PASS); Serial.print(F("connecting to WiFi ")); Serial.println(AP_SSID); diff --git a/libraries/esp8266/examples/MMU48K/MMU48K.ino b/libraries/esp8266/examples/MMU48K/MMU48K.ino index d75d91232b..e33a08ebb0 100644 --- a/libraries/esp8266/examples/MMU48K/MMU48K.ino +++ b/libraries/esp8266/examples/MMU48K/MMU48K.ino @@ -4,21 +4,21 @@ #include #if defined(CORE_MOCK) -#define XCHAL_INSTRAM1_VADDR 0x40100000 +#define XCHAL_INSTRAM1_VADDR 0x40100000 #else #include // For config/core-isa.h #endif -uint32_t timed_byte_read(char *pc, uint32_t * o); -uint32_t timed_byte_read2(char *pc, uint32_t * o); +uint32_t timed_byte_read(char* pc, uint32_t* o); +uint32_t timed_byte_read2(char* pc, uint32_t* o); int divideA_B(int a, int b); int* nullPointer = NULL; -char *probe_b = NULL; -short *probe_s = NULL; -char *probe_c = (char *)0x40110000; -short *unaligned_probe_s = NULL; +char* probe_b = NULL; +short* probe_s = NULL; +char* probe_c = (char*)0x40110000; +short* unaligned_probe_s = NULL; uint32_t read_var = 0x11223344; @@ -30,10 +30,10 @@ uint32_t read_var = 0x11223344; */ #if defined(MMU_IRAM_HEAP) || defined(MMU_SEC_HEAP) -uint32_t *gobble; +uint32_t* gobble; size_t gobble_sz; -#elif (MMU_IRAM_SIZE > 32*1024) +#elif (MMU_IRAM_SIZE > 32 * 1024) uint32_t gobble[4 * 1024] IRAM_ATTR; constexpr size_t gobble_sz = sizeof(gobble); @@ -42,7 +42,7 @@ uint32_t gobble[256] IRAM_ATTR; constexpr size_t gobble_sz = sizeof(gobble); #endif -bool isValid(uint32_t *probe) { +bool isValid(uint32_t* probe) { bool rc = true; if (NULL == probe) { ets_uart_printf("\nNULL memory pointer %p ...\n", probe); @@ -54,7 +54,8 @@ bool isValid(uint32_t *probe) { uint32_t saveData = *probe; for (size_t i = 0; i < 32; i++) { *probe = BIT(i); - asm volatile("" ::: "memory"); + asm volatile("" :: + : "memory"); uint32_t val = *probe; if (val != BIT(i)) { ets_uart_printf(" Read 0x%08X != Wrote 0x%08X\n", val, (uint32_t)BIT(i)); @@ -67,9 +68,8 @@ bool isValid(uint32_t *probe) { return rc; } - -void dump_mem32(const void * addr, const size_t len) { - uint32_t *addr32 = (uint32_t *)addr; +void dump_mem32(const void* addr, const size_t len) { + uint32_t* addr32 = (uint32_t*)addr; ets_uart_printf("\n"); if ((uintptr_t)addr32 & 3) { ets_uart_printf("non-32-bit access\n"); @@ -93,7 +93,7 @@ void print_mmu_status(Print& oStream) { oStream.println(); oStream.println(); uint32_t iram_bank_reg = ESP8266_DREG(0x24); - if (0 == (iram_bank_reg & 0x10)) { // if bit clear, is enabled + if (0 == (iram_bank_reg & 0x10)) { // if bit clear, is enabled oStream.printf_P(PSTR(" IRAM block mapped to: 0x40108000")); oStream.println(); } @@ -122,7 +122,6 @@ void print_mmu_status(Print& oStream) { #endif } - void setup() { WiFi.persistent(false); WiFi.mode(WIFI_OFF); @@ -138,14 +137,14 @@ void setup() { HeapSelectIram ephemeral; // Serial.printf_P(PSTR("ESP.getFreeHeap(): %u\n"), ESP.getFreeHeap()); gobble_sz = ESP.getFreeHeap() - UMM_OVERHEAD_ADJUST; // - 4096; - gobble = (uint32_t *)malloc(gobble_sz); + gobble = (uint32_t*)malloc(gobble_sz); } Serial.printf_P(PSTR("\r\nmalloc() from IRAM Heap:\r\n")); Serial.printf_P(PSTR(" gobble_sz: %u\r\n"), gobble_sz); Serial.printf_P(PSTR(" gobble: %p\r\n"), gobble); #elif defined(MMU_SEC_HEAP) - gobble = (uint32_t *)MMU_SEC_HEAP; + gobble = (uint32_t*)MMU_SEC_HEAP; gobble_sz = MMU_SEC_HEAP_SIZE; #endif @@ -165,41 +164,40 @@ void setup() { // Lets peak over the edge Serial.printf_P(PSTR("\r\nPeek over the edge of memory at 0x4010C000\r\n")); - dump_mem32((void *)(0x4010C000 - 16 * 4), 32); - - probe_b = (char *)gobble; - probe_s = (short *)((uintptr_t)gobble); - unaligned_probe_s = (short *)((uintptr_t)gobble + 1); + dump_mem32((void*)(0x4010C000 - 16 * 4), 32); + probe_b = (char*)gobble; + probe_s = (short*)((uintptr_t)gobble); + unaligned_probe_s = (short*)((uintptr_t)gobble + 1); } void processKey(Print& out, int hotKey) { switch (hotKey) { case 't': { - uint32_t tmp; - out.printf_P(PSTR("Test how much time is added by exception handling")); - out.println(); - out.printf_P(PSTR("Timed byte read from iCACHE %u cpu cycle count, 0x%02X."), timed_byte_read((char *)0x40200003, &tmp), tmp); - out.println(); - out.printf_P(PSTR("Timed byte read from iCACHE %u cpu cycle count, 0x%02X."), timed_byte_read((char *)0x40200003, &tmp), tmp); - out.println(); - out.printf_P(PSTR("Timed byte read from iRAM %u cpu cycle count, 0x%02X."), timed_byte_read((char *)0x40108000, &tmp), tmp); - out.println(); - out.printf_P(PSTR("Timed byte read from dRAM %u cpu cycle count, 0x%02X."), timed_byte_read((char *)((uintptr_t)&read_var + 1), &tmp), tmp); - out.println(); - out.printf_P(PSTR("Test how much time is used by the inline function method")); - out.println(); - out.printf_P(PSTR("Timed byte read from iCACHE %u cpu cycle count, 0x%02X."), timed_byte_read2((char *)0x40200003, &tmp), tmp); - out.println(); - out.printf_P(PSTR("Timed byte read from iCACHE %u cpu cycle count, 0x%02X."), timed_byte_read2((char *)0x40200003, &tmp), tmp); - out.println(); - out.printf_P(PSTR("Timed byte read from iRAM %u cpu cycle count, 0x%02X."), timed_byte_read2((char *)0x40108000, &tmp), tmp); - out.println(); - out.printf_P(PSTR("Timed byte read from dRAM %u cpu cycle count, 0x%02X."), timed_byte_read2((char *)((uintptr_t)&read_var + 1), &tmp), tmp); - out.println(); - out.println(); - break; - } + uint32_t tmp; + out.printf_P(PSTR("Test how much time is added by exception handling")); + out.println(); + out.printf_P(PSTR("Timed byte read from iCACHE %u cpu cycle count, 0x%02X."), timed_byte_read((char*)0x40200003, &tmp), tmp); + out.println(); + out.printf_P(PSTR("Timed byte read from iCACHE %u cpu cycle count, 0x%02X."), timed_byte_read((char*)0x40200003, &tmp), tmp); + out.println(); + out.printf_P(PSTR("Timed byte read from iRAM %u cpu cycle count, 0x%02X."), timed_byte_read((char*)0x40108000, &tmp), tmp); + out.println(); + out.printf_P(PSTR("Timed byte read from dRAM %u cpu cycle count, 0x%02X."), timed_byte_read((char*)((uintptr_t)&read_var + 1), &tmp), tmp); + out.println(); + out.printf_P(PSTR("Test how much time is used by the inline function method")); + out.println(); + out.printf_P(PSTR("Timed byte read from iCACHE %u cpu cycle count, 0x%02X."), timed_byte_read2((char*)0x40200003, &tmp), tmp); + out.println(); + out.printf_P(PSTR("Timed byte read from iCACHE %u cpu cycle count, 0x%02X."), timed_byte_read2((char*)0x40200003, &tmp), tmp); + out.println(); + out.printf_P(PSTR("Timed byte read from iRAM %u cpu cycle count, 0x%02X."), timed_byte_read2((char*)0x40108000, &tmp), tmp); + out.println(); + out.printf_P(PSTR("Timed byte read from dRAM %u cpu cycle count, 0x%02X."), timed_byte_read2((char*)((uintptr_t)&read_var + 1), &tmp), tmp); + out.println(); + out.println(); + break; + } case '9': out.printf_P(PSTR("Unaligned exception by reading short")); out.println(); @@ -228,17 +226,17 @@ void processKey(Print& out, int hotKey) { out.println(); break; case 'B': { - out.printf_P(PSTR("Load/Store exception by writing byte to iRAM")); - out.println(); - char val = 0x55; - out.printf_P(PSTR("Write byte, 0x%02X, to iRAM at %p"), val, probe_b); - out.println(); - out.flush(); - probe_b[0] = val; - out.printf_P(PSTR("Read Byte back from iRAM, 0x%02X at %p"), probe_b[0], probe_b); - out.println(); - break; - } + out.printf_P(PSTR("Load/Store exception by writing byte to iRAM")); + out.println(); + char val = 0x55; + out.printf_P(PSTR("Write byte, 0x%02X, to iRAM at %p"), val, probe_b); + out.println(); + out.flush(); + probe_b[0] = val; + out.printf_P(PSTR("Read Byte back from iRAM, 0x%02X at %p"), probe_b[0], probe_b); + out.println(); + break; + } case 's': out.printf_P(PSTR("Load/Store exception by reading short from iRAM")); out.println(); @@ -247,17 +245,17 @@ void processKey(Print& out, int hotKey) { out.println(); break; case 'S': { - out.printf_P(PSTR("Load/Store exception by writing short to iRAM")); - out.println(); - short int val = 0x0AA0; - out.printf_P(PSTR("Write short, 0x%04X, to iRAM at %p"), val, probe_s); - out.println(); - out.flush(); - probe_s[0] = val; - out.printf_P(PSTR("Read short back from iRAM, 0x%04X at %p"), probe_s[0], probe_s); - out.println(); - break; - } + out.printf_P(PSTR("Load/Store exception by writing short to iRAM")); + out.println(); + short int val = 0x0AA0; + out.printf_P(PSTR("Write short, 0x%04X, to iRAM at %p"), val, probe_s); + out.println(); + out.flush(); + probe_s[0] = val; + out.printf_P(PSTR("Read short back from iRAM, 0x%04X at %p"), probe_s[0], probe_s); + out.println(); + break; + } case 'R': out.printf_P(PSTR("Restart, ESP.restart(); ...")); out.println(); @@ -310,7 +308,6 @@ void processKey(Print& out, int hotKey) { } } - void serialClientLoop(void) { if (Serial.available() > 0) { int hotKey = Serial.read(); @@ -322,7 +319,6 @@ void loop() { serialClientLoop(); } - int __attribute__((noinline)) divideA_B(int a, int b) { return (a / b); } diff --git a/libraries/esp8266/examples/NTP-TZ-DST/NTP-TZ-DST.ino b/libraries/esp8266/examples/NTP-TZ-DST/NTP-TZ-DST.ino index f6c2df08fc..31a6f26cc6 100644 --- a/libraries/esp8266/examples/NTP-TZ-DST/NTP-TZ-DST.ino +++ b/libraries/esp8266/examples/NTP-TZ-DST/NTP-TZ-DST.ino @@ -12,16 +12,14 @@ This example code is in the public domain. */ - #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif // initial time (possibly given by an external RTC) #define RTC_UTC_TEST 1510592825 // 1510592825 = Monday 13 November 2017 17:07:05 UTC - // This database is autogenerated from IANA timezone database // https://www.iana.org/time-zones // and can be updated on demand in this repository @@ -44,17 +42,17 @@ //////////////////////////////////////////////////////// #include -#include // settimeofday_cb() +#include // settimeofday_cb() #include #include -#include // time() ctime() -#include // struct timeval +#include // time() ctime() +#include // struct timeval -#include // sntp_servermode_dhcp() +#include // sntp_servermode_dhcp() // for testing purpose: -extern "C" int clock_gettime(clockid_t unused, struct timespec *tp); +extern "C" int clock_gettime(clockid_t unused, struct timespec* tp); //////////////////////////////////////////////////////// @@ -86,15 +84,21 @@ static bool time_machine_run_once = false; // return 15000; // 15s //} -#define PTM(w) \ +#define PTM(w) \ Serial.print(" " #w "="); \ Serial.print(tm->tm_##w); void printTm(const char* what, const tm* tm) { Serial.print(what); - PTM(isdst); PTM(yday); PTM(wday); - PTM(year); PTM(mon); PTM(mday); - PTM(hour); PTM(min); PTM(sec); + PTM(isdst); + PTM(yday); + PTM(wday); + PTM(year); + PTM(mon); + PTM(mday); + PTM(hour); + PTM(min); + PTM(sec); } void showTime() { @@ -135,7 +139,7 @@ void showTime() { Serial.println((uint32_t)now); // timezone and demo in the future - Serial.printf("timezone: %s\n", getenv("TZ") ? : "(none)"); + Serial.printf("timezone: %s\n", getenv("TZ") ?: "(none)"); // human readable Serial.print("ctime: "); @@ -153,8 +157,8 @@ void showTime() { Serial.printf("%s ", sntp.toString().c_str()); } Serial.printf("- IPv6: %s - Reachability: %o\n", - sntp.isV6() ? "Yes" : "No", - sntp_getreachability(i)); + sntp.isV6() ? "Yes" : "No", + sntp_getreachability(i)); } } @@ -169,11 +173,11 @@ void showTime() { gettimeofday(&tv, nullptr); if (tv.tv_sec != prevtv.tv_sec) { Serial.printf("time(): %u gettimeofday(): %u.%06u seconds are unchanged\n", - (uint32_t)prevtime, - (uint32_t)prevtv.tv_sec, (uint32_t)prevtv.tv_usec); + (uint32_t)prevtime, + (uint32_t)prevtv.tv_sec, (uint32_t)prevtv.tv_usec); Serial.printf("time(): %u gettimeofday(): %u.%06u <-- seconds have changed\n", - (uint32_t)(prevtime = time(nullptr)), - (uint32_t)tv.tv_sec, (uint32_t)tv.tv_usec); + (uint32_t)(prevtime = time(nullptr)), + (uint32_t)tv.tv_sec, (uint32_t)tv.tv_usec); break; } prevtv = tv; @@ -213,8 +217,8 @@ void time_is_set(bool from_sntp /* <= this parameter is optional */) { now = time(nullptr); const tm* tm = localtime(&now); Serial.printf(": future=%3ddays: DST=%s - ", - time_machine_days, - tm->tm_isdst ? "true " : "false"); + time_machine_days, + tm->tm_isdst ? "true " : "false"); Serial.print(ctime(&now)); gettimeofday(&tv, nullptr); constexpr int days = 30; diff --git a/libraries/esp8266/examples/RTCUserMemory/RTCUserMemory.ino b/libraries/esp8266/examples/RTCUserMemory/RTCUserMemory.ino index 9736995c74..170eabe38c 100644 --- a/libraries/esp8266/examples/RTCUserMemory/RTCUserMemory.ino +++ b/libraries/esp8266/examples/RTCUserMemory/RTCUserMemory.ino @@ -13,7 +13,7 @@ // This example code is in the public domain. // CRC function used to ensure data validity -uint32_t calculateCRC32(const uint8_t *data, size_t length); +uint32_t calculateCRC32(const uint8_t* data, size_t length); // helper function to dump memory contents as hex void printMemory(); @@ -34,11 +34,11 @@ void setup() { delay(1000); // Read struct from RTC memory - if (ESP.rtcUserMemoryRead(0, (uint32_t*) &rtcData, sizeof(rtcData))) { + if (ESP.rtcUserMemoryRead(0, (uint32_t*)&rtcData, sizeof(rtcData))) { Serial.println("Read: "); printMemory(); Serial.println(); - uint32_t crcOfData = calculateCRC32((uint8_t*) &rtcData.data[0], sizeof(rtcData.data)); + uint32_t crcOfData = calculateCRC32((uint8_t*)&rtcData.data[0], sizeof(rtcData.data)); Serial.print("CRC32 of data: "); Serial.println(crcOfData, HEX); Serial.print("CRC32 read from RTC: "); @@ -55,9 +55,9 @@ void setup() { rtcData.data[i] = random(0, 128); } // Update CRC32 of data - rtcData.crc32 = calculateCRC32((uint8_t*) &rtcData.data[0], sizeof(rtcData.data)); + rtcData.crc32 = calculateCRC32((uint8_t*)&rtcData.data[0], sizeof(rtcData.data)); // Write struct to RTC memory - if (ESP.rtcUserMemoryWrite(0, (uint32_t*) &rtcData, sizeof(rtcData))) { + if (ESP.rtcUserMemoryWrite(0, (uint32_t*)&rtcData, sizeof(rtcData))) { Serial.println("Write: "); printMemory(); Serial.println(); @@ -70,7 +70,7 @@ void setup() { void loop() { } -uint32_t calculateCRC32(const uint8_t *data, size_t length) { +uint32_t calculateCRC32(const uint8_t* data, size_t length) { uint32_t crc = 0xffffffff; while (length--) { uint8_t c = *data++; @@ -91,7 +91,7 @@ uint32_t calculateCRC32(const uint8_t *data, size_t length) { //prints all rtcData, including the leading crc32 void printMemory() { char buf[3]; - uint8_t *ptr = (uint8_t *)&rtcData; + uint8_t* ptr = (uint8_t*)&rtcData; for (size_t i = 0; i < sizeof(rtcData); i++) { sprintf(buf, "%02X", ptr[i]); Serial.print(buf); diff --git a/libraries/esp8266/examples/SerialDetectBaudrate/SerialDetectBaudrate.ino b/libraries/esp8266/examples/SerialDetectBaudrate/SerialDetectBaudrate.ino index 61967c691f..d2fd2f2e21 100644 --- a/libraries/esp8266/examples/SerialDetectBaudrate/SerialDetectBaudrate.ino +++ b/libraries/esp8266/examples/SerialDetectBaudrate/SerialDetectBaudrate.ino @@ -1,4 +1,4 @@ -#define TIMEOUT (10000UL) // Maximum time to wait for serial activity to start +#define TIMEOUT (10000UL) // Maximum time to wait for serial activity to start void setup() { // put your setup code here, to run once: @@ -29,6 +29,4 @@ void setup() { void loop() { // put your main code here, to run repeatedly: - } - diff --git a/libraries/esp8266/examples/SerialStress/SerialStress.ino b/libraries/esp8266/examples/SerialStress/SerialStress.ino index a19eb9f270..b899c76eac 100644 --- a/libraries/esp8266/examples/SerialStress/SerialStress.ino +++ b/libraries/esp8266/examples/SerialStress/SerialStress.ino @@ -11,18 +11,18 @@ #include #include -#define SSBAUD 115200 // logger on console for humans -#define BAUD 3000000 // hardware serial stress test -#define BUFFER_SIZE 4096 // may be useless to use more than 2*SERIAL_SIZE_RX -#define SERIAL_SIZE_RX 1024 // Serial.setRxBufferSize() +#define SSBAUD 115200 // logger on console for humans +#define BAUD 3000000 // hardware serial stress test +#define BUFFER_SIZE 4096 // may be useless to use more than 2*SERIAL_SIZE_RX +#define SERIAL_SIZE_RX 1024 // Serial.setRxBufferSize() #define FAKE_INCREASED_AVAILABLE 100 // test readBytes's timeout #define TIMEOUT 5000 #define DEBUG(x...) //x -uint8_t buf [BUFFER_SIZE]; -uint8_t temp [BUFFER_SIZE]; +uint8_t buf[BUFFER_SIZE]; +uint8_t temp[BUFFER_SIZE]; bool reading = true; size_t testReadBytesTimeout = 0; @@ -38,7 +38,7 @@ Stream* logger; void error(const char* what) { logger->printf("\nerror: %s after %ld minutes\nread idx: %d\nwrite idx: %d\ntotal: %ld\nlast read: %d\nmaxavail: %d\n", - what, (long)((millis() - start_ms) / 60000), in_idx, out_idx, (long)in_total, (int)local_receive_size, maxavail); + what, (long)((millis() - start_ms) / 60000), in_idx, out_idx, (long)in_total, (int)local_receive_size, maxavail); if (Serial.hasOverrun()) { logger->printf("overrun!\n"); } @@ -76,7 +76,7 @@ void setup() { int baud = Serial.baudRate(); logger->printf(ESP.getFullVersion().c_str()); logger->printf("\n\nBAUD: %d - CoreRxBuffer: %d bytes - TestBuffer: %d bytes\n", - baud, SERIAL_SIZE_RX, BUFFER_SIZE); + baud, SERIAL_SIZE_RX, BUFFER_SIZE); size_for_1sec = baud / 10; // 8n1=10baudFor8bits logger->printf("led changes state every %zd bytes (= 1 second)\n", size_for_1sec); @@ -91,7 +91,8 @@ void setup() { // bind RX and TX USC0(0) |= (1 << UCLBE); - while (Serial.read() == -1); + while (Serial.read() == -1) + ; if (Serial.hasOverrun()) { logger->print("overrun?\n"); } @@ -107,9 +108,7 @@ void loop() { maxlen = BUFFER_SIZE - out_idx; } // check if not cycling more than buffer size relatively to input - size_t in_out = out_idx == in_idx ? - BUFFER_SIZE : - (in_idx + BUFFER_SIZE - out_idx - 1) % BUFFER_SIZE; + size_t in_out = out_idx == in_idx ? BUFFER_SIZE : (in_idx + BUFFER_SIZE - out_idx - 1) % BUFFER_SIZE; if (maxlen > in_out) { maxlen = in_out; } @@ -172,7 +171,7 @@ void loop() { unsigned long now_ms = millis(); int bwkbps_avg = ((((uint64_t)in_total) * 8000) / (now_ms - start_ms)) >> 10; - int bwkbps_now = (((in_total - in_prev) * 8000) / (now_ms - last_ms)) >> 10 ; + int bwkbps_now = (((in_total - in_prev) * 8000) / (now_ms - last_ms)) >> 10; logger->printf("bwavg=%d bwnow=%d kbps maxavail=%i\n", bwkbps_avg, bwkbps_now, maxavail); in_prev = in_total; diff --git a/libraries/esp8266/examples/SigmaDeltaDemo/SigmaDeltaDemo.ino b/libraries/esp8266/examples/SigmaDeltaDemo/SigmaDeltaDemo.ino index bdc1799eb7..7b432bf2da 100644 --- a/libraries/esp8266/examples/SigmaDeltaDemo/SigmaDeltaDemo.ino +++ b/libraries/esp8266/examples/SigmaDeltaDemo/SigmaDeltaDemo.ino @@ -14,7 +14,6 @@ void setup() { Serial.println(); Serial.println("Start Sigma Delta Example\n"); Serial.printf("Frequency = %u\n", realFreq); - } void loop() { @@ -36,7 +35,6 @@ void loop() { sigmaDeltaWrite(0, duty); delay(10); } - } Serial.println("Detaching builtin led & playing a blinkie\n"); diff --git a/libraries/esp8266/examples/StreamString/StreamString.ino b/libraries/esp8266/examples/StreamString/StreamString.ino index c9c6b46025..446f1e0c75 100644 --- a/libraries/esp8266/examples/StreamString/StreamString.ino +++ b/libraries/esp8266/examples/StreamString/StreamString.ino @@ -21,7 +21,7 @@ void checksketch(const char* what, const char* res1, const char* res2) { #endif void testStringPtrProgmem() { - static const char inProgmem [] PROGMEM = "I am in progmem"; + static const char inProgmem[] PROGMEM = "I am in progmem"; auto inProgmem2 = F("I am too in progmem"); int heap = (int)ESP.getFreeHeap(); @@ -46,7 +46,6 @@ void testStreamString() { // In non-default non-consume mode, it will just move a pointer. That one // can be ::resetPointer(pos) anytime. See the example below. - // The String included in 'result' will not be modified by read: // (this is not the default) result.resetPointer(); @@ -182,7 +181,7 @@ void setup() { testStreamString(); Serial.printf("sizeof: String:%d Stream:%d StreamString:%d SStream:%d\n", - (int)sizeof(String), (int)sizeof(Stream), (int)sizeof(StreamString), (int)sizeof(S2Stream)); + (int)sizeof(String), (int)sizeof(Stream), (int)sizeof(StreamString), (int)sizeof(S2Stream)); } #endif diff --git a/libraries/esp8266/examples/TestEspApi/TestEspApi.ino b/libraries/esp8266/examples/TestEspApi/TestEspApi.ino index 49ff525898..0daff924c4 100644 --- a/libraries/esp8266/examples/TestEspApi/TestEspApi.ino +++ b/libraries/esp8266/examples/TestEspApi/TestEspApi.ino @@ -28,7 +28,7 @@ Stream& ehConsolePort(Serial); // UNLESS: You swap the TX pin using the alternate pinout. const uint8_t LED_PIN = 1; -const char * const RST_REASONS[] = { +const char* const RST_REASONS[] = { "REASON_DEFAULT_RST", "REASON_WDT_RST", "REASON_EXCEPTION_RST", @@ -38,7 +38,7 @@ const char * const RST_REASONS[] = { "REASON_EXT_SYS_RST" }; -const char * const FLASH_SIZE_MAP_NAMES[] = { +const char* const FLASH_SIZE_MAP_NAMES[] = { "FLASH_SIZE_4M_MAP_256_256", "FLASH_SIZE_2M", "FLASH_SIZE_8M_MAP_512_512", @@ -48,14 +48,14 @@ const char * const FLASH_SIZE_MAP_NAMES[] = { "FLASH_SIZE_32M_MAP_1024_1024" }; -const char * const OP_MODE_NAMES[] { +const char* const OP_MODE_NAMES[] { "NULL_MODE", "STATION_MODE", "SOFTAP_MODE", "STATIONAP_MODE" }; -const char * const AUTH_MODE_NAMES[] { +const char* const AUTH_MODE_NAMES[] { "AUTH_OPEN", "AUTH_WEP", "AUTH_WPA_PSK", @@ -64,14 +64,14 @@ const char * const AUTH_MODE_NAMES[] { "AUTH_MAX" }; -const char * const PHY_MODE_NAMES[] { +const char* const PHY_MODE_NAMES[] { "", "PHY_MODE_11B", "PHY_MODE_11G", "PHY_MODE_11N" }; -const char * const EVENT_NAMES[] { +const char* const EVENT_NAMES[] { "EVENT_STAMODE_CONNECTED", "EVENT_STAMODE_DISCONNECTED", "EVENT_STAMODE_AUTHMODE_CHANGE", @@ -81,7 +81,7 @@ const char * const EVENT_NAMES[] { "EVENT_MAX" }; -const char * const EVENT_REASONS[] { +const char* const EVENT_REASONS[] { "", "REASON_UNSPECIFIED", "REASON_AUTH_EXPIRE", @@ -108,12 +108,12 @@ const char * const EVENT_REASONS[] { "REASON_CIPHER_SUITE_REJECTED", }; -const char * const EVENT_REASONS_200[] { +const char* const EVENT_REASONS_200[] { "REASON_BEACON_TIMEOUT", "REASON_NO_AP_FOUND" }; -void wifi_event_handler_cb(System_Event_t * event) { +void wifi_event_handler_cb(System_Event_t* event) { ehConsolePort.print(EVENT_NAMES[event->event]); ehConsolePort.print(" ("); @@ -128,27 +128,26 @@ void wifi_event_handler_cb(System_Event_t * event) { break; case EVENT_SOFTAPMODE_STACONNECTED: case EVENT_SOFTAPMODE_STADISCONNECTED: { - char mac[32] = {0}; - snprintf(mac, 32, MACSTR ", aid: %d", MAC2STR(event->event_info.sta_connected.mac), event->event_info.sta_connected.aid); + char mac[32] = { 0 }; + snprintf(mac, 32, MACSTR ", aid: %d", MAC2STR(event->event_info.sta_connected.mac), event->event_info.sta_connected.aid); - ehConsolePort.print(mac); - } - break; + ehConsolePort.print(mac); + } break; } ehConsolePort.println(")"); } -void print_softap_config(Stream & consolePort, softap_config const& config) { +void print_softap_config(Stream& consolePort, softap_config const& config) { consolePort.println(); consolePort.println(F("SoftAP Configuration")); consolePort.println(F("--------------------")); consolePort.print(F("ssid: ")); - consolePort.println((char *) config.ssid); + consolePort.println((char*)config.ssid); consolePort.print(F("password: ")); - consolePort.println((char *) config.password); + consolePort.println((char*)config.password); consolePort.print(F("ssid_len: ")); consolePort.println(config.ssid_len); @@ -173,8 +172,8 @@ void print_softap_config(Stream & consolePort, softap_config const& config) { consolePort.println(); } -void print_system_info(Stream & consolePort) { - const rst_info * resetInfo = system_get_rst_info(); +void print_system_info(Stream& consolePort) { + const rst_info* resetInfo = system_get_rst_info(); consolePort.print(F("system_get_rst_info() reset reason: ")); consolePort.println(RST_REASONS[resetInfo->reason]); @@ -211,7 +210,7 @@ void print_system_info(Stream & consolePort) { consolePort.println(FLASH_SIZE_MAP_NAMES[system_get_flash_size_map()]); } -void print_wifi_general(Stream & consolePort) { +void print_wifi_general(Stream& consolePort) { consolePort.print(F("wifi_get_channel(): ")); consolePort.println(wifi_get_channel()); @@ -219,8 +218,8 @@ void print_wifi_general(Stream & consolePort) { consolePort.println(PHY_MODE_NAMES[wifi_get_phy_mode()]); } -void secure_softap_config(softap_config * config, const char * ssid, const char * password) { - size_t ssidLen = strlen(ssid) < sizeof(config->ssid) ? strlen(ssid) : sizeof(config->ssid); +void secure_softap_config(softap_config* config, const char* ssid, const char* password) { + size_t ssidLen = strlen(ssid) < sizeof(config->ssid) ? strlen(ssid) : sizeof(config->ssid); size_t passwordLen = strlen(password) < sizeof(config->password) ? strlen(password) : sizeof(config->password); memset(config->ssid, 0, sizeof(config->ssid)); @@ -230,7 +229,7 @@ void secure_softap_config(softap_config * config, const char * ssid, const char memcpy(config->password, password, passwordLen); config->ssid_len = ssidLen; - config->channel = 1; + config->channel = 1; config->authmode = AUTH_WPA2_PSK; // config->ssid_hidden = 1; config->max_connection = 4; @@ -293,4 +292,3 @@ void loop() { Serial.println(system_get_time()); delay(1000); } - diff --git a/libraries/esp8266/examples/UartDownload/UartDownload.ino b/libraries/esp8266/examples/UartDownload/UartDownload.ino index cf581c8890..97a28813dc 100644 --- a/libraries/esp8266/examples/UartDownload/UartDownload.ino +++ b/libraries/esp8266/examples/UartDownload/UartDownload.ino @@ -59,9 +59,8 @@ constexpr char slipFrameMarker = '\xC0'; // <0xC0><32 bit cksum><0xC0> // Slip packet for ESP_SYNC, minus the frame markers ('\xC0') captured from // esptool using the `--trace` option. -const char syncPkt[] PROGMEM = - "\x00\x08\x24\x00\x00\x00\x00\x00\x07\x07\x12\x20" - "UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"; +const char syncPkt[] PROGMEM = "\x00\x08\x24\x00\x00\x00\x00\x00\x07\x07\x12\x20" + "UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"; constexpr size_t syncPktSz = sizeof(syncPkt) - 1; // Don't compare zero terminator char @@ -90,7 +89,7 @@ void proxyEspSync() { } // Assume RX FIFO data is garbled and flush all RX data. - while (0 <= Serial.read()) {} // Clear FIFO + while (0 <= Serial.read()) { } // Clear FIFO // If your Serial requirements need a specific timeout value, you would // restore those here. @@ -112,12 +111,12 @@ void setup() { Serial.begin(115200); Serial.println(F( - "\r\n\r\n" - "Boot UART Download Demo - initialization started.\r\n" - "\r\n" - "For a quick test to see the UART Download work,\r\n" - "stop your serial terminal APP and run:\r\n" - " esptool.py --chip esp8266 --before no_reset --after soft_reset flash_id\r\n")); + "\r\n\r\n" + "Boot UART Download Demo - initialization started.\r\n" + "\r\n" + "For a quick test to see the UART Download work,\r\n" + "stop your serial terminal APP and run:\r\n" + " esptool.py --chip esp8266 --before no_reset --after soft_reset flash_id\r\n")); // ... } @@ -143,7 +142,7 @@ void cmdLoop(Print& oStream, int key) { ESP.restart(); break; - // ... + // ... case '?': oStream.println(F("\r\nHot key help:")); @@ -162,7 +161,6 @@ void cmdLoop(Print& oStream, int key) { oStream.println(); } - void loop() { // In this example, we can have Serial data from a user keystroke for our diff --git a/libraries/esp8266/examples/interactive/interactive.ino b/libraries/esp8266/examples/interactive/interactive.ino index b3bd1ff931..a13b817508 100644 --- a/libraries/esp8266/examples/interactive/interactive.ino +++ b/libraries/esp8266/examples/interactive/interactive.ino @@ -12,11 +12,11 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char * SSID = STASSID; -const char * PSK = STAPSK; +const char* SSID = STASSID; +const char* PSK = STAPSK; IPAddress staticip(192, 168, 1, 123); IPAddress gateway(192, 168, 1, 254); @@ -36,15 +36,14 @@ void setup() { Serial.println(); Serial.println(WiFi.localIP()); Serial.print( - "WL_IDLE_STATUS = 0\n" - "WL_NO_SSID_AVAIL = 1\n" - "WL_SCAN_COMPLETED = 2\n" - "WL_CONNECTED = 3\n" - "WL_CONNECT_FAILED = 4\n" - "WL_CONNECTION_LOST = 5\n" - "WL_WRONG_PASSWORD = 6\n" - "WL_DISCONNECTED = 7\n" - ); + "WL_IDLE_STATUS = 0\n" + "WL_NO_SSID_AVAIL = 1\n" + "WL_SCAN_COMPLETED = 2\n" + "WL_CONNECTED = 3\n" + "WL_CONNECT_FAILED = 4\n" + "WL_CONNECTION_LOST = 5\n" + "WL_WRONG_PASSWORD = 6\n" + "WL_DISCONNECTED = 7\n"); } void WiFiOn() { @@ -63,11 +62,18 @@ void WiFiOff() { } void loop() { -#define TEST(name, var, varinit, func) \ +#define TEST(name, var, varinit, func) \ static decltype(func) var = (varinit); \ - if ((var) != (func)) { var = (func); Serial.printf("**** %s: ", name); Serial.println(var); } + if ((var) != (func)) { \ + var = (func); \ + Serial.printf("**** %s: ", name); \ + Serial.println(var); \ + } -#define DO(x...) Serial.println(F( #x )); x; break +#define DO(x...) \ + Serial.println(F(#x)); \ + x; \ + break TEST("Free Heap", freeHeap, 0, ESP.getFreeHeap()); TEST("WiFiStatus", status, WL_IDLE_STATUS, WiFi.status()); @@ -75,23 +81,41 @@ void loop() { TEST("AP-IP", apIp, (uint32_t)0, WiFi.softAPIP()); switch (Serial.read()) { - case 'F': DO(WiFiOff()); - case 'N': DO(WiFiOn()); - case '1': DO(WiFi.mode(WIFI_AP)); - case '2': DO(WiFi.mode(WIFI_AP_STA)); - case '3': DO(WiFi.mode(WIFI_STA)); - case 'R': DO(if (((GPI >> 16) & 0xf) == 1) ESP.reset() /* else must hard reset */); - case 'd': DO(WiFi.disconnect()); - case 'b': DO(WiFi.begin()); - case 'B': DO(WiFi.begin(SSID, PSK)); - case 'r': DO(WiFi.reconnect()); - case 'c': DO(wifi_station_connect()); - case 'a': DO(WiFi.setAutoReconnect(false)); - case 'A': DO(WiFi.setAutoReconnect(true)); - case 'n': DO(WiFi.setSleepMode(WIFI_NONE_SLEEP)); - case 'l': DO(WiFi.setSleepMode(WIFI_LIGHT_SLEEP)); - case 'm': DO(WiFi.setSleepMode(WIFI_MODEM_SLEEP)); - case 'S': DO(WiFi.config(staticip, gateway, subnet)); // use static address - case 's': DO(WiFi.config(0u, 0u, 0u)); // back to dhcp client + case 'F': + DO(WiFiOff()); + case 'N': + DO(WiFiOn()); + case '1': + DO(WiFi.mode(WIFI_AP)); + case '2': + DO(WiFi.mode(WIFI_AP_STA)); + case '3': + DO(WiFi.mode(WIFI_STA)); + case 'R': + DO(if (((GPI >> 16) & 0xf) == 1) ESP.reset() /* else must hard reset */); + case 'd': + DO(WiFi.disconnect()); + case 'b': + DO(WiFi.begin()); + case 'B': + DO(WiFi.begin(SSID, PSK)); + case 'r': + DO(WiFi.reconnect()); + case 'c': + DO(wifi_station_connect()); + case 'a': + DO(WiFi.setAutoReconnect(false)); + case 'A': + DO(WiFi.setAutoReconnect(true)); + case 'n': + DO(WiFi.setSleepMode(WIFI_NONE_SLEEP)); + case 'l': + DO(WiFi.setSleepMode(WIFI_LIGHT_SLEEP)); + case 'm': + DO(WiFi.setSleepMode(WIFI_MODEM_SLEEP)); + case 'S': + DO(WiFi.config(staticip, gateway, subnet)); // use static address + case 's': + DO(WiFi.config(0u, 0u, 0u)); // back to dhcp client } } diff --git a/libraries/esp8266/examples/irammem/irammem.ino b/libraries/esp8266/examples/irammem/irammem.ino index 5cd1db7b36..429b9a389c 100644 --- a/libraries/esp8266/examples/irammem/irammem.ino +++ b/libraries/esp8266/examples/irammem/irammem.ino @@ -9,7 +9,6 @@ // #define USE_SET_IRAM_HEAP - #ifndef ETS_PRINTF #define ETS_PRINTF ets_uart_printf #endif @@ -21,9 +20,8 @@ #pragma GCC push_options // reference -#pragma GCC optimize("O0") // We expect -O0 to generate the correct results -__attribute__((noinline)) -void aliasTestReference(uint16_t *x) { +#pragma GCC optimize("O0") // We expect -O0 to generate the correct results +__attribute__((noinline)) void aliasTestReference(uint16_t* x) { // Without adhearance to strict-aliasing, this sequence of code would fail // when optimized by GCC Version 10.3 size_t len = 3; @@ -36,8 +34,7 @@ void aliasTestReference(uint16_t *x) { } // Tests #pragma GCC optimize("Os") -__attribute__((noinline)) -void aliasTestOs(uint16_t *x) { +__attribute__((noinline)) void aliasTestOs(uint16_t* x) { size_t len = 3; for (size_t u = 0; u < len; u++) { uint16_t x1 = mmu_get_uint16(&x[0]); @@ -47,8 +44,7 @@ void aliasTestOs(uint16_t *x) { } } #pragma GCC optimize("O2") -__attribute__((noinline)) -void aliasTestO2(uint16_t *x) { +__attribute__((noinline)) void aliasTestO2(uint16_t* x) { size_t len = 3; for (size_t u = 0; u < len; u++) { uint16_t x1 = mmu_get_uint16(&x[0]); @@ -58,8 +54,7 @@ void aliasTestO2(uint16_t *x) { } } #pragma GCC optimize("O3") -__attribute__((noinline)) -void aliasTestO3(uint16_t *x) { +__attribute__((noinline)) void aliasTestO3(uint16_t* x) { size_t len = 3; for (size_t u = 0; u < len; u++) { uint16_t x1 = mmu_get_uint16(&x[0]); @@ -74,7 +69,8 @@ void aliasTestO3(uint16_t *x) { // the exception handler. For this case the -O0 version will appear faster. #pragma GCC optimize("O0") __attribute__((noinline)) IRAM_ATTR -uint32_t timedRead_Reference(uint8_t *res) { + uint32_t + timedRead_Reference(uint8_t* res) { // This test case was verified with GCC 10.3 // There is a code case that can result in 32-bit wide IRAM load from memory // being optimized down to an 8-bit memory access. In this test case we need @@ -82,31 +78,34 @@ uint32_t timedRead_Reference(uint8_t *res) { // This section verifies that the workaround implimented by the inline // function mmu_get_uint8() is preventing this. See comments for function // mmu_get_uint8(() in mmu_iram.h for more details. - const uint8_t *x = (const uint8_t *)0x40100003ul; + const uint8_t* x = (const uint8_t*)0x40100003ul; uint32_t b = ESP.getCycleCount(); *res = mmu_get_uint8(x); return ESP.getCycleCount() - b; } #pragma GCC optimize("Os") __attribute__((noinline)) IRAM_ATTR -uint32_t timedRead_Os(uint8_t *res) { - const uint8_t *x = (const uint8_t *)0x40100003ul; + uint32_t + timedRead_Os(uint8_t* res) { + const uint8_t* x = (const uint8_t*)0x40100003ul; uint32_t b = ESP.getCycleCount(); *res = mmu_get_uint8(x); return ESP.getCycleCount() - b; } #pragma GCC optimize("O2") __attribute__((noinline)) IRAM_ATTR -uint32_t timedRead_O2(uint8_t *res) { - const uint8_t *x = (const uint8_t *)0x40100003ul; + uint32_t + timedRead_O2(uint8_t* res) { + const uint8_t* x = (const uint8_t*)0x40100003ul; uint32_t b = ESP.getCycleCount(); *res = mmu_get_uint8(x); return ESP.getCycleCount() - b; } #pragma GCC optimize("O3") __attribute__((noinline)) IRAM_ATTR -uint32_t timedRead_O3(uint8_t *res) { - const uint8_t *x = (const uint8_t *)0x40100003ul; + uint32_t + timedRead_O3(uint8_t* res) { + const uint8_t* x = (const uint8_t*)0x40100003ul; uint32_t b = ESP.getCycleCount(); *res = mmu_get_uint8(x); return ESP.getCycleCount() - b; @@ -153,7 +152,7 @@ bool test4_32bit_loads() { return result; } -void printPunFail(uint16_t *ref, uint16_t *x, size_t sz) { +void printPunFail(uint16_t* ref, uint16_t* x, size_t sz) { Serial.printf(" Expected:"); for (size_t i = 0; i < sz; i++) { Serial.printf(" %3u", ref[i]); @@ -168,12 +167,12 @@ void printPunFail(uint16_t *ref, uint16_t *x, size_t sz) { bool testPunning() { bool result = true; // Get reference result for verifing test - alignas(uint32_t) uint16_t x_ref[] = {1, 2, 3, 0}; - aliasTestReference(x_ref); // -O0 + alignas(uint32_t) uint16_t x_ref[] = { 1, 2, 3, 0 }; + aliasTestReference(x_ref); // -O0 Serial.printf("mmu_get_uint16() strict-aliasing tests with different optimizations:\r\n"); { - alignas(alignof(uint32_t)) uint16_t x[] = {1, 2, 3, 0}; + alignas(alignof(uint32_t)) uint16_t x[] = { 1, 2, 3, 0 }; aliasTestOs(x); Serial.printf(" Option -Os "); if (0 == memcmp(x_ref, x, sizeof(x_ref))) { @@ -185,7 +184,7 @@ bool testPunning() { } } { - alignas(alignof(uint32_t)) uint16_t x[] = {1, 2, 3, 0}; + alignas(alignof(uint32_t)) uint16_t x[] = { 1, 2, 3, 0 }; aliasTestO2(x); Serial.printf(" Option -O2 "); if (0 == memcmp(x_ref, x, sizeof(x_ref))) { @@ -197,7 +196,7 @@ bool testPunning() { } } { - alignas(alignof(uint32_t)) uint16_t x[] = {1, 2, 3, 0}; + alignas(alignof(uint32_t)) uint16_t x[] = { 1, 2, 3, 0 }; aliasTestO3(x); Serial.printf(" Option -O3 "); if (0 == memcmp(x_ref, x, sizeof(x_ref))) { @@ -211,8 +210,7 @@ bool testPunning() { return result; } - -uint32_t cyclesToRead_nKx32(int n, unsigned int *x, uint32_t *res) { +uint32_t cyclesToRead_nKx32(int n, unsigned int* x, uint32_t* res) { uint32_t b = ESP.getCycleCount(); uint32_t sum = 0; for (int i = 0; i < n * 1024; i++) { @@ -222,7 +220,7 @@ uint32_t cyclesToRead_nKx32(int n, unsigned int *x, uint32_t *res) { return ESP.getCycleCount() - b; } -uint32_t cyclesToWrite_nKx32(int n, unsigned int *x) { +uint32_t cyclesToWrite_nKx32(int n, unsigned int* x) { uint32_t b = ESP.getCycleCount(); uint32_t sum = 0; for (int i = 0; i < n * 1024; i++) { @@ -232,7 +230,7 @@ uint32_t cyclesToWrite_nKx32(int n, unsigned int *x) { return ESP.getCycleCount() - b; } -uint32_t cyclesToRead_nKx16(int n, unsigned short *x, uint32_t *res) { +uint32_t cyclesToRead_nKx16(int n, unsigned short* x, uint32_t* res) { uint32_t b = ESP.getCycleCount(); uint32_t sum = 0; for (int i = 0; i < n * 1024; i++) { @@ -242,7 +240,7 @@ uint32_t cyclesToRead_nKx16(int n, unsigned short *x, uint32_t *res) { return ESP.getCycleCount() - b; } -uint32_t cyclesToWrite_nKx16(int n, unsigned short *x) { +uint32_t cyclesToWrite_nKx16(int n, unsigned short* x) { uint32_t b = ESP.getCycleCount(); uint32_t sum = 0; for (int i = 0; i < n * 1024; i++) { @@ -252,7 +250,7 @@ uint32_t cyclesToWrite_nKx16(int n, unsigned short *x) { return ESP.getCycleCount() - b; } -uint32_t cyclesToRead_nKxs16(int n, short *x, int32_t *res) { +uint32_t cyclesToRead_nKxs16(int n, short* x, int32_t* res) { uint32_t b = ESP.getCycleCount(); int32_t sum = 0; for (int i = 0; i < n * 1024; i++) { @@ -262,7 +260,7 @@ uint32_t cyclesToRead_nKxs16(int n, short *x, int32_t *res) { return ESP.getCycleCount() - b; } -uint32_t cyclesToWrite_nKxs16(int n, short *x) { +uint32_t cyclesToWrite_nKxs16(int n, short* x) { uint32_t b = ESP.getCycleCount(); int32_t sum = 0; for (int i = 0; i < n * 1024; i++) { @@ -272,7 +270,7 @@ uint32_t cyclesToWrite_nKxs16(int n, short *x) { return ESP.getCycleCount() - b; } -uint32_t cyclesToRead_nKx8(int n, unsigned char*x, uint32_t *res) { +uint32_t cyclesToRead_nKx8(int n, unsigned char* x, uint32_t* res) { uint32_t b = ESP.getCycleCount(); uint32_t sum = 0; for (int i = 0; i < n * 1024; i++) { @@ -282,7 +280,7 @@ uint32_t cyclesToRead_nKx8(int n, unsigned char*x, uint32_t *res) { return ESP.getCycleCount() - b; } -uint32_t cyclesToWrite_nKx8(int n, unsigned char*x) { +uint32_t cyclesToWrite_nKx8(int n, unsigned char* x) { uint32_t b = ESP.getCycleCount(); uint32_t sum = 0; for (int i = 0; i < n * 1024; i++) { @@ -293,7 +291,7 @@ uint32_t cyclesToWrite_nKx8(int n, unsigned char*x) { } // Compare with Inline -uint32_t cyclesToRead_nKx16_viaInline(int n, unsigned short *x, uint32_t *res) { +uint32_t cyclesToRead_nKx16_viaInline(int n, unsigned short* x, uint32_t* res) { uint32_t b = ESP.getCycleCount(); uint32_t sum = 0; for (int i = 0; i < n * 1024; i++) { @@ -303,7 +301,7 @@ uint32_t cyclesToRead_nKx16_viaInline(int n, unsigned short *x, uint32_t *res) { return ESP.getCycleCount() - b; } -uint32_t cyclesToWrite_nKx16_viaInline(int n, unsigned short *x) { +uint32_t cyclesToWrite_nKx16_viaInline(int n, unsigned short* x) { uint32_t b = ESP.getCycleCount(); uint32_t sum = 0; for (int i = 0; i < n * 1024; i++) { @@ -314,7 +312,7 @@ uint32_t cyclesToWrite_nKx16_viaInline(int n, unsigned short *x) { return ESP.getCycleCount() - b; } -uint32_t cyclesToRead_nKxs16_viaInline(int n, short *x, int32_t *res) { +uint32_t cyclesToRead_nKxs16_viaInline(int n, short* x, int32_t* res) { uint32_t b = ESP.getCycleCount(); int32_t sum = 0; for (int i = 0; i < n * 1024; i++) { @@ -324,7 +322,7 @@ uint32_t cyclesToRead_nKxs16_viaInline(int n, short *x, int32_t *res) { return ESP.getCycleCount() - b; } -uint32_t cyclesToWrite_nKxs16_viaInline(int n, short *x) { +uint32_t cyclesToWrite_nKxs16_viaInline(int n, short* x) { uint32_t b = ESP.getCycleCount(); int32_t sum = 0; for (int i = 0; i < n * 1024; i++) { @@ -335,7 +333,7 @@ uint32_t cyclesToWrite_nKxs16_viaInline(int n, short *x) { return ESP.getCycleCount() - b; } -uint32_t cyclesToRead_nKx8_viaInline(int n, unsigned char*x, uint32_t *res) { +uint32_t cyclesToRead_nKx8_viaInline(int n, unsigned char* x, uint32_t* res) { uint32_t b = ESP.getCycleCount(); uint32_t sum = 0; for (int i = 0; i < n * 1024; i++) { @@ -345,7 +343,7 @@ uint32_t cyclesToRead_nKx8_viaInline(int n, unsigned char*x, uint32_t *res) { return ESP.getCycleCount() - b; } -uint32_t cyclesToWrite_nKx8_viaInline(int n, unsigned char*x) { +uint32_t cyclesToWrite_nKx8_viaInline(int n, unsigned char* x) { uint32_t b = ESP.getCycleCount(); uint32_t sum = 0; for (int i = 0; i < n * 1024; i++) { @@ -356,14 +354,14 @@ uint32_t cyclesToWrite_nKx8_viaInline(int n, unsigned char*x) { return ESP.getCycleCount() - b; } - -bool perfTest_nK(int nK, uint32_t *mem, uint32_t *imem) { +bool perfTest_nK(int nK, uint32_t* mem, uint32_t* imem) { uint32_t res, verify_res; uint32_t t; bool success = true; int sres, verify_sres; - Serial.printf("\r\nPerformance numbers for 16 bit access - using inline macros or exception handling for IRAM.\r\n");; + Serial.printf("\r\nPerformance numbers for 16 bit access - using inline macros or exception handling for IRAM.\r\n"); + ; t = cyclesToWrite_nKx16(nK, (uint16_t*)mem); Serial.printf("DRAM Memory Write: %7d cycles for %dK by uint16, %3d AVG cycles/transfer\r\n", t, nK, t / (nK * 1024)); t = cyclesToRead_nKx16(nK, (uint16_t*)mem, &verify_res); @@ -416,7 +414,8 @@ bool perfTest_nK(int nK, uint32_t *mem, uint32_t *imem) { success = false; } - Serial.printf("\r\nPerformance numbers for 8 bit access - using inline macros or exception handling for IRAM access.\r\n");; + Serial.printf("\r\nPerformance numbers for 8 bit access - using inline macros or exception handling for IRAM access.\r\n"); + ; t = cyclesToWrite_nKx8(nK, (uint8_t*)mem); Serial.printf("DRAM Memory Write: %7d cycles for %dK by uint8, %3d AVG cycles/transfer\r\n", t, nK, t / (nK * 1024)); t = cyclesToRead_nKx8(nK, (uint8_t*)mem, &verify_res); @@ -467,7 +466,7 @@ void setup() { // IRAM region. It will continue to use the builtin DRAM until we request // otherwise. Serial.printf("DRAM free: %6d\r\n", ESP.getFreeHeap()); - uint32_t *mem = (uint32_t *)malloc(2 * 1024 * sizeof(uint32_t)); + uint32_t* mem = (uint32_t*)malloc(2 * 1024 * sizeof(uint32_t)); Serial.printf("DRAM buffer: Address %p, free %d\r\n", mem, ESP.getFreeHeap()); if (!mem) { return; @@ -477,12 +476,12 @@ void setup() { #ifdef USE_SET_IRAM_HEAP ESP.setIramHeap(); Serial.printf("IRAM free: %6d\r\n", ESP.getFreeHeap()); - uint32_t *imem = (uint32_t *)malloc(2 * 1024 * sizeof(uint32_t)); + uint32_t* imem = (uint32_t*)malloc(2 * 1024 * sizeof(uint32_t)); Serial.printf("IRAM buffer: Address %p, free %d\r\n", imem, ESP.getFreeHeap()); // Make sure we go back to the DRAM heap for other allocations. Don't forget to ESP.resetHeap()! ESP.resetHeap(); #else - uint32_t *imem; + uint32_t* imem; { HeapSelectIram ephemeral; // This class effectively does this @@ -491,7 +490,7 @@ void setup() { // ... // umm_set_heap_by_id(_heap_id); Serial.printf("IRAM free: %6d\r\n", ESP.getFreeHeap()); - imem = (uint32_t *)malloc(2 * 1024 * sizeof(uint32_t)); + imem = (uint32_t*)malloc(2 * 1024 * sizeof(uint32_t)); Serial.printf("IRAM buffer: Address %p, free %d\r\n", imem, ESP.getFreeHeap()); } #endif @@ -502,7 +501,8 @@ void setup() { uint32_t res; uint32_t t; int nK = 1; - Serial.printf("\r\nPerformance numbers for 32 bit access - no exception handler or inline macros needed.\r\n");; + Serial.printf("\r\nPerformance numbers for 32 bit access - no exception handler or inline macros needed.\r\n"); + ; t = cyclesToWrite_nKx32(nK, mem); Serial.printf("DRAM Memory Write: %7d cycles for %dK by uint32, %3d AVG cycles/transfer\r\n", t, nK, t / (nK * 1024)); t = cyclesToRead_nKx32(nK, mem, &res); @@ -514,7 +514,6 @@ void setup() { Serial.printf("IRAM Memory Read: %7d cycles for %dK by uint32, %3d AVG cycles/transfer (sum %08x)\r\n", t, nK, t / (nK * 1024), res); Serial.println(); - if (perfTest_nK(1, mem, imem) && testPunning() && test4_32bit_loads()) { Serial.println(); } else { @@ -596,9 +595,9 @@ void setup() { uint8_t hfrag; ESP.getHeapStats(&hfree, &hmax, &hfrag); ETS_PRINTF("ESP.getHeapStats(free: %u, max: %u, frag: %u)\n", - hfree, hmax, hfrag); + hfree, hmax, hfrag); if (free_iram > UMM_OVERHEAD_ADJUST) { - void *all = malloc(free_iram - UMM_OVERHEAD_ADJUST); + void* all = malloc(free_iram - UMM_OVERHEAD_ADJUST); ETS_PRINTF("%p = malloc(%u)\n", all, free_iram); umm_info(NULL, true); @@ -614,26 +613,26 @@ void setup() { void processKey(Print& out, int hotKey) { switch (hotKey) { case 'd': { - HeapSelectDram ephemeral; - umm_info(NULL, true); - break; - } + HeapSelectDram ephemeral; + umm_info(NULL, true); + break; + } case 'i': { + HeapSelectIram ephemeral; + umm_info(NULL, true); + break; + } + case 'h': { + { HeapSelectIram ephemeral; - umm_info(NULL, true); - break; + Serial.printf(PSTR("IRAM ESP.getFreeHeap: %u\n"), ESP.getFreeHeap()); } - case 'h': { - { - HeapSelectIram ephemeral; - Serial.printf(PSTR("IRAM ESP.getFreeHeap: %u\n"), ESP.getFreeHeap()); - } - { - HeapSelectDram ephemeral; - Serial.printf(PSTR("DRAM ESP.getFreeHeap: %u\r\n"), ESP.getFreeHeap()); - } - break; + { + HeapSelectDram ephemeral; + Serial.printf(PSTR("DRAM ESP.getFreeHeap: %u\r\n"), ESP.getFreeHeap()); } + break; + } case 'R': out.printf_P(PSTR("Restart, ESP.restart(); ...\r\n")); ESP.restart(); @@ -660,7 +659,6 @@ void processKey(Print& out, int hotKey) { } } - void loop(void) { if (Serial.available() > 0) { int hotKey = Serial.read(); diff --git a/libraries/esp8266/examples/virtualmem/virtualmem.ino b/libraries/esp8266/examples/virtualmem/virtualmem.ino index 47b9396cc7..3a2fc65fe1 100644 --- a/libraries/esp8266/examples/virtualmem/virtualmem.ino +++ b/libraries/esp8266/examples/virtualmem/virtualmem.ino @@ -1,5 +1,5 @@ -uint32_t cyclesToRead1Kx32(unsigned int *x, uint32_t *res) { +uint32_t cyclesToRead1Kx32(unsigned int* x, uint32_t* res) { uint32_t b = ESP.getCycleCount(); uint32_t sum = 0; for (int i = 0; i < 1024; i++) { @@ -9,7 +9,7 @@ uint32_t cyclesToRead1Kx32(unsigned int *x, uint32_t *res) { return ESP.getCycleCount() - b; } -uint32_t cyclesToWrite1Kx32(unsigned int *x) { +uint32_t cyclesToWrite1Kx32(unsigned int* x) { uint32_t b = ESP.getCycleCount(); uint32_t sum = 0; for (int i = 0; i < 1024; i++) { @@ -19,8 +19,7 @@ uint32_t cyclesToWrite1Kx32(unsigned int *x) { return ESP.getCycleCount() - b; } - -uint32_t cyclesToRead1Kx16(unsigned short *x, uint32_t *res) { +uint32_t cyclesToRead1Kx16(unsigned short* x, uint32_t* res) { uint32_t b = ESP.getCycleCount(); uint32_t sum = 0; for (int i = 0; i < 1024; i++) { @@ -30,7 +29,7 @@ uint32_t cyclesToRead1Kx16(unsigned short *x, uint32_t *res) { return ESP.getCycleCount() - b; } -uint32_t cyclesToWrite1Kx16(unsigned short *x) { +uint32_t cyclesToWrite1Kx16(unsigned short* x) { uint32_t b = ESP.getCycleCount(); uint32_t sum = 0; for (int i = 0; i < 1024; i++) { @@ -40,7 +39,7 @@ uint32_t cyclesToWrite1Kx16(unsigned short *x) { return ESP.getCycleCount() - b; } -uint32_t cyclesToRead1Kx8(unsigned char*x, uint32_t *res) { +uint32_t cyclesToRead1Kx8(unsigned char* x, uint32_t* res) { uint32_t b = ESP.getCycleCount(); uint32_t sum = 0; for (int i = 0; i < 1024; i++) { @@ -50,7 +49,7 @@ uint32_t cyclesToRead1Kx8(unsigned char*x, uint32_t *res) { return ESP.getCycleCount() - b; } -uint32_t cyclesToWrite1Kx8(unsigned char*x) { +uint32_t cyclesToWrite1Kx8(unsigned char* x) { uint32_t b = ESP.getCycleCount(); uint32_t sum = 0; for (int i = 0; i < 1024; i++) { @@ -66,12 +65,12 @@ void setup() { // Enabling VM does not change malloc to use the external region. It will continue to // use the normal RAM until we request otherwise. - uint32_t *mem = (uint32_t *)malloc(1024 * sizeof(uint32_t)); + uint32_t* mem = (uint32_t*)malloc(1024 * sizeof(uint32_t)); Serial.printf("Internal buffer: Address %p, free %d\n", mem, ESP.getFreeHeap()); // Now request from the VM heap ESP.setExternalHeap(); - uint32_t *vm = (uint32_t *)malloc(1024 * sizeof(uint32_t)); + uint32_t* vm = (uint32_t*)malloc(1024 * sizeof(uint32_t)); Serial.printf("External buffer: Address %p, free %d\n", vm, ESP.getFreeHeap()); // Make sure we go back to the internal heap for other allocations. Don't forget to ESP.resetHeap()! ESP.resetHeap(); @@ -134,5 +133,4 @@ void setup() { } void loop() { - } diff --git a/libraries/lwIP_PPP/examples/PPPServer/PPPServer.ino b/libraries/lwIP_PPP/examples/PPPServer/PPPServer.ino index ed2943c278..c9139e6852 100644 --- a/libraries/lwIP_PPP/examples/PPPServer/PPPServer.ino +++ b/libraries/lwIP_PPP/examples/PPPServer/PPPServer.ino @@ -25,7 +25,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif #define LOGGERBAUD 115200 @@ -43,9 +43,9 @@ PPPServer ppp(&ppplink); void PPPConnectedCallback(netif* nif) { logger.printf("ppp: ip=%s/mask=%s/gw=%s\n", - IPAddress(&nif->ip_addr).toString().c_str(), - IPAddress(&nif->netmask).toString().c_str(), - IPAddress(&nif->gw).toString().c_str()); + IPAddress(&nif->ip_addr).toString().c_str(), + IPAddress(&nif->netmask).toString().c_str(), + IPAddress(&nif->gw).toString().c_str()); logger.printf("Heap before: %d\n", ESP.getFreeHeap()); err_t ret = ip_napt_init(NAPT, NAPT_PORT); @@ -80,9 +80,9 @@ void setup() { delay(500); } logger.printf("\nSTA: %s (dns: %s / %s)\n", - WiFi.localIP().toString().c_str(), - WiFi.dnsIP(0).toString().c_str(), - WiFi.dnsIP(1).toString().c_str()); + WiFi.localIP().toString().c_str(), + WiFi.dnsIP(0).toString().c_str(), + WiFi.dnsIP(1).toString().c_str()); ppplink.begin(PPPLINKBAUD); ppplink.enableIntTx(true); @@ -97,7 +97,6 @@ void setup() { logger.printf("ppp: %d\n", ret); } - #else void setup() { diff --git a/libraries/lwIP_PPP/src/PPPServer.cpp b/libraries/lwIP_PPP/src/PPPServer.cpp index 04512102fd..1b8279a56b 100644 --- a/libraries/lwIP_PPP/src/PPPServer.cpp +++ b/libraries/lwIP_PPP/src/PPPServer.cpp @@ -17,7 +17,9 @@ #include "PPPServer.h" PPPServer::PPPServer(Stream* sio) - : _sio(sio), _cb(netif_status_cb_s), _enabled(false) + : _sio(sio) + , _cb(netif_status_cb_s) + , _enabled(false) { } @@ -44,85 +46,85 @@ void PPPServer::link_status_cb_s(ppp_pcb* pcb, int err_code, void* ctx) switch (err_code) { - case PPPERR_NONE: /* No error. */ - { + case PPPERR_NONE: /* No error. */ + { #if LWIP_DNS - const ip_addr_t* ns; + const ip_addr_t* ns; #endif /* LWIP_DNS */ - ets_printf("ppp_link_status_cb: PPPERR_NONE\n\r"); + ets_printf("ppp_link_status_cb: PPPERR_NONE\n\r"); #if LWIP_IPV4 - ets_printf(" our_ip4addr = %s\n\r", ip4addr_ntoa(netif_ip4_addr(nif))); - ets_printf(" his_ipaddr = %s\n\r", ip4addr_ntoa(netif_ip4_gw(nif))); - ets_printf(" netmask = %s\n\r", ip4addr_ntoa(netif_ip4_netmask(nif))); + ets_printf(" our_ip4addr = %s\n\r", ip4addr_ntoa(netif_ip4_addr(nif))); + ets_printf(" his_ipaddr = %s\n\r", ip4addr_ntoa(netif_ip4_gw(nif))); + ets_printf(" netmask = %s\n\r", ip4addr_ntoa(netif_ip4_netmask(nif))); #endif /* LWIP_IPV4 */ #if LWIP_IPV6 - ets_printf(" our_ip6addr = %s\n\r", ip6addr_ntoa(netif_ip6_addr(nif, 0))); + ets_printf(" our_ip6addr = %s\n\r", ip6addr_ntoa(netif_ip6_addr(nif, 0))); #endif /* LWIP_IPV6 */ #if LWIP_DNS - ns = dns_getserver(0); - ets_printf(" dns1 = %s\n\r", ipaddr_ntoa(ns)); - ns = dns_getserver(1); - ets_printf(" dns2 = %s\n\r", ipaddr_ntoa(ns)); + ns = dns_getserver(0); + ets_printf(" dns1 = %s\n\r", ipaddr_ntoa(ns)); + ns = dns_getserver(1); + ets_printf(" dns2 = %s\n\r", ipaddr_ntoa(ns)); #endif /* LWIP_DNS */ #if PPP_IPV6_SUPPORT - ets_printf(" our6_ipaddr = %s\n\r", ip6addr_ntoa(netif_ip6_addr(nif, 0))); + ets_printf(" our6_ipaddr = %s\n\r", ip6addr_ntoa(netif_ip6_addr(nif, 0))); #endif /* PPP_IPV6_SUPPORT */ - } - stop = false; - break; + } + stop = false; + break; - case PPPERR_PARAM: /* Invalid parameter. */ - ets_printf("ppp_link_status_cb: PPPERR_PARAM\n"); - break; + case PPPERR_PARAM: /* Invalid parameter. */ + ets_printf("ppp_link_status_cb: PPPERR_PARAM\n"); + break; - case PPPERR_OPEN: /* Unable to open PPP session. */ - ets_printf("ppp_link_status_cb: PPPERR_OPEN\n"); - break; + case PPPERR_OPEN: /* Unable to open PPP session. */ + ets_printf("ppp_link_status_cb: PPPERR_OPEN\n"); + break; - case PPPERR_DEVICE: /* Invalid I/O device for PPP. */ - ets_printf("ppp_link_status_cb: PPPERR_DEVICE\n"); - break; + case PPPERR_DEVICE: /* Invalid I/O device for PPP. */ + ets_printf("ppp_link_status_cb: PPPERR_DEVICE\n"); + break; - case PPPERR_ALLOC: /* Unable to allocate resources. */ - ets_printf("ppp_link_status_cb: PPPERR_ALLOC\n"); - break; + case PPPERR_ALLOC: /* Unable to allocate resources. */ + ets_printf("ppp_link_status_cb: PPPERR_ALLOC\n"); + break; - case PPPERR_USER: /* User interrupt. */ - ets_printf("ppp_link_status_cb: PPPERR_USER\n"); - break; + case PPPERR_USER: /* User interrupt. */ + ets_printf("ppp_link_status_cb: PPPERR_USER\n"); + break; - case PPPERR_CONNECT: /* Connection lost. */ - ets_printf("ppp_link_status_cb: PPPERR_CONNECT\n"); - break; + case PPPERR_CONNECT: /* Connection lost. */ + ets_printf("ppp_link_status_cb: PPPERR_CONNECT\n"); + break; - case PPPERR_AUTHFAIL: /* Failed authentication challenge. */ - ets_printf("ppp_link_status_cb: PPPERR_AUTHFAIL\n"); - break; + case PPPERR_AUTHFAIL: /* Failed authentication challenge. */ + ets_printf("ppp_link_status_cb: PPPERR_AUTHFAIL\n"); + break; - case PPPERR_PROTOCOL: /* Failed to meet protocol. */ - ets_printf("ppp_link_status_cb: PPPERR_PROTOCOL\n"); - break; + case PPPERR_PROTOCOL: /* Failed to meet protocol. */ + ets_printf("ppp_link_status_cb: PPPERR_PROTOCOL\n"); + break; - case PPPERR_PEERDEAD: /* Connection timeout. */ - ets_printf("ppp_link_status_cb: PPPERR_PEERDEAD\n"); - break; + case PPPERR_PEERDEAD: /* Connection timeout. */ + ets_printf("ppp_link_status_cb: PPPERR_PEERDEAD\n"); + break; - case PPPERR_IDLETIMEOUT: /* Idle Timeout. */ - ets_printf("ppp_link_status_cb: PPPERR_IDLETIMEOUT\n"); - break; + case PPPERR_IDLETIMEOUT: /* Idle Timeout. */ + ets_printf("ppp_link_status_cb: PPPERR_IDLETIMEOUT\n"); + break; - case PPPERR_CONNECTTIME: /* PPPERR_CONNECTTIME. */ - ets_printf("ppp_link_status_cb: PPPERR_CONNECTTIME\n"); - break; + case PPPERR_CONNECTTIME: /* PPPERR_CONNECTTIME. */ + ets_printf("ppp_link_status_cb: PPPERR_CONNECTTIME\n"); + break; - case PPPERR_LOOPBACK: /* Connection timeout. */ - ets_printf("ppp_link_status_cb: PPPERR_LOOPBACK\n"); - break; + case PPPERR_LOOPBACK: /* Connection timeout. */ + ets_printf("ppp_link_status_cb: PPPERR_LOOPBACK\n"); + break; - default: - ets_printf("ppp_link_status_cb: unknown errCode %d\n", err_code); - break; + default: + ets_printf("ppp_link_status_cb: unknown errCode %d\n", err_code); + break; } if (stop) @@ -141,7 +143,7 @@ u32_t PPPServer::output_cb_s(ppp_pcb* pcb, u8_t* data, u32_t len, void* ctx) void PPPServer::netif_status_cb_s(netif* nif) { ets_printf("PPPNETIF: %c%c%d is %s\n", nif->name[0], nif->name[1], nif->num, - netif_is_up(nif) ? "UP" : "DOWN"); + netif_is_up(nif) ? "UP" : "DOWN"); #if LWIP_IPV4 ets_printf("IPV4: Host at %s ", ip4addr_ntoa(netif_ip4_addr(nif))); ets_printf("mask %s ", ip4addr_ntoa(netif_ip4_netmask(nif))); @@ -179,8 +181,8 @@ bool PPPServer::begin(const IPAddress& ourAddress, const IPAddress& peer) _enabled = true; if (!schedule_recurrent_function_us([&]() - { return this->handlePackets(); }, - 1000)) + { return this->handlePackets(); }, + 1000)) { netif_remove(&_netif); return false; diff --git a/libraries/lwIP_PPP/src/PPPServer.h b/libraries/lwIP_PPP/src/PPPServer.h index 5bae0ebe6b..326aa16f69 100644 --- a/libraries/lwIP_PPP/src/PPPServer.h +++ b/libraries/lwIP_PPP/src/PPPServer.h @@ -38,7 +38,7 @@ class PPPServer { - public: +public: PPPServer(Stream* sio); bool begin(const IPAddress& ourAddress, const IPAddress& peer = IPAddress(172, 31, 255, 254)); @@ -53,7 +53,7 @@ class PPPServer return &_netif.gw; } - protected: +protected: static constexpr size_t _bufsize = 128; Stream* _sio; ppp_pcb* _ppp; diff --git a/libraries/lwIP_enc28j60/src/utility/enc28j60.cpp b/libraries/lwIP_enc28j60/src/utility/enc28j60.cpp index 0fa4ca0989..bbc00041ca 100644 --- a/libraries/lwIP_enc28j60/src/utility/enc28j60.cpp +++ b/libraries/lwIP_enc28j60/src/utility/enc28j60.cpp @@ -149,7 +149,9 @@ void serial_printf(const char* fmt, ...) static const SPISettings spiSettings(20000000, MSBFIRST, SPI_MODE0); ENC28J60::ENC28J60(int8_t cs, SPIClass& spi, int8_t intr) - : _bank(ERXTX_BANK), _cs(cs), _spi(spi) + : _bank(ERXTX_BANK) + , _cs(cs) + , _spi(spi) { (void)intr; } @@ -173,14 +175,14 @@ ENC28J60::is_mac_mii_reg(uint8_t reg) /* MAC or MII register (otherwise, ETH register)? */ switch (_bank) { - case MACONX_BANK: - return reg < EIE; - case MAADRX_BANK: - return reg <= MAADR2 || reg == MISTAT; - case ERXTX_BANK: - case EPKTCNT_BANK: - default: - return 0; + case MACONX_BANK: + return reg < EIE; + case MAADRX_BANK: + return reg <= MAADR2 || reg == MISTAT; + case ERXTX_BANK: + case EPKTCNT_BANK: + default: + return 0; } } /*---------------------------------------------------------------------------*/ @@ -304,12 +306,12 @@ ENC28J60::readrev(void) rev = readreg(EREVID); switch (rev) { - case 2: - return 1; - case 6: - return 7; - default: - return rev; + case 2: + return 1; + case 6: + return 7; + default: + return rev; } } //#endif @@ -463,8 +465,7 @@ bool ENC28J60::reset(void) setregbitfield(MACON1, MACON1_MARXEN | MACON1_TXPAUS | MACON1_RXPAUS); /* Set padding, crc, full duplex */ - setregbitfield(MACON3, MACON3_PADCFG_FULL | MACON3_TXCRCEN | MACON3_FULDPX | - MACON3_FRMLNEN); + setregbitfield(MACON3, MACON3_PADCFG_FULL | MACON3_TXCRCEN | MACON3_FULDPX | MACON3_FRMLNEN); /* Don't modify MACON4 */ @@ -616,8 +617,8 @@ ENC28J60::sendFrame(const uint8_t* data, uint16_t datalen) else { PRINTF("enc28j60: tx: %d: %02x:%02x:%02x:%02x:%02x:%02x\n", datalen, - 0xff & data[0], 0xff & data[1], 0xff & data[2], - 0xff & data[3], 0xff & data[4], 0xff & data[5]); + 0xff & data[0], 0xff & data[1], 0xff & data[2], + 0xff & data[3], 0xff & data[4], 0xff & data[5]); } #endif @@ -728,8 +729,8 @@ ENC28J60::readFrameData(uint8_t* buffer, uint16_t framesize) return 0; } PRINTF("enc28j60: rx: %d: %02x:%02x:%02x:%02x:%02x:%02x\n", _len, - 0xff & buffer[0], 0xff & buffer[1], 0xff & buffer[2], - 0xff & buffer[3], 0xff & buffer[4], 0xff & buffer[5]); + 0xff & buffer[0], 0xff & buffer[1], 0xff & buffer[2], + 0xff & buffer[3], 0xff & buffer[4], 0xff & buffer[5]); //received_packets++; //PRINTF("enc28j60: received_packets %d\n", received_packets); diff --git a/libraries/lwIP_enc28j60/src/utility/enc28j60.h b/libraries/lwIP_enc28j60/src/utility/enc28j60.h index fb544e1bfc..fe5ef49576 100644 --- a/libraries/lwIP_enc28j60/src/utility/enc28j60.h +++ b/libraries/lwIP_enc28j60/src/utility/enc28j60.h @@ -46,7 +46,7 @@ */ class ENC28J60 { - public: +public: /** Constructor that uses the default hardware SPI pins @param cs the Arduino Chip Select / Slave Select pin (default 10 on Uno) @@ -79,7 +79,7 @@ class ENC28J60 */ virtual uint16_t readFrame(uint8_t* buffer, uint16_t bufsize); - protected: +protected: static constexpr bool interruptIsPossible() { return false; @@ -109,7 +109,7 @@ class ENC28J60 */ uint16_t readFrameData(uint8_t* frame, uint16_t framesize); - private: +private: uint8_t is_mac_mii_reg(uint8_t reg); uint8_t readreg(uint8_t reg); void writereg(uint8_t reg, uint8_t data); diff --git a/libraries/lwIP_w5100/src/utility/w5100.cpp b/libraries/lwIP_w5100/src/utility/w5100.cpp index 1251579744..aae85a154b 100644 --- a/libraries/lwIP_w5100/src/utility/w5100.cpp +++ b/libraries/lwIP_w5100/src/utility/w5100.cpp @@ -204,7 +204,8 @@ void Wiznet5100::wizchip_sw_reset() } Wiznet5100::Wiznet5100(int8_t cs, SPIClass& spi, int8_t intr) - : _spi(spi), _cs(cs) + : _spi(spi) + , _cs(cs) { (void)intr; } diff --git a/libraries/lwIP_w5100/src/utility/w5100.h b/libraries/lwIP_w5100/src/utility/w5100.h index f099b22ea1..12c09085ef 100644 --- a/libraries/lwIP_w5100/src/utility/w5100.h +++ b/libraries/lwIP_w5100/src/utility/w5100.h @@ -41,7 +41,7 @@ class Wiznet5100 { - public: +public: /** Constructor that uses the default hardware SPI pins @param cs the Arduino Chip Select / Slave Select pin (default 10) @@ -79,7 +79,7 @@ class Wiznet5100 */ uint16_t readFrame(uint8_t* buffer, uint16_t bufsize); - protected: +protected: static constexpr bool interruptIsPossible() { return false; @@ -109,7 +109,7 @@ class Wiznet5100 */ uint16_t readFrameData(uint8_t* frame, uint16_t framesize); - private: +private: static const uint16_t TxBufferAddress = 0x4000; /* Internal Tx buffer address of the iinchip */ static const uint16_t RxBufferAddress = 0x6000; /* Internal Rx buffer address of the iinchip */ static const uint8_t TxBufferSize = 0x3; /* Buffer size configuration: 0=1kb, 1=2kB, 2=4kB, 3=8kB */ diff --git a/libraries/lwIP_w5500/src/utility/w5500.cpp b/libraries/lwIP_w5500/src/utility/w5500.cpp index 90f607f0cf..723e85ac19 100644 --- a/libraries/lwIP_w5500/src/utility/w5500.cpp +++ b/libraries/lwIP_w5500/src/utility/w5500.cpp @@ -278,7 +278,8 @@ int8_t Wiznet5500::wizphy_setphypmode(uint8_t pmode) } Wiznet5500::Wiznet5500(int8_t cs, SPIClass& spi, int8_t intr) - : _spi(spi), _cs(cs) + : _spi(spi) + , _cs(cs) { (void)intr; } diff --git a/libraries/lwIP_w5500/src/utility/w5500.h b/libraries/lwIP_w5500/src/utility/w5500.h index 8b41529610..232b0e7939 100644 --- a/libraries/lwIP_w5500/src/utility/w5500.h +++ b/libraries/lwIP_w5500/src/utility/w5500.h @@ -41,7 +41,7 @@ class Wiznet5500 { - public: +public: /** Constructor that uses the default hardware SPI pins @param cs the Arduino Chip Select / Slave Select pin (default 10) @@ -79,7 +79,7 @@ class Wiznet5500 */ uint16_t readFrame(uint8_t* buffer, uint16_t bufsize); - protected: +protected: static constexpr bool interruptIsPossible() { return false; @@ -109,7 +109,7 @@ class Wiznet5500 */ uint16_t readFrameData(uint8_t* frame, uint16_t framesize); - private: +private: //< SPI interface Read operation in Control Phase static const uint8_t AccessModeRead = (0x00 << 2); diff --git a/tests/astyle_core.conf b/tests/astyle_core.conf deleted file mode 100644 index f9ee90adb6..0000000000 --- a/tests/astyle_core.conf +++ /dev/null @@ -1,32 +0,0 @@ -# Code formatting rules for Arduino examples, taken from: -# -# https://github.com/arduino/Arduino/blob/master/build/shared/examples_formatter.conf -# - -mode=c -lineend=linux -style=allman - -# 4 spaces indentation -indent=spaces=4 - -# also indent macros -#indent-preprocessor - -# indent classes, switches (and cases), comments starting at column 1 -indent-col1-comments - -# put a space around operators -pad-oper - -# put a space after if/for/while -pad-header - -# if you like one-liners, keep them -keep-one-line-statements - -attach-closing-while -unpad-paren -pad-oper -remove-comment-prefix -add-braces diff --git a/tests/astyle_examples.conf b/tests/astyle_examples.conf deleted file mode 100644 index f3b77f2cb4..0000000000 --- a/tests/astyle_examples.conf +++ /dev/null @@ -1,44 +0,0 @@ -# Code formatting rules for Arduino examples, taken from: -# -# https://github.com/arduino/Arduino/blob/master/build/shared/examples_formatter.conf -# - -mode=c -lineend=linux - -# 2 spaces indentation -indent=spaces=2 - -# also indent macros -#indent-preprocessor - -# indent classes, switches (and cases), comments starting at column 1 -indent-classes -indent-switches -indent-cases -indent-col1-comments - -# put a space around operators -pad-oper - -# put a space after if/for/while -pad-header - -# if you like one-liners, keep them -keep-one-line-statements -add-braces - -style=java -attach-namespaces -attach-classes -attach-inlines -attach-extern-c -indent-modifiers -indent-namespaces -indent-labels -#indent-preproc-block -#indent-preproc-define -#indent-preproc-cond -unpad-paren -add-braces -remove-comment-prefix \ No newline at end of file diff --git a/tests/clang-format-arduino b/tests/clang-format-arduino new file mode 100644 index 0000000000..69b5a295f8 --- /dev/null +++ b/tests/clang-format-arduino @@ -0,0 +1,5 @@ +BasedOnStyle: WebKit +IndentWidth: 2 +SortIncludes: false +BreakBeforeBraces: Attach +IndentCaseLabels: true diff --git a/.clang-format b/tests/clang-format-core similarity index 88% rename from .clang-format rename to tests/clang-format-core index 0bde5080d7..7d0d1d9c90 100644 --- a/.clang-format +++ b/tests/clang-format-core @@ -1,4 +1,4 @@ -BasedOnStyle: Chromium +BasedOnStyle: WebKit AlignTrailingComments: true BreakBeforeBraces: Allman ColumnLimit: 0 diff --git a/tests/device/libraries/BSTest/src/BSArduino.h b/tests/device/libraries/BSTest/src/BSArduino.h index f77e6d0f86..b70a265ea0 100644 --- a/tests/device/libraries/BSTest/src/BSArduino.h +++ b/tests/device/libraries/BSTest/src/BSArduino.h @@ -6,7 +6,7 @@ namespace bs { class ArduinoIOHelper { - public: +public: ArduinoIOHelper(Stream& stream) : m_stream(stream) { @@ -66,7 +66,7 @@ class ArduinoIOHelper return len; } - protected: +protected: Stream& m_stream; }; diff --git a/tests/device/libraries/BSTest/src/BSArgs.h b/tests/device/libraries/BSTest/src/BSArgs.h index e939f55534..d7ce60500f 100644 --- a/tests/device/libraries/BSTest/src/BSArgs.h +++ b/tests/device/libraries/BSTest/src/BSArgs.h @@ -17,19 +17,19 @@ namespace protocol { #define SS_FLAG_ESCAPE 0x8 -typedef enum -{ - /* parsing the space between arguments */ - SS_SPACE = 0x0, - /* parsing an argument which isn't quoted */ - SS_ARG = 0x1, - /* parsing a quoted argument */ - SS_QUOTED_ARG = 0x2, - /* parsing an escape sequence within unquoted argument */ - SS_ARG_ESCAPED = SS_ARG | SS_FLAG_ESCAPE, - /* parsing an escape sequence within a quoted argument */ - SS_QUOTED_ARG_ESCAPED = SS_QUOTED_ARG | SS_FLAG_ESCAPE, -} split_state_t; + typedef enum + { + /* parsing the space between arguments */ + SS_SPACE = 0x0, + /* parsing an argument which isn't quoted */ + SS_ARG = 0x1, + /* parsing a quoted argument */ + SS_QUOTED_ARG = 0x2, + /* parsing an escape sequence within unquoted argument */ + SS_ARG_ESCAPED = SS_ARG | SS_FLAG_ESCAPE, + /* parsing an escape sequence within a quoted argument */ + SS_QUOTED_ARG_ESCAPED = SS_QUOTED_ARG | SS_FLAG_ESCAPE, + } split_state_t; /* helper macro, called when done with an argument */ #define END_ARG() \ @@ -40,7 +40,7 @@ typedef enum state = SS_SPACE; \ } while (0); -/** + /** * @brief Split command line into arguments in place * * - This function finds whitespace-separated arguments in the given input line. @@ -64,26 +64,26 @@ typedef enum * @param argv_size number of elements in argv_array (max. number of arguments will be argv_size - 1) * @return number of arguments found (argc) */ -inline size_t split_args(char* line, char** argv, size_t argv_size) -{ - const int QUOTE = '"'; - const int ESCAPE = '\\'; - const int SPACE = ' '; - split_state_t state = SS_SPACE; - size_t argc = 0; - char* next_arg_start = line; - char* out_ptr = line; - for (char* in_ptr = line; argc < argv_size - 1; ++in_ptr) + inline size_t split_args(char* line, char** argv, size_t argv_size) { - int char_in = (unsigned char)*in_ptr; - if (char_in == 0) + const int QUOTE = '"'; + const int ESCAPE = '\\'; + const int SPACE = ' '; + split_state_t state = SS_SPACE; + size_t argc = 0; + char* next_arg_start = line; + char* out_ptr = line; + for (char* in_ptr = line; argc < argv_size - 1; ++in_ptr) { - break; - } - int char_out = -1; + int char_in = (unsigned char)*in_ptr; + if (char_in == 0) + { + break; + } + int char_out = -1; - switch (state) - { + switch (state) + { case SS_SPACE: if (char_in == SPACE) { @@ -149,26 +149,26 @@ inline size_t split_args(char* line, char** argv, size_t argv_size) char_out = char_in; } break; + } + /* need to output anything? */ + if (char_out >= 0) + { + *out_ptr = char_out; + ++out_ptr; + } } - /* need to output anything? */ - if (char_out >= 0) + /* make sure the final argument is terminated */ + *out_ptr = 0; + /* finalize the last argument */ + if (state != SS_SPACE && argc < argv_size - 1) { - *out_ptr = char_out; - ++out_ptr; + argv[argc++] = next_arg_start; } - } - /* make sure the final argument is terminated */ - *out_ptr = 0; - /* finalize the last argument */ - if (state != SS_SPACE && argc < argv_size - 1) - { - argv[argc++] = next_arg_start; - } - /* add a NULL at the end of argv */ - argv[argc] = NULL; + /* add a NULL at the end of argv */ + argv[argc] = NULL; - return argc; -} + return argc; + } } // namespace protocol diff --git a/tests/device/libraries/BSTest/src/BSProtocol.h b/tests/device/libraries/BSTest/src/BSProtocol.h index 08400e02ce..9b1d128ae1 100644 --- a/tests/device/libraries/BSTest/src/BSProtocol.h +++ b/tests/device/libraries/BSTest/src/BSProtocol.h @@ -11,115 +11,115 @@ namespace bs { namespace protocol { -template -void output_test_start(IO& io, const char* file, size_t line, const char* name, const char* desc) -{ - io.printf(BS_LINE_PREFIX "start file=\"%s\" line=%d name=\"%s\" desc=\"%s\"\n", file, line, name, desc); -} - -template -void output_check_failure(IO& io, size_t line) -{ - io.printf(BS_LINE_PREFIX "check_failure line=%d\n", line); -} - -template -void output_test_end(IO& io, bool success, size_t checks, size_t failed_checks, size_t line = 0) -{ - io.printf(BS_LINE_PREFIX "end line=%d result=%d checks=%d failed_checks=%d\n", line, success, checks, failed_checks); -} + template + void output_test_start(IO& io, const char* file, size_t line, const char* name, const char* desc) + { + io.printf(BS_LINE_PREFIX "start file=\"%s\" line=%d name=\"%s\" desc=\"%s\"\n", file, line, name, desc); + } -template -void output_menu_begin(IO& io) -{ - io.printf(BS_LINE_PREFIX "menu_begin\n"); -} + template + void output_check_failure(IO& io, size_t line) + { + io.printf(BS_LINE_PREFIX "check_failure line=%d\n", line); + } -template -void output_menu_item(IO& io, int index, const char* name, const char* desc) -{ - io.printf(BS_LINE_PREFIX "item id=%d name=\"%s\" desc=\"%s\"\n", index, name, desc); -} + template + void output_test_end(IO& io, bool success, size_t checks, size_t failed_checks, size_t line = 0) + { + io.printf(BS_LINE_PREFIX "end line=%d result=%d checks=%d failed_checks=%d\n", line, success, checks, failed_checks); + } -template -void output_menu_end(IO& io) -{ - io.printf(BS_LINE_PREFIX "menu_end\n"); -} + template + void output_menu_begin(IO& io) + { + io.printf(BS_LINE_PREFIX "menu_begin\n"); + } -template -void output_setenv_result(IO& io, const char* key, const char* value) -{ - io.printf(BS_LINE_PREFIX "setenv key=\"%s\" value=\"%s\"\n", key, value); -} + template + void output_menu_item(IO& io, int index, const char* name, const char* desc) + { + io.printf(BS_LINE_PREFIX "item id=%d name=\"%s\" desc=\"%s\"\n", index, name, desc); + } -template -void output_getenv_result(IO& io, const char* key, const char* value) -{ - (void)key; - io.printf(BS_LINE_PREFIX "getenv value=\"%s\"\n", value); -} + template + void output_menu_end(IO& io) + { + io.printf(BS_LINE_PREFIX "menu_end\n"); + } -template -void output_pretest_result(IO& io, bool res) -{ - io.printf(BS_LINE_PREFIX "pretest result=%d\n", res ? 1 : 0); -} + template + void output_setenv_result(IO& io, const char* key, const char* value) + { + io.printf(BS_LINE_PREFIX "setenv key=\"%s\" value=\"%s\"\n", key, value); + } -template -bool input_handle(IO& io, char* line_buf, size_t line_buf_size, int& test_num) -{ - int cb_read = io.read_line(line_buf, line_buf_size); - if (cb_read == 0 || line_buf[0] == '\n') + template + void output_getenv_result(IO& io, const char* key, const char* value) { - return false; + (void)key; + io.printf(BS_LINE_PREFIX "getenv value=\"%s\"\n", value); } - char* argv[4]; - size_t argc = split_args(line_buf, argv, sizeof(argv) / sizeof(argv[0])); - if (argc == 0) + + template + void output_pretest_result(IO& io, bool res) { - return false; + io.printf(BS_LINE_PREFIX "pretest result=%d\n", res ? 1 : 0); } - if (strcmp(argv[0], "setenv") == 0) + + template + bool input_handle(IO& io, char* line_buf, size_t line_buf_size, int& test_num) { - if (argc != 3) + int cb_read = io.read_line(line_buf, line_buf_size); + if (cb_read == 0 || line_buf[0] == '\n') { return false; } - setenv(argv[1], argv[2], 1); - output_setenv_result(io, argv[1], argv[2]); - test_num = -1; - return false; /* we didn't get the test number yet, so return false */ - } - if (strcmp(argv[0], "getenv") == 0) - { - if (argc != 2) + char* argv[4]; + size_t argc = split_args(line_buf, argv, sizeof(argv) / sizeof(argv[0])); + if (argc == 0) { return false; } - const char* value = getenv(argv[1]); - output_getenv_result(io, argv[1], (value != NULL) ? value : ""); - return false; - } - if (strcmp(argv[0], "pretest") == 0) - { - if (argc != 1) + if (strcmp(argv[0], "setenv") == 0) { + if (argc != 3) + { + return false; + } + setenv(argv[1], argv[2], 1); + output_setenv_result(io, argv[1], argv[2]); + test_num = -1; + return false; /* we didn't get the test number yet, so return false */ + } + if (strcmp(argv[0], "getenv") == 0) + { + if (argc != 2) + { + return false; + } + const char* value = getenv(argv[1]); + output_getenv_result(io, argv[1], (value != NULL) ? value : ""); return false; } - bool res = ::pretest(); - output_pretest_result(io, res); - return false; - } - /* not one of the commands, try to parse as test number */ - char* endptr; - test_num = (int)strtol(argv[0], &endptr, 10); - if (endptr != argv[0] + strlen(argv[0])) - { - return false; + if (strcmp(argv[0], "pretest") == 0) + { + if (argc != 1) + { + return false; + } + bool res = ::pretest(); + output_pretest_result(io, res); + return false; + } + /* not one of the commands, try to parse as test number */ + char* endptr; + test_num = (int)strtol(argv[0], &endptr, 10); + if (endptr != argv[0] + strlen(argv[0])) + { + return false; + } + return true; } - return true; -} } // namespace protocol } // namespace bs diff --git a/tests/device/libraries/BSTest/src/BSStdio.h b/tests/device/libraries/BSTest/src/BSStdio.h index 97a2c1230c..892ecaa9d4 100644 --- a/tests/device/libraries/BSTest/src/BSStdio.h +++ b/tests/device/libraries/BSTest/src/BSStdio.h @@ -8,7 +8,7 @@ namespace bs { class StdIOHelper { - public: +public: StdIOHelper() { } diff --git a/tests/device/libraries/BSTest/src/BSTest.h b/tests/device/libraries/BSTest/src/BSTest.h index bc9154a5ae..d4e9126265 100644 --- a/tests/device/libraries/BSTest/src/BSTest.h +++ b/tests/device/libraries/BSTest/src/BSTest.h @@ -24,9 +24,13 @@ typedef void (*test_case_func_t)(); class TestCase { - public: +public: TestCase(TestCase* prev, test_case_func_t func, const char* file, size_t line, const char* name, const char* desc) - : m_func(func), m_file(file), m_line(line), m_name(name), m_desc(desc) + : m_func(func) + , m_file(file) + , m_line(line) + , m_name(name) + , m_desc(desc) { if (prev) { @@ -64,7 +68,7 @@ class TestCase return (m_desc) ? m_desc : ""; } - protected: +protected: TestCase* m_next = nullptr; test_case_func_t m_func; const char* m_file; @@ -103,7 +107,7 @@ class Runner { typedef Runner Tself; - public: +public: Runner(IO& io) : m_io(io) { @@ -143,7 +147,7 @@ class Runner bs::fatal(); } - protected: +protected: bool do_menu() { protocol::output_menu_begin(m_io); @@ -181,7 +185,7 @@ class Runner } } - protected: +protected: IO& m_io; size_t m_check_pass_count; size_t m_check_fail_count; @@ -189,7 +193,7 @@ class Runner class AutoReg { - public: +public: AutoReg(test_case_func_t func, const char* file, size_t line, const char* name, const char* desc = nullptr) { g_env.m_registry.add(func, file, line, name, desc); @@ -227,12 +231,12 @@ inline void require(bool condition, size_t line) #define BS_NAME_LINE(name, line) BS_NAME_LINE2(name, line) #define BS_UNIQUE_NAME(name) BS_NAME_LINE(name, __LINE__) -#define TEST_CASE(...) \ - static void BS_UNIQUE_NAME(TEST_FUNC__)(); \ - namespace \ - { \ - bs::AutoReg BS_UNIQUE_NAME(test_autoreg__)(&BS_UNIQUE_NAME(TEST_FUNC__), __FILE__, __LINE__, __VA_ARGS__); \ - } \ +#define TEST_CASE(...) \ + static void BS_UNIQUE_NAME(TEST_FUNC__)(); \ + namespace \ + { \ + bs::AutoReg BS_UNIQUE_NAME(test_autoreg__)(&BS_UNIQUE_NAME(TEST_FUNC__), __FILE__, __LINE__, __VA_ARGS__); \ + } \ static void BS_UNIQUE_NAME(TEST_FUNC__)() #define CHECK(condition) bs::check((condition), __LINE__) @@ -242,7 +246,7 @@ inline void require(bool condition, size_t line) #define BS_ENV_DECLARE() \ namespace bs \ { \ - Env g_env; \ + Env g_env; \ } #define BS_RUN(...) \ do \ diff --git a/tests/device/test_libc/memmove1.c b/tests/device/test_libc/memmove1.c index 8aadfb7753..7a4c915b4b 100644 --- a/tests/device/test_libc/memmove1.c +++ b/tests/device/test_libc/memmove1.c @@ -91,7 +91,7 @@ void xmemmove(unsigned char* dest, unsigned char* src, size_t n) { errors++; DEBUGP("memmove of n bytes returned %p instead of dest=%p\n", - retp, dest); + retp, dest); } } diff --git a/tests/device/test_libc/tstring.c b/tests/device/test_libc/tstring.c index fd6e16842e..ddf326934f 100644 --- a/tests/device/test_libc/tstring.c +++ b/tests/device/test_libc/tstring.c @@ -30,10 +30,10 @@ void eprintf(int line, char* result, char* expected, int size) { if (size != 0) printf("Failure at line %d, result is <%.*s>, should be <%s> of size %d\n", - line, size, result, expected, size); + line, size, result, expected, size); else printf("Failure at line %d, result is <%s>, should be <%s>\n", - line, result, expected); + line, result, expected); } void mycopy(char* target, char* source, int size) @@ -87,113 +87,77 @@ void tstring_main(void) tmp2[0] = 'Z'; tmp2[1] = '\0'; - if (memset(target, 'X', 0) != target || - memcpy(target, "Y", 0) != target || - memmove(target, "K", 0) != target || - strncpy(tmp2, "4", 0) != tmp2 || - strncat(tmp2, "123", 0) != tmp2 || - strcat(target, "") != target) + if (memset(target, 'X', 0) != target || memcpy(target, "Y", 0) != target || memmove(target, "K", 0) != target || strncpy(tmp2, "4", 0) != tmp2 || strncat(tmp2, "123", 0) != tmp2 || strcat(target, "") != target) { eprintf(__LINE__, target, "A", 0); test_failed = 1; } - if (strcmp(target, "A") || strlen(target) != 1 || memchr(target, 'A', 0) != NULL || memcmp(target, "J", 0) || strncmp(target, "A", 1) || strncmp(target, "J", 0) || - tmp2[0] != 'Z' || tmp2[1] != '\0') + if (strcmp(target, "A") || strlen(target) != 1 || memchr(target, 'A', 0) != NULL || memcmp(target, "J", 0) || strncmp(target, "A", 1) || strncmp(target, "J", 0) || tmp2[0] != 'Z' || tmp2[1] != '\0') { eprintf(__LINE__, target, "A", 0); test_failed = 1; } tmp2[2] = 'A'; - if (strcpy(target, "") != target || - strncpy(tmp2, "", 4) != tmp2 || - strcat(target, "") != target) + if (strcpy(target, "") != target || strncpy(tmp2, "", 4) != tmp2 || strcat(target, "") != target) { eprintf(__LINE__, target, "", 0); test_failed = 1; } - if (target[0] != '\0' || strncmp(target, "", 1) || - memcmp(tmp2, "\0\0\0\0", 4)) + if (target[0] != '\0' || strncmp(target, "", 1) || memcmp(tmp2, "\0\0\0\0", 4)) { eprintf(__LINE__, target, "", 0); test_failed = 1; } tmp2[2] = 'A'; - if (strncat(tmp2, "1", 3) != tmp2 || - memcmp(tmp2, "1\0A", 3)) + if (strncat(tmp2, "1", 3) != tmp2 || memcmp(tmp2, "1\0A", 3)) { eprintf(__LINE__, tmp2, "1\0A", 3); test_failed = 1; } - if (strcpy(tmp3, target) != tmp3 || - strcat(tmp3, "X") != tmp3 || - strncpy(tmp2, "X", 2) != tmp2 || - memset(target, tmp2[0], 1) != target) + if (strcpy(tmp3, target) != tmp3 || strcat(tmp3, "X") != tmp3 || strncpy(tmp2, "X", 2) != tmp2 || memset(target, tmp2[0], 1) != target) { eprintf(__LINE__, target, "X", 0); test_failed = 1; } - if (strcmp(target, "X") || strlen(target) != 1 || - memchr(target, 'X', 2) != target || - strchr(target, 'X') != target || - memchr(target, 'Y', 2) != NULL || - strchr(target, 'Y') != NULL || - strcmp(tmp3, target) || - strncmp(tmp3, target, 2) || - memcmp(target, "K", 0) || - strncmp(target, tmp3, 3)) + if (strcmp(target, "X") || strlen(target) != 1 || memchr(target, 'X', 2) != target || strchr(target, 'X') != target || memchr(target, 'Y', 2) != NULL || strchr(target, 'Y') != NULL || strcmp(tmp3, target) || strncmp(tmp3, target, 2) || memcmp(target, "K", 0) || strncmp(target, tmp3, 3)) { eprintf(__LINE__, target, "X", 0); test_failed = 1; } - if (strcpy(tmp3, "Y") != tmp3 || - strcat(tmp3, "Y") != tmp3 || - memset(target, 'Y', 2) != target) + if (strcpy(tmp3, "Y") != tmp3 || strcat(tmp3, "Y") != tmp3 || memset(target, 'Y', 2) != target) { eprintf(__LINE__, target, "Y", 0); test_failed = 1; } target[2] = '\0'; - if (memcmp(target, "YY", 2) || strcmp(target, "YY") || - strlen(target) != 2 || memchr(target, 'Y', 2) != target || - strcmp(tmp3, target) || - strncmp(target, tmp3, 3) || - strncmp(target, tmp3, 4) || - strncmp(target, tmp3, 2) || - strchr(target, 'Y') != target) + if (memcmp(target, "YY", 2) || strcmp(target, "YY") || strlen(target) != 2 || memchr(target, 'Y', 2) != target || strcmp(tmp3, target) || strncmp(target, tmp3, 3) || strncmp(target, tmp3, 4) || strncmp(target, tmp3, 2) || strchr(target, 'Y') != target) { eprintf(__LINE__, target, "YY", 2); test_failed = 1; } strcpy(target, "WW"); - if (memcmp(target, "WW", 2) || strcmp(target, "WW") || - strlen(target) != 2 || memchr(target, 'W', 2) != target || - strchr(target, 'W') != target) + if (memcmp(target, "WW", 2) || strcmp(target, "WW") || strlen(target) != 2 || memchr(target, 'W', 2) != target || strchr(target, 'W') != target) { eprintf(__LINE__, target, "WW", 2); test_failed = 1; } - if (strncpy(target, "XX", 16) != target || - memcmp(target, "XX\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16)) + if (strncpy(target, "XX", 16) != target || memcmp(target, "XX\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16)) { eprintf(__LINE__, target, "XX\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16); test_failed = 1; } - if (strcpy(tmp3, "ZZ") != tmp3 || - strcat(tmp3, "Z") != tmp3 || - memcpy(tmp4, "Z", 2) != tmp4 || - strcat(tmp4, "ZZ") != tmp4 || - memset(target, 'Z', 3) != target) + if (strcpy(tmp3, "ZZ") != tmp3 || strcat(tmp3, "Z") != tmp3 || memcpy(tmp4, "Z", 2) != tmp4 || strcat(tmp4, "ZZ") != tmp4 || memset(target, 'Z', 3) != target) { eprintf(__LINE__, target, "ZZZ", 3); test_failed = 1; @@ -202,32 +166,21 @@ void tstring_main(void) target[3] = '\0'; tmp5[0] = '\0'; strncat(tmp5, "123", 2); - if (memcmp(target, "ZZZ", 3) || strcmp(target, "ZZZ") || - strcmp(tmp3, target) || strcmp(tmp4, target) || - strncmp(target, "ZZZ", 4) || strncmp(target, "ZZY", 3) <= 0 || - strncmp("ZZY", target, 4) >= 0 || - memcmp(tmp5, "12", 3) || - strlen(target) != 3) + if (memcmp(target, "ZZZ", 3) || strcmp(target, "ZZZ") || strcmp(tmp3, target) || strcmp(tmp4, target) || strncmp(target, "ZZZ", 4) || strncmp(target, "ZZY", 3) <= 0 || strncmp("ZZY", target, 4) >= 0 || memcmp(tmp5, "12", 3) || strlen(target) != 3) { eprintf(__LINE__, target, "ZZZ", 3); test_failed = 1; } target[2] = 'K'; - if (memcmp(target, "ZZZ", 2) || strcmp(target, "ZZZ") >= 0 || - memcmp(target, "ZZZ", 3) >= 0 || strlen(target) != 3 || - memchr(target, 'K', 3) != target + 2 || - strncmp(target, "ZZZ", 2) || strncmp(target, "ZZZ", 4) >= 0 || - strchr(target, 'K') != target + 2) + if (memcmp(target, "ZZZ", 2) || strcmp(target, "ZZZ") >= 0 || memcmp(target, "ZZZ", 3) >= 0 || strlen(target) != 3 || memchr(target, 'K', 3) != target + 2 || strncmp(target, "ZZZ", 2) || strncmp(target, "ZZZ", 4) >= 0 || strchr(target, 'K') != target + 2) { eprintf(__LINE__, target, "ZZK", 3); test_failed = 1; } strcpy(target, "AAA"); - if (memcmp(target, "AAA", 3) || strcmp(target, "AAA") || - strncmp(target, "AAA", 3) || - strlen(target) != 3) + if (memcmp(target, "AAA", 3) || strcmp(target, "AAA") || strncmp(target, "AAA", 3) || strlen(target) != 3) { eprintf(__LINE__, target, "AAA", 3); test_failed = 1; @@ -281,8 +234,7 @@ void tstring_main(void) test_failed = 1; } tmp2[i - z] = first_char + 1; - if (memmove(tmp2 + z + 1, tmp2 + z, i - z - 1) != tmp2 + z + 1 || - memset(tmp3, first_char, i) != tmp3) + if (memmove(tmp2 + z + 1, tmp2 + z, i - z - 1) != tmp2 + z + 1 || memset(tmp3, first_char, i) != tmp3) { printf("error at line %d\n", __LINE__); test_failed = 1; @@ -290,8 +242,7 @@ void tstring_main(void) myset(tmp4, first_char, i); tmp5[0] = '\0'; - if (strncpy(tmp5, tmp1, i + 1) != tmp5 || - strcat(tmp5, tmp1) != tmp5) + if (strncpy(tmp5, tmp1, i + 1) != tmp5 || strcat(tmp5, tmp1) != tmp5) { printf("error at line %d\n", __LINE__); test_failed = 1; @@ -304,19 +255,7 @@ void tstring_main(void) (void)strchr(tmp1, second_char); - if (memcmp(tmp1, expected, i) || strcmp(tmp1, expected) || - strncmp(tmp1, expected, i) || - strncmp(tmp1, expected, i + 1) || - strcmp(tmp1, tmp2) >= 0 || memcmp(tmp1, tmp2, i) >= 0 || - strncmp(tmp1, tmp2, i + 1) >= 0 || - (int)strlen(tmp1) != i || memchr(tmp1, first_char, i) != tmp1 || - strchr(tmp1, first_char) != tmp1 || - memchr(tmp1, second_char, i) != tmp1 + z || - strchr(tmp1, second_char) != tmp1 + z || - strcmp(tmp5, tmp6) || - strncat(tmp7, tmp1, i + 2) != tmp7 || - strcmp(tmp7, tmp6) || - tmp7[2 * i + z] != second_char) + if (memcmp(tmp1, expected, i) || strcmp(tmp1, expected) || strncmp(tmp1, expected, i) || strncmp(tmp1, expected, i + 1) || strcmp(tmp1, tmp2) >= 0 || memcmp(tmp1, tmp2, i) >= 0 || strncmp(tmp1, tmp2, i + 1) >= 0 || (int)strlen(tmp1) != i || memchr(tmp1, first_char, i) != tmp1 || strchr(tmp1, first_char) != tmp1 || memchr(tmp1, second_char, i) != tmp1 + z || strchr(tmp1, second_char) != tmp1 + z || strcmp(tmp5, tmp6) || strncat(tmp7, tmp1, i + 2) != tmp7 || strcmp(tmp7, tmp6) || tmp7[2 * i + z] != second_char) { eprintf(__LINE__, tmp1, expected, 0); printf("x is %d\n", x); @@ -329,21 +268,17 @@ void tstring_main(void) for (k = 1; k <= align_test_iterations && k <= i; ++k) { - if (memcmp(tmp3, tmp4, i - k + 1) != 0 || - strncmp(tmp3, tmp4, i - k + 1) != 0) + if (memcmp(tmp3, tmp4, i - k + 1) != 0 || strncmp(tmp3, tmp4, i - k + 1) != 0) { printf("Failure at line %d, comparing %.*s with %.*s\n", - __LINE__, i, tmp3, i, tmp4); + __LINE__, i, tmp3, i, tmp4); test_failed = 1; } tmp4[i - k] = first_char + 1; - if (memcmp(tmp3, tmp4, i) >= 0 || - strncmp(tmp3, tmp4, i) >= 0 || - memcmp(tmp4, tmp3, i) <= 0 || - strncmp(tmp4, tmp3, i) <= 0) + if (memcmp(tmp3, tmp4, i) >= 0 || strncmp(tmp3, tmp4, i) >= 0 || memcmp(tmp4, tmp3, i) <= 0 || strncmp(tmp4, tmp3, i) <= 0) { printf("Failure at line %d, comparing %.*s with %.*s\n", - __LINE__, i, tmp3, i, tmp4); + __LINE__, i, tmp3, i, tmp4); test_failed = 1; } tmp4[i - k] = first_char; diff --git a/tests/host/common/Arduino.cpp b/tests/host/common/Arduino.cpp index 2662fc3b5c..67bcc8ca34 100644 --- a/tests/host/common/Arduino.cpp +++ b/tests/host/common/Arduino.cpp @@ -21,7 +21,7 @@ #include #include -static struct timeval gtod0 = {0, 0}; +static struct timeval gtod0 = { 0, 0 }; extern "C" unsigned long millis() { diff --git a/tests/host/common/ArduinoMain.cpp b/tests/host/common/ArduinoMain.cpp index f8f0e9d13e..13e570281d 100644 --- a/tests/host/common/ArduinoMain.cpp +++ b/tests/host/common/ArduinoMain.cpp @@ -146,21 +146,20 @@ void help(const char* argv0, int exitcode) exit(exitcode); } -static struct option options[] = - { - {"help", no_argument, NULL, 'h'}, - {"fast", no_argument, NULL, 'f'}, - {"local", no_argument, NULL, 'l'}, - {"sigint", no_argument, NULL, 'c'}, - {"blockinguart", no_argument, NULL, 'b'}, - {"verbose", no_argument, NULL, 'v'}, - {"timestamp", no_argument, NULL, 'T'}, - {"interface", required_argument, NULL, 'i'}, - {"fspath", required_argument, NULL, 'P'}, - {"spiffskb", required_argument, NULL, 'S'}, - {"littlefskb", required_argument, NULL, 'L'}, - {"portshifter", required_argument, NULL, 's'}, - {"once", no_argument, NULL, '1'}, +static struct option options[] = { + { "help", no_argument, NULL, 'h' }, + { "fast", no_argument, NULL, 'f' }, + { "local", no_argument, NULL, 'l' }, + { "sigint", no_argument, NULL, 'c' }, + { "blockinguart", no_argument, NULL, 'b' }, + { "verbose", no_argument, NULL, 'v' }, + { "timestamp", no_argument, NULL, 'T' }, + { "interface", required_argument, NULL, 'i' }, + { "fspath", required_argument, NULL, 'P' }, + { "spiffskb", required_argument, NULL, 'S' }, + { "littlefskb", required_argument, NULL, 'L' }, + { "portshifter", required_argument, NULL, 's' }, + { "once", no_argument, NULL, '1' }, }; void cleanup() @@ -219,47 +218,47 @@ int main(int argc, char* const argv[]) break; switch (n) { - case 'h': - help(argv[0], EXIT_SUCCESS); - break; - case 'i': - host_interface = optarg; - break; - case 'l': - global_ipv4_netfmt = NO_GLOBAL_BINDING; - break; - case 's': - mock_port_shifter = atoi(optarg); - break; - case 'c': - ignore_sigint = true; - break; - case 'f': - fast = true; - break; - case 'S': - spiffs_kb = atoi(optarg); - break; - case 'L': - littlefs_kb = atoi(optarg); - break; - case 'P': - fspath = optarg; - break; - case 'b': - blocking_uart = true; - break; - case 'v': - mockdebug = true; - break; - case 'T': - serial_timestamp = true; - break; - case '1': - run_once = true; - break; - default: - help(argv[0], EXIT_FAILURE); + case 'h': + help(argv[0], EXIT_SUCCESS); + break; + case 'i': + host_interface = optarg; + break; + case 'l': + global_ipv4_netfmt = NO_GLOBAL_BINDING; + break; + case 's': + mock_port_shifter = atoi(optarg); + break; + case 'c': + ignore_sigint = true; + break; + case 'f': + fast = true; + break; + case 'S': + spiffs_kb = atoi(optarg); + break; + case 'L': + littlefs_kb = atoi(optarg); + break; + case 'P': + fspath = optarg; + break; + case 'b': + blocking_uart = true; + break; + case 'v': + mockdebug = true; + break; + case 'T': + serial_timestamp = true; + break; + case '1': + run_once = true; + break; + default: + help(argv[0], EXIT_FAILURE); } } diff --git a/tests/host/common/EEPROM.h b/tests/host/common/EEPROM.h index 669d60bfaf..3a30906ec4 100644 --- a/tests/host/common/EEPROM.h +++ b/tests/host/common/EEPROM.h @@ -34,7 +34,7 @@ class EEPROMClass { - public: +public: EEPROMClass(uint32_t sector); EEPROMClass(void); ~EEPROMClass(); @@ -70,7 +70,7 @@ class EEPROMClass //uint8_t& operator[](int const address) { return read(address); } uint8_t operator[](int address) { return read(address); } - protected: +protected: size_t _size = 0; int _fd = -1; }; diff --git a/tests/host/common/HostWiring.cpp b/tests/host/common/HostWiring.cpp index 892b336b2c..638457762e 100644 --- a/tests/host/common/HostWiring.cpp +++ b/tests/host/common/HostWiring.cpp @@ -46,29 +46,29 @@ void pinMode(uint8_t pin, uint8_t mode) const char* m; switch (mode) { - case INPUT: - m = "INPUT"; - break; - case OUTPUT: - m = "OUTPUT"; - break; - case INPUT_PULLUP: - m = "INPUT_PULLUP"; - break; - case OUTPUT_OPEN_DRAIN: - m = "OUTPUT_OPEN_DRAIN"; - break; - case INPUT_PULLDOWN_16: - m = "INPUT_PULLDOWN_16"; - break; - case WAKEUP_PULLUP: - m = "WAKEUP_PULLUP"; - break; - case WAKEUP_PULLDOWN: - m = "WAKEUP_PULLDOWN"; - break; - default: - m = "(special)"; + case INPUT: + m = "INPUT"; + break; + case OUTPUT: + m = "OUTPUT"; + break; + case INPUT_PULLUP: + m = "INPUT_PULLUP"; + break; + case OUTPUT_OPEN_DRAIN: + m = "OUTPUT_OPEN_DRAIN"; + break; + case INPUT_PULLDOWN_16: + m = "INPUT_PULLDOWN_16"; + break; + case WAKEUP_PULLUP: + m = "WAKEUP_PULLUP"; + break; + case WAKEUP_PULLDOWN: + m = "WAKEUP_PULLDOWN"; + break; + default: + m = "(special)"; } VERBOSE("gpio%d: mode='%s'\n", pin, m); } diff --git a/tests/host/common/MockEsp.cpp b/tests/host/common/MockEsp.cpp index 21908ba447..29e2653965 100644 --- a/tests/host/common/MockEsp.cpp +++ b/tests/host/common/MockEsp.cpp @@ -208,22 +208,22 @@ uint32_t EspClass::magicFlashChipSize(uint8_t byte) { switch (byte & 0x0F) { - case 0x0: // 4 Mbit (512KB) - return (512_kB); - case 0x1: // 2 MBit (256KB) - return (256_kB); - case 0x2: // 8 MBit (1MB) - return (1_MB); - case 0x3: // 16 MBit (2MB) - return (2_MB); - case 0x4: // 32 MBit (4MB) - return (4_MB); - case 0x8: // 64 MBit (8MB) - return (8_MB); - case 0x9: // 128 MBit (16MB) - return (16_MB); - default: // fail? - return 0; + case 0x0: // 4 Mbit (512KB) + return (512_kB); + case 0x1: // 2 MBit (256KB) + return (256_kB); + case 0x2: // 8 MBit (1MB) + return (1_MB); + case 0x3: // 16 MBit (2MB) + return (2_MB); + case 0x4: // 32 MBit (4MB) + return (4_MB); + case 0x8: // 64 MBit (8MB) + return (8_MB); + case 0x9: // 128 MBit (16MB) + return (16_MB); + default: // fail? + return 0; } } diff --git a/tests/host/common/MockTools.cpp b/tests/host/common/MockTools.cpp index fda6895949..43254efb7b 100644 --- a/tests/host/common/MockTools.cpp +++ b/tests/host/common/MockTools.cpp @@ -52,16 +52,16 @@ extern "C" return len; } - void stack_thunk_add_ref() {} - void stack_thunk_del_ref() {} - void stack_thunk_repaint() {} + void stack_thunk_add_ref() { } + void stack_thunk_del_ref() { } + void stack_thunk_repaint() { } uint32_t stack_thunk_get_refcnt() { return 0; } uint32_t stack_thunk_get_stack_top() { return 0; } uint32_t stack_thunk_get_stack_bot() { return 0; } uint32_t stack_thunk_get_cont_sp() { return 0; } uint32_t stack_thunk_get_max_usage() { return 0; } - void stack_thunk_dump_stack() {} + void stack_thunk_dump_stack() { } // Thunking macro #define make_stack_thunk(fcnToThunk) diff --git a/tests/host/common/MockUART.cpp b/tests/host/common/MockUART.cpp index 4ea89cddc1..0eafde29e0 100644 --- a/tests/host/common/MockUART.cpp +++ b/tests/host/common/MockUART.cpp @@ -43,7 +43,7 @@ extern "C" static int s_uart_debug_nr = UART1; - static uart_t* UART[2] = {NULL, NULL}; + static uart_t* UART[2] = { NULL, NULL }; struct uart_rx_buffer_ { @@ -348,42 +348,42 @@ extern "C" switch (uart->uart_nr) { - case UART0: - uart->rx_enabled = (mode != UART_TX_ONLY); - uart->tx_enabled = (mode != UART_RX_ONLY); - if (uart->rx_enabled) + case UART0: + uart->rx_enabled = (mode != UART_TX_ONLY); + uart->tx_enabled = (mode != UART_RX_ONLY); + if (uart->rx_enabled) + { + struct uart_rx_buffer_* rx_buffer = (struct uart_rx_buffer_*)malloc(sizeof(struct uart_rx_buffer_)); + if (rx_buffer == NULL) + { + free(uart); + return NULL; + } + rx_buffer->size = rx_size; //var this + rx_buffer->rpos = 0; + rx_buffer->wpos = 0; + rx_buffer->buffer = (uint8_t*)malloc(rx_buffer->size); + if (rx_buffer->buffer == NULL) { - struct uart_rx_buffer_* rx_buffer = (struct uart_rx_buffer_*)malloc(sizeof(struct uart_rx_buffer_)); - if (rx_buffer == NULL) - { - free(uart); - return NULL; - } - rx_buffer->size = rx_size; //var this - rx_buffer->rpos = 0; - rx_buffer->wpos = 0; - rx_buffer->buffer = (uint8_t*)malloc(rx_buffer->size); - if (rx_buffer->buffer == NULL) - { - free(rx_buffer); - free(uart); - return NULL; - } - uart->rx_buffer = rx_buffer; + free(rx_buffer); + free(uart); + return NULL; } - break; - - case UART1: - // Note: uart_interrupt_handler does not support RX on UART 1. - uart->rx_enabled = false; - uart->tx_enabled = (mode != UART_RX_ONLY); - break; - - case UART_NO: - default: - // big fail! - free(uart); - return NULL; + uart->rx_buffer = rx_buffer; + } + break; + + case UART1: + // Note: uart_interrupt_handler does not support RX on UART 1. + uart->rx_enabled = false; + uart->tx_enabled = (mode != UART_RX_ONLY); + break; + + case UART_NO: + default: + // big fail! + free(uart); + return NULL; } uart_set_baudrate(uart, baudrate); diff --git a/tests/host/common/flash_hal_mock.cpp b/tests/host/common/flash_hal_mock.cpp index 396d2c6362..e4d912bd77 100644 --- a/tests/host/common/flash_hal_mock.cpp +++ b/tests/host/common/flash_hal_mock.cpp @@ -26,8 +26,7 @@ int32_t flash_hal_write(uint32_t addr, uint32_t size, const uint8_t* src) int32_t flash_hal_erase(uint32_t addr, uint32_t size) { - if ((size & (FLASH_SECTOR_SIZE - 1)) != 0 || - (addr & (FLASH_SECTOR_SIZE - 1)) != 0) + if ((size & (FLASH_SECTOR_SIZE - 1)) != 0 || (addr & (FLASH_SECTOR_SIZE - 1)) != 0) { abort(); } diff --git a/tests/host/common/include/ClientContext.h b/tests/host/common/include/ClientContext.h index cec57b3030..f10760aae4 100644 --- a/tests/host/common/include/ClientContext.h +++ b/tests/host/common/include/ClientContext.h @@ -32,15 +32,25 @@ typedef void (*discard_cb_t)(void*, ClientContext*); class ClientContext { - public: +public: ClientContext(tcp_pcb* pcb, discard_cb_t discard_cb, void* discard_cb_arg) - : _discard_cb(discard_cb), _discard_cb_arg(discard_cb_arg), _refcnt(0), _next(0), _sync(::getDefaultPrivateGlobalSyncValue()), _sock(-1) + : _discard_cb(discard_cb) + , _discard_cb_arg(discard_cb_arg) + , _refcnt(0) + , _next(0) + , _sync(::getDefaultPrivateGlobalSyncValue()) + , _sock(-1) { (void)pcb; } ClientContext(int sock) - : _discard_cb(nullptr), _discard_cb_arg(nullptr), _refcnt(0), _next(nullptr), _sync(::getDefaultPrivateGlobalSyncValue()), _sock(sock) + : _discard_cb(nullptr) + , _discard_cb_arg(nullptr) + , _refcnt(0) + , _next(nullptr) + , _sync(::getDefaultPrivateGlobalSyncValue()) + , _sock(sock) { } @@ -301,7 +311,7 @@ class ClientContext _inbufsize -= consume; } - private: +private: discard_cb_t _discard_cb = nullptr; void* _discard_cb_arg = nullptr; diff --git a/tests/host/common/include/UdpContext.h b/tests/host/common/include/UdpContext.h index bbb079739a..eb8a071703 100644 --- a/tests/host/common/include/UdpContext.h +++ b/tests/host/common/include/UdpContext.h @@ -36,11 +36,12 @@ extern netif netif0; class UdpContext { - public: +public: typedef std::function rxhandler_t; UdpContext() - : _on_rx(nullptr), _refcnt(0) + : _on_rx(nullptr) + , _refcnt(0) { _sock = mockUDPSocket(); } @@ -253,10 +254,10 @@ class UdpContext _on_rx(); } - public: +public: static uint32_t staticMCastAddr; - private: +private: void translate_addr() { if (addrsize == 4) diff --git a/tests/host/common/littlefs_mock.h b/tests/host/common/littlefs_mock.h index bbbbe7c0cb..3d411c7027 100644 --- a/tests/host/common/littlefs_mock.h +++ b/tests/host/common/littlefs_mock.h @@ -29,12 +29,12 @@ class LittleFSMock { - public: +public: LittleFSMock(ssize_t fs_size, size_t fs_block, size_t fs_page, const String& storage = emptyString); void reset(); ~LittleFSMock(); - protected: +protected: void load(); void save(); diff --git a/tests/host/common/md5.c b/tests/host/common/md5.c index 8b84713aa4..dfdb80fc80 100644 --- a/tests/host/common/md5.c +++ b/tests/host/common/md5.c @@ -72,11 +72,11 @@ static void MD5Transform(uint32_t state[4], const uint8_t block[64]); static void Encode(uint8_t* output, uint32_t* input, uint32_t len); static void Decode(uint32_t* output, const uint8_t* input, uint32_t len); -static const uint8_t PADDING[64] = - { - 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; +static const uint8_t PADDING[64] = { + 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; /* F, G, H and I are basic MD5 functions. */ @@ -304,6 +304,5 @@ static void Decode(uint32_t* output, const uint8_t* input, uint32_t len) uint32_t i, j; for (i = 0, j = 0; j < len; i++, j += 4) - output[i] = ((uint32_t)input[j]) | (((uint32_t)input[j + 1]) << 8) | - (((uint32_t)input[j + 2]) << 16) | (((uint32_t)input[j + 3]) << 24); + output[i] = ((uint32_t)input[j]) | (((uint32_t)input[j + 1]) << 8) | (((uint32_t)input[j + 2]) << 16) | (((uint32_t)input[j + 3]) << 24); } diff --git a/tests/host/common/queue.h b/tests/host/common/queue.h index 2c2d89ba34..c1d8f7151a 100644 --- a/tests/host/common/queue.h +++ b/tests/host/common/queue.h @@ -157,21 +157,20 @@ #define SLIST_NEXT(elm, field) ((elm)->field.sle_next) -#define SLIST_REMOVE(head, elm, type, field) \ - do \ - { \ - if (SLIST_FIRST((head)) == (elm)) \ - { \ - SLIST_REMOVE_HEAD((head), field); \ - } \ - else \ - { \ - struct type* curelm = SLIST_FIRST((head)); \ - while (SLIST_NEXT(curelm, field) != (elm)) \ - curelm = SLIST_NEXT(curelm, field); \ - SLIST_NEXT(curelm, field) = \ - SLIST_NEXT(SLIST_NEXT(curelm, field), field); \ - } \ +#define SLIST_REMOVE(head, elm, type, field) \ + do \ + { \ + if (SLIST_FIRST((head)) == (elm)) \ + { \ + SLIST_REMOVE_HEAD((head), field); \ + } \ + else \ + { \ + struct type* curelm = SLIST_FIRST((head)); \ + while (SLIST_NEXT(curelm, field) != (elm)) \ + curelm = SLIST_NEXT(curelm, field); \ + SLIST_NEXT(curelm, field) = SLIST_NEXT(SLIST_NEXT(curelm, field), field); \ + } \ } while (0) #define SLIST_REMOVE_HEAD(head, field) \ @@ -260,30 +259,28 @@ #define STAILQ_NEXT(elm, field) ((elm)->field.stqe_next) -#define STAILQ_REMOVE(head, elm, type, field) \ - do \ - { \ - if (STAILQ_FIRST((head)) == (elm)) \ - { \ - STAILQ_REMOVE_HEAD((head), field); \ - } \ - else \ - { \ - struct type* curelm = STAILQ_FIRST((head)); \ - while (STAILQ_NEXT(curelm, field) != (elm)) \ - curelm = STAILQ_NEXT(curelm, field); \ - if ((STAILQ_NEXT(curelm, field) = \ - STAILQ_NEXT(STAILQ_NEXT(curelm, field), field)) == NULL) \ - (head)->stqh_last = &STAILQ_NEXT((curelm), field); \ - } \ +#define STAILQ_REMOVE(head, elm, type, field) \ + do \ + { \ + if (STAILQ_FIRST((head)) == (elm)) \ + { \ + STAILQ_REMOVE_HEAD((head), field); \ + } \ + else \ + { \ + struct type* curelm = STAILQ_FIRST((head)); \ + while (STAILQ_NEXT(curelm, field) != (elm)) \ + curelm = STAILQ_NEXT(curelm, field); \ + if ((STAILQ_NEXT(curelm, field) = STAILQ_NEXT(STAILQ_NEXT(curelm, field), field)) == NULL) \ + (head)->stqh_last = &STAILQ_NEXT((curelm), field); \ + } \ } while (0) -#define STAILQ_REMOVE_HEAD(head, field) \ - do \ - { \ - if ((STAILQ_FIRST((head)) = \ - STAILQ_NEXT(STAILQ_FIRST((head)), field)) == NULL) \ - (head)->stqh_last = &STAILQ_FIRST((head)); \ +#define STAILQ_REMOVE_HEAD(head, field) \ + do \ + { \ + if ((STAILQ_FIRST((head)) = STAILQ_NEXT(STAILQ_FIRST((head)), field)) == NULL) \ + (head)->stqh_last = &STAILQ_FIRST((head)); \ } while (0) #define STAILQ_REMOVE_HEAD_UNTIL(head, elm, field) \ @@ -333,14 +330,13 @@ LIST_FIRST((head)) = NULL; \ } while (0) -#define LIST_INSERT_AFTER(listelm, elm, field) \ - do \ - { \ - if ((LIST_NEXT((elm), field) = LIST_NEXT((listelm), field)) != NULL) \ - LIST_NEXT((listelm), field)->field.le_prev = \ - &LIST_NEXT((elm), field); \ - LIST_NEXT((listelm), field) = (elm); \ - (elm)->field.le_prev = &LIST_NEXT((listelm), field); \ +#define LIST_INSERT_AFTER(listelm, elm, field) \ + do \ + { \ + if ((LIST_NEXT((elm), field) = LIST_NEXT((listelm), field)) != NULL) \ + LIST_NEXT((listelm), field)->field.le_prev = &LIST_NEXT((elm), field); \ + LIST_NEXT((listelm), field) = (elm); \ + (elm)->field.le_prev = &LIST_NEXT((listelm), field); \ } while (0) #define LIST_INSERT_BEFORE(listelm, elm, field) \ @@ -363,13 +359,12 @@ #define LIST_NEXT(elm, field) ((elm)->field.le_next) -#define LIST_REMOVE(elm, field) \ - do \ - { \ - if (LIST_NEXT((elm), field) != NULL) \ - LIST_NEXT((elm), field)->field.le_prev = \ - (elm)->field.le_prev; \ - *(elm)->field.le_prev = LIST_NEXT((elm), field); \ +#define LIST_REMOVE(elm, field) \ + do \ + { \ + if (LIST_NEXT((elm), field) != NULL) \ + LIST_NEXT((elm), field)->field.le_prev = (elm)->field.le_prev; \ + *(elm)->field.le_prev = LIST_NEXT((elm), field); \ } while (0) /* @@ -430,16 +425,15 @@ (head)->tqh_last = &TAILQ_FIRST((head)); \ } while (0) -#define TAILQ_INSERT_AFTER(head, listelm, elm, field) \ - do \ - { \ - if ((TAILQ_NEXT((elm), field) = TAILQ_NEXT((listelm), field)) != NULL) \ - TAILQ_NEXT((elm), field)->field.tqe_prev = \ - &TAILQ_NEXT((elm), field); \ - else \ - (head)->tqh_last = &TAILQ_NEXT((elm), field); \ - TAILQ_NEXT((listelm), field) = (elm); \ - (elm)->field.tqe_prev = &TAILQ_NEXT((listelm), field); \ +#define TAILQ_INSERT_AFTER(head, listelm, elm, field) \ + do \ + { \ + if ((TAILQ_NEXT((elm), field) = TAILQ_NEXT((listelm), field)) != NULL) \ + TAILQ_NEXT((elm), field)->field.tqe_prev = &TAILQ_NEXT((elm), field); \ + else \ + (head)->tqh_last = &TAILQ_NEXT((elm), field); \ + TAILQ_NEXT((listelm), field) = (elm); \ + (elm)->field.tqe_prev = &TAILQ_NEXT((listelm), field); \ } while (0) #define TAILQ_INSERT_BEFORE(listelm, elm, field) \ @@ -451,16 +445,15 @@ (listelm)->field.tqe_prev = &TAILQ_NEXT((elm), field); \ } while (0) -#define TAILQ_INSERT_HEAD(head, elm, field) \ - do \ - { \ - if ((TAILQ_NEXT((elm), field) = TAILQ_FIRST((head))) != NULL) \ - TAILQ_FIRST((head))->field.tqe_prev = \ - &TAILQ_NEXT((elm), field); \ - else \ - (head)->tqh_last = &TAILQ_NEXT((elm), field); \ - TAILQ_FIRST((head)) = (elm); \ - (elm)->field.tqe_prev = &TAILQ_FIRST((head)); \ +#define TAILQ_INSERT_HEAD(head, elm, field) \ + do \ + { \ + if ((TAILQ_NEXT((elm), field) = TAILQ_FIRST((head))) != NULL) \ + TAILQ_FIRST((head))->field.tqe_prev = &TAILQ_NEXT((elm), field); \ + else \ + (head)->tqh_last = &TAILQ_NEXT((elm), field); \ + TAILQ_FIRST((head)) = (elm); \ + (elm)->field.tqe_prev = &TAILQ_FIRST((head)); \ } while (0) #define TAILQ_INSERT_TAIL(head, elm, field) \ @@ -480,15 +473,14 @@ #define TAILQ_PREV(elm, headname, field) \ (*(((struct headname*)((elm)->field.tqe_prev))->tqh_last)) -#define TAILQ_REMOVE(head, elm, field) \ - do \ - { \ - if ((TAILQ_NEXT((elm), field)) != NULL) \ - TAILQ_NEXT((elm), field)->field.tqe_prev = \ - (elm)->field.tqe_prev; \ - else \ - (head)->tqh_last = (elm)->field.tqe_prev; \ - *(elm)->field.tqe_prev = TAILQ_NEXT((elm), field); \ +#define TAILQ_REMOVE(head, elm, field) \ + do \ + { \ + if ((TAILQ_NEXT((elm), field)) != NULL) \ + TAILQ_NEXT((elm), field)->field.tqe_prev = (elm)->field.tqe_prev; \ + else \ + (head)->tqh_last = (elm)->field.tqe_prev; \ + *(elm)->field.tqe_prev = TAILQ_NEXT((elm), field); \ } while (0) #ifdef _KERNEL diff --git a/tests/host/common/sdfs_mock.h b/tests/host/common/sdfs_mock.h index 462d8fffe1..d628c953f2 100644 --- a/tests/host/common/sdfs_mock.h +++ b/tests/host/common/sdfs_mock.h @@ -23,7 +23,7 @@ class SDFSMock { - public: +public: SDFSMock(ssize_t fs_size, size_t fs_block, size_t fs_page, const String& storage = emptyString) { (void)fs_size; @@ -31,8 +31,8 @@ class SDFSMock (void)fs_page; (void)storage; } - void reset() {} - ~SDFSMock() {} + void reset() { } + ~SDFSMock() { } }; extern uint64_t _sdCardSizeB; diff --git a/tests/host/common/spiffs_mock.h b/tests/host/common/spiffs_mock.h index 098f73c3f4..76c4b4165f 100644 --- a/tests/host/common/spiffs_mock.h +++ b/tests/host/common/spiffs_mock.h @@ -26,12 +26,12 @@ class SpiffsMock { - public: +public: SpiffsMock(ssize_t fs_size, size_t fs_block, size_t fs_page, const String& storage = emptyString); void reset(); ~SpiffsMock(); - protected: +protected: void load(); void save(); diff --git a/tests/host/common/strl.cpp b/tests/host/common/strl.cpp index 95c98913d6..ce26d5b60e 100644 --- a/tests/host/common/strl.cpp +++ b/tests/host/common/strl.cpp @@ -5,10 +5,10 @@ '_cups_strlcat()' - Safely concatenate two strings. */ -size_t /* O - Length of string */ -strlcat(char* dst, /* O - Destination string */ - const char* src, /* I - Source string */ - size_t size) /* I - Size of destination string buffer */ +size_t /* O - Length of string */ +strlcat(char* dst, /* O - Destination string */ + const char* src, /* I - Source string */ + size_t size) /* I - Size of destination string buffer */ { size_t srclen; /* Length of source string */ size_t dstlen; /* Length of destination string */ @@ -52,10 +52,10 @@ strlcat(char* dst, /* O - Destination string */ '_cups_strlcpy()' - Safely copy two strings. */ -size_t /* O - Length of string */ -strlcpy(char* dst, /* O - Destination string */ - const char* src, /* I - Source string */ - size_t size) /* I - Size of destination string buffer */ +size_t /* O - Length of string */ +strlcpy(char* dst, /* O - Destination string */ + const char* src, /* I - Source string */ + size_t size) /* I - Size of destination string buffer */ { size_t srclen; /* Length of source string */ diff --git a/tests/host/common/user_interface.cpp b/tests/host/common/user_interface.cpp index 0091d77ba6..9103e40648 100644 --- a/tests/host/common/user_interface.cpp +++ b/tests/host/common/user_interface.cpp @@ -505,7 +505,7 @@ extern "C" ip_addr_t dns_getserver(u8_t numdns) { (void)numdns; - ip_addr_t addr = {0x7f000001}; + ip_addr_t addr = { 0x7f000001 }; return addr; } diff --git a/tests/host/core/test_string.cpp b/tests/host/core/test_string.cpp index db6244a059..8f6b00eb4a 100644 --- a/tests/host/core/test_string.cpp +++ b/tests/host/core/test_string.cpp @@ -97,7 +97,7 @@ TEST_CASE("String constructors", "[core][String]") REQUIRE(ssh == "3.14159_abcd"); String flash = (F("hello from flash")); REQUIRE(flash == "hello from flash"); - const char textarray[6] = {'h', 'e', 'l', 'l', 'o', 0}; + const char textarray[6] = { 'h', 'e', 'l', 'l', 'o', 0 }; String hello(textarray); REQUIRE(hello == "hello"); String hello2; @@ -442,8 +442,8 @@ TEST_CASE("String SSO handles junk in memory", "[core][String]") // Tests from #5883 bool useURLencode = false; - const char euro[4] = {(char)0xe2, (char)0x82, (char)0xac, 0}; // Unicode euro symbol - const char yen[3] = {(char)0xc2, (char)0xa5, 0}; // Unicode yen symbol + const char euro[4] = { (char)0xe2, (char)0x82, (char)0xac, 0 }; // Unicode euro symbol + const char yen[3] = { (char)0xc2, (char)0xa5, 0 }; // Unicode yen symbol memset(space, 0xff, 64); new (s) String("%ssid%"); @@ -533,7 +533,7 @@ TEST_CASE("Strings with NULs", "[core][String]") REQUIRE(str3.length() == 32); str3 += str3; REQUIRE(str3.length() == 64); - static char zeros[64] = {0}; + static char zeros[64] = { 0 }; const char* p = str3.c_str(); REQUIRE(!memcmp(p, zeros, 64)); } @@ -559,11 +559,12 @@ TEST_CASE("Replace and string expansion", "[core][String]") TEST_CASE("String chaining", "[core][String]") { - const char* chunks[]{ + const char* chunks[] { "~12345", "67890", "qwertyuiopasdfghjkl", - "zxcvbnm"}; + "zxcvbnm" + }; String all; for (auto* chunk : chunks) diff --git a/tests/host/fs/test_fs.cpp b/tests/host/fs/test_fs.cpp index be7b26ad14..73fc1b2cc6 100644 --- a/tests/host/fs/test_fs.cpp +++ b/tests/host/fs/test_fs.cpp @@ -144,7 +144,7 @@ TEST_CASE("SD.h FILE_WRITE macro is append", "[fs]") f.write(65); f.write("bbcc"); f.write("theend", 6); - char block[3] = {'x', 'y', 'z'}; + char block[3] = { 'x', 'y', 'z' }; f.write(block, 3); uint32_t bigone = 0x40404040; f.write((const uint8_t*)&bigone, 4); diff --git a/tests/restyle.sh b/tests/restyle.sh index b8438e089b..c038133941 100755 --- a/tests/restyle.sh +++ b/tests/restyle.sh @@ -25,6 +25,7 @@ tests # core +cp tests/clang-format-core .clang-format for d in $all; do if [ -d "$d" ]; then echo "-------- directory $d:" @@ -39,10 +40,8 @@ done # examples +cp tests/clang-format-arduino .clang-format for d in libraries; do echo "-------- examples in $d:" - find $d -name "*.ino" -exec \ - astyle \ - --suffix=none \ - --options=${org}/astyle_examples.conf {} \; + find $d -name "*.ino" -exec clang-format-12 -i {} \; done From 3a40b86d7715aa61e092f30ad7f066c264095bea Mon Sep 17 00:00:00 2001 From: david gauchard Date: Thu, 20 Jan 2022 02:05:22 +0100 Subject: [PATCH 08/15] one more pass --- cores/esp8266/LwipDhcpServer.cpp | 6 ++++-- cores/esp8266/LwipIntf.cpp | 3 ++- cores/esp8266/LwipIntf.h | 3 ++- cores/esp8266/LwipIntfDev.h | 5 ++++- .../examples/BearSSL_Server/BearSSL_Server.ino | 8 ++++---- .../examples/SPISlave_Master/SPISlave_Master.ino | 3 +-- .../SPISlave_SafeMaster/SPISlave_SafeMaster.ino | 3 +-- libraries/lwIP_enc28j60/src/utility/enc28j60.cpp | 9 +++------ tests/device/libraries/BSTest/src/BSArgs.h | 4 ++-- tests/device/libraries/BSTest/src/BSProtocol.h | 4 ++-- tests/device/libraries/BSTest/src/BSTest.h | 2 +- tests/device/test_libc/memmove1.c | 13 ++++++------- tests/device/test_libc/tstring.c | 3 ++- tests/host/common/MockTools.cpp | 3 ++- tests/host/common/MockUART.cpp | 10 ++-------- tests/host/common/include/UdpContext.h | 3 ++- tests/host/common/user_interface.cpp | 3 ++- tests/host/fs/test_fs.cpp | 15 +++++++-------- 18 files changed, 49 insertions(+), 51 deletions(-) diff --git a/cores/esp8266/LwipDhcpServer.cpp b/cores/esp8266/LwipDhcpServer.cpp index c5b5342fef..d7eddd02d9 100644 --- a/cores/esp8266/LwipDhcpServer.cpp +++ b/cores/esp8266/LwipDhcpServer.cpp @@ -983,7 +983,8 @@ void DhcpServer::init_dhcps_lease(uint32 ip) { /*config ip information must be in the same segment as the local ip*/ softap_ip >>= 8; - if (((start_ip >> 8 != softap_ip) || (end_ip >> 8 != softap_ip)) || (end_ip - start_ip > DHCPS_MAX_LEASE)) + if (((start_ip >> 8 != softap_ip) || (end_ip >> 8 != softap_ip)) + || (end_ip - start_ip > DHCPS_MAX_LEASE)) { dhcps_lease.enable = false; } @@ -1146,7 +1147,8 @@ bool DhcpServer::set_dhcps_lease(struct dhcps_lease* please) /*config ip information must be in the same segment as the local ip*/ softap_ip >>= 8; - if ((start_ip >> 8 != softap_ip) || (end_ip >> 8 != softap_ip)) + if ((start_ip >> 8 != softap_ip) + || (end_ip >> 8 != softap_ip)) { return false; } diff --git a/cores/esp8266/LwipIntf.cpp b/cores/esp8266/LwipIntf.cpp index 10d42aaf23..44359e6fc1 100644 --- a/cores/esp8266/LwipIntf.cpp +++ b/cores/esp8266/LwipIntf.cpp @@ -25,7 +25,8 @@ extern "C" // // result stored into gateway/netmask/dns1 -bool LwipIntf::ipAddressReorder(const IPAddress& local_ip, const IPAddress& arg1, const IPAddress& arg2, const IPAddress& arg3, IPAddress& gateway, IPAddress& netmask, IPAddress& dns1) +bool LwipIntf::ipAddressReorder(const IPAddress& local_ip, const IPAddress& arg1, const IPAddress& arg2, const IPAddress& arg3, + IPAddress& gateway, IPAddress& netmask, IPAddress& dns1) { //To allow compatibility, check first octet of 3rd arg. If 255, interpret as ESP order, otherwise Arduino order. gateway = arg1; diff --git a/cores/esp8266/LwipIntf.h b/cores/esp8266/LwipIntf.h index 7943c6cb5a..10acf716c7 100644 --- a/cores/esp8266/LwipIntf.h +++ b/cores/esp8266/LwipIntf.h @@ -23,7 +23,8 @@ class LwipIntf // arg3 | dns1 netmask // // result stored into gateway/netmask/dns1 - static bool ipAddressReorder(const IPAddress& local_ip, const IPAddress& arg1, const IPAddress& arg2, const IPAddress& arg3, IPAddress& gateway, IPAddress& netmask, IPAddress& dns1); + static bool ipAddressReorder(const IPAddress& local_ip, const IPAddress& arg1, const IPAddress& arg2, const IPAddress& arg3, + IPAddress& gateway, IPAddress& netmask, IPAddress& dns1); String hostname(); bool hostname(const String& aHostname) diff --git a/cores/esp8266/LwipIntfDev.h b/cores/esp8266/LwipIntfDev.h index bebba74266..4dccfa0cba 100644 --- a/cores/esp8266/LwipIntfDev.h +++ b/cores/esp8266/LwipIntfDev.h @@ -278,7 +278,10 @@ err_t LwipIntfDev::netif_init() _netif.name[1] = '0' + _netif.num; _netif.mtu = _mtu; _netif.chksum_flags = NETIF_CHECKSUM_ENABLE_ALL; - _netif.flags = NETIF_FLAG_ETHARP | NETIF_FLAG_IGMP | NETIF_FLAG_BROADCAST | NETIF_FLAG_LINK_UP; + _netif.flags = NETIF_FLAG_ETHARP + | NETIF_FLAG_IGMP + | NETIF_FLAG_BROADCAST + | NETIF_FLAG_LINK_UP; // lwIP's doc: This function typically first resolves the hardware // address, then sends the packet. For ethernet physical layer, this is diff --git a/libraries/ESP8266WiFi/examples/BearSSL_Server/BearSSL_Server.ino b/libraries/ESP8266WiFi/examples/BearSSL_Server/BearSSL_Server.ino index 9677178521..08d81c697b 100644 --- a/libraries/ESP8266WiFi/examples/BearSSL_Server/BearSSL_Server.ino +++ b/libraries/ESP8266WiFi/examples/BearSSL_Server/BearSSL_Server.ino @@ -139,10 +139,10 @@ GBEnkz4KpKv7TkHoW+j7F5EMcLcSrUIpyw== #endif #define CACHE_SIZE 5 // Number of sessions to cache. -#define USE_CACHE // Enable SSL session caching. \ - // Caching SSL sessions shortens the length of the SSL handshake. \ - // You can see the performance improvement by looking at the \ - // Network tab of the developer tools of your browser. +// Caching SSL sessions shortens the length of the SSL handshake. +// You can see the performance improvement by looking at the +// Network tab of the developer tools of your browser. +#define USE_CACHE // Enable SSL session caching. //#define DYNAMIC_CACHE // Whether to dynamically allocate the cache. #if defined(USE_CACHE) && defined(DYNAMIC_CACHE) diff --git a/libraries/SPISlave/examples/SPISlave_Master/SPISlave_Master.ino b/libraries/SPISlave/examples/SPISlave_Master/SPISlave_Master.ino index a564b3c027..f6f38d95fa 100644 --- a/libraries/SPISlave/examples/SPISlave_Master/SPISlave_Master.ino +++ b/libraries/SPISlave/examples/SPISlave_Master/SPISlave_Master.ino @@ -22,8 +22,7 @@ class ESPMaster { public: ESPMaster(uint8_t pin) - : _ss_pin(pin) { - } + : _ss_pin(pin) { } void begin() { pinMode(_ss_pin, OUTPUT); digitalWrite(_ss_pin, HIGH); diff --git a/libraries/SPISlave/examples/SPISlave_SafeMaster/SPISlave_SafeMaster.ino b/libraries/SPISlave/examples/SPISlave_SafeMaster/SPISlave_SafeMaster.ino index 6019e5fb54..2b1d3bbbbc 100644 --- a/libraries/SPISlave/examples/SPISlave_SafeMaster/SPISlave_SafeMaster.ino +++ b/libraries/SPISlave/examples/SPISlave_SafeMaster/SPISlave_SafeMaster.ino @@ -28,8 +28,7 @@ class ESPSafeMaster { public: ESPSafeMaster(uint8_t pin) - : _ss_pin(pin) { - } + : _ss_pin(pin) { } void begin() { pinMode(_ss_pin, OUTPUT); _pulseSS(); diff --git a/libraries/lwIP_enc28j60/src/utility/enc28j60.cpp b/libraries/lwIP_enc28j60/src/utility/enc28j60.cpp index bbc00041ca..8ba961b969 100644 --- a/libraries/lwIP_enc28j60/src/utility/enc28j60.cpp +++ b/libraries/lwIP_enc28j60/src/utility/enc28j60.cpp @@ -391,9 +391,7 @@ bool ENC28J60::reset(void) /* Wait for OST */ PRINTF("waiting for ESTAT_CLKRDY\n"); - while ((readreg(ESTAT) & ESTAT_CLKRDY) == 0) - { - }; + while ((readreg(ESTAT) & ESTAT_CLKRDY) == 0) { }; PRINTF("ESTAT_CLKRDY\n"); setregbank(ERXTX_BANK); @@ -606,9 +604,8 @@ ENC28J60::sendFrame(const uint8_t* data, uint16_t datalen) readdata(tsv, sizeof(tsv)); writereg(ERDPTL, erdpt & 0xff); writereg(ERDPTH, erdpt >> 8); - PRINTF( - "enc28j60: tx err: %d: %02x:%02x:%02x:%02x:%02x:%02x\n" - " tsv: %02x%02x%02x%02x%02x%02x%02x\n", + PRINTF("enc28j60: tx err: %d: %02x:%02x:%02x:%02x:%02x:%02x\n" + " tsv: %02x%02x%02x%02x%02x%02x%02x\n", datalen, 0xff & data[0], 0xff & data[1], 0xff & data[2], 0xff & data[3], 0xff & data[4], 0xff & data[5], diff --git a/tests/device/libraries/BSTest/src/BSArgs.h b/tests/device/libraries/BSTest/src/BSArgs.h index d7ce60500f..b989802c2d 100644 --- a/tests/device/libraries/BSTest/src/BSArgs.h +++ b/tests/device/libraries/BSTest/src/BSArgs.h @@ -170,8 +170,8 @@ namespace protocol return argc; } -} // namespace protocol - } // namespace bs +} // namespace protocol + #endif //BS_ARGS_H diff --git a/tests/device/libraries/BSTest/src/BSProtocol.h b/tests/device/libraries/BSTest/src/BSProtocol.h index 9b1d128ae1..868e5cceba 100644 --- a/tests/device/libraries/BSTest/src/BSProtocol.h +++ b/tests/device/libraries/BSTest/src/BSProtocol.h @@ -121,7 +121,7 @@ namespace protocol return true; } -} // namespace protocol -} // namespace bs +} // ::protocol +} // ::bs #endif //BS_PROTOCOL_H diff --git a/tests/device/libraries/BSTest/src/BSTest.h b/tests/device/libraries/BSTest/src/BSTest.h index d4e9126265..f792637e7e 100644 --- a/tests/device/libraries/BSTest/src/BSTest.h +++ b/tests/device/libraries/BSTest/src/BSTest.h @@ -225,7 +225,7 @@ inline void require(bool condition, size_t line) } } -} // namespace bs +} // ::bs #define BS_NAME_LINE2(name, line) name##line #define BS_NAME_LINE(name, line) BS_NAME_LINE2(name, line) diff --git a/tests/device/test_libc/memmove1.c b/tests/device/test_libc/memmove1.c index 7a4c915b4b..0d76f7cda7 100644 --- a/tests/device/test_libc/memmove1.c +++ b/tests/device/test_libc/memmove1.c @@ -65,7 +65,8 @@ int errors = 0; void mymemmove(unsigned char* dest, unsigned char* src, size_t n) { - if ((src <= dest && src + n <= dest) || src >= dest) + if ((src <= dest && src + n <= dest) + || src >= dest) while (n-- > 0) *dest++ = *src++; else @@ -153,9 +154,8 @@ void memmove_main(void) if (memcmp(to_known, to_test, sizeof(to_known)) != 0) { errors++; - DEBUGP( - "memmove failed for %d bytes," - " with src %d bytes before dest\n", + DEBUGP("memmove failed for %d bytes," + " with src %d bytes before dest\n", i, j); } } @@ -176,9 +176,8 @@ void memmove_main(void) if (memcmp(to_known, to_test, sizeof(to_known)) != 0) { errors++; - DEBUGP( - "memmove failed when moving %d bytes," - " with src %d bytes after dest\n", + DEBUGP("memmove failed when moving %d bytes," + " with src %d bytes after dest\n", i, j); } } diff --git a/tests/device/test_libc/tstring.c b/tests/device/test_libc/tstring.c index ddf326934f..9434523f85 100644 --- a/tests/device/test_libc/tstring.c +++ b/tests/device/test_libc/tstring.c @@ -93,7 +93,8 @@ void tstring_main(void) test_failed = 1; } - if (strcmp(target, "A") || strlen(target) != 1 || memchr(target, 'A', 0) != NULL || memcmp(target, "J", 0) || strncmp(target, "A", 1) || strncmp(target, "J", 0) || tmp2[0] != 'Z' || tmp2[1] != '\0') + if (strcmp(target, "A") || strlen(target) != 1 || memchr(target, 'A', 0) != NULL + || memcmp(target, "J", 0) || strncmp(target, "A", 1) || strncmp(target, "J", 0) || tmp2[0] != 'Z' || tmp2[1] != '\0') { eprintf(__LINE__, target, "A", 0); test_failed = 1; diff --git a/tests/host/common/MockTools.cpp b/tests/host/common/MockTools.cpp index 43254efb7b..e291486c5f 100644 --- a/tests/host/common/MockTools.cpp +++ b/tests/host/common/MockTools.cpp @@ -67,7 +67,8 @@ extern "C" #define make_stack_thunk(fcnToThunk) }; -void configTime(int timezone, int daylightOffset_sec, const char* server1, const char* server2, const char* server3) +void configTime(int timezone, int daylightOffset_sec, + const char* server1, const char* server2, const char* server3) { (void)server1; (void)server2; diff --git a/tests/host/common/MockUART.cpp b/tests/host/common/MockUART.cpp index 0eafde29e0..b87ea3b0f9 100644 --- a/tests/host/common/MockUART.cpp +++ b/tests/host/common/MockUART.cpp @@ -494,14 +494,8 @@ extern "C" } }; -size_t uart_peek_available(uart_t* uart) -{ - return 0; -} -const char* uart_peek_buffer(uart_t* uart) -{ - return nullptr; -} +size_t uart_peek_available(uart_t* uart) { return 0; } +const char* uart_peek_buffer(uart_t* uart) { return nullptr; } void uart_peek_consume(uart_t* uart, size_t consume) { (void)uart; diff --git a/tests/host/common/include/UdpContext.h b/tests/host/common/include/UdpContext.h index eb8a071703..a070108459 100644 --- a/tests/host/common/include/UdpContext.h +++ b/tests/host/common/include/UdpContext.h @@ -237,7 +237,8 @@ class UdpContext return trySend(addr, port, false) == ERR_OK; } - bool sendTimeout(ip_addr_t* addr, uint16_t port, esp8266::polledTimeout::oneShotFastMs::timeType timeoutMs) + bool sendTimeout(ip_addr_t* addr, uint16_t port, + esp8266::polledTimeout::oneShotFastMs::timeType timeoutMs) { err_t err; esp8266::polledTimeout::oneShotFastMs timeout(timeoutMs); diff --git a/tests/host/common/user_interface.cpp b/tests/host/common/user_interface.cpp index 9103e40648..aede8d2d39 100644 --- a/tests/host/common/user_interface.cpp +++ b/tests/host/common/user_interface.cpp @@ -185,7 +185,8 @@ extern "C" for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) { mockverbose("host: interface: %s", ifa->ifa_name); - if (ifa->ifa_addr && ifa->ifa_addr->sa_family == AF_INET // ip_info is IPv4 only + if (ifa->ifa_addr + && ifa->ifa_addr->sa_family == AF_INET // ip_info is IPv4 only ) { auto test_ipv4 = lwip_ntohl(*(uint32_t*)&((struct sockaddr_in*)ifa->ifa_addr)->sin_addr); diff --git a/tests/host/fs/test_fs.cpp b/tests/host/fs/test_fs.cpp index 73fc1b2cc6..ae88591388 100644 --- a/tests/host/fs/test_fs.cpp +++ b/tests/host/fs/test_fs.cpp @@ -59,7 +59,7 @@ TEST_CASE("SPIFFS checks the config object passed in", "[fs]") } #pragma GCC diagnostic pop -}; // namespace spiffs_test +}; namespace littlefs_test { @@ -93,7 +93,7 @@ TEST_CASE("LittleFS checks the config object passed in", "[fs]") REQUIRE(LittleFS.setConfig(l)); } -}; // namespace littlefs_test +}; namespace sdfs_test { @@ -101,11 +101,10 @@ namespace sdfs_test #define TESTPRE "SDFS - " #define TESTPAT "[sdfs]" // SDFS supports long paths (MAXPATH) -#define TOOLONGFILENAME \ - "/" \ - "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" \ - "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" \ - "12345678901234567890123456789012345678901234567890123456" +#define TOOLONGFILENAME "/" \ + "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" \ + "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" \ + "12345678901234567890123456789012345678901234567890123456" #define FS_MOCK_DECLARE SDFS_MOCK_DECLARE #define FS_MOCK_RESET SDFS_MOCK_RESET #define FS_HAS_DIRS @@ -164,4 +163,4 @@ TEST_CASE("SD.h FILE_WRITE macro is append", "[fs]") REQUIRE(u == 0); } -}; // namespace sdfs_test +}; From 591336c10e0f366a13ca6b1a25a7089c2ad81671 Mon Sep 17 00:00:00 2001 From: David Gauchard Date: Thu, 20 Jan 2022 11:04:35 +0100 Subject: [PATCH 09/15] update and embed clang-format configuration into tests/restyle.sh --- cores/esp8266/LwipDhcpServer-NonOS.cpp | 2 +- cores/esp8266/LwipDhcpServer.cpp | 278 ++--- cores/esp8266/LwipDhcpServer.h | 106 +- cores/esp8266/LwipIntf.cpp | 8 +- cores/esp8266/LwipIntf.h | 6 +- cores/esp8266/LwipIntfCB.cpp | 14 +- cores/esp8266/LwipIntfDev.h | 58 +- cores/esp8266/StreamSend.cpp | 26 +- cores/esp8266/StreamString.h | 112 +- cores/esp8266/core_esp8266_si2c.cpp | 176 +-- .../ArduinoOTA/examples/BasicOTA/BasicOTA.ino | 83 +- .../ArduinoOTA/examples/OTALeds/OTALeds.ino | 39 +- .../CaptivePortalAdvanced.ino | 71 +- .../CaptivePortalAdvanced/handleHttp.ino | 63 +- .../examples/CaptivePortalAdvanced/tools.ino | 15 +- .../Arduino_Wifi_AVRISP.ino | 46 +- .../examples/Authorization/Authorization.ino | 24 +- .../BasicHttpClient/BasicHttpClient.ino | 31 +- .../BasicHttpsClient/BasicHttpsClient.ino | 33 +- .../DigestAuthorization.ino | 60 +- .../PostHttpClient/PostHttpClient.ino | 26 +- .../ReuseConnectionV2/ReuseConnectionV2.ino | 36 +- .../StreamHttpClient/StreamHttpClient.ino | 38 +- .../StreamHttpsClient/StreamHttpsClient.ino | 49 +- .../SecureBearSSLUpdater.ino | 32 +- .../SecureWebUpdater/SecureWebUpdater.ino | 26 +- .../examples/WebUpdater/WebUpdater.ino | 18 +- .../LLMNR_Web_Server/LLMNR_Web_Server.ino | 19 +- .../examples/ESP_NBNST/ESP_NBNST.ino | 18 +- libraries/ESP8266SSDP/examples/SSDP/SSDP.ino | 31 +- .../AdvancedWebServer/AdvancedWebServer.ino | 48 +- .../examples/FSBrowser/FSBrowser.ino | 311 +++-- .../ESP8266WebServer/examples/Graph/Graph.ino | 153 ++- .../examples/HelloServer/HelloServer.ino | 164 +-- .../HelloServerBearSSL/HelloServerBearSSL.ino | 56 +- .../HttpAdvancedAuth/HttpAdvancedAuth.ino | 50 +- .../examples/HttpBasicAuth/HttpBasicAuth.ino | 31 +- .../HttpHashCredAuth/HttpHashCredAuth.ino | 111 +- .../examples/PathArgServer/PathArgServer.ino | 41 +- .../examples/PostServer/PostServer.ino | 52 +- .../ServerSentEvents/ServerSentEvents.ino | 148 ++- .../SimpleAuthentication.ino | 57 +- .../examples/WebServer/WebServer.ino | 146 ++- .../examples/WebUpdate/WebUpdate.ino | 97 +- .../BearSSL_CertStore/BearSSL_CertStore.ino | 50 +- .../BearSSL_MaxFragmentLength.ino | 50 +- .../BearSSL_Server/BearSSL_Server.ino | 66 +- .../BearSSL_ServerClientCert.ino | 60 +- .../BearSSL_Sessions/BearSSL_Sessions.ino | 39 +- .../BearSSL_Validation/BearSSL_Validation.ino | 63 +- .../examples/HTTPSRequest/HTTPSRequest.ino | 32 +- libraries/ESP8266WiFi/examples/IPv6/IPv6.ino | 96 +- .../examples/NTPClient/NTPClient.ino | 69 +- .../examples/PagerServer/PagerServer.ino | 32 +- .../RangeExtender-NAPT/RangeExtender-NAPT.ino | 32 +- .../examples/StaticLease/StaticLease.ino | 39 +- libraries/ESP8266WiFi/examples/Udp/Udp.ino | 30 +- .../WiFiAccessPoint/WiFiAccessPoint.ino | 13 +- .../examples/WiFiClient/WiFiClient.ino | 37 +- .../WiFiClientBasic/WiFiClientBasic.ino | 20 +- .../examples/WiFiEcho/WiFiEcho.ino | 94 +- .../examples/WiFiEvents/WiFiEvents.ino | 41 +- .../WiFiManualWebServer.ino | 32 +- .../examples/WiFiScan/WiFiScan.ino | 48 +- .../examples/WiFiShutdown/WiFiShutdown.ino | 18 +- .../WiFiTelnetToSerial/WiFiTelnetToSerial.ino | 78 +- .../examples/HelloEspnow/HelloEspnow.ino | 203 ++-- .../examples/HelloMesh/HelloMesh.ino | 109 +- .../examples/HelloTcpIp/HelloTcpIp.ino | 137 ++- .../examples/httpUpdate/httpUpdate.ino | 29 +- .../httpUpdateLittleFS/httpUpdateLittleFS.ino | 20 +- .../httpUpdateSecure/httpUpdateSecure.ino | 35 +- .../httpUpdateSigned/httpUpdateSigned.ino | 25 +- .../LEAmDNS/mDNS_Clock/mDNS_Clock.ino | 105 +- .../mDNS_ServiceMonitor.ino | 125 +- .../OTA-mDNS-LittleFS/OTA-mDNS-LittleFS.ino | 73 +- .../mDNS-SD_Extended/mDNS-SD_Extended.ino | 32 +- .../mDNS_Web_Server/mDNS_Web_Server.ino | 48 +- libraries/ESP8266mDNS/src/LEAmDNS.cpp | 356 +++--- libraries/ESP8266mDNS/src/LEAmDNS.h | 1018 ++++++++--------- libraries/ESP8266mDNS/src/LEAmDNS_Control.cpp | 238 ++-- libraries/ESP8266mDNS/src/LEAmDNS_Helpers.cpp | 100 +- libraries/ESP8266mDNS/src/LEAmDNS_Structs.cpp | 367 +++--- .../ESP8266mDNS/src/LEAmDNS_Transfer.cpp | 606 +++++----- .../InputSerialPlotter/InputSerialPlotter.ino | 19 +- .../I2S/examples/SimpleTone/SimpleTone.ino | 26 +- .../LittleFS_Timestamp/LittleFS_Timestamp.ino | 83 +- .../LittleFS/examples/SpeedTest/SpeedTest.ino | 98 +- .../Netdump/examples/Netdump/Netdump.ino | 108 +- libraries/Netdump/src/Netdump.cpp | 30 +- libraries/Netdump/src/Netdump.h | 36 +- libraries/Netdump/src/NetdumpIP.cpp | 12 +- libraries/Netdump/src/NetdumpIP.h | 18 +- libraries/Netdump/src/NetdumpPacket.cpp | 2 +- libraries/Netdump/src/NetdumpPacket.h | 53 +- libraries/Netdump/src/PacketType.h | 4 +- .../SD/examples/Datalogger/Datalogger.ino | 21 +- libraries/SD/examples/DumpFile/DumpFile.ino | 18 +- libraries/SD/examples/Files/Files.ino | 30 +- libraries/SD/examples/ReadWrite/ReadWrite.ino | 26 +- libraries/SD/examples/listfiles/listfiles.ino | 33 +- .../SPISlave_Master/SPISlave_Master.ino | 46 +- .../SPISlave_SafeMaster.ino | 49 +- .../examples/SPISlave_Test/SPISlave_Test.ino | 56 +- libraries/Servo/examples/Sweep/Sweep.ino | 24 +- .../examples/drawCircle/drawCircle.ino | 18 +- .../examples/drawLines/drawLines.ino | 16 +- .../examples/drawNumber/drawNumber.ino | 24 +- .../examples/drawRectangle/drawRectangle.ino | 10 +- .../examples/paint/paint.ino | 33 +- .../examples/shapes/shapes.ino | 15 +- .../examples/text/text.ino | 24 +- .../examples/tftbmp/tftbmp.ino | 96 +- .../examples/tftbmp2/tftbmp2.ino | 147 ++- .../examples/TickerBasic/TickerBasic.ino | 21 +- .../TickerFunctional/TickerFunctional.ino | 42 +- libraries/Wire/Wire.cpp | 36 +- libraries/Wire/Wire.h | 60 +- .../examples/master_reader/master_reader.ino | 24 +- .../examples/master_writer/master_writer.ino | 21 +- .../slave_receiver/slave_receiver.ino | 29 +- .../examples/slave_sender/slave_sender.ino | 17 +- libraries/esp8266/examples/Blink/Blink.ino | 16 +- .../BlinkPolledTimeout/BlinkPolledTimeout.ino | 40 +- .../BlinkWithoutDelay/BlinkWithoutDelay.ino | 24 +- .../examples/CallBackList/CallBackGeneric.ino | 50 +- .../examples/CheckFlashCRC/CheckFlashCRC.ino | 17 +- .../CheckFlashConfig/CheckFlashConfig.ino | 24 +- .../examples/ConfigFile/ConfigFile.ino | 46 +- .../FadePolledTimeout/FadePolledTimeout.ino | 31 +- .../examples/HeapMetric/HeapMetric.ino | 48 +- .../examples/HelloCrypto/HelloCrypto.ino | 31 +- .../examples/HwdtStackDump/HwdtStackDump.ino | 30 +- .../examples/HwdtStackDump/ProcessKey.ino | 26 +- .../examples/I2STransmit/I2STransmit.ino | 27 +- .../examples/IramReserve/IramReserve.ino | 35 +- .../examples/IramReserve/ProcessKey.ino | 26 +- .../examples/LowPowerDemo/LowPowerDemo.ino | 373 +++--- libraries/esp8266/examples/MMU48K/MMU48K.ino | 103 +- .../examples/NTP-TZ-DST/NTP-TZ-DST.ino | 127 +- .../examples/RTCUserMemory/RTCUserMemory.ino | 59 +- .../SerialDetectBaudrate.ino | 18 +- .../examples/SerialStress/SerialStress.ino | 119 +- .../SigmaDeltaDemo/SigmaDeltaDemo.ino | 24 +- .../examples/StreamString/StreamString.ino | 45 +- .../examples/TestEspApi/TestEspApi.ino | 45 +- .../examples/UartDownload/UartDownload.ino | 49 +- .../examples/interactive/interactive.ino | 33 +- .../esp8266/examples/irammem/irammem.ino | 372 +++--- .../examples/virtualmem/virtualmem.ino | 57 +- .../lwIP_PPP/examples/PPPServer/PPPServer.ino | 44 +- libraries/lwIP_PPP/src/PPPServer.cpp | 16 +- libraries/lwIP_PPP/src/PPPServer.h | 16 +- .../lwIP_enc28j60/src/utility/enc28j60.cpp | 34 +- .../lwIP_enc28j60/src/utility/enc28j60.h | 52 +- libraries/lwIP_w5100/src/utility/w5100.cpp | 19 +- libraries/lwIP_w5100/src/utility/w5100.h | 156 +-- libraries/lwIP_w5500/src/utility/w5500.cpp | 9 +- libraries/lwIP_w5500/src/utility/w5500.h | 230 ++-- tests/clang-format-arduino | 5 - tests/clang-format-core | 8 - tests/device/libraries/BSTest/src/BSArduino.h | 12 +- tests/device/libraries/BSTest/src/BSArgs.h | 34 +- .../device/libraries/BSTest/src/BSProtocol.h | 2 +- tests/device/libraries/BSTest/src/BSStdio.h | 2 +- tests/device/libraries/BSTest/src/BSTest.h | 48 +- tests/device/test_libc/libm_string.c | 12 +- tests/device/test_libc/memcpy-1.c | 53 +- tests/device/test_libc/memmove1.c | 10 +- tests/device/test_libc/strcmp-1.c | 95 +- tests/device/test_libc/tstring.c | 72 +- tests/host/common/Arduino.cpp | 4 +- tests/host/common/ArduinoMain.cpp | 26 +- tests/host/common/ArduinoMainLittlefs.cpp | 2 +- tests/host/common/ArduinoMainSpiffs.cpp | 2 +- tests/host/common/ArduinoMainUdp.cpp | 4 +- tests/host/common/ClientContextSocket.cpp | 14 +- tests/host/common/ClientContextTools.cpp | 2 +- tests/host/common/EEPROM.h | 12 +- tests/host/common/MockDigital.cpp | 2 +- tests/host/common/MockEEPROM.cpp | 3 +- tests/host/common/MockEsp.cpp | 6 +- tests/host/common/MockTools.cpp | 18 +- tests/host/common/MockUART.cpp | 56 +- tests/host/common/MockWiFiServerSocket.cpp | 14 +- tests/host/common/MocklwIP.cpp | 4 +- tests/host/common/UdpContextSocket.cpp | 14 +- tests/host/common/c_types.h | 44 +- tests/host/common/flash_hal_mock.cpp | 10 +- tests/host/common/include/ClientContext.h | 36 +- tests/host/common/include/UdpContext.h | 39 +- tests/host/common/littlefs_mock.cpp | 16 +- tests/host/common/littlefs_mock.h | 8 +- tests/host/common/md5.c | 28 +- tests/host/common/mock.h | 40 +- tests/host/common/noniso.c | 14 +- tests/host/common/queue.h | 154 +-- tests/host/common/sdfs_mock.cpp | 2 +- tests/host/common/spiffs_mock.cpp | 18 +- tests/host/common/spiffs_mock.h | 8 +- tests/host/common/strl.cpp | 16 +- tests/host/common/user_interface.cpp | 38 +- tests/host/core/test_PolledTimeout.cpp | 6 +- tests/host/core/test_Print.cpp | 28 +- tests/host/core/test_Updater.cpp | 2 +- tests/host/core/test_md5builder.cpp | 2 +- tests/host/core/test_pgmspace.cpp | 2 +- tests/host/core/test_string.cpp | 46 +- tests/host/fs/test_fs.cpp | 20 +- tests/host/sys/pgmspace.h | 20 +- tests/restyle.sh | 43 +- 211 files changed, 7138 insertions(+), 5608 deletions(-) delete mode 100644 tests/clang-format-arduino delete mode 100644 tests/clang-format-core diff --git a/cores/esp8266/LwipDhcpServer-NonOS.cpp b/cores/esp8266/LwipDhcpServer-NonOS.cpp index aee22b6d5c..56122c6074 100644 --- a/cores/esp8266/LwipDhcpServer-NonOS.cpp +++ b/cores/esp8266/LwipDhcpServer-NonOS.cpp @@ -31,7 +31,7 @@ extern netif netif_git[2]; // global DHCP instance for softAP interface -DhcpServer dhcpSoftAP(&netif_git[SOFTAP_IF]); +DhcpServer dhcpSoftAP(&netif_git[SOFTAP_IF]); extern "C" { diff --git a/cores/esp8266/LwipDhcpServer.cpp b/cores/esp8266/LwipDhcpServer.cpp index d7eddd02d9..8cc189a83a 100644 --- a/cores/esp8266/LwipDhcpServer.cpp +++ b/cores/esp8266/LwipDhcpServer.cpp @@ -59,30 +59,30 @@ typedef struct dhcps_state typedef struct dhcps_msg { - uint8_t op, htype, hlen, hops; - uint8_t xid[4]; + uint8_t op, htype, hlen, hops; + uint8_t xid[4]; uint16_t secs, flags; - uint8_t ciaddr[4]; - uint8_t yiaddr[4]; - uint8_t siaddr[4]; - uint8_t giaddr[4]; - uint8_t chaddr[16]; - uint8_t sname[64]; - uint8_t file[128]; - uint8_t options[312]; + uint8_t ciaddr[4]; + uint8_t yiaddr[4]; + uint8_t siaddr[4]; + uint8_t giaddr[4]; + uint8_t chaddr[16]; + uint8_t sname[64]; + uint8_t file[128]; + uint8_t options[312]; } dhcps_msg; #ifndef LWIP_OPEN_SRC struct dhcps_lease { - bool enable; + bool enable; struct ipv4_addr start_ip; struct ipv4_addr end_ip; }; enum dhcps_offer_option { - OFFER_START = 0x00, + OFFER_START = 0x00, OFFER_ROUTER = 0x01, OFFER_END }; @@ -103,10 +103,10 @@ typedef enum struct dhcps_pool { struct ipv4_addr ip; - uint8 mac[6]; - uint32 lease_timer; - dhcps_type_t type; - dhcps_state_t state; + uint8 mac[6]; + uint32 lease_timer; + dhcps_type_t type; + dhcps_state_t state; }; #define DHCPS_LEASE_TIMER dhcps_lease_time //0x05A0 @@ -175,20 +175,20 @@ const char mem_debug_file[] ICACHE_RODATA_ATTR = __FILE__; #define LWIP_IS_OK(what, err) ((err) == ERR_OK) #endif -const uint32 DhcpServer::magic_cookie = 0x63538263; // https://tools.ietf.org/html/rfc1497 +const uint32 DhcpServer::magic_cookie = 0x63538263; // https://tools.ietf.org/html/rfc1497 -int fw_has_started_softap_dhcps = 0; +int fw_has_started_softap_dhcps = 0; //////////////////////////////////////////////////////////////////////////////////// -DhcpServer::DhcpServer(netif* netif) - : _netif(netif) +DhcpServer::DhcpServer(netif* netif) : + _netif(netif) { - pcb_dhcps = nullptr; + pcb_dhcps = nullptr; dns_address.addr = 0; - plist = nullptr; - offer = 0xFF; - renew = false; + plist = nullptr; + offer = 0xFF; + renew = false; dhcps_lease_time = DHCPS_LEASE_TIME_DEF; //minute if (netif->num == SOFTAP_IF && fw_has_started_softap_dhcps == 1) @@ -210,7 +210,7 @@ DhcpServer::DhcpServer(netif* netif) // wifi_softap_set_station_info is missing in user_interface.h: extern "C" void wifi_softap_set_station_info(uint8_t* mac, struct ipv4_addr*); -void DhcpServer::dhcps_set_dns(int num, const ipv4_addr_t* dns) +void DhcpServer::dhcps_set_dns(int num, const ipv4_addr_t* dns) { (void)num; if (!ip4_addr_isany(dns)) @@ -227,7 +227,7 @@ void DhcpServer::dhcps_set_dns(int num, const ipv4_addr_t* dns) *******************************************************************************/ void DhcpServer::node_insert_to_list(list_node** phead, list_node* pinsert) { - list_node* plist = nullptr; + list_node* plist = nullptr; struct dhcps_pool* pdhcps_pool = nullptr; struct dhcps_pool* pdhcps_node = nullptr; if (*phead == nullptr) @@ -236,14 +236,14 @@ void DhcpServer::node_insert_to_list(list_node** phead, list_node* pinsert) } else { - plist = *phead; + plist = *phead; pdhcps_node = (struct dhcps_pool*)pinsert->pnode; pdhcps_pool = (struct dhcps_pool*)plist->pnode; if (pdhcps_node->ip.addr < pdhcps_pool->ip.addr) { pinsert->pnext = plist; - *phead = pinsert; + *phead = pinsert; } else { @@ -253,7 +253,7 @@ void DhcpServer::node_insert_to_list(list_node** phead, list_node* pinsert) if (pdhcps_node->ip.addr < pdhcps_pool->ip.addr) { pinsert->pnext = plist->pnext; - plist->pnext = pinsert; + plist->pnext = pinsert; break; } plist = plist->pnext; @@ -278,7 +278,7 @@ void DhcpServer::node_remove_from_list(list_node** phead, list_node* pdelete) { list_node* plist = nullptr; - plist = *phead; + plist = *phead; if (plist == nullptr) { *phead = nullptr; @@ -287,7 +287,7 @@ void DhcpServer::node_remove_from_list(list_node** phead, list_node* pdelete) { if (plist == pdelete) { - *phead = plist->pnext; + *phead = plist->pnext; pdelete->pnext = nullptr; } else @@ -296,7 +296,7 @@ void DhcpServer::node_remove_from_list(list_node** phead, list_node* pdelete) { if (plist->pnext == pdelete) { - plist->pnext = pdelete->pnext; + plist->pnext = pdelete->pnext; pdelete->pnext = nullptr; } plist = plist->pnext; @@ -314,10 +314,10 @@ void DhcpServer::node_remove_from_list(list_node** phead, list_node* pdelete) bool DhcpServer::add_dhcps_lease(uint8* macaddr) { struct dhcps_pool* pdhcps_pool = nullptr; - list_node* pback_node = nullptr; + list_node* pback_node = nullptr; - uint32 start_ip = dhcps_lease.start_ip.addr; - uint32 end_ip = dhcps_lease.end_ip.addr; + uint32 start_ip = dhcps_lease.start_ip.addr; + uint32 end_ip = dhcps_lease.end_ip.addr; for (pback_node = plist; pback_node != nullptr; pback_node = pback_node->pnext) { @@ -343,15 +343,15 @@ bool DhcpServer::add_dhcps_lease(uint8* macaddr) return false; } - pdhcps_pool = (struct dhcps_pool*)zalloc(sizeof(struct dhcps_pool)); + pdhcps_pool = (struct dhcps_pool*)zalloc(sizeof(struct dhcps_pool)); pdhcps_pool->ip.addr = start_ip; memcpy(pdhcps_pool->mac, macaddr, sizeof(pdhcps_pool->mac)); pdhcps_pool->lease_timer = DHCPS_LEASE_TIMER; - pdhcps_pool->type = DHCPS_TYPE_STATIC; - pdhcps_pool->state = DHCPS_STATE_ONLINE; - pback_node = (list_node*)zalloc(sizeof(list_node)); - pback_node->pnode = pdhcps_pool; - pback_node->pnext = nullptr; + pdhcps_pool->type = DHCPS_TYPE_STATIC; + pdhcps_pool->state = DHCPS_STATE_ONLINE; + pback_node = (list_node*)zalloc(sizeof(list_node)); + pback_node->pnode = pdhcps_pool; + pback_node->pnext = nullptr; node_insert_to_list(&plist, pback_node); return true; @@ -503,12 +503,12 @@ void DhcpServer::create_msg(struct dhcps_msg* m) client.addr = client_address.addr; - m->op = DHCP_REPLY; - m->htype = DHCP_HTYPE_ETHERNET; - m->hlen = 6; - m->hops = 0; - m->secs = 0; - m->flags = htons(BOOTP_BROADCAST); + m->op = DHCP_REPLY; + m->htype = DHCP_HTYPE_ETHERNET; + m->hlen = 6; + m->hops = 0; + m->secs = 0; + m->flags = htons(BOOTP_BROADCAST); memcpy((char*)m->yiaddr, (char*)&client.addr, sizeof(m->yiaddr)); memset((char*)m->ciaddr, 0, sizeof(m->ciaddr)); @@ -528,18 +528,18 @@ void DhcpServer::create_msg(struct dhcps_msg* m) /////////////////////////////////////////////////////////////////////////////////// void DhcpServer::send_offer(struct dhcps_msg* m) { - uint8_t* end; + uint8_t* end; struct pbuf *p, *q; - u8_t* data; - u16_t cnt = 0; - u16_t i; + u8_t* data; + u16_t cnt = 0; + u16_t i; create_msg(m); end = add_msg_type(&m->options[4], DHCPOFFER); end = add_offer_options(end); end = add_end(end); - p = pbuf_alloc(PBUF_TRANSPORT, sizeof(struct dhcps_msg), PBUF_RAM); + p = pbuf_alloc(PBUF_TRANSPORT, sizeof(struct dhcps_msg), PBUF_RAM); #if DHCPS_DEBUG os_printf("udhcp: send_offer>>p->ref = %d\n", p->ref); #endif @@ -592,17 +592,17 @@ void DhcpServer::send_offer(struct dhcps_msg* m) /////////////////////////////////////////////////////////////////////////////////// void DhcpServer::send_nak(struct dhcps_msg* m) { - u8_t* end; + u8_t* end; struct pbuf *p, *q; - u8_t* data; - u16_t cnt = 0; - u16_t i; + u8_t* data; + u16_t cnt = 0; + u16_t i; create_msg(m); end = add_msg_type(&m->options[4], DHCPNAK); end = add_end(end); - p = pbuf_alloc(PBUF_TRANSPORT, sizeof(struct dhcps_msg), PBUF_RAM); + p = pbuf_alloc(PBUF_TRANSPORT, sizeof(struct dhcps_msg), PBUF_RAM); #if DHCPS_DEBUG os_printf("udhcp: send_nak>>p->ref = %d\n", p->ref); #endif @@ -650,18 +650,18 @@ void DhcpServer::send_nak(struct dhcps_msg* m) /////////////////////////////////////////////////////////////////////////////////// void DhcpServer::send_ack(struct dhcps_msg* m) { - u8_t* end; + u8_t* end; struct pbuf *p, *q; - u8_t* data; - u16_t cnt = 0; - u16_t i; + u8_t* data; + u16_t cnt = 0; + u16_t i; create_msg(m); end = add_msg_type(&m->options[4], DHCPACK); end = add_offer_options(end); end = add_end(end); - p = pbuf_alloc(PBUF_TRANSPORT, sizeof(struct dhcps_msg), PBUF_RAM); + p = pbuf_alloc(PBUF_TRANSPORT, sizeof(struct dhcps_msg), PBUF_RAM); #if DHCPS_DEBUG os_printf("udhcp: send_ack>>p->ref = %d\n", p->ref); #endif @@ -718,16 +718,16 @@ void DhcpServer::send_ack(struct dhcps_msg* m) /////////////////////////////////////////////////////////////////////////////////// uint8_t DhcpServer::parse_options(uint8_t* optptr, sint16_t len) { - struct ipv4_addr client; - bool is_dhcp_parse_end = false; + struct ipv4_addr client; + bool is_dhcp_parse_end = false; struct dhcps_state s; client.addr = client_address.addr; - u8_t* end = optptr + len; - u16_t type = 0; + u8_t* end = optptr + len; + u16_t type = 0; - s.state = DHCPS_STATE_IDLE; + s.state = DHCPS_STATE_IDLE; while (optptr < end) { @@ -822,15 +822,15 @@ uint8_t DhcpServer::parse_options(uint8_t* optptr, sint16_t len) sint16_t DhcpServer::parse_msg(struct dhcps_msg* m, u16_t len) { if (memcmp((char*)m->options, - &magic_cookie, - sizeof(magic_cookie)) + &magic_cookie, + sizeof(magic_cookie)) == 0) { struct ipv4_addr ip; memcpy(&ip.addr, m->ciaddr, sizeof(ip.addr)); client_address.addr = dhcps_client_update(m->chaddr, &ip); - sint16_t ret = parse_options(&m->options[4], len); + sint16_t ret = parse_options(&m->options[4], len); if (ret == DHCPS_STATE_RELEASE) { @@ -855,32 +855,32 @@ sint16_t DhcpServer::parse_msg(struct dhcps_msg* m, u16_t len) */ /////////////////////////////////////////////////////////////////////////////////// -void DhcpServer::S_handle_dhcp(void* arg, - struct udp_pcb* pcb, - struct pbuf* p, - const ip_addr_t* addr, - uint16_t port) +void DhcpServer::S_handle_dhcp(void* arg, + struct udp_pcb* pcb, + struct pbuf* p, + const ip_addr_t* addr, + uint16_t port) { DhcpServer* instance = reinterpret_cast(arg); instance->handle_dhcp(pcb, p, addr, port); } void DhcpServer::handle_dhcp( - struct udp_pcb* pcb, - struct pbuf* p, + struct udp_pcb* pcb, + struct pbuf* p, const ip_addr_t* addr, - uint16_t port) + uint16_t port) { (void)pcb; (void)addr; (void)port; - struct dhcps_msg* pmsg_dhcps = nullptr; - sint16_t tlen = 0; - u16_t i = 0; - u16_t dhcps_msg_cnt = 0; - u8_t* p_dhcps_msg = nullptr; - u8_t* data = nullptr; + struct dhcps_msg* pmsg_dhcps = nullptr; + sint16_t tlen = 0; + u16_t i = 0; + u16_t dhcps_msg_cnt = 0; + u8_t* p_dhcps_msg = nullptr; + u8_t* data = nullptr; #if DHCPS_DEBUG os_printf("dhcps: handle_dhcp-> receive a packet\n"); @@ -897,8 +897,8 @@ void DhcpServer::handle_dhcp( return; } p_dhcps_msg = (u8_t*)pmsg_dhcps; - tlen = p->tot_len; - data = (u8_t*)p->payload; + tlen = p->tot_len; + data = (u8_t*)p->payload; #if DHCPS_DEBUG os_printf("dhcps: handle_dhcp-> p->tot_len = %d\n", tlen); @@ -968,12 +968,12 @@ void DhcpServer::init_dhcps_lease(uint32 ip) { uint32 softap_ip = 0, local_ip = 0; uint32 start_ip = 0; - uint32 end_ip = 0; + uint32 end_ip = 0; if (dhcps_lease.enable == true) { softap_ip = htonl(ip); - start_ip = htonl(dhcps_lease.start_ip.addr); - end_ip = htonl(dhcps_lease.end_ip.addr); + start_ip = htonl(dhcps_lease.start_ip.addr); + end_ip = htonl(dhcps_lease.end_ip.addr); /*config ip information can't contain local ip*/ if ((start_ip <= softap_ip) && (softap_ip <= end_ip)) { @@ -1007,9 +1007,9 @@ void DhcpServer::init_dhcps_lease(uint32 ip) bzero(&dhcps_lease, sizeof(dhcps_lease)); dhcps_lease.start_ip.addr = softap_ip | local_ip; - dhcps_lease.end_ip.addr = softap_ip | (local_ip + DHCPS_MAX_LEASE - 1); + dhcps_lease.end_ip.addr = softap_ip | (local_ip + DHCPS_MAX_LEASE - 1); dhcps_lease.start_ip.addr = htonl(dhcps_lease.start_ip.addr); - dhcps_lease.end_ip.addr = htonl(dhcps_lease.end_ip.addr); + dhcps_lease.end_ip.addr = htonl(dhcps_lease.end_ip.addr); } // dhcps_lease.start_ip.addr = htonl(dhcps_lease.start_ip.addr); // dhcps_lease.end_ip.addr= htonl(dhcps_lease.end_ip.addr); @@ -1071,20 +1071,20 @@ void DhcpServer::end() udp_disconnect(pcb_dhcps); udp_remove(pcb_dhcps); - pcb_dhcps = nullptr; + pcb_dhcps = nullptr; //udp_remove(pcb_dhcps); - list_node* pnode = nullptr; - list_node* pback_node = nullptr; - struct dhcps_pool* dhcp_node = nullptr; - struct ipv4_addr ip_zero; + list_node* pnode = nullptr; + list_node* pback_node = nullptr; + struct dhcps_pool* dhcp_node = nullptr; + struct ipv4_addr ip_zero; memset(&ip_zero, 0x0, sizeof(ip_zero)); pnode = plist; while (pnode != nullptr) { pback_node = pnode; - pnode = pback_node->pnext; + pnode = pback_node->pnext; node_remove_from_list(&plist, pback_node); dhcp_node = (struct dhcps_pool*)pback_node->pnode; //dhcps_client_leave(dhcp_node->mac,&dhcp_node->ip,true); // force to delete @@ -1114,8 +1114,8 @@ bool DhcpServer::isRunning() bool DhcpServer::set_dhcps_lease(struct dhcps_lease* please) { uint32 softap_ip = 0; - uint32 start_ip = 0; - uint32 end_ip = 0; + uint32 start_ip = 0; + uint32 end_ip = 0; if (_netif->num == SOFTAP_IF || _netif->num == STATION_IF) { @@ -1137,8 +1137,8 @@ bool DhcpServer::set_dhcps_lease(struct dhcps_lease* please) // - is wrong // - limited to /24 address plans softap_ip = htonl(ip_2_ip4(&_netif->ip_addr)->addr); - start_ip = htonl(please->start_ip.addr); - end_ip = htonl(please->end_ip.addr); + start_ip = htonl(please->start_ip.addr); + end_ip = htonl(please->end_ip.addr); /*config ip information can't contain local ip*/ if ((start_ip <= softap_ip) && (softap_ip <= end_ip)) { @@ -1162,7 +1162,7 @@ bool DhcpServer::set_dhcps_lease(struct dhcps_lease* please) // dhcps_lease.start_ip.addr = start_ip; // dhcps_lease.end_ip.addr = end_ip; dhcps_lease.start_ip.addr = please->start_ip.addr; - dhcps_lease.end_ip.addr = please->end_ip.addr; + dhcps_lease.end_ip.addr = please->end_ip.addr; } dhcps_lease.enable = please->enable; // dhcps_lease_flag = false; @@ -1215,32 +1215,32 @@ bool DhcpServer::get_dhcps_lease(struct dhcps_lease* please) // please->end_ip.addr = dhcps_lease.end_ip.addr; // } please->start_ip.addr = dhcps_lease.start_ip.addr; - please->end_ip.addr = dhcps_lease.end_ip.addr; + please->end_ip.addr = dhcps_lease.end_ip.addr; return true; } void DhcpServer::kill_oldest_dhcps_pool(void) { - list_node *pre = nullptr, *p = nullptr; - list_node *minpre = nullptr, *minp = nullptr; + list_node * pre = nullptr, *p = nullptr; + list_node * minpre = nullptr, *minp = nullptr; struct dhcps_pool *pdhcps_pool = nullptr, *pmin_pool = nullptr; - pre = plist; - p = pre->pnext; + pre = plist; + p = pre->pnext; minpre = pre; - minp = p; + minp = p; while (p != nullptr) { pdhcps_pool = (struct dhcps_pool*)p->pnode; - pmin_pool = (struct dhcps_pool*)minp->pnode; + pmin_pool = (struct dhcps_pool*)minp->pnode; if (pdhcps_pool->lease_timer < pmin_pool->lease_timer) { - minp = p; + minp = p; minpre = pre; } pre = p; - p = p->pnext; + p = p->pnext; } - minpre->pnext = minp->pnext; + minpre->pnext = minp->pnext; pdhcps_pool->state = DHCPS_STATE_OFFLINE; free(minp->pnode); minp->pnode = nullptr; @@ -1250,11 +1250,11 @@ void DhcpServer::kill_oldest_dhcps_pool(void) void DhcpServer::dhcps_coarse_tmr(void) { - uint8 num_dhcps_pool = 0; - list_node* pback_node = nullptr; - list_node* pnode = nullptr; - struct dhcps_pool* pdhcps_pool = nullptr; - pnode = plist; + uint8 num_dhcps_pool = 0; + list_node* pback_node = nullptr; + list_node* pnode = nullptr; + struct dhcps_pool* pdhcps_pool = nullptr; + pnode = plist; while (pnode != nullptr) { pdhcps_pool = (struct dhcps_pool*)pnode->pnode; @@ -1265,7 +1265,7 @@ void DhcpServer::dhcps_coarse_tmr(void) if (pdhcps_pool->lease_timer == 0) { pback_node = pnode; - pnode = pback_node->pnext; + pnode = pback_node->pnext; node_remove_from_list(&plist, pback_node); free(pback_node->pnode); pback_node->pnode = nullptr; @@ -1302,7 +1302,7 @@ bool DhcpServer::set_dhcps_offer_option(uint8 level, void* optarg) switch (level) { case OFFER_ROUTER: - offer = (*(uint8*)optarg) & 0x01; + offer = (*(uint8*)optarg) & 0x01; offer_flag = true; break; default: @@ -1363,7 +1363,7 @@ uint32 DhcpServer::get_dhcps_lease_time(void) // minute void DhcpServer::dhcps_client_leave(u8* bssid, struct ipv4_addr* ip, bool force) { struct dhcps_pool* pdhcps_pool = nullptr; - list_node* pback_node = nullptr; + list_node* pback_node = nullptr; if ((bssid == nullptr) || (ip == nullptr)) { @@ -1412,13 +1412,13 @@ void DhcpServer::dhcps_client_leave(u8* bssid, struct ipv4_addr* ip, bool force) uint32 DhcpServer::dhcps_client_update(u8* bssid, struct ipv4_addr* ip) { struct dhcps_pool* pdhcps_pool = nullptr; - list_node* pback_node = nullptr; - list_node* pmac_node = nullptr; - list_node* pip_node = nullptr; - bool flag = false; - uint32 start_ip = dhcps_lease.start_ip.addr; - uint32 end_ip = dhcps_lease.end_ip.addr; - dhcps_type_t type = DHCPS_TYPE_DYNAMIC; + list_node* pback_node = nullptr; + list_node* pmac_node = nullptr; + list_node* pip_node = nullptr; + bool flag = false; + uint32 start_ip = dhcps_lease.start_ip.addr; + uint32 end_ip = dhcps_lease.end_ip.addr; + dhcps_type_t type = DHCPS_TYPE_DYNAMIC; if (bssid == nullptr) { return IPADDR_ANY; @@ -1522,12 +1522,12 @@ uint32 DhcpServer::dhcps_client_update(u8* bssid, struct ipv4_addr* ip) else { renew = true; - type = DHCPS_TYPE_DYNAMIC; + type = DHCPS_TYPE_DYNAMIC; } pdhcps_pool->lease_timer = DHCPS_LEASE_TIMER; - pdhcps_pool->type = type; - pdhcps_pool->state = DHCPS_STATE_ONLINE; + pdhcps_pool->type = type; + pdhcps_pool->state = DHCPS_STATE_ONLINE; } else { @@ -1547,8 +1547,8 @@ uint32 DhcpServer::dhcps_client_update(u8* bssid, struct ipv4_addr* ip) node_remove_from_list(&plist, pmac_node); pdhcps_pool->lease_timer = DHCPS_LEASE_TIMER; - pdhcps_pool->type = type; - pdhcps_pool->state = DHCPS_STATE_ONLINE; + pdhcps_pool->type = type; + pdhcps_pool->state = DHCPS_STATE_ONLINE; node_insert_to_list(&plist, pmac_node); } } @@ -1563,8 +1563,8 @@ uint32 DhcpServer::dhcps_client_update(u8* bssid, struct ipv4_addr* ip) } memcpy(pdhcps_pool->mac, bssid, sizeof(pdhcps_pool->mac)); pdhcps_pool->lease_timer = DHCPS_LEASE_TIMER; - pdhcps_pool->type = type; - pdhcps_pool->state = DHCPS_STATE_ONLINE; + pdhcps_pool->type = type; + pdhcps_pool->state = DHCPS_STATE_ONLINE; } else { @@ -1589,11 +1589,11 @@ uint32 DhcpServer::dhcps_client_update(u8* bssid, struct ipv4_addr* ip) } memcpy(pdhcps_pool->mac, bssid, sizeof(pdhcps_pool->mac)); pdhcps_pool->lease_timer = DHCPS_LEASE_TIMER; - pdhcps_pool->type = type; - pdhcps_pool->state = DHCPS_STATE_ONLINE; - pback_node = (list_node*)zalloc(sizeof(list_node)); - pback_node->pnode = pdhcps_pool; - pback_node->pnext = nullptr; + pdhcps_pool->type = type; + pdhcps_pool->state = DHCPS_STATE_ONLINE; + pback_node = (list_node*)zalloc(sizeof(list_node)); + pback_node->pnode = pdhcps_pool; + pback_node->pnext = nullptr; node_insert_to_list(&plist, pback_node); } } diff --git a/cores/esp8266/LwipDhcpServer.h b/cores/esp8266/LwipDhcpServer.h index 74fa3a4018..73004cd075 100644 --- a/cores/esp8266/LwipDhcpServer.h +++ b/cores/esp8266/LwipDhcpServer.h @@ -39,11 +39,11 @@ class DhcpServer DhcpServer(netif* netif); ~DhcpServer(); - void setDns(int num, const ipv4_addr_t* dns); + void setDns(int num, const ipv4_addr_t* dns); - bool begin(ip_info* info); - void end(); - bool isRunning(); + bool begin(ip_info* info); + void end(); + bool isRunning(); // this is the C interface encapsulated in a class // (originally dhcpserver.c in lwIP-v1.4 in NonOS-SDK) @@ -52,71 +52,71 @@ class DhcpServer // legacy public C structure and API to eventually turn into C++ - void init_dhcps_lease(uint32 ip); - bool set_dhcps_lease(struct dhcps_lease* please); - bool get_dhcps_lease(struct dhcps_lease* please); - bool set_dhcps_offer_option(uint8 level, void* optarg); - bool set_dhcps_lease_time(uint32 minute); - bool reset_dhcps_lease_time(void); + void init_dhcps_lease(uint32 ip); + bool set_dhcps_lease(struct dhcps_lease* please); + bool get_dhcps_lease(struct dhcps_lease* please); + bool set_dhcps_offer_option(uint8 level, void* optarg); + bool set_dhcps_lease_time(uint32 minute); + bool reset_dhcps_lease_time(void); uint32 get_dhcps_lease_time(void); - bool add_dhcps_lease(uint8* macaddr); + bool add_dhcps_lease(uint8* macaddr); - void dhcps_set_dns(int num, const ipv4_addr_t* dns); + void dhcps_set_dns(int num, const ipv4_addr_t* dns); protected: // legacy C structure and API to eventually turn into C++ typedef struct _list_node { - void* pnode; + void* pnode; struct _list_node* pnext; } list_node; - void node_insert_to_list(list_node** phead, list_node* pinsert); - void node_remove_from_list(list_node** phead, list_node* pdelete); - uint8_t* add_msg_type(uint8_t* optptr, uint8_t type); - uint8_t* add_offer_options(uint8_t* optptr); - uint8_t* add_end(uint8_t* optptr); - void create_msg(struct dhcps_msg* m); - void send_offer(struct dhcps_msg* m); - void send_nak(struct dhcps_msg* m); - void send_ack(struct dhcps_msg* m); - uint8_t parse_options(uint8_t* optptr, sint16_t len); - sint16_t parse_msg(struct dhcps_msg* m, u16_t len); - static void S_handle_dhcp(void* arg, - struct udp_pcb* pcb, - struct pbuf* p, - const ip_addr_t* addr, - uint16_t port); - void handle_dhcp( - struct udp_pcb* pcb, - struct pbuf* p, - const ip_addr_t* addr, - uint16_t port); - void kill_oldest_dhcps_pool(void); - void dhcps_coarse_tmr(void); // CURRENTLY NOT CALLED - void dhcps_client_leave(u8* bssid, struct ipv4_addr* ip, bool force); - uint32 dhcps_client_update(u8* bssid, struct ipv4_addr* ip); - - netif* _netif; - - struct udp_pcb* pcb_dhcps; - ip_addr_t broadcast_dhcps; - struct ipv4_addr server_address; - struct ipv4_addr client_address; - struct ipv4_addr dns_address; - uint32 dhcps_lease_time; - - struct dhcps_lease dhcps_lease; - list_node* plist; - uint8 offer; - bool renew; + void node_insert_to_list(list_node** phead, list_node* pinsert); + void node_remove_from_list(list_node** phead, list_node* pdelete); + uint8_t* add_msg_type(uint8_t* optptr, uint8_t type); + uint8_t* add_offer_options(uint8_t* optptr); + uint8_t* add_end(uint8_t* optptr); + void create_msg(struct dhcps_msg* m); + void send_offer(struct dhcps_msg* m); + void send_nak(struct dhcps_msg* m); + void send_ack(struct dhcps_msg* m); + uint8_t parse_options(uint8_t* optptr, sint16_t len); + sint16_t parse_msg(struct dhcps_msg* m, u16_t len); + static void S_handle_dhcp(void* arg, + struct udp_pcb* pcb, + struct pbuf* p, + const ip_addr_t* addr, + uint16_t port); + void handle_dhcp( + struct udp_pcb* pcb, + struct pbuf* p, + const ip_addr_t* addr, + uint16_t port); + void kill_oldest_dhcps_pool(void); + void dhcps_coarse_tmr(void); // CURRENTLY NOT CALLED + void dhcps_client_leave(u8* bssid, struct ipv4_addr* ip, bool force); + uint32 dhcps_client_update(u8* bssid, struct ipv4_addr* ip); + + netif* _netif; + + struct udp_pcb* pcb_dhcps; + ip_addr_t broadcast_dhcps; + struct ipv4_addr server_address; + struct ipv4_addr client_address; + struct ipv4_addr dns_address; + uint32 dhcps_lease_time; + + struct dhcps_lease dhcps_lease; + list_node* plist; + uint8 offer; + bool renew; static const uint32 magic_cookie; }; // SoftAP DHCP server always exists and is started on boot extern DhcpServer dhcpSoftAP; -extern "C" int fw_has_started_softap_dhcps; +extern "C" int fw_has_started_softap_dhcps; #endif // __DHCPS_H__ diff --git a/cores/esp8266/LwipIntf.cpp b/cores/esp8266/LwipIntf.cpp index 44359e6fc1..b4ae7e06e9 100644 --- a/cores/esp8266/LwipIntf.cpp +++ b/cores/esp8266/LwipIntf.cpp @@ -26,19 +26,19 @@ extern "C" // result stored into gateway/netmask/dns1 bool LwipIntf::ipAddressReorder(const IPAddress& local_ip, const IPAddress& arg1, const IPAddress& arg2, const IPAddress& arg3, - IPAddress& gateway, IPAddress& netmask, IPAddress& dns1) + IPAddress& gateway, IPAddress& netmask, IPAddress& dns1) { //To allow compatibility, check first octet of 3rd arg. If 255, interpret as ESP order, otherwise Arduino order. gateway = arg1; netmask = arg2; - dns1 = arg3; + dns1 = arg3; if (netmask[0] != 255) { //octet is not 255 => interpret as Arduino order gateway = arg2; netmask = arg3[0] == 0 ? IPAddress(255, 255, 255, 0) : arg3; //arg order is arduino and 4th arg not given => assign it arduino default - dns1 = arg1; + dns1 = arg1; } // check whether all is IPv4 (or gateway not set) @@ -154,7 +154,7 @@ bool LwipIntf::hostname(const char* aHostname) if (lwipret != ERR_OK) { DEBUGV("WiFi.hostname(%s): lwIP error %d on interface %c%c (index %d)\n", - intf->hostname, (int)lwipret, intf->name[0], intf->name[1], intf->num); + intf->hostname, (int)lwipret, intf->name[0], intf->name[1], intf->num); ret = false; } } diff --git a/cores/esp8266/LwipIntf.h b/cores/esp8266/LwipIntf.h index 10acf716c7..13a8e56d3b 100644 --- a/cores/esp8266/LwipIntf.h +++ b/cores/esp8266/LwipIntf.h @@ -24,10 +24,10 @@ class LwipIntf // // result stored into gateway/netmask/dns1 static bool ipAddressReorder(const IPAddress& local_ip, const IPAddress& arg1, const IPAddress& arg2, const IPAddress& arg3, - IPAddress& gateway, IPAddress& netmask, IPAddress& dns1); + IPAddress& gateway, IPAddress& netmask, IPAddress& dns1); - String hostname(); - bool hostname(const String& aHostname) + String hostname(); + bool hostname(const String& aHostname) { return hostname(aHostname.c_str()); } diff --git a/cores/esp8266/LwipIntfCB.cpp b/cores/esp8266/LwipIntfCB.cpp index 71047dcdd1..a5e9b445ca 100644 --- a/cores/esp8266/LwipIntfCB.cpp +++ b/cores/esp8266/LwipIntfCB.cpp @@ -5,10 +5,10 @@ #define NETIF_STATUS_CB_SIZE 3 -static int netifStatusChangeListLength = 0; +static int netifStatusChangeListLength = 0; LwipIntf::CBType netifStatusChangeList[NETIF_STATUS_CB_SIZE]; -extern "C" void netif_status_changed(struct netif* netif) +extern "C" void netif_status_changed(struct netif* netif) { // override the default empty weak function for (int i = 0; i < netifStatusChangeListLength; i++) @@ -34,9 +34,9 @@ bool LwipIntf::stateChangeSysCB(LwipIntf::CBType&& cb) bool LwipIntf::stateUpCB(LwipIntf::CBType&& cb) { return stateChangeSysCB([cb](netif* nif) - { - if (netif_is_up(nif)) - schedule_function([cb, nif]() - { cb(nif); }); - }); + { + if (netif_is_up(nif)) + schedule_function([cb, nif]() + { cb(nif); }); + }); } diff --git a/cores/esp8266/LwipIntfDev.h b/cores/esp8266/LwipIntfDev.h index 4dccfa0cba..9931daa3c5 100644 --- a/cores/esp8266/LwipIntfDev.h +++ b/cores/esp8266/LwipIntfDev.h @@ -29,20 +29,20 @@ template class LwipIntfDev : public LwipIntf, public RawDev { public: - LwipIntfDev(int8_t cs = SS, SPIClass& spi = SPI, int8_t intr = -1) - : RawDev(cs, spi, intr) - , _mtu(DEFAULT_MTU) - , _intrPin(intr) - , _started(false) - , _default(false) + LwipIntfDev(int8_t cs = SS, SPIClass& spi = SPI, int8_t intr = -1) : + RawDev(cs, spi, intr), + _mtu(DEFAULT_MTU), + _intrPin(intr), + _started(false), + _default(false) { memset(&_netif, 0, sizeof(_netif)); } - boolean config(const IPAddress& local_ip, const IPAddress& arg1, const IPAddress& arg2, const IPAddress& arg3 = IPADDR_NONE, const IPAddress& dns2 = IPADDR_NONE); + boolean config(const IPAddress& local_ip, const IPAddress& arg1, const IPAddress& arg2, const IPAddress& arg3 = IPADDR_NONE, const IPAddress& dns2 = IPADDR_NONE); // default mac-address is inferred from esp8266's STA interface - boolean begin(const uint8_t* macAddress = nullptr, const uint16_t mtu = DEFAULT_MTU); + boolean begin(const uint8_t* macAddress = nullptr, const uint16_t mtu = DEFAULT_MTU); const netif* getNetIf() const { @@ -75,25 +75,25 @@ class LwipIntfDev : public LwipIntf, public RawDev wl_status_t status(); protected: - err_t netif_init(); - void netif_status_callback(); + err_t netif_init(); + void netif_status_callback(); static err_t netif_init_s(netif* netif); static err_t linkoutput_s(netif* netif, struct pbuf* p); - static void netif_status_callback_s(netif* netif); + static void netif_status_callback_s(netif* netif); // called on a regular basis or on interrupt - err_t handlePackets(); + err_t handlePackets(); // members - netif _netif; + netif _netif; - uint16_t _mtu; - int8_t _intrPin; - uint8_t _macAddress[6]; - bool _started; - bool _default; + uint16_t _mtu; + int8_t _intrPin; + uint8_t _macAddress[6]; + bool _started; + bool _default; }; template @@ -218,11 +218,11 @@ boolean LwipIntfDev::begin(const uint8_t* macAddress, const uint16_t mtu } if (_intrPin < 0 && !schedule_recurrent_function_us([&]() - { - this->handlePackets(); - return true; - }, - 100)) + { + this->handlePackets(); + return true; + }, + 100)) { netif_remove(&_netif); return false; @@ -274,11 +274,11 @@ void LwipIntfDev::netif_status_callback_s(struct netif* netif) template err_t LwipIntfDev::netif_init() { - _netif.name[0] = 'e'; - _netif.name[1] = '0' + _netif.num; - _netif.mtu = _mtu; + _netif.name[0] = 'e'; + _netif.name[1] = '0' + _netif.num; + _netif.mtu = _mtu; _netif.chksum_flags = NETIF_CHECKSUM_ENABLE_ALL; - _netif.flags = NETIF_FLAG_ETHARP + _netif.flags = NETIF_FLAG_ETHARP | NETIF_FLAG_IGMP | NETIF_FLAG_BROADCAST | NETIF_FLAG_LINK_UP; @@ -286,11 +286,11 @@ err_t LwipIntfDev::netif_init() // lwIP's doc: This function typically first resolves the hardware // address, then sends the packet. For ethernet physical layer, this is // usually lwIP's etharp_output() - _netif.output = etharp_output; + _netif.output = etharp_output; // lwIP's doc: This function outputs the pbuf as-is on the link medium // (this must points to the raw ethernet driver, meaning: us) - _netif.linkoutput = linkoutput_s; + _netif.linkoutput = linkoutput_s; _netif.status_callback = netif_status_callback_s; diff --git a/cores/esp8266/StreamSend.cpp b/cores/esp8266/StreamSend.cpp index 948e46e5fb..13f4e47cda 100644 --- a/cores/esp8266/StreamSend.cpp +++ b/cores/esp8266/StreamSend.cpp @@ -22,10 +22,10 @@ #include #include -size_t Stream::sendGeneric(Print* to, - const ssize_t len, - const int readUntilChar, - const esp8266::polledTimeout::oneShotFastMs::timeType timeoutMs) +size_t Stream::sendGeneric(Print* to, + const ssize_t len, + const int readUntilChar, + const esp8266::polledTimeout::oneShotFastMs::timeType timeoutMs) { setReport(Report::Success); @@ -61,8 +61,8 @@ size_t Stream::SendGenericPeekBuffer(Print* to, const ssize_t len, const int rea // "neverExpires (default, impossible)" is translated to default timeout esp8266::polledTimeout::oneShotFastMs timedOut(timeoutMs >= esp8266::polledTimeout::oneShotFastMs::neverExpires ? getTimeout() : timeoutMs); // len==-1 => maxLen=0 <=> until starvation - const size_t maxLen = std::max((ssize_t)0, len); - size_t written = 0; + const size_t maxLen = std::max((ssize_t)0, len); + size_t written = 0; while (!maxLen || written < maxLen) { @@ -88,13 +88,13 @@ size_t Stream::SendGenericPeekBuffer(Print* to, const ssize_t len, const int rea if (w) { const char* directbuf = peekBuffer(); - bool foundChar = false; + bool foundChar = false; if (readUntilChar >= 0) { const char* last = (const char*)memchr(directbuf, readUntilChar, w); if (last) { - w = std::min((size_t)(last - directbuf), w); + w = std::min((size_t)(last - directbuf), w); foundChar = true; } } @@ -151,8 +151,8 @@ size_t Stream::SendGenericRegularUntil(Print* to, const ssize_t len, const int r // "neverExpires (default, impossible)" is translated to default timeout esp8266::polledTimeout::oneShotFastMs timedOut(timeoutMs >= esp8266::polledTimeout::oneShotFastMs::neverExpires ? getTimeout() : timeoutMs); // len==-1 => maxLen=0 <=> until starvation - const size_t maxLen = std::max((ssize_t)0, len); - size_t written = 0; + const size_t maxLen = std::max((ssize_t)0, len); + size_t written = 0; while (!maxLen || written < maxLen) { @@ -227,8 +227,8 @@ size_t Stream::SendGenericRegular(Print* to, const ssize_t len, const esp8266::p // "neverExpires (default, impossible)" is translated to default timeout esp8266::polledTimeout::oneShotFastMs timedOut(timeoutMs >= esp8266::polledTimeout::oneShotFastMs::neverExpires ? getTimeout() : timeoutMs); // len==-1 => maxLen=0 <=> until starvation - const size_t maxLen = std::max((ssize_t)0, len); - size_t written = 0; + const size_t maxLen = std::max((ssize_t)0, len); + size_t written = 0; while (!maxLen || written < maxLen) { @@ -254,7 +254,7 @@ size_t Stream::SendGenericRegular(Print* to, const ssize_t len, const esp8266::p w = std::min(w, (decltype(w))temporaryStackBufferSize); if (w) { - char temp[w]; + char temp[w]; ssize_t r = read(temp, w); if (r < 0) { diff --git a/cores/esp8266/StreamString.h b/cores/esp8266/StreamString.h index 7bda5dde68..a16f8ce6a4 100644 --- a/cores/esp8266/StreamString.h +++ b/cores/esp8266/StreamString.h @@ -35,15 +35,13 @@ class S2Stream : public Stream { public: - S2Stream(String& string, int peekPointer = -1) - : string(&string) - , peekPointer(peekPointer) + S2Stream(String& string, int peekPointer = -1) : + string(&string), peekPointer(peekPointer) { } - S2Stream(String* string, int peekPointer = -1) - : string(string) - , peekPointer(peekPointer) + S2Stream(String* string, int peekPointer = -1) : + string(string), peekPointer(peekPointer) { } @@ -209,7 +207,7 @@ class S2Stream : public Stream protected: String* string; - int peekPointer; // -1:String is consumed / >=0:resettable pointer + int peekPointer; // -1:String is consumed / >=0:resettable pointer }; // StreamString is a S2Stream holding the String @@ -226,80 +224,38 @@ class StreamString : public String, public S2Stream } public: - StreamString(StreamString&& bro) - : String(bro) - , S2Stream(this) - { - } - StreamString(const StreamString& bro) - : String(bro) - , S2Stream(this) - { - } + StreamString(StreamString&& bro) : + String(bro), S2Stream(this) { } + StreamString(const StreamString& bro) : + String(bro), S2Stream(this) { } // duplicate String constructors and operator=: - StreamString(const char* text = nullptr) - : String(text) - , S2Stream(this) - { - } - StreamString(const String& string) - : String(string) - , S2Stream(this) - { - } - StreamString(const __FlashStringHelper* str) - : String(str) - , S2Stream(this) - { - } - StreamString(String&& string) - : String(string) - , S2Stream(this) - { - } - - explicit StreamString(char c) - : String(c) - , S2Stream(this) - { - } - explicit StreamString(unsigned char c, unsigned char base = 10) - : String(c, base) - , S2Stream(this) - { - } - explicit StreamString(int i, unsigned char base = 10) - : String(i, base) - , S2Stream(this) - { - } - explicit StreamString(unsigned int i, unsigned char base = 10) - : String(i, base) - , S2Stream(this) - { - } - explicit StreamString(long l, unsigned char base = 10) - : String(l, base) - , S2Stream(this) - { - } - explicit StreamString(unsigned long l, unsigned char base = 10) - : String(l, base) - , S2Stream(this) - { - } - explicit StreamString(float f, unsigned char decimalPlaces = 2) - : String(f, decimalPlaces) - , S2Stream(this) - { - } - explicit StreamString(double d, unsigned char decimalPlaces = 2) - : String(d, decimalPlaces) - , S2Stream(this) - { - } + StreamString(const char* text = nullptr) : + String(text), S2Stream(this) { } + StreamString(const String& string) : + String(string), S2Stream(this) { } + StreamString(const __FlashStringHelper* str) : + String(str), S2Stream(this) { } + StreamString(String&& string) : + String(string), S2Stream(this) { } + + explicit StreamString(char c) : + String(c), S2Stream(this) { } + explicit StreamString(unsigned char c, unsigned char base = 10) : + String(c, base), S2Stream(this) { } + explicit StreamString(int i, unsigned char base = 10) : + String(i, base), S2Stream(this) { } + explicit StreamString(unsigned int i, unsigned char base = 10) : + String(i, base), S2Stream(this) { } + explicit StreamString(long l, unsigned char base = 10) : + String(l, base), S2Stream(this) { } + explicit StreamString(unsigned long l, unsigned char base = 10) : + String(l, base), S2Stream(this) { } + explicit StreamString(float f, unsigned char decimalPlaces = 2) : + String(f, decimalPlaces), S2Stream(this) { } + explicit StreamString(double d, unsigned char decimalPlaces = 2) : + String(d, decimalPlaces), S2Stream(this) { } StreamString& operator=(const StreamString& rhs) { diff --git a/cores/esp8266/core_esp8266_si2c.cpp b/cores/esp8266/core_esp8266_si2c.cpp index e56b8b5fba..7f26656564 100644 --- a/cores/esp8266/core_esp8266_si2c.cpp +++ b/cores/esp8266/core_esp8266_si2c.cpp @@ -60,61 +60,61 @@ static inline __attribute__((always_inline)) bool SCL_READ(const int twi_scl) class Twi { private: - unsigned int preferred_si2c_clock = 100000; - uint32_t twi_dcount = 18; - unsigned char twi_sda = 0; - unsigned char twi_scl = 0; - unsigned char twi_addr = 0; - uint32_t twi_clockStretchLimit = 0; + unsigned int preferred_si2c_clock = 100000; + uint32_t twi_dcount = 18; + unsigned char twi_sda = 0; + unsigned char twi_scl = 0; + unsigned char twi_addr = 0; + uint32_t twi_clockStretchLimit = 0; // These are int-wide, even though they could all fit in a byte, to reduce code size and avoid any potential // issues about RmW on packed bytes. The int-wide variations of asm instructions are smaller than the equivalent // byte-wide ones, and since these emums are used everywhere, the difference adds up fast. There is only a single // instance of the class, though, so the extra 12 bytes of RAM used here saves a lot more IRAM. volatile enum { TWIPM_UNKNOWN = 0, - TWIPM_IDLE, - TWIPM_ADDRESSED, - TWIPM_WAIT } twip_mode + TWIPM_IDLE, + TWIPM_ADDRESSED, + TWIPM_WAIT } twip_mode = TWIPM_IDLE; volatile enum { TWIP_UNKNOWN = 0, - TWIP_IDLE, - TWIP_START, - TWIP_SEND_ACK, - TWIP_WAIT_ACK, - TWIP_WAIT_STOP, - TWIP_SLA_W, - TWIP_SLA_R, - TWIP_REP_START, - TWIP_READ, - TWIP_STOP, - TWIP_REC_ACK, - TWIP_READ_ACK, - TWIP_RWAIT_ACK, - TWIP_WRITE, - TWIP_BUS_ERR } twip_state + TWIP_IDLE, + TWIP_START, + TWIP_SEND_ACK, + TWIP_WAIT_ACK, + TWIP_WAIT_STOP, + TWIP_SLA_W, + TWIP_SLA_R, + TWIP_REP_START, + TWIP_READ, + TWIP_STOP, + TWIP_REC_ACK, + TWIP_READ_ACK, + TWIP_RWAIT_ACK, + TWIP_WRITE, + TWIP_BUS_ERR } twip_state = TWIP_IDLE; - volatile int twip_status = TW_NO_INFO; - volatile int bitCount = 0; + volatile int twip_status = TW_NO_INFO; + volatile int bitCount = 0; - volatile uint8_t twi_data = 0x00; - volatile int twi_ack = 0; - volatile int twi_ack_rec = 0; - volatile int twi_timeout_ms = 10; + volatile uint8_t twi_data = 0x00; + volatile int twi_ack = 0; + volatile int twi_ack_rec = 0; + volatile int twi_timeout_ms = 10; volatile enum { TWI_READY = 0, - TWI_MRX, - TWI_MTX, - TWI_SRX, - TWI_STX } twi_state + TWI_MRX, + TWI_MTX, + TWI_SRX, + TWI_STX } twi_state = TWI_READY; volatile uint8_t twi_error = 0xFF; - uint8_t twi_txBuffer[TWI_BUFFER_LENGTH]; - volatile int twi_txBufferIndex = 0; - volatile int twi_txBufferLength = 0; + uint8_t twi_txBuffer[TWI_BUFFER_LENGTH]; + volatile int twi_txBufferIndex = 0; + volatile int twi_txBufferLength = 0; - uint8_t twi_rxBuffer[TWI_BUFFER_LENGTH]; - volatile int twi_rxBufferIndex = 0; + uint8_t twi_rxBuffer[TWI_BUFFER_LENGTH]; + volatile int twi_rxBufferIndex = 0; void (*twi_onSlaveTransmit)(void); void (*twi_onSlaveReceive)(uint8_t*, size_t); @@ -128,35 +128,35 @@ class Twi enum { TWI_SIG_RANGE = 0x00000100, - TWI_SIG_RX = 0x00000101, - TWI_SIG_TX = 0x00000102 + TWI_SIG_RX = 0x00000101, + TWI_SIG_TX = 0x00000102 }; - ETSEvent eventTaskQueue[EVENTTASK_QUEUE_SIZE]; - ETSTimer timer; + ETSEvent eventTaskQueue[EVENTTASK_QUEUE_SIZE]; + ETSTimer timer; // Event/IRQ callbacks, so they can't use "this" and need to be static static void IRAM_ATTR onSclChange(void); static void IRAM_ATTR onSdaChange(void); - static void eventTask(ETSEvent* e); + static void eventTask(ETSEvent* e); static void IRAM_ATTR onTimer(void* unused); // Allow not linking in the slave code if there is no call to setAddress - bool _slaveEnabled = false; + bool _slaveEnabled = false; // Internal use functions - void IRAM_ATTR busywait(unsigned int v); - bool write_start(void); - bool write_stop(void); - bool write_bit(bool bit); - bool read_bit(void); - bool write_byte(unsigned char byte); - unsigned char read_byte(bool nack); - void IRAM_ATTR onTwipEvent(uint8_t status); + void IRAM_ATTR busywait(unsigned int v); + bool write_start(void); + bool write_stop(void); + bool write_bit(bool bit); + bool read_bit(void); + bool write_byte(unsigned char byte); + unsigned char read_byte(bool nack); + void IRAM_ATTR onTwipEvent(uint8_t status); // Handle the case where a slave needs to stretch the clock with a time-limited busy wait - inline void WAIT_CLOCK_STRETCH() + inline void WAIT_CLOCK_STRETCH() { - esp8266::polledTimeout::oneShotFastUs timeout(twi_clockStretchLimit); + esp8266::polledTimeout::oneShotFastUs timeout(twi_clockStretchLimit); esp8266::polledTimeout::periodicFastUs yieldTimeout(5000); while (!timeout && !SCL_READ(twi_scl)) // outer loop is stretch duration up to stretch limit { @@ -171,19 +171,19 @@ class Twi void twi_scl_valley(void); public: - void setClock(unsigned int freq); - void setClockStretchLimit(uint32_t limit); - void init(unsigned char sda, unsigned char scl); - void setAddress(uint8_t address); - unsigned char writeTo(unsigned char address, unsigned char* buf, unsigned int len, unsigned char sendStop); - unsigned char readFrom(unsigned char address, unsigned char* buf, unsigned int len, unsigned char sendStop); - uint8_t status(); - uint8_t transmit(const uint8_t* data, uint8_t length); - void attachSlaveRxEvent(void (*function)(uint8_t*, size_t)); - void attachSlaveTxEvent(void (*function)(void)); + void setClock(unsigned int freq); + void setClockStretchLimit(uint32_t limit); + void init(unsigned char sda, unsigned char scl); + void setAddress(uint8_t address); + unsigned char writeTo(unsigned char address, unsigned char* buf, unsigned int len, unsigned char sendStop); + unsigned char readFrom(unsigned char address, unsigned char* buf, unsigned int len, unsigned char sendStop); + uint8_t status(); + uint8_t transmit(const uint8_t* data, uint8_t length); + void attachSlaveRxEvent(void (*function)(uint8_t*, size_t)); + void attachSlaveTxEvent(void (*function)(void)); void IRAM_ATTR reply(uint8_t ack); void IRAM_ATTR releaseBus(void); - void enableSlave(); + void enableSlave(); }; static Twi twi; @@ -549,7 +549,7 @@ void IRAM_ATTR Twi::onTwipEvent(uint8_t status) case TW_SR_ARB_LOST_SLA_ACK: // lost arbitration, returned ack case TW_SR_ARB_LOST_GCALL_ACK: // lost arbitration, returned ack // enter slave receiver mode - twi_state = TWI_SRX; + twi_state = TWI_SRX; // indicate that rx buffer can be overwritten and ack twi_rxBufferIndex = 0; reply(1); @@ -593,9 +593,9 @@ void IRAM_ATTR Twi::onTwipEvent(uint8_t status) case TW_ST_SLA_ACK: // addressed, returned ack case TW_ST_ARB_LOST_SLA_ACK: // arbitration lost, returned ack // enter slave transmitter mode - twi_state = TWI_STX; + twi_state = TWI_STX; // ready the tx buffer index for iteration - twi_txBufferIndex = 0; + twi_txBufferIndex = 0; // set tx buffer length to be zero, to verify if user changes it twi_txBufferLength = 0; // callback to user-defined callback over event task to allow for non-RAM-residing code @@ -650,7 +650,7 @@ void IRAM_ATTR Twi::onTimer(void* unused) (void)unused; twi.releaseBus(); twi.onTwipEvent(TW_BUS_ERROR); - twi.twip_mode = TWIPM_WAIT; + twi.twip_mode = TWIPM_WAIT; twi.twip_state = TWIP_BUS_ERR; } @@ -670,7 +670,7 @@ void Twi::eventTask(ETSEvent* e) if (twi.twi_txBufferLength == 0) { twi.twi_txBufferLength = 1; - twi.twi_txBuffer[0] = 0x00; + twi.twi_txBuffer[0] = 0x00; } // Initiate transmission @@ -701,10 +701,10 @@ void IRAM_ATTR Twi::onSclChange(void) // Store bool return in int to reduce final code size. - sda = SDA_READ(twi.twi_sda); - scl = SCL_READ(twi.twi_scl); + sda = SDA_READ(twi.twi_sda); + scl = SCL_READ(twi.twi_scl); - twi.twip_status = 0xF8; // reset TWI status + twi.twip_status = 0xF8; // reset TWI status int twip_state_mask = S2M(twi.twip_state); IFSTATE(S2M(TWIP_START) | S2M(TWIP_REP_START) | S2M(TWIP_SLA_W) | S2M(TWIP_READ)) @@ -785,7 +785,7 @@ void IRAM_ATTR Twi::onSclChange(void) if (!(twi.twi_data & 0x01)) { twi.onTwipEvent(TW_SR_SLA_ACK); - twi.bitCount = 8; + twi.bitCount = 8; twi.twip_state = TWIP_SLA_W; } else @@ -802,13 +802,13 @@ void IRAM_ATTR Twi::onSclChange(void) if (!twi.twi_ack) { twi.onTwipEvent(TW_SR_DATA_NACK); - twi.twip_mode = TWIPM_WAIT; + twi.twip_mode = TWIPM_WAIT; twi.twip_state = TWIP_WAIT_STOP; } else { twi.onTwipEvent(TW_SR_DATA_ACK); - twi.bitCount = 8; + twi.bitCount = 8; twi.twip_state = TWIP_READ; } } @@ -864,7 +864,7 @@ void IRAM_ATTR Twi::onSclChange(void) else { twi.twi_ack_rec = !sda; - twi.twip_state = TWIP_RWAIT_ACK; + twi.twip_state = TWIP_RWAIT_ACK; } } else IFSTATE(S2M(TWIP_RWAIT_ACK)) @@ -885,7 +885,7 @@ void IRAM_ATTR Twi::onSclChange(void) { // we have no more data to send and/or the master doesn't want anymore twi.onTwipEvent(twi.twi_ack_rec ? TW_ST_LAST_DATA : TW_ST_DATA_NACK); - twi.twip_mode = TWIPM_WAIT; + twi.twip_mode = TWIPM_WAIT; twi.twip_state = TWIP_WAIT_STOP; } } @@ -898,8 +898,8 @@ void IRAM_ATTR Twi::onSdaChange(void) unsigned int scl; // Store bool return in int to reduce final code size. - sda = SDA_READ(twi.twi_sda); - scl = SCL_READ(twi.twi_scl); + sda = SDA_READ(twi.twi_sda); + scl = SCL_READ(twi.twi_scl); int twip_state_mask = S2M(twi.twip_state); if (scl) /* !DATA */ @@ -913,7 +913,7 @@ void IRAM_ATTR Twi::onSdaChange(void) else { // START - twi.bitCount = 8; + twi.bitCount = 8; twi.twip_state = TWIP_START; ets_timer_arm_new(&twi.timer, twi.twi_timeout_ms, false, true); // Once, ms } @@ -923,7 +923,7 @@ void IRAM_ATTR Twi::onSdaChange(void) // START or STOP SDA_HIGH(twi.twi_sda); // Should not be necessary twi.onTwipEvent(TW_BUS_ERROR); - twi.twip_mode = TWIPM_WAIT; + twi.twip_mode = TWIPM_WAIT; twi.twip_state = TWIP_BUS_ERR; } else IFSTATE(S2M(TWIP_WAIT_STOP) | S2M(TWIP_BUS_ERR)) @@ -934,7 +934,7 @@ void IRAM_ATTR Twi::onSdaChange(void) SCL_LOW(twi.twi_scl); // generates a low SCL pulse after STOP ets_timer_disarm(&twi.timer); twi.twip_state = TWIP_IDLE; - twi.twip_mode = TWIPM_IDLE; + twi.twip_mode = TWIPM_IDLE; SCL_HIGH(twi.twi_scl); } else @@ -946,7 +946,7 @@ void IRAM_ATTR Twi::onSdaChange(void) } else { - twi.bitCount = 8; + twi.bitCount = 8; twi.twip_state = TWIP_REP_START; ets_timer_arm_new(&twi.timer, twi.twi_timeout_ms, false, true); // Once, ms } @@ -959,7 +959,7 @@ void IRAM_ATTR Twi::onSdaChange(void) { // inside byte transfer - error twi.onTwipEvent(TW_BUS_ERROR); - twi.twip_mode = TWIPM_WAIT; + twi.twip_mode = TWIPM_WAIT; twi.twip_state = TWIP_BUS_ERR; } else @@ -972,7 +972,7 @@ void IRAM_ATTR Twi::onSdaChange(void) // STOP ets_timer_disarm(&twi.timer); twi.twip_state = TWIP_IDLE; - twi.twip_mode = TWIPM_IDLE; + twi.twip_mode = TWIPM_IDLE; } else { @@ -980,7 +980,7 @@ void IRAM_ATTR Twi::onSdaChange(void) twi.bitCount = 8; ets_timer_arm_new(&twi.timer, twi.twi_timeout_ms, false, true); // Once, ms twi.twip_state = TWIP_REP_START; - twi.twip_mode = TWIPM_IDLE; + twi.twip_mode = TWIPM_IDLE; } } } diff --git a/libraries/ArduinoOTA/examples/BasicOTA/BasicOTA.ino b/libraries/ArduinoOTA/examples/BasicOTA/BasicOTA.ino index 95c1c4efac..1c7effc626 100644 --- a/libraries/ArduinoOTA/examples/BasicOTA/BasicOTA.ino +++ b/libraries/ArduinoOTA/examples/BasicOTA/BasicOTA.ino @@ -8,15 +8,17 @@ #define STAPSK "your-password" #endif -const char* ssid = STASSID; +const char* ssid = STASSID; const char* password = STAPSK; -void setup() { +void setup() +{ Serial.begin(115200); Serial.println("Booting"); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); - while (WiFi.waitForConnectResult() != WL_CONNECTED) { + while (WiFi.waitForConnectResult() != WL_CONNECTED) + { Serial.println("Connection Failed! Rebooting..."); delay(5000); ESP.restart(); @@ -35,43 +37,56 @@ void setup() { // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3 // ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3"); - ArduinoOTA.onStart([]() { - String type; - if (ArduinoOTA.getCommand() == U_FLASH) { - type = "sketch"; - } else { // U_FS - type = "filesystem"; - } + ArduinoOTA.onStart([]() + { + String type; + if (ArduinoOTA.getCommand() == U_FLASH) + { + type = "sketch"; + } + else + { // U_FS + type = "filesystem"; + } - // NOTE: if updating FS this would be the place to unmount FS using FS.end() - Serial.println("Start updating " + type); - }); - ArduinoOTA.onEnd([]() { - Serial.println("\nEnd"); - }); - ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { - Serial.printf("Progress: %u%%\r", (progress / (total / 100))); - }); - ArduinoOTA.onError([](ota_error_t error) { - Serial.printf("Error[%u]: ", error); - if (error == OTA_AUTH_ERROR) { - Serial.println("Auth Failed"); - } else if (error == OTA_BEGIN_ERROR) { - Serial.println("Begin Failed"); - } else if (error == OTA_CONNECT_ERROR) { - Serial.println("Connect Failed"); - } else if (error == OTA_RECEIVE_ERROR) { - Serial.println("Receive Failed"); - } else if (error == OTA_END_ERROR) { - Serial.println("End Failed"); - } - }); + // NOTE: if updating FS this would be the place to unmount FS using FS.end() + Serial.println("Start updating " + type); + }); + ArduinoOTA.onEnd([]() + { Serial.println("\nEnd"); }); + ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) + { Serial.printf("Progress: %u%%\r", (progress / (total / 100))); }); + ArduinoOTA.onError([](ota_error_t error) + { + Serial.printf("Error[%u]: ", error); + if (error == OTA_AUTH_ERROR) + { + Serial.println("Auth Failed"); + } + else if (error == OTA_BEGIN_ERROR) + { + Serial.println("Begin Failed"); + } + else if (error == OTA_CONNECT_ERROR) + { + Serial.println("Connect Failed"); + } + else if (error == OTA_RECEIVE_ERROR) + { + Serial.println("Receive Failed"); + } + else if (error == OTA_END_ERROR) + { + Serial.println("End Failed"); + } + }); ArduinoOTA.begin(); Serial.println("Ready"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); } -void loop() { +void loop() +{ ArduinoOTA.handle(); } diff --git a/libraries/ArduinoOTA/examples/OTALeds/OTALeds.ino b/libraries/ArduinoOTA/examples/OTALeds/OTALeds.ino index 7c72b122e4..347a7a8925 100644 --- a/libraries/ArduinoOTA/examples/OTALeds/OTALeds.ino +++ b/libraries/ArduinoOTA/examples/OTALeds/OTALeds.ino @@ -8,15 +8,16 @@ #define STAPSK "your-password" #endif -const char* ssid = STASSID; +const char* ssid = STASSID; const char* password = STAPSK; -const char* host = "OTA-LEDS"; +const char* host = "OTA-LEDS"; -int led_pin = 13; +int led_pin = 13; #define N_DIMMERS 3 -int dimmer_pin[] = { 14, 5, 15 }; +int dimmer_pin[] = { 14, 5, 15 }; -void setup() { +void setup() +{ Serial.begin(115200); /* switch on led */ @@ -28,7 +29,8 @@ void setup() { WiFi.begin(ssid, password); - while (WiFi.waitForConnectResult() != WL_CONNECTED) { + while (WiFi.waitForConnectResult() != WL_CONNECTED) + { WiFi.begin(ssid, password); Serial.println("Retrying connection..."); } @@ -39,36 +41,41 @@ void setup() { analogWriteRange(1000); analogWrite(led_pin, 990); - for (int i = 0; i < N_DIMMERS; i++) { + for (int i = 0; i < N_DIMMERS; i++) + { pinMode(dimmer_pin[i], OUTPUT); analogWrite(dimmer_pin[i], 50); } ArduinoOTA.setHostname(host); - ArduinoOTA.onStart([]() { // switch off all the PWMs during upgrade - for (int i = 0; i < N_DIMMERS; i++) { + ArduinoOTA.onStart([]() { // switch off all the PWMs during upgrade + for (int i = 0; i < N_DIMMERS; i++) + { analogWrite(dimmer_pin[i], 0); } analogWrite(led_pin, 0); }); - ArduinoOTA.onEnd([]() { // do a fancy thing with our board led at end - for (int i = 0; i < 30; i++) { + ArduinoOTA.onEnd([]() { // do a fancy thing with our board led at end + for (int i = 0; i < 30; i++) + { analogWrite(led_pin, (i * 100) % 1001); delay(50); } }); - ArduinoOTA.onError([](ota_error_t error) { - (void)error; - ESP.restart(); - }); + ArduinoOTA.onError([](ota_error_t error) + { + (void)error; + ESP.restart(); + }); /* setup the OTA server */ ArduinoOTA.begin(); Serial.println("Ready"); } -void loop() { +void loop() +{ ArduinoOTA.handle(); } diff --git a/libraries/DNSServer/examples/CaptivePortalAdvanced/CaptivePortalAdvanced.ino b/libraries/DNSServer/examples/CaptivePortalAdvanced/CaptivePortalAdvanced.ino index 27bfab06ce..44328a8fb1 100644 --- a/libraries/DNSServer/examples/CaptivePortalAdvanced/CaptivePortalAdvanced.ino +++ b/libraries/DNSServer/examples/CaptivePortalAdvanced/CaptivePortalAdvanced.ino @@ -23,37 +23,38 @@ #define APPSK "12345678" #endif -const char* softAP_ssid = APSSID; -const char* softAP_password = APPSK; +const char* softAP_ssid = APSSID; +const char* softAP_password = APPSK; /* hostname for mDNS. Should work at least on windows. Try http://esp8266.local */ -const char* myHostname = "esp8266"; +const char* myHostname = "esp8266"; /* Don't set this wifi credentials. They are configurated at runtime and stored on EEPROM */ -char ssid[33] = ""; -char password[65] = ""; +char ssid[33] = ""; +char password[65] = ""; // DNS server -const byte DNS_PORT = 53; -DNSServer dnsServer; +const byte DNS_PORT = 53; +DNSServer dnsServer; // Web server ESP8266WebServer server(80); /* Soft AP network parameters */ -IPAddress apIP(172, 217, 28, 1); -IPAddress netMsk(255, 255, 255, 0); +IPAddress apIP(172, 217, 28, 1); +IPAddress netMsk(255, 255, 255, 0); /** Should I connect to WLAN asap? */ -boolean connect; +boolean connect; /** Last time I tried to connect to WLAN */ -unsigned long lastConnectTry = 0; +unsigned long lastConnectTry = 0; /** Current WLAN status */ -unsigned int status = WL_IDLE_STATUS; +unsigned int status = WL_IDLE_STATUS; -void setup() { +void setup() +{ delay(1000); Serial.begin(115200); Serial.println(); @@ -61,7 +62,7 @@ void setup() { /* You can remove the password parameter if you want the AP to be open. */ WiFi.softAPConfig(apIP, apIP, netMsk); WiFi.softAP(softAP_ssid, softAP_password); - delay(500); // Without delay I've seen the IP address blank + delay(500); // Without delay I've seen the IP address blank Serial.print("AP IP address: "); Serial.println(WiFi.softAPIP()); @@ -73,16 +74,17 @@ void setup() { server.on("/", handleRoot); server.on("/wifi", handleWifi); server.on("/wifisave", handleWifiSave); - server.on("/generate_204", handleRoot); //Android captive portal. Maybe not needed. Might be handled by notFound handler. - server.on("/fwlink", handleRoot); //Microsoft captive portal. Maybe not needed. Might be handled by notFound handler. + server.on("/generate_204", handleRoot); //Android captive portal. Maybe not needed. Might be handled by notFound handler. + server.on("/fwlink", handleRoot); //Microsoft captive portal. Maybe not needed. Might be handled by notFound handler. server.onNotFound(handleNotFound); - server.begin(); // Web server start + server.begin(); // Web server start Serial.println("HTTP server started"); - loadCredentials(); // Load WLAN credentials from network - connect = strlen(ssid) > 0; // Request WLAN connect if there is a SSID + loadCredentials(); // Load WLAN credentials from network + connect = strlen(ssid) > 0; // Request WLAN connect if there is a SSID } -void connectWifi() { +void connectWifi() +{ Serial.println("Connecting as wifi client..."); WiFi.disconnect(); WiFi.begin(ssid, password); @@ -91,8 +93,10 @@ void connectWifi() { Serial.println(connRes); } -void loop() { - if (connect) { +void loop() +{ + if (connect) + { Serial.println("Connect requested"); connect = false; connectWifi(); @@ -100,16 +104,19 @@ void loop() { } { unsigned int s = WiFi.status(); - if (s == 0 && millis() > (lastConnectTry + 60000)) { + if (s == 0 && millis() > (lastConnectTry + 60000)) + { /* If WLAN disconnected and idle try to connect */ /* Don't set retry time too low as retry interfere the softAP operation */ connect = true; } - if (status != s) { // WLAN status change + if (status != s) + { // WLAN status change Serial.print("Status: "); Serial.println(s); status = s; - if (s == WL_CONNECTED) { + if (s == WL_CONNECTED) + { /* Just connected to WLAN */ Serial.println(""); Serial.print("Connected to "); @@ -118,18 +125,24 @@ void loop() { Serial.println(WiFi.localIP()); // Setup MDNS responder - if (!MDNS.begin(myHostname)) { + if (!MDNS.begin(myHostname)) + { Serial.println("Error setting up MDNS responder!"); - } else { + } + else + { Serial.println("mDNS responder started"); // Add service to MDNS-SD MDNS.addService("http", "tcp", 80); } - } else if (s == WL_NO_SSID_AVAIL) { + } + else if (s == WL_NO_SSID_AVAIL) + { WiFi.disconnect(); } } - if (s == WL_CONNECTED) { + if (s == WL_CONNECTED) + { MDNS.update(); } } diff --git a/libraries/DNSServer/examples/CaptivePortalAdvanced/handleHttp.ino b/libraries/DNSServer/examples/CaptivePortalAdvanced/handleHttp.ino index 276aad2a2d..a333748e60 100644 --- a/libraries/DNSServer/examples/CaptivePortalAdvanced/handleHttp.ino +++ b/libraries/DNSServer/examples/CaptivePortalAdvanced/handleHttp.ino @@ -1,6 +1,8 @@ /** Handle root or redirect to captive portal */ -void handleRoot() { - if (captivePortal()) { // If caprive portal redirect instead of displaying the page. +void handleRoot() +{ + if (captivePortal()) + { // If caprive portal redirect instead of displaying the page. return; } server.sendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); @@ -13,9 +15,12 @@ void handleRoot() { "" "CaptivePortal" "

      HELLO WORLD!!

      "); - if (server.client().localIP() == apIP) { + if (server.client().localIP() == apIP) + { Page += String(F("

      You are connected through the soft AP: ")) + softAP_ssid + F("

      "); - } else { + } + else + { Page += String(F("

      You are connected through the wifi network: ")) + ssid + F("

      "); } Page += F( @@ -26,19 +31,22 @@ void handleRoot() { } /** Redirect to captive portal if we got a request for another domain. Return true in that case so the page handler do not try to handle the request again. */ -boolean captivePortal() { - if (!isIp(server.hostHeader()) && server.hostHeader() != (String(myHostname) + ".local")) { +boolean captivePortal() +{ + if (!isIp(server.hostHeader()) && server.hostHeader() != (String(myHostname) + ".local")) + { Serial.println("Request redirected to captive portal"); server.sendHeader("Location", String("http://") + toStringIp(server.client().localIP()), true); - server.send(302, "text/plain", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. - server.client().stop(); // Stop is needed because we sent no content length + server.send(302, "text/plain", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. + server.client().stop(); // Stop is needed because we sent no content length return true; } return false; } /** Wifi config page handler */ -void handleWifi() { +void handleWifi() +{ server.sendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); server.sendHeader("Pragma", "no-cache"); server.sendHeader("Expires", "-1"); @@ -49,9 +57,12 @@ void handleWifi() { "" "CaptivePortal" "

      Wifi config

      "); - if (server.client().localIP() == apIP) { + if (server.client().localIP() == apIP) + { Page += String(F("

      You are connected through the soft AP: ")) + softAP_ssid + F("

      "); - } else { + } + else + { Page += String(F("

      You are connected through the wifi network: ")) + ssid + F("

      "); } Page += String(F( @@ -74,11 +85,15 @@ void handleWifi() { Serial.println("scan start"); int n = WiFi.scanNetworks(); Serial.println("scan done"); - if (n > 0) { - for (int i = 0; i < n; i++) { + if (n > 0) + { + for (int i = 0; i < n; i++) + { Page += String(F("\r\nSSID ")) + WiFi.SSID(i) + ((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? F(" ") : F(" *")) + F(" (") + WiFi.RSSI(i) + F(")"); } - } else { + } + else + { Page += F("No WLAN found"); } Page += F( @@ -90,11 +105,12 @@ void handleWifi() { "

      You may want to return to the home page.

      " ""); server.send(200, "text/html", Page); - server.client().stop(); // Stop is needed because we sent no content length + server.client().stop(); // Stop is needed because we sent no content length } /** Handle the WLAN save form and redirect to WLAN config page again */ -void handleWifiSave() { +void handleWifiSave() +{ Serial.println("wifi save"); server.arg("n").toCharArray(ssid, sizeof(ssid) - 1); server.arg("p").toCharArray(password, sizeof(password) - 1); @@ -102,14 +118,16 @@ void handleWifiSave() { server.sendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); server.sendHeader("Pragma", "no-cache"); server.sendHeader("Expires", "-1"); - server.send(302, "text/plain", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. - server.client().stop(); // Stop is needed because we sent no content length + server.send(302, "text/plain", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. + server.client().stop(); // Stop is needed because we sent no content length saveCredentials(); - connect = strlen(ssid) > 0; // Request WLAN connect with new credentials if there is a SSID + connect = strlen(ssid) > 0; // Request WLAN connect with new credentials if there is a SSID } -void handleNotFound() { - if (captivePortal()) { // If caprive portal redirect instead of displaying the error page. +void handleNotFound() +{ + if (captivePortal()) + { // If caprive portal redirect instead of displaying the error page. return; } String message = F("File Not Found\n\n"); @@ -121,7 +139,8 @@ void handleNotFound() { message += server.args(); message += F("\n"); - for (uint8_t i = 0; i < server.args(); i++) { + for (uint8_t i = 0; i < server.args(); i++) + { message += String(F(" ")) + server.argName(i) + F(": ") + server.arg(i) + F("\n"); } server.sendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); diff --git a/libraries/DNSServer/examples/CaptivePortalAdvanced/tools.ino b/libraries/DNSServer/examples/CaptivePortalAdvanced/tools.ino index 6ed7b05b7d..e8fb014d35 100644 --- a/libraries/DNSServer/examples/CaptivePortalAdvanced/tools.ino +++ b/libraries/DNSServer/examples/CaptivePortalAdvanced/tools.ino @@ -1,8 +1,11 @@ /** Is this an IP? */ -boolean isIp(String str) { - for (size_t i = 0; i < str.length(); i++) { +boolean isIp(String str) +{ + for (size_t i = 0; i < str.length(); i++) + { int c = str.charAt(i); - if (c != '.' && (c < '0' || c > '9')) { + if (c != '.' && (c < '0' || c > '9')) + { return false; } } @@ -10,9 +13,11 @@ boolean isIp(String str) { } /** IP to String? */ -String toStringIp(IPAddress ip) { +String toStringIp(IPAddress ip) +{ String res = ""; - for (int i = 0; i < 3; i++) { + for (int i = 0; i < 3; i++) + { res += String((ip >> (8 * i)) & 0xFF) + "."; } res += String(((ip >> 8 * 3)) & 0xFF); diff --git a/libraries/ESP8266AVRISP/examples/Arduino_Wifi_AVRISP/Arduino_Wifi_AVRISP.ino b/libraries/ESP8266AVRISP/examples/Arduino_Wifi_AVRISP/Arduino_Wifi_AVRISP.ino index 01b7388bb2..b3db7894c6 100644 --- a/libraries/ESP8266AVRISP/examples/Arduino_Wifi_AVRISP/Arduino_Wifi_AVRISP.ino +++ b/libraries/ESP8266AVRISP/examples/Arduino_Wifi_AVRISP/Arduino_Wifi_AVRISP.ino @@ -8,23 +8,25 @@ #define STAPSK "your-password" #endif -const char* host = "esp8266-avrisp"; -const char* ssid = STASSID; -const char* pass = STAPSK; -const uint16_t port = 328; -const uint8_t reset_pin = 5; +const char* host = "esp8266-avrisp"; +const char* ssid = STASSID; +const char* pass = STAPSK; +const uint16_t port = 328; +const uint8_t reset_pin = 5; -ESP8266AVRISP avrprog(port, reset_pin); +ESP8266AVRISP avrprog(port, reset_pin); -void setup() { +void setup() +{ Serial.begin(115200); Serial.println(""); Serial.println("Arduino AVR-ISP over TCP"); - avrprog.setReset(false); // let the AVR run + avrprog.setReset(false); // let the AVR run WiFi.mode(WIFI_STA); WiFi.begin(ssid, pass); - while (WiFi.waitForConnectResult() != WL_CONNECTED) { + while (WiFi.waitForConnectResult() != WL_CONNECTED) + { WiFi.begin(ssid, pass); Serial.println("WiFi failed, retrying."); } @@ -46,22 +48,28 @@ void setup() { avrprog.begin(); } -void loop() { +void loop() +{ static AVRISPState_t last_state = AVRISP_STATE_IDLE; - AVRISPState_t new_state = avrprog.update(); - if (last_state != new_state) { - switch (new_state) { - case AVRISP_STATE_IDLE: { + AVRISPState_t new_state = avrprog.update(); + if (last_state != new_state) + { + switch (new_state) + { + case AVRISP_STATE_IDLE: + { Serial.printf("[AVRISP] now idle\r\n"); // Use the SPI bus for other purposes break; } - case AVRISP_STATE_PENDING: { + case AVRISP_STATE_PENDING: + { Serial.printf("[AVRISP] connection pending\r\n"); // Clean up your other purposes and prepare for programming mode break; } - case AVRISP_STATE_ACTIVE: { + case AVRISP_STATE_ACTIVE: + { Serial.printf("[AVRISP] programming mode\r\n"); // Stand by for completion break; @@ -70,11 +78,13 @@ void loop() { last_state = new_state; } // Serve the client - if (last_state != AVRISP_STATE_IDLE) { + if (last_state != AVRISP_STATE_IDLE) + { avrprog.serve(); } - if (WiFi.status() == WL_CONNECTED) { + if (WiFi.status() == WL_CONNECTED) + { MDNS.update(); } } diff --git a/libraries/ESP8266HTTPClient/examples/Authorization/Authorization.ino b/libraries/ESP8266HTTPClient/examples/Authorization/Authorization.ino index 878cab95b5..add86f1f10 100644 --- a/libraries/ESP8266HTTPClient/examples/Authorization/Authorization.ino +++ b/libraries/ESP8266HTTPClient/examples/Authorization/Authorization.ino @@ -16,8 +16,8 @@ ESP8266WiFiMulti WiFiMulti; -void setup() { - +void setup() +{ Serial.begin(115200); // Serial.setDebugOutput(true); @@ -25,7 +25,8 @@ void setup() { Serial.println(); Serial.println(); - for (uint8_t t = 4; t > 0; t--) { + for (uint8_t t = 4; t > 0; t--) + { Serial.printf("[SETUP] WAIT %d...\n", t); Serial.flush(); delay(1000); @@ -35,10 +36,11 @@ void setup() { WiFiMulti.addAP("SSID", "PASSWORD"); } -void loop() { +void loop() +{ // wait for WiFi connection - if ((WiFiMulti.run() == WL_CONNECTED)) { - + if ((WiFiMulti.run() == WL_CONNECTED)) + { WiFiClient client; HTTPClient http; @@ -63,16 +65,20 @@ void loop() { int httpCode = http.GET(); // httpCode will be negative on error - if (httpCode > 0) { + if (httpCode > 0) + { // HTTP header has been send and Server response header has been handled Serial.printf("[HTTP] GET... code: %d\n", httpCode); // file found at server - if (httpCode == HTTP_CODE_OK) { + if (httpCode == HTTP_CODE_OK) + { String payload = http.getString(); Serial.println(payload); } - } else { + } + else + { Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str()); } diff --git a/libraries/ESP8266HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino b/libraries/ESP8266HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino index 18f225b797..0ae48db06c 100644 --- a/libraries/ESP8266HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino +++ b/libraries/ESP8266HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino @@ -16,8 +16,8 @@ ESP8266WiFiMulti WiFiMulti; -void setup() { - +void setup() +{ Serial.begin(115200); // Serial.setDebugOutput(true); @@ -25,7 +25,8 @@ void setup() { Serial.println(); Serial.println(); - for (uint8_t t = 4; t > 0; t--) { + for (uint8_t t = 4; t > 0; t--) + { Serial.printf("[SETUP] WAIT %d...\n", t); Serial.flush(); delay(1000); @@ -35,37 +36,45 @@ void setup() { WiFiMulti.addAP("SSID", "PASSWORD"); } -void loop() { +void loop() +{ // wait for WiFi connection - if ((WiFiMulti.run() == WL_CONNECTED)) { - + if ((WiFiMulti.run() == WL_CONNECTED)) + { WiFiClient client; HTTPClient http; Serial.print("[HTTP] begin...\n"); - if (http.begin(client, "http://jigsaw.w3.org/HTTP/connection.html")) { // HTTP + if (http.begin(client, "http://jigsaw.w3.org/HTTP/connection.html")) + { // HTTP Serial.print("[HTTP] GET...\n"); // start connection and send HTTP header int httpCode = http.GET(); // httpCode will be negative on error - if (httpCode > 0) { + if (httpCode > 0) + { // HTTP header has been send and Server response header has been handled Serial.printf("[HTTP] GET... code: %d\n", httpCode); // file found at server - if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { + if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) + { String payload = http.getString(); Serial.println(payload); } - } else { + } + else + { Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str()); } http.end(); - } else { + } + else + { Serial.printf("[HTTP} Unable to connect\n"); } } diff --git a/libraries/ESP8266HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino b/libraries/ESP8266HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino index efb653fc76..b91f8f116f 100644 --- a/libraries/ESP8266HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino +++ b/libraries/ESP8266HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino @@ -14,12 +14,12 @@ #include // Fingerprint for demo URL, expires on June 2, 2021, needs to be updated well before this date -const uint8_t fingerprint[20] = { 0x40, 0xaf, 0x00, 0x6b, 0xec, 0x90, 0x22, 0x41, 0x8e, 0xa3, 0xad, 0xfa, 0x1a, 0xe8, 0x25, 0x41, 0x1d, 0x1a, 0x54, 0xb3 }; +const uint8_t fingerprint[20] = { 0x40, 0xaf, 0x00, 0x6b, 0xec, 0x90, 0x22, 0x41, 0x8e, 0xa3, 0xad, 0xfa, 0x1a, 0xe8, 0x25, 0x41, 0x1d, 0x1a, 0x54, 0xb3 }; ESP8266WiFiMulti WiFiMulti; -void setup() { - +void setup() +{ Serial.begin(115200); // Serial.setDebugOutput(true); @@ -27,7 +27,8 @@ void setup() { Serial.println(); Serial.println(); - for (uint8_t t = 4; t > 0; t--) { + for (uint8_t t = 4; t > 0; t--) + { Serial.printf("[SETUP] WAIT %d...\n", t); Serial.flush(); delay(1000); @@ -37,10 +38,11 @@ void setup() { WiFiMulti.addAP("SSID", "PASSWORD"); } -void loop() { +void loop() +{ // wait for WiFi connection - if ((WiFiMulti.run() == WL_CONNECTED)) { - + if ((WiFiMulti.run() == WL_CONNECTED)) + { std::unique_ptr client(new BearSSL::WiFiClientSecure); client->setFingerprint(fingerprint); @@ -50,28 +52,35 @@ void loop() { HTTPClient https; Serial.print("[HTTPS] begin...\n"); - if (https.begin(*client, "https://jigsaw.w3.org/HTTP/connection.html")) { // HTTPS + if (https.begin(*client, "https://jigsaw.w3.org/HTTP/connection.html")) + { // HTTPS Serial.print("[HTTPS] GET...\n"); // start connection and send HTTP header int httpCode = https.GET(); // httpCode will be negative on error - if (httpCode > 0) { + if (httpCode > 0) + { // HTTP header has been send and Server response header has been handled Serial.printf("[HTTPS] GET... code: %d\n", httpCode); // file found at server - if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { + if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) + { String payload = https.getString(); Serial.println(payload); } - } else { + } + else + { Serial.printf("[HTTPS] GET... failed, error: %s\n", https.errorToString(httpCode).c_str()); } https.end(); - } else { + } + else + { Serial.printf("[HTTPS] Unable to connect\n"); } } diff --git a/libraries/ESP8266HTTPClient/examples/DigestAuthorization/DigestAuthorization.ino b/libraries/ESP8266HTTPClient/examples/DigestAuthorization/DigestAuthorization.ino index a538fd4799..e7b838f01f 100644 --- a/libraries/ESP8266HTTPClient/examples/DigestAuthorization/DigestAuthorization.ino +++ b/libraries/ESP8266HTTPClient/examples/DigestAuthorization/DigestAuthorization.ino @@ -16,49 +16,54 @@ #define STAPSK "your-password" #endif -const char* ssid = STASSID; +const char* ssid = STASSID; const char* ssidPassword = STAPSK; -const char* username = "admin"; -const char* password = "admin"; +const char* username = "admin"; +const char* password = "admin"; -const char* server = "http://httpbin.org"; -const char* uri = "/digest-auth/auth/admin/admin/MD5"; +const char* server = "http://httpbin.org"; +const char* uri = "/digest-auth/auth/admin/admin/MD5"; -String exractParam(String& authReq, const String& param, const char delimit) { +String exractParam(String& authReq, const String& param, const char delimit) +{ int _begin = authReq.indexOf(param); - if (_begin == -1) { + if (_begin == -1) + { return ""; } return authReq.substring(_begin + param.length(), authReq.indexOf(delimit, _begin + param.length())); } -String getCNonce(const int len) { +String getCNonce(const int len) +{ static const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; String s = ""; - for (int i = 0; i < len; ++i) { + for (int i = 0; i < len; ++i) + { s += alphanum[rand() % (sizeof(alphanum) - 1)]; } return s; } -String getDigestAuth(String& authReq, const String& username, const String& password, const String& method, const String& uri, unsigned int counter) { +String getDigestAuth(String& authReq, const String& username, const String& password, const String& method, const String& uri, unsigned int counter) +{ // extracting required parameters for RFC 2069 simpler Digest - String realm = exractParam(authReq, "realm=\"", '"'); - String nonce = exractParam(authReq, "nonce=\"", '"'); + String realm = exractParam(authReq, "realm=\"", '"'); + String nonce = exractParam(authReq, "nonce=\"", '"'); String cNonce = getCNonce(8); - char nc[9]; + char nc[9]; snprintf(nc, sizeof(nc), "%08x", counter); // parameters for the RFC 2617 newer Digest MD5Builder md5; md5.begin(); - md5.add(username + ":" + realm + ":" + password); // md5 of the user:realm:user + md5.add(username + ":" + realm + ":" + password); // md5 of the user:realm:user md5.calculate(); String h1 = md5.toString(); @@ -70,7 +75,7 @@ String getDigestAuth(String& authReq, const String& username, const String& pass md5.begin(); md5.add(h1 + ":" + nonce + ":" + String(nc) + ":" + cNonce + ":" + "auth" + ":" + h2); md5.calculate(); - String response = md5.toString(); + String response = md5.toString(); String authorization = "Digest username=\"" + username + "\", realm=\"" + realm + "\", nonce=\"" + nonce + "\", uri=\"" + uri + "\", algorithm=\"MD5\", qop=auth, nc=" + String(nc) + ", cnonce=\"" + cNonce + "\", response=\"" + response + "\""; Serial.println(authorization); @@ -78,14 +83,16 @@ String getDigestAuth(String& authReq, const String& username, const String& pass return authorization; } -void setup() { +void setup() +{ randomSeed(RANDOM_REG32); Serial.begin(115200); WiFi.mode(WIFI_STA); WiFi.begin(ssid, ssidPassword); - while (WiFi.status() != WL_CONNECTED) { + while (WiFi.status() != WL_CONNECTED) + { delay(500); Serial.print("."); } @@ -96,9 +103,10 @@ void setup() { Serial.println(WiFi.localIP()); } -void loop() { +void loop() +{ WiFiClient client; - HTTPClient http; //must be declared after WiFiClient for correct destruction order, because used by http.begin(client,...) + HTTPClient http; //must be declared after WiFiClient for correct destruction order, because used by http.begin(client,...) Serial.print("[HTTP] begin...\n"); @@ -112,7 +120,8 @@ void loop() { // start connection and send HTTP header int httpCode = http.GET(); - if (httpCode > 0) { + if (httpCode > 0) + { String authReq = http.header("WWW-Authenticate"); Serial.println(authReq); @@ -124,13 +133,18 @@ void loop() { http.addHeader("Authorization", authorization); int httpCode = http.GET(); - if (httpCode > 0) { + if (httpCode > 0) + { String payload = http.getString(); Serial.println(payload); - } else { + } + else + { Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str()); } - } else { + } + else + { Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str()); } diff --git a/libraries/ESP8266HTTPClient/examples/PostHttpClient/PostHttpClient.ino b/libraries/ESP8266HTTPClient/examples/PostHttpClient/PostHttpClient.ino index 01f7c34eff..5ac3868708 100644 --- a/libraries/ESP8266HTTPClient/examples/PostHttpClient/PostHttpClient.ino +++ b/libraries/ESP8266HTTPClient/examples/PostHttpClient/PostHttpClient.ino @@ -23,8 +23,8 @@ #define STAPSK "your-password" #endif -void setup() { - +void setup() +{ Serial.begin(115200); Serial.println(); @@ -33,7 +33,8 @@ void setup() { WiFi.begin(STASSID, STAPSK); - while (WiFi.status() != WL_CONNECTED) { + while (WiFi.status() != WL_CONNECTED) + { delay(500); Serial.print("."); } @@ -42,16 +43,17 @@ void setup() { Serial.println(WiFi.localIP()); } -void loop() { +void loop() +{ // wait for WiFi connection - if ((WiFi.status() == WL_CONNECTED)) { - + if ((WiFi.status() == WL_CONNECTED)) + { WiFiClient client; HTTPClient http; Serial.print("[HTTP] begin...\n"); // configure traged server and url - http.begin(client, "http://" SERVER_IP "/postplain/"); //HTTP + http.begin(client, "http://" SERVER_IP "/postplain/"); //HTTP http.addHeader("Content-Type", "application/json"); Serial.print("[HTTP] POST...\n"); @@ -59,18 +61,22 @@ void loop() { int httpCode = http.POST("{\"hello\":\"world\"}"); // httpCode will be negative on error - if (httpCode > 0) { + if (httpCode > 0) + { // HTTP header has been send and Server response header has been handled Serial.printf("[HTTP] POST... code: %d\n", httpCode); // file found at server - if (httpCode == HTTP_CODE_OK) { + if (httpCode == HTTP_CODE_OK) + { const String& payload = http.getString(); Serial.println("received payload:\n<<"); Serial.println(payload); Serial.println(">>"); } - } else { + } + else + { Serial.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpCode).c_str()); } diff --git a/libraries/ESP8266HTTPClient/examples/ReuseConnectionV2/ReuseConnectionV2.ino b/libraries/ESP8266HTTPClient/examples/ReuseConnectionV2/ReuseConnectionV2.ino index 4cfc3911bf..9f5c29db5b 100644 --- a/libraries/ESP8266HTTPClient/examples/ReuseConnectionV2/ReuseConnectionV2.ino +++ b/libraries/ESP8266HTTPClient/examples/ReuseConnectionV2/ReuseConnectionV2.ino @@ -17,11 +17,11 @@ ESP8266WiFiMulti WiFiMulti; -HTTPClient http; -WiFiClient client; - -void setup() { +HTTPClient http; +WiFiClient client; +void setup() +{ Serial.begin(115200); // Serial.setDebugOutput(true); @@ -33,7 +33,8 @@ void setup() { WiFiMulti.addAP(STASSID, STAPSK); // wait for WiFi connection - while ((WiFiMulti.run() != WL_CONNECTED)) { + while ((WiFiMulti.run() != WL_CONNECTED)) + { Serial.write('.'); delay(500); } @@ -46,22 +47,28 @@ void setup() { //http.begin(client, "jigsaw.w3.org", 80, "/HTTP/connection.html"); } -int pass = 0; +int pass = 0; -void loop() { +void loop() +{ // First 10 loop()s, retrieve the URL - if (pass < 10) { + if (pass < 10) + { pass++; Serial.printf("Reuse connection example, GET url for the %d time\n", pass); int httpCode = http.GET(); - if (httpCode > 0) { + if (httpCode > 0) + { Serial.printf("[HTTP] GET... code: %d\n", httpCode); // file found at server - if (httpCode == HTTP_CODE_OK) { + if (httpCode == HTTP_CODE_OK) + { http.writeToStream(&Serial); } - } else { + } + else + { Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str()); // Something went wrong with the connection, try to reconnect http.end(); @@ -69,10 +76,13 @@ void loop() { //http.begin(client, "jigsaw.w3.org", 80, "/HTTP/connection.html"); } - if (pass == 10) { + if (pass == 10) + { http.end(); Serial.println("Done testing"); - } else { + } + else + { Serial.println("\n\n\nWait 5 second...\n"); delay(5000); } diff --git a/libraries/ESP8266HTTPClient/examples/StreamHttpClient/StreamHttpClient.ino b/libraries/ESP8266HTTPClient/examples/StreamHttpClient/StreamHttpClient.ino index 7a813c7e10..a165646677 100644 --- a/libraries/ESP8266HTTPClient/examples/StreamHttpClient/StreamHttpClient.ino +++ b/libraries/ESP8266HTTPClient/examples/StreamHttpClient/StreamHttpClient.ino @@ -14,8 +14,8 @@ ESP8266WiFiMulti WiFiMulti; -void setup() { - +void setup() +{ Serial.begin(115200); // Serial.setDebugOutput(true); @@ -23,7 +23,8 @@ void setup() { Serial.println(); Serial.println(); - for (uint8_t t = 4; t > 0; t--) { + for (uint8_t t = 4; t > 0; t--) + { Serial.printf("[SETUP] WAIT %d...\n", t); Serial.flush(); delay(1000); @@ -33,12 +34,13 @@ void setup() { WiFiMulti.addAP("SSID", "PASSWORD"); } -void loop() { +void loop() +{ // wait for WiFi connection - if ((WiFiMulti.run() == WL_CONNECTED)) { - + if ((WiFiMulti.run() == WL_CONNECTED)) + { WiFiClient client; - HTTPClient http; //must be declared after WiFiClient for correct destruction order, because used by http.begin(client,...) + HTTPClient http; //must be declared after WiFiClient for correct destruction order, because used by http.begin(client,...) Serial.print("[HTTP] begin...\n"); @@ -49,15 +51,16 @@ void loop() { Serial.print("[HTTP] GET...\n"); // start connection and send HTTP header int httpCode = http.GET(); - if (httpCode > 0) { + if (httpCode > 0) + { // HTTP header has been send and Server response header has been handled Serial.printf("[HTTP] GET... code: %d\n", httpCode); // file found at server - if (httpCode == HTTP_CODE_OK) { - + if (httpCode == HTTP_CODE_OK) + { // get length of document (is -1 when Server sends no Content-Length header) - int len = http.getSize(); + int len = http.getSize(); // create buffer for read uint8_t buff[128] = { 0 }; @@ -72,18 +75,21 @@ void loop() { WiFiClient* stream = &client; // read all data from server - while (http.connected() && (len > 0 || len == -1)) { + while (http.connected() && (len > 0 || len == -1)) + { // read up to 128 byte int c = stream->readBytes(buff, std::min((size_t)len, sizeof(buff))); Serial.printf("readBytes: %d\n", c); - if (!c) { + if (!c) + { Serial.println("read timeout"); } // write it to Serial Serial.write(buff, c); - if (len > 0) { + if (len > 0) + { len -= c; } } @@ -92,7 +98,9 @@ void loop() { Serial.println(); Serial.print("[HTTP] connection closed or file end.\n"); } - } else { + } + else + { Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str()); } diff --git a/libraries/ESP8266HTTPClient/examples/StreamHttpsClient/StreamHttpsClient.ino b/libraries/ESP8266HTTPClient/examples/StreamHttpsClient/StreamHttpsClient.ino index 9ba575bd78..011ef3a569 100644 --- a/libraries/ESP8266HTTPClient/examples/StreamHttpsClient/StreamHttpsClient.ino +++ b/libraries/ESP8266HTTPClient/examples/StreamHttpsClient/StreamHttpsClient.ino @@ -14,8 +14,8 @@ ESP8266WiFiMulti WiFiMulti; -void setup() { - +void setup() +{ Serial.begin(115200); // Serial.setDebugOutput(true); @@ -23,7 +23,8 @@ void setup() { Serial.println(); Serial.println(); - for (uint8_t t = 4; t > 0; t--) { + for (uint8_t t = 4; t > 0; t--) + { Serial.printf("[SETUP] WAIT %d...\n", t); Serial.flush(); delay(1000); @@ -33,16 +34,18 @@ void setup() { WiFiMulti.addAP("SSID", "PASSWORD"); } -void loop() { +void loop() +{ // wait for WiFi connection - if ((WiFiMulti.run() == WL_CONNECTED)) { - + if ((WiFiMulti.run() == WL_CONNECTED)) + { std::unique_ptr client(new BearSSL::WiFiClientSecure); - bool mfln = client->probeMaxFragmentLength("tls.mbed.org", 443, 1024); + bool mfln = client->probeMaxFragmentLength("tls.mbed.org", 443, 1024); Serial.printf("\nConnecting to https://tls.mbed.org\n"); Serial.printf("Maximum fragment Length negotiation supported: %s\n", mfln ? "yes" : "no"); - if (mfln) { + if (mfln) + { client->setBufferSizes(1024, 1024); } @@ -55,37 +58,41 @@ void loop() { HTTPClient https; - if (https.begin(*client, "https://tls.mbed.org/")) { - + if (https.begin(*client, "https://tls.mbed.org/")) + { Serial.print("[HTTPS] GET...\n"); // start connection and send HTTP header int httpCode = https.GET(); - if (httpCode > 0) { + if (httpCode > 0) + { // HTTP header has been send and Server response header has been handled Serial.printf("[HTTPS] GET... code: %d\n", httpCode); // file found at server - if (httpCode == HTTP_CODE_OK) { - + if (httpCode == HTTP_CODE_OK) + { // get length of document (is -1 when Server sends no Content-Length header) - int len = https.getSize(); + int len = https.getSize(); // create buffer for read static uint8_t buff[128] = { 0 }; // read all data from server - while (https.connected() && (len > 0 || len == -1)) { + while (https.connected() && (len > 0 || len == -1)) + { // get available data size size_t size = client->available(); - if (size) { + if (size) + { // read up to 128 byte int c = client->readBytes(buff, ((size > sizeof(buff)) ? sizeof(buff) : size)); // write it to Serial Serial.write(buff, c); - if (len > 0) { + if (len > 0) + { len -= c; } } @@ -95,12 +102,16 @@ void loop() { Serial.println(); Serial.print("[HTTPS] connection closed or file end.\n"); } - } else { + } + else + { Serial.printf("[HTTPS] GET... failed, error: %s\n", https.errorToString(httpCode).c_str()); } https.end(); - } else { + } + else + { Serial.printf("Unable to connect\n"); } } diff --git a/libraries/ESP8266HTTPUpdateServer/examples/SecureBearSSLUpdater/SecureBearSSLUpdater.ino b/libraries/ESP8266HTTPUpdateServer/examples/SecureBearSSLUpdater/SecureBearSSLUpdater.ino index d849181a6c..0feea5c4f4 100644 --- a/libraries/ESP8266HTTPUpdateServer/examples/SecureBearSSLUpdater/SecureBearSSLUpdater.ino +++ b/libraries/ESP8266HTTPUpdateServer/examples/SecureBearSSLUpdater/SecureBearSSLUpdater.ino @@ -24,17 +24,17 @@ #define STAPSK "your-password" #endif -const char* host = "esp8266-webupdate"; -const char* update_path = "/firmware"; -const char* update_username = "admin"; -const char* update_password = "admin"; -const char* ssid = STASSID; -const char* password = STAPSK; - -ESP8266WebServerSecure httpServer(443); +const char* host = "esp8266-webupdate"; +const char* update_path = "/firmware"; +const char* update_username = "admin"; +const char* update_password = "admin"; +const char* ssid = STASSID; +const char* password = STAPSK; + +ESP8266WebServerSecure httpServer(443); ESP8266HTTPUpdateServerSecure httpUpdater; -static const char serverCert[] PROGMEM = R"EOF( +static const char serverCert[] PROGMEM = R"EOF( -----BEGIN CERTIFICATE----- MIIDSzCCAjMCCQD2ahcfZAwXxDANBgkqhkiG9w0BAQsFADCBiTELMAkGA1UEBhMC VVMxEzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU9yYW5nZSBDb3VudHkx @@ -57,7 +57,7 @@ JfUvYadSYxh3nblvA4OL+iEZiW8NE3hbW6WPXxvS7Euge0uWMPc4uEcnsE0ZVG3m -----END CERTIFICATE----- )EOF"; -static const char serverKey[] PROGMEM = R"EOF( +static const char serverKey[] PROGMEM = R"EOF( -----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEA9UoHBtn4oNKXjRgIOQ/rLxK/iI0a8Q5mDxhfuwa9//FkftSI IFY8UhGk2YNJpnfKOyYWqbqwuJhIZJ2sEIWp2301OnavuGBrpKOgBJJljgH2l/4Z @@ -87,15 +87,16 @@ gz5JWYhbD6c38khSzJb0pNXCo3EuYAVa36kDM96k1BtWuhRS10Q1VXk= -----END RSA PRIVATE KEY----- )EOF"; -void setup() { - +void setup() +{ Serial.begin(115200); Serial.println(); Serial.println("Booting Sketch..."); WiFi.mode(WIFI_AP_STA); WiFi.begin(ssid, password); - while (WiFi.waitForConnectResult() != WL_CONNECTED) { + while (WiFi.waitForConnectResult() != WL_CONNECTED) + { WiFi.begin(ssid, password); Serial.println("WiFi failed, retrying."); } @@ -112,10 +113,11 @@ void setup() { Serial.printf("BearSSLUpdateServer ready!\nOpen https://%s.local%s in " "your browser and login with username '%s' and password " "'%s'\n", - host, update_path, update_username, update_password); + host, update_path, update_username, update_password); } -void loop() { +void loop() +{ httpServer.handleClient(); MDNS.update(); } diff --git a/libraries/ESP8266HTTPUpdateServer/examples/SecureWebUpdater/SecureWebUpdater.ino b/libraries/ESP8266HTTPUpdateServer/examples/SecureWebUpdater/SecureWebUpdater.ino index d37ef3f1f6..ace93bdf93 100644 --- a/libraries/ESP8266HTTPUpdateServer/examples/SecureWebUpdater/SecureWebUpdater.ino +++ b/libraries/ESP8266HTTPUpdateServer/examples/SecureWebUpdater/SecureWebUpdater.ino @@ -13,25 +13,26 @@ #define STAPSK "your-password" #endif -const char* host = "esp8266-webupdate"; -const char* update_path = "/firmware"; -const char* update_username = "admin"; -const char* update_password = "admin"; -const char* ssid = STASSID; -const char* password = STAPSK; - -ESP8266WebServer httpServer(80); +const char* host = "esp8266-webupdate"; +const char* update_path = "/firmware"; +const char* update_username = "admin"; +const char* update_password = "admin"; +const char* ssid = STASSID; +const char* password = STAPSK; + +ESP8266WebServer httpServer(80); ESP8266HTTPUpdateServer httpUpdater; -void setup(void) { - +void setup(void) +{ Serial.begin(115200); Serial.println(); Serial.println("Booting Sketch..."); WiFi.mode(WIFI_AP_STA); WiFi.begin(ssid, password); - while (WiFi.waitForConnectResult() != WL_CONNECTED) { + while (WiFi.waitForConnectResult() != WL_CONNECTED) + { WiFi.begin(ssid, password); Serial.println("WiFi failed, retrying."); } @@ -45,7 +46,8 @@ void setup(void) { Serial.printf("HTTPUpdateServer ready! Open http://%s.local%s in your browser and login with username '%s' and password '%s'\n", host, update_path, update_username, update_password); } -void loop(void) { +void loop(void) +{ httpServer.handleClient(); MDNS.update(); } diff --git a/libraries/ESP8266HTTPUpdateServer/examples/WebUpdater/WebUpdater.ino b/libraries/ESP8266HTTPUpdateServer/examples/WebUpdater/WebUpdater.ino index 89b5f62a90..411998b1dd 100644 --- a/libraries/ESP8266HTTPUpdateServer/examples/WebUpdater/WebUpdater.ino +++ b/libraries/ESP8266HTTPUpdateServer/examples/WebUpdater/WebUpdater.ino @@ -13,22 +13,23 @@ #define STAPSK "your-password" #endif -const char* host = "esp8266-webupdate"; -const char* ssid = STASSID; -const char* password = STAPSK; +const char* host = "esp8266-webupdate"; +const char* ssid = STASSID; +const char* password = STAPSK; -ESP8266WebServer httpServer(80); +ESP8266WebServer httpServer(80); ESP8266HTTPUpdateServer httpUpdater; -void setup(void) { - +void setup(void) +{ Serial.begin(115200); Serial.println(); Serial.println("Booting Sketch..."); WiFi.mode(WIFI_AP_STA); WiFi.begin(ssid, password); - while (WiFi.waitForConnectResult() != WL_CONNECTED) { + while (WiFi.waitForConnectResult() != WL_CONNECTED) + { WiFi.begin(ssid, password); Serial.println("WiFi failed, retrying."); } @@ -42,7 +43,8 @@ void setup(void) { Serial.printf("HTTPUpdateServer ready! Open http://%s.local/update in your browser\n", host); } -void loop(void) { +void loop(void) +{ httpServer.handleClient(); MDNS.update(); } diff --git a/libraries/ESP8266LLMNR/examples/LLMNR_Web_Server/LLMNR_Web_Server.ino b/libraries/ESP8266LLMNR/examples/LLMNR_Web_Server/LLMNR_Web_Server.ino index f36da85aeb..ddc8f44432 100644 --- a/libraries/ESP8266LLMNR/examples/LLMNR_Web_Server/LLMNR_Web_Server.ino +++ b/libraries/ESP8266LLMNR/examples/LLMNR_Web_Server/LLMNR_Web_Server.ino @@ -65,20 +65,23 @@ #define STAPSK "your-password" #endif -const char* ssid = STASSID; -const char* password = STAPSK; +const char* ssid = STASSID; +const char* password = STAPSK; ESP8266WebServer web_server(80); -void handle_http_not_found() { +void handle_http_not_found() +{ web_server.send(404, "text/plain", "Not Found"); } -void handle_http_root() { +void handle_http_root() +{ web_server.send(200, "text/plain", "It works!"); } -void setup(void) { +void setup(void) +{ Serial.begin(115200); // Connect to WiFi network @@ -87,7 +90,8 @@ void setup(void) { Serial.println(""); // Wait for connection - while (WiFi.status() != WL_CONNECTED) { + while (WiFi.status() != WL_CONNECTED) + { delay(500); Serial.print("."); } @@ -107,6 +111,7 @@ void setup(void) { Serial.println("HTTP server started"); } -void loop(void) { +void loop(void) +{ web_server.handleClient(); } diff --git a/libraries/ESP8266NetBIOS/examples/ESP_NBNST/ESP_NBNST.ino b/libraries/ESP8266NetBIOS/examples/ESP_NBNST/ESP_NBNST.ino index 4d7998667b..3ecf5ea95e 100644 --- a/libraries/ESP8266NetBIOS/examples/ESP_NBNST/ESP_NBNST.ino +++ b/libraries/ESP8266NetBIOS/examples/ESP_NBNST/ESP_NBNST.ino @@ -7,13 +7,14 @@ #define STAPSK "your-password" #endif -const char* ssid = STASSID; -const char* password = STAPSK; +const char* ssid = STASSID; +const char* password = STAPSK; ESP8266WebServer wwwserver(80); -String content; +String content; -static void handleRoot(void) { +static void handleRoot(void) +{ content = F("\nHello world from ESP8266"); content += F("

      "); content += F(""); @@ -21,7 +22,8 @@ static void handleRoot(void) { wwwserver.send(200, F("text/html"), content); } -void setup() { +void setup() +{ Serial.begin(115200); // Connect to WiFi network @@ -30,7 +32,8 @@ void setup() { Serial.println(""); // Wait for connection - while (WiFi.status() != WL_CONNECTED) { + while (WiFi.status() != WL_CONNECTED) + { delay(500); Serial.print("."); } @@ -46,6 +49,7 @@ void setup() { NBNS.begin("ESP"); } -void loop() { +void loop() +{ wwwserver.handleClient(); } diff --git a/libraries/ESP8266SSDP/examples/SSDP/SSDP.ino b/libraries/ESP8266SSDP/examples/SSDP/SSDP.ino index c081869696..7fff5454f5 100644 --- a/libraries/ESP8266SSDP/examples/SSDP/SSDP.ino +++ b/libraries/ESP8266SSDP/examples/SSDP/SSDP.ino @@ -7,27 +7,26 @@ #define STAPSK "your-password" #endif -const char* ssid = STASSID; -const char* password = STAPSK; +const char* ssid = STASSID; +const char* password = STAPSK; ESP8266WebServer HTTP(80); -void setup() { +void setup() +{ Serial.begin(115200); Serial.println(); Serial.println("Starting WiFi..."); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); - if (WiFi.waitForConnectResult() == WL_CONNECTED) { - + if (WiFi.waitForConnectResult() == WL_CONNECTED) + { Serial.printf("Starting HTTP...\n"); - HTTP.on("/index.html", HTTP_GET, []() { - HTTP.send(200, "text/plain", "Hello World!"); - }); - HTTP.on("/description.xml", HTTP_GET, []() { - SSDP.schema(HTTP.client()); - }); + HTTP.on("/index.html", HTTP_GET, []() + { HTTP.send(200, "text/plain", "Hello World!"); }); + HTTP.on("/description.xml", HTTP_GET, []() + { SSDP.schema(HTTP.client()); }); HTTP.begin(); Serial.printf("Starting SSDP...\n"); @@ -44,15 +43,19 @@ void setup() { SSDP.begin(); Serial.printf("Ready!\n"); - } else { + } + else + { Serial.printf("WiFi Failed\n"); - while (1) { + while (1) + { delay(100); } } } -void loop() { +void loop() +{ HTTP.handleClient(); delay(1); } diff --git a/libraries/ESP8266WebServer/examples/AdvancedWebServer/AdvancedWebServer.ino b/libraries/ESP8266WebServer/examples/AdvancedWebServer/AdvancedWebServer.ino index c20d1ddb15..c91e8779d8 100644 --- a/libraries/ESP8266WebServer/examples/AdvancedWebServer/AdvancedWebServer.ino +++ b/libraries/ESP8266WebServer/examples/AdvancedWebServer/AdvancedWebServer.ino @@ -38,23 +38,24 @@ #define STAPSK "your-password" #endif -const char* ssid = STASSID; -const char* password = STAPSK; +const char* ssid = STASSID; +const char* password = STAPSK; ESP8266WebServer server(80); -const int led = 13; +const int led = 13; -void handleRoot() { +void handleRoot() +{ digitalWrite(led, 1); char temp[400]; - int sec = millis() / 1000; - int min = sec / 60; - int hr = min / 60; + int sec = millis() / 1000; + int min = sec / 60; + int hr = min / 60; snprintf(temp, 400, - "\ + "\ \ \ ESP8266 Demo\ @@ -69,12 +70,13 @@ void handleRoot() { \ ", - hr, min % 60, sec % 60); + hr, min % 60, sec % 60); server.send(200, "text/html", temp); digitalWrite(led, 0); } -void handleNotFound() { +void handleNotFound() +{ digitalWrite(led, 1); String message = "File Not Found\n\n"; message += "URI: "; @@ -85,7 +87,8 @@ void handleNotFound() { message += server.args(); message += "\n"; - for (uint8_t i = 0; i < server.args(); i++) { + for (uint8_t i = 0; i < server.args(); i++) + { message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; } @@ -93,7 +96,8 @@ void handleNotFound() { digitalWrite(led, 0); } -void drawGraph() { +void drawGraph() +{ String out; out.reserve(2600); char temp[70]; @@ -101,7 +105,8 @@ void drawGraph() { out += "\n"; out += "\n"; int y = rand() % 130; - for (int x = 10; x < 390; x += 10) { + for (int x = 10; x < 390; x += 10) + { int y2 = rand() % 130; sprintf(temp, "\n", x, 140 - y, x + 10, 140 - y2); out += temp; @@ -112,7 +117,8 @@ void drawGraph() { server.send(200, "image/svg+xml", out); } -void setup(void) { +void setup(void) +{ pinMode(led, OUTPUT); digitalWrite(led, 0); Serial.begin(115200); @@ -121,7 +127,8 @@ void setup(void) { Serial.println(""); // Wait for connection - while (WiFi.status() != WL_CONNECTED) { + while (WiFi.status() != WL_CONNECTED) + { delay(500); Serial.print("."); } @@ -132,21 +139,22 @@ void setup(void) { Serial.print("IP address: "); Serial.println(WiFi.localIP()); - if (MDNS.begin("esp8266")) { + if (MDNS.begin("esp8266")) + { Serial.println("MDNS responder started"); } server.on("/", handleRoot); server.on("/test.svg", drawGraph); - server.on("/inline", []() { - server.send(200, "text/plain", "this works as well"); - }); + server.on("/inline", []() + { server.send(200, "text/plain", "this works as well"); }); server.onNotFound(handleNotFound); server.begin(); Serial.println("HTTP server started"); } -void loop(void) { +void loop(void) +{ server.handleClient(); MDNS.update(); } diff --git a/libraries/ESP8266WebServer/examples/FSBrowser/FSBrowser.ino b/libraries/ESP8266WebServer/examples/FSBrowser/FSBrowser.ino index 686f4327ed..e816a49354 100644 --- a/libraries/ESP8266WebServer/examples/FSBrowser/FSBrowser.ino +++ b/libraries/ESP8266WebServer/examples/FSBrowser/FSBrowser.ino @@ -49,19 +49,19 @@ #if defined USE_SPIFFS #include -const char* fsName = "SPIFFS"; -FS* fileSystem = &SPIFFS; -SPIFFSConfig fileSystemConfig = SPIFFSConfig(); +const char* fsName = "SPIFFS"; +FS* fileSystem = &SPIFFS; +SPIFFSConfig fileSystemConfig = SPIFFSConfig(); #elif defined USE_LITTLEFS #include -const char* fsName = "LittleFS"; -FS* fileSystem = &LittleFS; +const char* fsName = "LittleFS"; +FS* fileSystem = &LittleFS; LittleFSConfig fileSystemConfig = LittleFSConfig(); #elif defined USE_SDFS #include -const char* fsName = "SDFS"; -FS* fileSystem = &SDFS; -SDFSConfig fileSystemConfig = SDFSConfig(); +const char* fsName = "SDFS"; +FS* fileSystem = &SDFS; +SDFSConfig fileSystemConfig = SDFSConfig(); // fileSystemConfig.setCSPin(chipSelectPin); #else #error Please select a filesystem first by uncommenting one of the "#define USE_xxx" lines at the beginning of the sketch. @@ -74,42 +74,47 @@ SDFSConfig fileSystemConfig = SDFSConfig(); #define STAPSK "your-password" #endif -const char* ssid = STASSID; -const char* password = STAPSK; -const char* host = "fsbrowser"; +const char* ssid = STASSID; +const char* password = STAPSK; +const char* host = "fsbrowser"; -ESP8266WebServer server(80); +ESP8266WebServer server(80); -static bool fsOK; -String unsupportedFiles = String(); +static bool fsOK; +String unsupportedFiles = String(); -File uploadFile; +File uploadFile; -static const char TEXT_PLAIN[] PROGMEM = "text/plain"; -static const char FS_INIT_ERROR[] PROGMEM = "FS INIT ERROR"; +static const char TEXT_PLAIN[] PROGMEM = "text/plain"; +static const char FS_INIT_ERROR[] PROGMEM = "FS INIT ERROR"; static const char FILE_NOT_FOUND[] PROGMEM = "FileNotFound"; //////////////////////////////// // Utils to return HTTP codes, and determine content-type -void replyOK() { +void replyOK() +{ server.send(200, FPSTR(TEXT_PLAIN), ""); } -void replyOKWithMsg(String msg) { +void replyOKWithMsg(String msg) +{ server.send(200, FPSTR(TEXT_PLAIN), msg); } -void replyNotFound(String msg) { +void replyNotFound(String msg) +{ server.send(404, FPSTR(TEXT_PLAIN), msg); } -void replyBadRequest(String msg) { +void replyBadRequest(String msg) +{ DBG_OUTPUT_PORT.println(msg); server.send(400, FPSTR(TEXT_PLAIN), msg + "\r\n"); } -void replyServerError(String msg) { +void replyServerError(String msg) +{ DBG_OUTPUT_PORT.println(msg); server.send(500, FPSTR(TEXT_PLAIN), msg + "\r\n"); } @@ -119,15 +124,19 @@ void replyServerError(String msg) { Checks filename for character combinations that are not supported by FSBrowser (alhtough valid on SPIFFS). Returns an empty String if supported, or detail of error(s) if unsupported */ -String checkForUnsupportedPath(String filename) { +String checkForUnsupportedPath(String filename) +{ String error = String(); - if (!filename.startsWith("/")) { + if (!filename.startsWith("/")) + { error += F("!NO_LEADING_SLASH! "); } - if (filename.indexOf("//") != -1) { + if (filename.indexOf("//") != -1) + { error += F("!DOUBLE_SLASH! "); } - if (filename.endsWith("/")) { + if (filename.endsWith("/")) + { error += F("!TRAILING_SLASH! "); } return error; @@ -140,7 +149,8 @@ String checkForUnsupportedPath(String filename) { /* Return the FS type, status and size info */ -void handleStatus() { +void handleStatus() +{ DBG_OUTPUT_PORT.println("handleStatus"); FSInfo fs_info; String json; @@ -149,14 +159,17 @@ void handleStatus() { json = "{\"type\":\""; json += fsName; json += "\", \"isOk\":"; - if (fsOK) { + if (fsOK) + { fileSystem->info(fs_info); json += F("\"true\", \"totalBytes\":\""); json += fs_info.totalBytes; json += F("\", \"usedBytes\":\""); json += fs_info.usedBytes; json += "\""; - } else { + } + else + { json += "\"false\""; } json += F(",\"unsupportedFiles\":\""); @@ -170,17 +183,21 @@ void handleStatus() { Return the list of files in the directory specified by the "dir" query string parameter. Also demonstrates the use of chunked responses. */ -void handleFileList() { - if (!fsOK) { +void handleFileList() +{ + if (!fsOK) + { return replyServerError(FPSTR(FS_INIT_ERROR)); } - if (!server.hasArg("dir")) { + if (!server.hasArg("dir")) + { return replyBadRequest(F("DIR ARG MISSING")); } String path = server.arg("dir"); - if (path != "/" && !fileSystem->exists(path)) { + if (path != "/" && !fileSystem->exists(path)) + { return replyBadRequest("BAD PATH"); } @@ -189,7 +206,8 @@ void handleFileList() { path.clear(); // use HTTP/1.1 Chunked response to avoid building a huge temporary string - if (!server.chunkedResponseModeStart(200, "text/json")) { + if (!server.chunkedResponseModeStart(200, "text/json")) + { server.send(505, F("text/html"), F("HTTP1.1 required")); return; } @@ -197,36 +215,47 @@ void handleFileList() { // use the same string for every line String output; output.reserve(64); - while (dir.next()) { + while (dir.next()) + { #ifdef USE_SPIFFS String error = checkForUnsupportedPath(dir.fileName()); - if (error.length() > 0) { + if (error.length() > 0) + { DBG_OUTPUT_PORT.println(String("Ignoring ") + error + dir.fileName()); continue; } #endif - if (output.length()) { + if (output.length()) + { // send string from previous iteration // as an HTTP chunk server.sendContent(output); output = ','; - } else { + } + else + { output = '['; } output += "{\"type\":\""; - if (dir.isDirectory()) { + if (dir.isDirectory()) + { output += "dir"; - } else { + } + else + { output += F("file\",\"size\":\""); output += dir.fileSize(); } output += F("\",\"name\":\""); // Always return names without leading "/" - if (dir.fileName()[0] == '/') { + if (dir.fileName()[0] == '/') + { output += &(dir.fileName()[1]); - } else { + } + else + { output += dir.fileName(); } @@ -242,31 +271,40 @@ void handleFileList() { /* Read the given file from the filesystem and stream it back to the client */ -bool handleFileRead(String path) { +bool handleFileRead(String path) +{ DBG_OUTPUT_PORT.println(String("handleFileRead: ") + path); - if (!fsOK) { + if (!fsOK) + { replyServerError(FPSTR(FS_INIT_ERROR)); return true; } - if (path.endsWith("/")) { + if (path.endsWith("/")) + { path += "index.htm"; } String contentType; - if (server.hasArg("download")) { + if (server.hasArg("download")) + { contentType = F("application/octet-stream"); - } else { + } + else + { contentType = mime::getContentType(path); } - if (!fileSystem->exists(path)) { + if (!fileSystem->exists(path)) + { // File not found, try gzip version path = path + ".gz"; } - if (fileSystem->exists(path)) { + if (fileSystem->exists(path)) + { File file = fileSystem->open(path, "r"); - if (server.streamFile(file, contentType) != file.size()) { + if (server.streamFile(file, contentType) != file.size()) + { DBG_OUTPUT_PORT.println("Sent less data than expected!"); } file.close(); @@ -280,12 +318,17 @@ bool handleFileRead(String path) { As some FS (e.g. LittleFS) delete the parent folder when the last child has been removed, return the path of the closest parent still existing */ -String lastExistingParent(String path) { - while (!path.isEmpty() && !fileSystem->exists(path)) { - if (path.lastIndexOf('/') > 0) { +String lastExistingParent(String path) +{ + while (!path.isEmpty() && !fileSystem->exists(path)) + { + if (path.lastIndexOf('/') > 0) + { path = path.substring(0, path.lastIndexOf('/')); - } else { - path = String(); // No slash => the top folder does not exist + } + else + { + path = String(); // No slash => the top folder does not exist } } DBG_OUTPUT_PORT.println(String("Last existing parent: ") + path); @@ -303,71 +346,93 @@ String lastExistingParent(String path) { Rename folder | parent of source folder Move folder | parent of source folder, or remaining ancestor */ -void handleFileCreate() { - if (!fsOK) { +void handleFileCreate() +{ + if (!fsOK) + { return replyServerError(FPSTR(FS_INIT_ERROR)); } String path = server.arg("path"); - if (path.isEmpty()) { + if (path.isEmpty()) + { return replyBadRequest(F("PATH ARG MISSING")); } #ifdef USE_SPIFFS - if (checkForUnsupportedPath(path).length() > 0) { + if (checkForUnsupportedPath(path).length() > 0) + { return replyServerError(F("INVALID FILENAME")); } #endif - if (path == "/") { + if (path == "/") + { return replyBadRequest("BAD PATH"); } - if (fileSystem->exists(path)) { + if (fileSystem->exists(path)) + { return replyBadRequest(F("PATH FILE EXISTS")); } String src = server.arg("src"); - if (src.isEmpty()) { + if (src.isEmpty()) + { // No source specified: creation DBG_OUTPUT_PORT.println(String("handleFileCreate: ") + path); - if (path.endsWith("/")) { + if (path.endsWith("/")) + { // Create a folder path.remove(path.length() - 1); - if (!fileSystem->mkdir(path)) { + if (!fileSystem->mkdir(path)) + { return replyServerError(F("MKDIR FAILED")); } - } else { + } + else + { // Create a file File file = fileSystem->open(path, "w"); - if (file) { + if (file) + { file.write((const char*)0); file.close(); - } else { + } + else + { return replyServerError(F("CREATE FAILED")); } } - if (path.lastIndexOf('/') > -1) { + if (path.lastIndexOf('/') > -1) + { path = path.substring(0, path.lastIndexOf('/')); } replyOKWithMsg(path); - } else { + } + else + { // Source specified: rename - if (src == "/") { + if (src == "/") + { return replyBadRequest("BAD SRC"); } - if (!fileSystem->exists(src)) { + if (!fileSystem->exists(src)) + { return replyBadRequest(F("SRC FILE NOT FOUND")); } DBG_OUTPUT_PORT.println(String("handleFileCreate: ") + path + " from " + src); - if (path.endsWith("/")) { + if (path.endsWith("/")) + { path.remove(path.length() - 1); } - if (src.endsWith("/")) { + if (src.endsWith("/")) + { src.remove(src.length() - 1); } - if (!fileSystem->rename(src, path)) { + if (!fileSystem->rename(src, path)) + { return replyServerError(F("RENAME FAILED")); } replyOKWithMsg(lastExistingParent(src)); @@ -383,13 +448,15 @@ void handleFileCreate() { This use is just for demonstration purpose, and FSBrowser might crash in case of deeply nested filesystems. Please don't do this on a production system. */ -void deleteRecursive(String path) { - File file = fileSystem->open(path, "r"); +void deleteRecursive(String path) +{ + File file = fileSystem->open(path, "r"); bool isDir = file.isDirectory(); file.close(); // If it's a plain file, delete it - if (!isDir) { + if (!isDir) + { fileSystem->remove(path); return; } @@ -397,7 +464,8 @@ void deleteRecursive(String path) { // Otherwise delete its contents first Dir dir = fileSystem->openDir(path); - while (dir.next()) { + while (dir.next()) + { deleteRecursive(path + '/' + dir.fileName()); } @@ -412,18 +480,22 @@ void deleteRecursive(String path) { Delete file | parent of deleted file, or remaining ancestor Delete folder | parent of deleted folder, or remaining ancestor */ -void handleFileDelete() { - if (!fsOK) { +void handleFileDelete() +{ + if (!fsOK) + { return replyServerError(FPSTR(FS_INIT_ERROR)); } String path = server.arg(0); - if (path.isEmpty() || path == "/") { + if (path.isEmpty() || path == "/") + { return replyBadRequest("BAD PATH"); } DBG_OUTPUT_PORT.println(String("handleFileDelete: ") + path); - if (!fileSystem->exists(path)) { + if (!fileSystem->exists(path)) + { return replyNotFound(FPSTR(FILE_NOT_FOUND)); } deleteRecursive(path); @@ -434,36 +506,49 @@ void handleFileDelete() { /* Handle a file upload request */ -void handleFileUpload() { - if (!fsOK) { +void handleFileUpload() +{ + if (!fsOK) + { return replyServerError(FPSTR(FS_INIT_ERROR)); } - if (server.uri() != "/edit") { + if (server.uri() != "/edit") + { return; } HTTPUpload& upload = server.upload(); - if (upload.status == UPLOAD_FILE_START) { + if (upload.status == UPLOAD_FILE_START) + { String filename = upload.filename; // Make sure paths always start with "/" - if (!filename.startsWith("/")) { + if (!filename.startsWith("/")) + { filename = "/" + filename; } DBG_OUTPUT_PORT.println(String("handleFileUpload Name: ") + filename); uploadFile = fileSystem->open(filename, "w"); - if (!uploadFile) { + if (!uploadFile) + { return replyServerError(F("CREATE FAILED")); } DBG_OUTPUT_PORT.println(String("Upload: START, filename: ") + filename); - } else if (upload.status == UPLOAD_FILE_WRITE) { - if (uploadFile) { + } + else if (upload.status == UPLOAD_FILE_WRITE) + { + if (uploadFile) + { size_t bytesWritten = uploadFile.write(upload.buf, upload.currentSize); - if (bytesWritten != upload.currentSize) { + if (bytesWritten != upload.currentSize) + { return replyServerError(F("WRITE FAILED")); } } DBG_OUTPUT_PORT.println(String("Upload: WRITE, Bytes: ") + upload.currentSize); - } else if (upload.status == UPLOAD_FILE_END) { - if (uploadFile) { + } + else if (upload.status == UPLOAD_FILE_END) + { + if (uploadFile) + { uploadFile.close(); } DBG_OUTPUT_PORT.println(String("Upload: END, Size: ") + upload.totalSize); @@ -475,14 +560,17 @@ void handleFileUpload() { First try to find and return the requested file from the filesystem, and if it fails, return a 404 page with debug information */ -void handleNotFound() { - if (!fsOK) { +void handleNotFound() +{ + if (!fsOK) + { return replyServerError(FPSTR(FS_INIT_ERROR)); } - String uri = ESP8266WebServer::urlDecode(server.uri()); // required to read paths with blanks + String uri = ESP8266WebServer::urlDecode(server.uri()); // required to read paths with blanks - if (handleFileRead(uri)) { + if (handleFileRead(uri)) + { return; } @@ -496,7 +584,8 @@ void handleNotFound() { message += F("\nArguments: "); message += server.args(); message += '\n'; - for (uint8_t i = 0; i < server.args(); i++) { + for (uint8_t i = 0; i < server.args(); i++) + { message += F(" NAME:"); message += server.argName(i); message += F("\n VALUE:"); @@ -517,8 +606,10 @@ void handleNotFound() { embedded in the program code. Otherwise, fails with a 404 page with debug information */ -void handleGetEdit() { - if (handleFileRead(F("/edit/index.htm"))) { +void handleGetEdit() +{ + if (handleFileRead(F("/edit/index.htm"))) + { return; } @@ -530,7 +621,8 @@ void handleGetEdit() { #endif } -void setup(void) { +void setup(void) +{ //////////////////////////////// // SERIAL INIT DBG_OUTPUT_PORT.begin(115200); @@ -549,11 +641,13 @@ void setup(void) { // Debug: dump on console contents of filesystem with no filter and check filenames validity Dir dir = fileSystem->openDir(""); DBG_OUTPUT_PORT.println(F("List of files at root of filesystem:")); - while (dir.next()) { - String error = checkForUnsupportedPath(dir.fileName()); + while (dir.next()) + { + String error = checkForUnsupportedPath(dir.fileName()); String fileInfo = dir.fileName() + (dir.isDirectory() ? " [DIR]" : String(" (") + dir.fileSize() + "b)"); DBG_OUTPUT_PORT.println(error + fileInfo); - if (error.length() > 0) { + if (error.length() > 0) + { unsupportedFiles += error + fileInfo + '\n'; } } @@ -570,7 +664,8 @@ void setup(void) { WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); // Wait for connection - while (WiFi.status() != WL_CONNECTED) { + while (WiFi.status() != WL_CONNECTED) + { delay(500); DBG_OUTPUT_PORT.print("."); } @@ -580,7 +675,8 @@ void setup(void) { //////////////////////////////// // MDNS INIT - if (MDNS.begin(host)) { + if (MDNS.begin(host)) + { MDNS.addService("http", "tcp", 80); DBG_OUTPUT_PORT.print(F("Open http://")); DBG_OUTPUT_PORT.print(host); @@ -619,7 +715,8 @@ void setup(void) { DBG_OUTPUT_PORT.println("HTTP server started"); } -void loop(void) { +void loop(void) +{ server.handleClient(); MDNS.update(); } diff --git a/libraries/ESP8266WebServer/examples/Graph/Graph.ino b/libraries/ESP8266WebServer/examples/Graph/Graph.ino index d4915f201f..5ce29247ed 100644 --- a/libraries/ESP8266WebServer/examples/Graph/Graph.ino +++ b/libraries/ESP8266WebServer/examples/Graph/Graph.ino @@ -38,15 +38,15 @@ #if defined USE_SPIFFS #include -FS* fileSystem = &SPIFFS; -SPIFFSConfig fileSystemConfig = SPIFFSConfig(); +FS* fileSystem = &SPIFFS; +SPIFFSConfig fileSystemConfig = SPIFFSConfig(); #elif defined USE_LITTLEFS #include -FS* fileSystem = &LittleFS; +FS* fileSystem = &LittleFS; LittleFSConfig fileSystemConfig = LittleFSConfig(); #elif defined USE_SDFS #include -FS* fileSystem = &SDFS; +FS* fileSystem = &SDFS; SDFSConfig fileSystemConfig = SDFSConfig(); // fileSystemConfig.setCSPin(chipSelectPin); #else @@ -63,39 +63,44 @@ SDFSConfig fileSystemConfig = SDFSConfig(); // Indicate which digital I/Os should be displayed on the chart. // From GPIO16 to GPIO0, a '1' means the corresponding GPIO will be shown // e.g. 0b11111000000111111 -unsigned int gpioMask; +unsigned int gpioMask; -const char* ssid = STASSID; -const char* password = STAPSK; -const char* host = "graph"; +const char* ssid = STASSID; +const char* password = STAPSK; +const char* host = "graph"; -ESP8266WebServer server(80); +ESP8266WebServer server(80); -static const char TEXT_PLAIN[] PROGMEM = "text/plain"; -static const char FS_INIT_ERROR[] PROGMEM = "FS INIT ERROR"; +static const char TEXT_PLAIN[] PROGMEM = "text/plain"; +static const char FS_INIT_ERROR[] PROGMEM = "FS INIT ERROR"; static const char FILE_NOT_FOUND[] PROGMEM = "FileNotFound"; //////////////////////////////// // Utils to return HTTP codes -void replyOK() { +void replyOK() +{ server.send(200, FPSTR(TEXT_PLAIN), ""); } -void replyOKWithMsg(String msg) { +void replyOKWithMsg(String msg) +{ server.send(200, FPSTR(TEXT_PLAIN), msg); } -void replyNotFound(String msg) { +void replyNotFound(String msg) +{ server.send(404, FPSTR(TEXT_PLAIN), msg); } -void replyBadRequest(String msg) { +void replyBadRequest(String msg) +{ DBG_OUTPUT_PORT.println(msg); server.send(400, FPSTR(TEXT_PLAIN), msg + "\r\n"); } -void replyServerError(String msg) { +void replyServerError(String msg) +{ DBG_OUTPUT_PORT.println(msg); server.send(500, FPSTR(TEXT_PLAIN), msg + "\r\n"); } @@ -106,22 +111,27 @@ void replyServerError(String msg) { /* Read the given file from the filesystem and stream it back to the client */ -bool handleFileRead(String path) { +bool handleFileRead(String path) +{ DBG_OUTPUT_PORT.println(String("handleFileRead: ") + path); - if (path.endsWith("/")) { + if (path.endsWith("/")) + { path += "index.htm"; } String contentType = mime::getContentType(path); - if (!fileSystem->exists(path)) { + if (!fileSystem->exists(path)) + { // File not found, try gzip version path = path + ".gz"; } - if (fileSystem->exists(path)) { + if (fileSystem->exists(path)) + { File file = fileSystem->open(path, "r"); - if (server.streamFile(file, contentType) != file.size()) { + if (server.streamFile(file, contentType) != file.size()) + { DBG_OUTPUT_PORT.println("Sent less data than expected!"); } file.close(); @@ -136,10 +146,12 @@ bool handleFileRead(String path) { First try to find and return the requested file from the filesystem, and if it fails, return a 404 page with debug information */ -void handleNotFound() { - String uri = ESP8266WebServer::urlDecode(server.uri()); // required to read paths with blanks +void handleNotFound() +{ + String uri = ESP8266WebServer::urlDecode(server.uri()); // required to read paths with blanks - if (handleFileRead(uri)) { + if (handleFileRead(uri)) + { return; } @@ -153,7 +165,8 @@ void handleNotFound() { message += F("\nArguments: "); message += server.args(); message += '\n'; - for (uint8_t i = 0; i < server.args(); i++) { + for (uint8_t i = 0; i < server.args(); i++) + { message += F(" NAME:"); message += server.argName(i); message += F("\n VALUE:"); @@ -168,7 +181,8 @@ void handleNotFound() { return replyNotFound(message); } -void setup(void) { +void setup(void) +{ //////////////////////////////// // SERIAL INIT DBG_OUTPUT_PORT.begin(115200); @@ -196,7 +210,8 @@ void setup(void) { WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); // Wait for connection - while (WiFi.status() != WL_CONNECTED) { + while (WiFi.status() != WL_CONNECTED) + { delay(500); DBG_OUTPUT_PORT.print("."); } @@ -206,7 +221,8 @@ void setup(void) { //////////////////////////////// // MDNS INIT - if (MDNS.begin(host)) { + if (MDNS.begin(host)) + { MDNS.addService("http", "tcp", 80); DBG_OUTPUT_PORT.print(F("Open http://")); DBG_OUTPUT_PORT.print(host); @@ -217,22 +233,23 @@ void setup(void) { // WEB SERVER INIT //get heap status, analog input value and all GPIO statuses in one json call - server.on("/espData", HTTP_GET, []() { - String json; - json.reserve(88); - json = "{\"time\":"; - json += millis(); - json += ", \"heap\":"; - json += ESP.getFreeHeap(); - json += ", \"analog\":"; - json += analogRead(A0); - json += ", \"gpioMask\":"; - json += gpioMask; - json += ", \"gpioData\":"; - json += (uint32_t)(((GPI | GPO) & 0xFFFF) | ((GP16I & 0x01) << 16)); - json += "}"; - server.send(200, "text/json", json); - }); + server.on("/espData", HTTP_GET, []() + { + String json; + json.reserve(88); + json = "{\"time\":"; + json += millis(); + json += ", \"heap\":"; + json += ESP.getFreeHeap(); + json += ", \"analog\":"; + json += analogRead(A0); + json += ", \"gpioMask\":"; + json += gpioMask; + json += ", \"gpioData\":"; + json += (uint32_t)(((GPI | GPO) & 0xFFFF) | ((GP16I & 0x01) << 16)); + json += "}"; + server.send(200, "text/json", json); + }); // Default handler for all URIs not defined above // Use it to read files from filesystem @@ -249,40 +266,48 @@ void setup(void) { } // Return default GPIO mask, that is all I/Os except SD card ones -unsigned int defaultMask() { +unsigned int defaultMask() +{ unsigned int mask = 0b11111111111111111; - for (auto pin = 0; pin <= 16; pin++) { - if (isFlashInterfacePin(pin)) { + for (auto pin = 0; pin <= 16; pin++) + { + if (isFlashInterfacePin(pin)) + { mask &= ~(1 << pin); } } return mask; } -int rgbMode = 1; // 0=off - 1=auto - 2=manual -int rgbValue = 0; +int rgbMode = 1; // 0=off - 1=auto - 2=manual +int rgbValue = 0; esp8266::polledTimeout::periodicMs timeToChange(1000); -bool modeChangeRequested = false; +bool modeChangeRequested = false; -void loop(void) { +void loop(void) +{ server.handleClient(); MDNS.update(); - if (digitalRead(4) == 0) { + if (digitalRead(4) == 0) + { // button pressed modeChangeRequested = true; } // see if one second has passed since last change, otherwise stop here - if (!timeToChange) { + if (!timeToChange) + { return; } // see if a mode change was requested - if (modeChangeRequested) { + if (modeChangeRequested) + { // increment mode (reset after 2) rgbMode++; - if (rgbMode > 2) { + if (rgbMode > 2) + { rgbMode = 0; } @@ -290,12 +315,13 @@ void loop(void) { } // act according to mode - switch (rgbMode) { - case 0: // off + switch (rgbMode) + { + case 0: // off gpioMask = defaultMask(); - gpioMask &= ~(1 << 12); // Hide GPIO 12 - gpioMask &= ~(1 << 13); // Hide GPIO 13 - gpioMask &= ~(1 << 15); // Hide GPIO 15 + gpioMask &= ~(1 << 12); // Hide GPIO 12 + gpioMask &= ~(1 << 13); // Hide GPIO 13 + gpioMask &= ~(1 << 15); // Hide GPIO 15 // reset outputs digitalWrite(12, 0); @@ -303,12 +329,13 @@ void loop(void) { digitalWrite(15, 0); break; - case 1: // auto + case 1: // auto gpioMask = defaultMask(); // increment value (reset after 7) rgbValue++; - if (rgbValue > 7) { + if (rgbValue > 7) + { rgbValue = 0; } @@ -318,7 +345,7 @@ void loop(void) { digitalWrite(15, rgbValue & 0b100); break; - case 2: // manual + case 2: // manual gpioMask = defaultMask(); // keep outputs unchanged diff --git a/libraries/ESP8266WebServer/examples/HelloServer/HelloServer.ino b/libraries/ESP8266WebServer/examples/HelloServer/HelloServer.ino index 68096d29ad..b8fcaef016 100644 --- a/libraries/ESP8266WebServer/examples/HelloServer/HelloServer.ino +++ b/libraries/ESP8266WebServer/examples/HelloServer/HelloServer.ino @@ -8,20 +8,22 @@ #define STAPSK "your-password" #endif -const char* ssid = STASSID; -const char* password = STAPSK; +const char* ssid = STASSID; +const char* password = STAPSK; ESP8266WebServer server(80); -const int led = 13; +const int led = 13; -void handleRoot() { +void handleRoot() +{ digitalWrite(led, 1); server.send(200, "text/plain", "hello from esp8266!\r\n"); digitalWrite(led, 0); } -void handleNotFound() { +void handleNotFound() +{ digitalWrite(led, 1); String message = "File Not Found\n\n"; message += "URI: "; @@ -31,14 +33,16 @@ void handleNotFound() { message += "\nArguments: "; message += server.args(); message += "\n"; - for (uint8_t i = 0; i < server.args(); i++) { + for (uint8_t i = 0; i < server.args(); i++) + { message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; } server.send(404, "text/plain", message); digitalWrite(led, 0); } -void setup(void) { +void setup(void) +{ pinMode(led, OUTPUT); digitalWrite(led, 0); Serial.begin(115200); @@ -47,7 +51,8 @@ void setup(void) { Serial.println(""); // Wait for connection - while (WiFi.status() != WL_CONNECTED) { + while (WiFi.status() != WL_CONNECTED) + { delay(500); Serial.print("."); } @@ -57,91 +62,99 @@ void setup(void) { Serial.print("IP address: "); Serial.println(WiFi.localIP()); - if (MDNS.begin("esp8266")) { + if (MDNS.begin("esp8266")) + { Serial.println("MDNS responder started"); } server.on("/", handleRoot); - server.on("/inline", []() { - server.send(200, "text/plain", "this works as well"); - }); - - server.on("/gif", []() { - static const uint8_t gif[] PROGMEM = { - 0x47, 0x49, 0x46, 0x38, 0x37, 0x61, 0x10, 0x00, 0x10, 0x00, 0x80, 0x01, - 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x2c, 0x00, 0x00, 0x00, 0x00, - 0x10, 0x00, 0x10, 0x00, 0x00, 0x02, 0x19, 0x8c, 0x8f, 0xa9, 0xcb, 0x9d, - 0x00, 0x5f, 0x74, 0xb4, 0x56, 0xb0, 0xb0, 0xd2, 0xf2, 0x35, 0x1e, 0x4c, - 0x0c, 0x24, 0x5a, 0xe6, 0x89, 0xa6, 0x4d, 0x01, 0x00, 0x3b - }; - char gif_colored[sizeof(gif)]; - memcpy_P(gif_colored, gif, sizeof(gif)); - // Set the background to a random set of colors - gif_colored[16] = millis() % 256; - gif_colored[17] = millis() % 256; - gif_colored[18] = millis() % 256; - server.send(200, "image/gif", gif_colored, sizeof(gif_colored)); - }); + server.on("/inline", []() + { server.send(200, "text/plain", "this works as well"); }); + + server.on("/gif", []() + { + static const uint8_t gif[] PROGMEM = { + 0x47, 0x49, 0x46, 0x38, 0x37, 0x61, 0x10, 0x00, 0x10, 0x00, 0x80, 0x01, + 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x2c, 0x00, 0x00, 0x00, 0x00, + 0x10, 0x00, 0x10, 0x00, 0x00, 0x02, 0x19, 0x8c, 0x8f, 0xa9, 0xcb, 0x9d, + 0x00, 0x5f, 0x74, 0xb4, 0x56, 0xb0, 0xb0, 0xd2, 0xf2, 0x35, 0x1e, 0x4c, + 0x0c, 0x24, 0x5a, 0xe6, 0x89, 0xa6, 0x4d, 0x01, 0x00, 0x3b + }; + char gif_colored[sizeof(gif)]; + memcpy_P(gif_colored, gif, sizeof(gif)); + // Set the background to a random set of colors + gif_colored[16] = millis() % 256; + gif_colored[17] = millis() % 256; + gif_colored[18] = millis() % 256; + server.send(200, "image/gif", gif_colored, sizeof(gif_colored)); + }); server.onNotFound(handleNotFound); ///////////////////////////////////////////////////////// // Hook examples - server.addHook([](const String& method, const String& url, WiFiClient* client, ESP8266WebServer::ContentTypeFunction contentType) { - (void)method; // GET, PUT, ... - (void)url; // example: /root/myfile.html - (void)client; // the webserver tcp client connection - (void)contentType; // contentType(".html") => "text/html" - Serial.printf("A useless web hook has passed\n"); - Serial.printf("(this hook is in 0x%08x area (401x=IRAM 402x=FLASH))\n", esp_get_program_counter()); - return ESP8266WebServer::CLIENT_REQUEST_CAN_CONTINUE; - }); - - server.addHook([](const String&, const String& url, WiFiClient*, ESP8266WebServer::ContentTypeFunction) { - if (url.startsWith("/fail")) { - Serial.printf("An always failing web hook has been triggered\n"); - return ESP8266WebServer::CLIENT_MUST_STOP; - } - return ESP8266WebServer::CLIENT_REQUEST_CAN_CONTINUE; - }); - - server.addHook([](const String&, const String& url, WiFiClient* client, ESP8266WebServer::ContentTypeFunction) { - if (url.startsWith("/dump")) { - Serial.printf("The dumper web hook is on the run\n"); + server.addHook([](const String& method, const String& url, WiFiClient* client, ESP8266WebServer::ContentTypeFunction contentType) + { + (void)method; // GET, PUT, ... + (void)url; // example: /root/myfile.html + (void)client; // the webserver tcp client connection + (void)contentType; // contentType(".html") => "text/html" + Serial.printf("A useless web hook has passed\n"); + Serial.printf("(this hook is in 0x%08x area (401x=IRAM 402x=FLASH))\n", esp_get_program_counter()); + return ESP8266WebServer::CLIENT_REQUEST_CAN_CONTINUE; + }); + + server.addHook([](const String&, const String& url, WiFiClient*, ESP8266WebServer::ContentTypeFunction) + { + if (url.startsWith("/fail")) + { + Serial.printf("An always failing web hook has been triggered\n"); + return ESP8266WebServer::CLIENT_MUST_STOP; + } + return ESP8266WebServer::CLIENT_REQUEST_CAN_CONTINUE; + }); + + server.addHook([](const String&, const String& url, WiFiClient* client, ESP8266WebServer::ContentTypeFunction) + { + if (url.startsWith("/dump")) + { + Serial.printf("The dumper web hook is on the run\n"); // Here the request is not interpreted, so we cannot for sure // swallow the exact amount matching the full request+content, // hence the tcp connection cannot be handled anymore by the // webserver. #ifdef STREAMSEND_API - // we are lucky - client->sendAll(Serial, 500); + // we are lucky + client->sendAll(Serial, 500); #else - auto last = millis(); - while ((millis() - last) < 500) { - char buf[32]; - size_t len = client->read((uint8_t*)buf, sizeof(buf)); - if (len > 0) { - Serial.printf("(<%d> chars)", (int)len); - Serial.write(buf, len); - last = millis(); - } - } + auto last = millis(); + while ((millis() - last) < 500) + { + char buf[32]; + size_t len = client->read((uint8_t*)buf, sizeof(buf)); + if (len > 0) + { + Serial.printf("(<%d> chars)", (int)len); + Serial.write(buf, len); + last = millis(); + } + } #endif - // Two choices: return MUST STOP and webserver will close it - // (we already have the example with '/fail' hook) - // or IS GIVEN and webserver will forget it - // trying with IS GIVEN and storing it on a dumb WiFiClient. - // check the client connection: it should not immediately be closed - // (make another '/dump' one to close the first) - Serial.printf("\nTelling server to forget this connection\n"); - static WiFiClient forgetme = *client; // stop previous one if present and transfer client refcounter - return ESP8266WebServer::CLIENT_IS_GIVEN; - } - return ESP8266WebServer::CLIENT_REQUEST_CAN_CONTINUE; - }); + // Two choices: return MUST STOP and webserver will close it + // (we already have the example with '/fail' hook) + // or IS GIVEN and webserver will forget it + // trying with IS GIVEN and storing it on a dumb WiFiClient. + // check the client connection: it should not immediately be closed + // (make another '/dump' one to close the first) + Serial.printf("\nTelling server to forget this connection\n"); + static WiFiClient forgetme = *client; // stop previous one if present and transfer client refcounter + return ESP8266WebServer::CLIENT_IS_GIVEN; + } + return ESP8266WebServer::CLIENT_REQUEST_CAN_CONTINUE; + }); // Hook examples ///////////////////////////////////////////////////////// @@ -150,7 +163,8 @@ void setup(void) { Serial.println("HTTP server started"); } -void loop(void) { +void loop(void) +{ server.handleClient(); MDNS.update(); } diff --git a/libraries/ESP8266WebServer/examples/HelloServerBearSSL/HelloServerBearSSL.ino b/libraries/ESP8266WebServer/examples/HelloServerBearSSL/HelloServerBearSSL.ino index 18d397249b..fb531a4d6f 100644 --- a/libraries/ESP8266WebServer/examples/HelloServerBearSSL/HelloServerBearSSL.ino +++ b/libraries/ESP8266WebServer/examples/HelloServerBearSSL/HelloServerBearSSL.ino @@ -21,13 +21,13 @@ #define STAPSK "your-password" #endif -const char* ssid = STASSID; -const char* password = STAPSK; +const char* ssid = STASSID; +const char* password = STAPSK; BearSSL::ESP8266WebServerSecure server(443); -BearSSL::ServerSessions serverCache(5); +BearSSL::ServerSessions serverCache(5); -static const char serverCert[] PROGMEM = R"EOF( +static const char serverCert[] PROGMEM = R"EOF( -----BEGIN CERTIFICATE----- MIIDSzCCAjMCCQD2ahcfZAwXxDANBgkqhkiG9w0BAQsFADCBiTELMAkGA1UEBhMC VVMxEzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU9yYW5nZSBDb3VudHkx @@ -50,7 +50,7 @@ JfUvYadSYxh3nblvA4OL+iEZiW8NE3hbW6WPXxvS7Euge0uWMPc4uEcnsE0ZVG3m -----END CERTIFICATE----- )EOF"; -static const char serverKey[] PROGMEM = R"EOF( +static const char serverKey[] PROGMEM = R"EOF( -----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEA9UoHBtn4oNKXjRgIOQ/rLxK/iI0a8Q5mDxhfuwa9//FkftSI IFY8UhGk2YNJpnfKOyYWqbqwuJhIZJ2sEIWp2301OnavuGBrpKOgBJJljgH2l/4Z @@ -80,15 +80,17 @@ gz5JWYhbD6c38khSzJb0pNXCo3EuYAVa36kDM96k1BtWuhRS10Q1VXk= -----END RSA PRIVATE KEY----- )EOF"; -const int led = 13; +const int led = 13; -void handleRoot() { +void handleRoot() +{ digitalWrite(led, 1); server.send(200, "text/plain", "Hello from esp8266 over HTTPS!"); digitalWrite(led, 0); } -void handleNotFound() { +void handleNotFound() +{ digitalWrite(led, 1); String message = "File Not Found\n\n"; message += "URI: "; @@ -98,14 +100,16 @@ void handleNotFound() { message += "\nArguments: "; message += server.args(); message += "\n"; - for (uint8_t i = 0; i < server.args(); i++) { + for (uint8_t i = 0; i < server.args(); i++) + { message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; } server.send(404, "text/plain", message); digitalWrite(led, 0); } -void setup(void) { +void setup(void) +{ pinMode(led, OUTPUT); digitalWrite(led, 0); Serial.begin(115200); @@ -113,7 +117,8 @@ void setup(void) { Serial.println(""); // Wait for connection - while (WiFi.status() != WL_CONNECTED) { + while (WiFi.status() != WL_CONNECTED) + { delay(500); Serial.print("."); } @@ -126,7 +131,8 @@ void setup(void) { Serial.print("IP address: "); Serial.println(WiFi.localIP()); - if (MDNS.begin("esp8266")) { + if (MDNS.begin("esp8266")) + { Serial.println("MDNS responder started"); } @@ -137,9 +143,8 @@ void setup(void) { server.on("/", handleRoot); - server.on("/inline", []() { - server.send(200, "text/plain", "this works as well"); - }); + server.on("/inline", []() + { server.send(200, "text/plain", "this works as well"); }); server.onNotFound(handleNotFound); @@ -149,19 +154,24 @@ void setup(void) { extern "C" void stack_thunk_dump_stack(); -void processKey(Print& out, int hotKey) { - switch (hotKey) { - case 'd': { +void processKey(Print& out, int hotKey) +{ + switch (hotKey) + { + case 'd': + { HeapSelectDram ephemeral; umm_info(NULL, true); break; } - case 'i': { + case 'i': + { HeapSelectIram ephemeral; umm_info(NULL, true); break; } - case 'h': { + case 'h': + { { HeapSelectIram ephemeral; Serial.printf(PSTR("IRAM ESP.getFreeHeap: %u\n"), ESP.getFreeHeap()); @@ -209,10 +219,12 @@ void processKey(Print& out, int hotKey) { } } -void loop(void) { +void loop(void) +{ server.handleClient(); MDNS.update(); - if (Serial.available() > 0) { + if (Serial.available() > 0) + { int hotKey = Serial.read(); processKey(Serial, hotKey); } diff --git a/libraries/ESP8266WebServer/examples/HttpAdvancedAuth/HttpAdvancedAuth.ino b/libraries/ESP8266WebServer/examples/HttpAdvancedAuth/HttpAdvancedAuth.ino index a3a01d4ced..23813a4159 100644 --- a/libraries/ESP8266WebServer/examples/HttpAdvancedAuth/HttpAdvancedAuth.ino +++ b/libraries/ESP8266WebServer/examples/HttpAdvancedAuth/HttpAdvancedAuth.ino @@ -14,43 +14,46 @@ #define STAPSK "your-password" #endif -const char* ssid = STASSID; -const char* password = STAPSK; +const char* ssid = STASSID; +const char* password = STAPSK; ESP8266WebServer server(80); -const char* www_username = "admin"; -const char* www_password = "esp8266"; +const char* www_username = "admin"; +const char* www_password = "esp8266"; // allows you to set the realm of authentication Default:"Login Required" -const char* www_realm = "Custom Auth Realm"; +const char* www_realm = "Custom Auth Realm"; // the Content of the HTML response in case of Unautherized Access Default:empty -String authFailResponse = "Authentication Failed"; +String authFailResponse = "Authentication Failed"; -void setup() { +void setup() +{ Serial.begin(115200); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); - if (WiFi.waitForConnectResult() != WL_CONNECTED) { + if (WiFi.waitForConnectResult() != WL_CONNECTED) + { Serial.println("WiFi Connect Failed! Rebooting..."); delay(1000); ESP.restart(); } ArduinoOTA.begin(); - server.on("/", []() { - if (!server.authenticate(www_username, www_password)) - //Basic Auth Method with Custom realm and Failure Response - //return server.requestAuthentication(BASIC_AUTH, www_realm, authFailResponse); - //Digest Auth Method with realm="Login Required" and empty Failure Response - //return server.requestAuthentication(DIGEST_AUTH); - //Digest Auth Method with Custom realm and empty Failure Response - //return server.requestAuthentication(DIGEST_AUTH, www_realm); - //Digest Auth Method with Custom realm and Failure Response - { - return server.requestAuthentication(DIGEST_AUTH, www_realm, authFailResponse); - } - server.send(200, "text/plain", "Login OK"); - }); + server.on("/", []() + { + if (!server.authenticate(www_username, www_password)) + //Basic Auth Method with Custom realm and Failure Response + //return server.requestAuthentication(BASIC_AUTH, www_realm, authFailResponse); + //Digest Auth Method with realm="Login Required" and empty Failure Response + //return server.requestAuthentication(DIGEST_AUTH); + //Digest Auth Method with Custom realm and empty Failure Response + //return server.requestAuthentication(DIGEST_AUTH, www_realm); + //Digest Auth Method with Custom realm and Failure Response + { + return server.requestAuthentication(DIGEST_AUTH, www_realm, authFailResponse); + } + server.send(200, "text/plain", "Login OK"); + }); server.begin(); Serial.print("Open http://"); @@ -58,7 +61,8 @@ void setup() { Serial.println("/ in your browser to see it working"); } -void loop() { +void loop() +{ ArduinoOTA.handle(); server.handleClient(); } diff --git a/libraries/ESP8266WebServer/examples/HttpBasicAuth/HttpBasicAuth.ino b/libraries/ESP8266WebServer/examples/HttpBasicAuth/HttpBasicAuth.ino index b7d5c16f41..7716fa4dca 100644 --- a/libraries/ESP8266WebServer/examples/HttpBasicAuth/HttpBasicAuth.ino +++ b/libraries/ESP8266WebServer/examples/HttpBasicAuth/HttpBasicAuth.ino @@ -8,31 +8,35 @@ #define STAPSK "your-password" #endif -const char* ssid = STASSID; -const char* password = STAPSK; +const char* ssid = STASSID; +const char* password = STAPSK; ESP8266WebServer server(80); -const char* www_username = "admin"; -const char* www_password = "esp8266"; +const char* www_username = "admin"; +const char* www_password = "esp8266"; -void setup() { +void setup() +{ Serial.begin(115200); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); - if (WiFi.waitForConnectResult() != WL_CONNECTED) { + if (WiFi.waitForConnectResult() != WL_CONNECTED) + { Serial.println("WiFi Connect Failed! Rebooting..."); delay(1000); ESP.restart(); } ArduinoOTA.begin(); - server.on("/", []() { - if (!server.authenticate(www_username, www_password)) { - return server.requestAuthentication(); - } - server.send(200, "text/plain", "Login OK"); - }); + server.on("/", []() + { + if (!server.authenticate(www_username, www_password)) + { + return server.requestAuthentication(); + } + server.send(200, "text/plain", "Login OK"); + }); server.begin(); Serial.print("Open http://"); @@ -40,7 +44,8 @@ void setup() { Serial.println("/ in your browser to see it working"); } -void loop() { +void loop() +{ ArduinoOTA.handle(); server.handleClient(); } diff --git a/libraries/ESP8266WebServer/examples/HttpHashCredAuth/HttpHashCredAuth.ino b/libraries/ESP8266WebServer/examples/HttpHashCredAuth/HttpHashCredAuth.ino index 2a9657e2fc..6bdb235db1 100644 --- a/libraries/ESP8266WebServer/examples/HttpHashCredAuth/HttpHashCredAuth.ino +++ b/libraries/ESP8266WebServer/examples/HttpHashCredAuth/HttpHashCredAuth.ino @@ -21,16 +21,16 @@ #define STAPSK "your-password" #endif -const char* ssid = STASSID; -const char* wifi_pw = STAPSK; +const char* ssid = STASSID; +const char* wifi_pw = STAPSK; -const String file_credentials = R"(/credentials.txt)"; // LittleFS file name for the saved credentials -const String change_creds = "changecreds"; // Address for a credential change +const String file_credentials = R"(/credentials.txt)"; // LittleFS file name for the saved credentials +const String change_creds = "changecreds"; // Address for a credential change //The ESP8266WebServerSecure requires an encryption certificate and matching key. //These can generated with the bash script available in the ESP8266 Arduino repository. //These values can be used for testing but are available publicly so should not be used in production. -static const char serverCert[] PROGMEM = R"EOF( +static const char serverCert[] PROGMEM = R"EOF( -----BEGIN CERTIFICATE----- MIIDSzCCAjMCCQD2ahcfZAwXxDANBgkqhkiG9w0BAQsFADCBiTELMAkGA1UEBhMC VVMxEzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU9yYW5nZSBDb3VudHkx @@ -52,7 +52,7 @@ JfUvYadSYxh3nblvA4OL+iEZiW8NE3hbW6WPXxvS7Euge0uWMPc4uEcnsE0ZVG3m 5tAF1D5vAAwA8nfPysumlLsIjohJZo4lgnhB++AlOg== -----END CERTIFICATE----- )EOF"; -static const char serverKey[] PROGMEM = R"EOF( +static const char serverKey[] PROGMEM = R"EOF( -----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEA9UoHBtn4oNKXjRgIOQ/rLxK/iI0a8Q5mDxhfuwa9//FkftSI IFY8UhGk2YNJpnfKOyYWqbqwuJhIZJ2sEIWp2301OnavuGBrpKOgBJJljgH2l/4Z @@ -85,16 +85,18 @@ gz5JWYhbD6c38khSzJb0pNXCo3EuYAVa36kDM96k1BtWuhRS10Q1VXk= ESP8266WebServerSecure server(443); //These are temporary credentials that will only be used if none are found saved in LittleFS. -String login = "admin"; -const String realm = "global"; -String H1 = ""; -String authentication_failed = "User authentication has failed."; +String login = "admin"; +const String realm = "global"; +String H1 = ""; +String authentication_failed = "User authentication has failed."; -void setup() { +void setup() +{ Serial.begin(115200); //Initialize LittleFS to save credentials - if (!LittleFS.begin()) { + if (!LittleFS.begin()) + { Serial.println("LittleFS initialization error, programmer flash configured?"); ESP.restart(); } @@ -105,15 +107,16 @@ void setup() { //Initialize wifi WiFi.mode(WIFI_STA); WiFi.begin(ssid, wifi_pw); - if (WiFi.waitForConnectResult() != WL_CONNECTED) { + if (WiFi.waitForConnectResult() != WL_CONNECTED) + { Serial.println("WiFi Connect Failed! Rebooting..."); delay(1000); ESP.restart(); } server.getServer().setRSACert(new BearSSL::X509List(serverCert), new BearSSL::PrivateKey(serverKey)); - server.on("/", showcredentialpage); //for this simple example, just show a simple page for changing credentials at the root - server.on("/" + change_creds, handlecredentialchange); //handles submission of credentials from the client + server.on("/", showcredentialpage); //for this simple example, just show a simple page for changing credentials at the root + server.on("/" + change_creds, handlecredentialchange); //handles submission of credentials from the client server.onNotFound(redirect); server.begin(); @@ -122,30 +125,36 @@ void setup() { Serial.println("/ in your browser to see it working"); } -void loop() { +void loop() +{ yield(); server.handleClient(); } //This function redirects home -void redirect() { +void redirect() +{ String url = "https://" + WiFi.localIP().toString(); Serial.println("Redirect called. Redirecting to " + url); server.sendHeader("Location", url, true); Serial.println("Header sent."); - server.send(302, "text/plain", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. + server.send(302, "text/plain", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. Serial.println("Empty page sent."); - server.client().stop(); // Stop is needed because we sent no content length + server.client().stop(); // Stop is needed because we sent no content length Serial.println("Client stopped."); } //This function checks whether the current session has been authenticated. If not, a request for credentials is sent. -bool session_authenticated() { +bool session_authenticated() +{ Serial.println("Checking authentication."); - if (server.authenticateDigest(login, H1)) { + if (server.authenticateDigest(login, H1)) + { Serial.println("Authentication confirmed."); return true; - } else { + } + else + { Serial.println("Not authenticated. Requesting credentials."); server.requestAuthentication(DIGEST_AUTH, realm.c_str(), authentication_failed); redirect(); @@ -154,9 +163,11 @@ bool session_authenticated() { } //This function sends a simple webpage for changing login credentials to the client -void showcredentialpage() { +void showcredentialpage() +{ Serial.println("Show credential page called."); - if (!session_authenticated()) { + if (!session_authenticated()) + { return; } @@ -189,15 +200,17 @@ void showcredentialpage() { } //Saves credentials to LittleFS -void savecredentials(String new_login, String new_password) { +void savecredentials(String new_login, String new_password) +{ //Set global variables to new values login = new_login; - H1 = ESP8266WebServer::credentialHash(new_login, realm, new_password); + H1 = ESP8266WebServer::credentialHash(new_login, realm, new_password); //Save new values to LittleFS for loading on next reboot Serial.println("Saving credentials."); - File f = LittleFS.open(file_credentials, "w"); //open as a brand new file, discard old contents - if (f) { + File f = LittleFS.open(file_credentials, "w"); //open as a brand new file, discard old contents + if (f) + { Serial.println("Modifying credentials in file system."); f.println(login); f.println(H1); @@ -209,48 +222,56 @@ void savecredentials(String new_login, String new_password) { } //loads credentials from LittleFS -void loadcredentials() { +void loadcredentials() +{ Serial.println("Searching for credentials."); File f; f = LittleFS.open(file_credentials, "r"); - if (f) { + if (f) + { Serial.println("Loading credentials from file system."); - String mod = f.readString(); //read the file to a String - int index_1 = mod.indexOf('\n', 0); //locate the first line break - int index_2 = mod.indexOf('\n', index_1 + 1); //locate the second line break - login = mod.substring(0, index_1 - 1); //get the first line (excluding the line break) - H1 = mod.substring(index_1 + 1, index_2 - 1); //get the second line (excluding the line break) + String mod = f.readString(); //read the file to a String + int index_1 = mod.indexOf('\n', 0); //locate the first line break + int index_2 = mod.indexOf('\n', index_1 + 1); //locate the second line break + login = mod.substring(0, index_1 - 1); //get the first line (excluding the line break) + H1 = mod.substring(index_1 + 1, index_2 - 1); //get the second line (excluding the line break) f.close(); - } else { - String default_login = "admin"; + } + else + { + String default_login = "admin"; String default_password = "changeme"; Serial.println("None found. Setting to default credentials."); Serial.println("user:" + default_login); Serial.println("password:" + default_password); login = default_login; - H1 = ESP8266WebServer::credentialHash(default_login, realm, default_password); + H1 = ESP8266WebServer::credentialHash(default_login, realm, default_password); } } //This function handles a credential change from a client. -void handlecredentialchange() { +void handlecredentialchange() +{ Serial.println("Handle credential change called."); - if (!session_authenticated()) { + if (!session_authenticated()) + { return; } Serial.println("Handling credential change request from client."); String login = server.arg("login"); - String pw1 = server.arg("password"); - String pw2 = server.arg("password_duplicate"); - - if (login != "" && pw1 != "" && pw1 == pw2) { + String pw1 = server.arg("password"); + String pw2 = server.arg("password_duplicate"); + if (login != "" && pw1 != "" && pw1 == pw2) + { savecredentials(login, pw1); server.send(200, "text/plain", "Credentials updated"); redirect(); - } else { + } + else + { server.send(200, "text/plain", "Malformed credentials"); redirect(); } diff --git a/libraries/ESP8266WebServer/examples/PathArgServer/PathArgServer.ino b/libraries/ESP8266WebServer/examples/PathArgServer/PathArgServer.ino index e27973cab2..7866659234 100644 --- a/libraries/ESP8266WebServer/examples/PathArgServer/PathArgServer.ino +++ b/libraries/ESP8266WebServer/examples/PathArgServer/PathArgServer.ino @@ -11,19 +11,21 @@ #define STAPSK "your-password" #endif -const char* ssid = STASSID; -const char* password = STAPSK; +const char* ssid = STASSID; +const char* password = STAPSK; ESP8266WebServer server(80); -void setup(void) { +void setup(void) +{ Serial.begin(115200); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); Serial.println(""); // Wait for connection - while (WiFi.status() != WL_CONNECTED) { + while (WiFi.status() != WL_CONNECTED) + { delay(500); Serial.print("."); } @@ -33,29 +35,32 @@ void setup(void) { Serial.print("IP address: "); Serial.println(WiFi.localIP()); - if (MDNS.begin("esp8266")) { + if (MDNS.begin("esp8266")) + { Serial.println("MDNS responder started"); } - server.on(F("/"), []() { - server.send(200, "text/plain", "hello from esp8266!"); - }); + server.on(F("/"), []() + { server.send(200, "text/plain", "hello from esp8266!"); }); - server.on(UriBraces("/users/{}"), []() { - String user = server.pathArg(0); - server.send(200, "text/plain", "User: '" + user + "'"); - }); + server.on(UriBraces("/users/{}"), []() + { + String user = server.pathArg(0); + server.send(200, "text/plain", "User: '" + user + "'"); + }); - server.on(UriRegex("^\\/users\\/([0-9]+)\\/devices\\/([0-9]+)$"), []() { - String user = server.pathArg(0); - String device = server.pathArg(1); - server.send(200, "text/plain", "User: '" + user + "' and Device: '" + device + "'"); - }); + server.on(UriRegex("^\\/users\\/([0-9]+)\\/devices\\/([0-9]+)$"), []() + { + String user = server.pathArg(0); + String device = server.pathArg(1); + server.send(200, "text/plain", "User: '" + user + "' and Device: '" + device + "'"); + }); server.begin(); Serial.println("HTTP server started"); } -void loop(void) { +void loop(void) +{ server.handleClient(); } diff --git a/libraries/ESP8266WebServer/examples/PostServer/PostServer.ino b/libraries/ESP8266WebServer/examples/PostServer/PostServer.ino index 6c787794e5..e25ce3fb72 100644 --- a/libraries/ESP8266WebServer/examples/PostServer/PostServer.ino +++ b/libraries/ESP8266WebServer/examples/PostServer/PostServer.ino @@ -8,14 +8,14 @@ #define STAPSK "your-password" #endif -const char* ssid = STASSID; -const char* password = STAPSK; +const char* ssid = STASSID; +const char* password = STAPSK; ESP8266WebServer server(80); -const int led = LED_BUILTIN; +const int led = LED_BUILTIN; -const String postForms = "\ +const String postForms = "\ \ ESP8266 Web Server POST handling\