From 19b7a29720a6f2c95d06e2ea4baa335dcf32e68f Mon Sep 17 00:00:00 2001 From: Maxim Prokhorov Date: Sun, 20 Feb 2022 19:23:33 +0300 Subject: [PATCH] Migrate from astyle to clang-format (#8464) --- .github/workflows/pull-request.yml | 11 +- cores/esp8266/LwipDhcpServer-NonOS.cpp | 7 +- cores/esp8266/LwipDhcpServer.cpp | 525 ++- cores/esp8266/LwipDhcpServer.h | 79 +- cores/esp8266/LwipIntf.cpp | 27 +- cores/esp8266/LwipIntf.h | 14 +- cores/esp8266/LwipIntfCB.cpp | 18 +- cores/esp8266/LwipIntfDev.h | 117 +- cores/esp8266/StreamSend.cpp | 67 +- cores/esp8266/StreamString.h | 75 +- cores/esp8266/core_esp8266_si2c.cpp | 317 +- cores/esp8266/debug.cpp | 2 +- cores/esp8266/debug.h | 46 +- .../ArduinoOTA/examples/BasicOTA/BasicOTA.ino | 4 +- .../ArduinoOTA/examples/OTALeds/OTALeds.ino | 9 +- .../CaptivePortalAdvanced.ino | 24 +- .../CaptivePortalAdvanced/handleHttp.ino | 74 +- .../examples/CaptivePortalAdvanced/tools.ino | 9 +- .../examples/eeprom_clear/eeprom_clear.ino | 7 +- .../examples/eeprom_read/eeprom_read.ino | 4 +- .../Arduino_Wifi_AVRISP.ino | 21 +- .../examples/Authorization/Authorization.ino | 1 - .../BasicHttpClient/BasicHttpClient.ino | 1 - .../BasicHttpsClient/BasicHttpsClient.ino | 4 +- .../DigestAuthorization.ino | 32 +- .../PostHttpClient/PostHttpClient.ino | 5 +- .../ReuseConnectionV2/ReuseConnectionV2.ino | 10 +- .../StreamHttpClient/StreamHttpClient.ino | 15 +- .../StreamHttpsClient/StreamHttpsClient.ino | 12 +- .../SecureBearSSLUpdater.ino | 19 +- .../SecureWebUpdater/SecureWebUpdater.ino | 2 +- .../examples/WebUpdater/WebUpdater.ino | 2 +- .../LLMNR_Web_Server/LLMNR_Web_Server.ino | 2 +- .../examples/ESP_NBNST/ESP_NBNST.ino | 2 +- libraries/ESP8266SSDP/examples/SSDP/SSDP.ino | 6 +- .../AdvancedWebServer/AdvancedWebServer.ino | 14 +- .../examples/FSBrowser/FSBrowser.ino | 149 +- .../ESP8266WebServer/examples/Graph/Graph.ino | 50 +- .../examples/HelloServer/HelloServer.ino | 26 +- .../HelloServerBearSSL/HelloServerBearSSL.ino | 37 +- .../HttpAdvancedAuth/HttpAdvancedAuth.ino | 16 +- .../examples/HttpBasicAuth/HttpBasicAuth.ino | 2 +- .../HttpHashCredAuth/HttpHashCredAuth.ino | 118 +- .../examples/PathArgServer/PathArgServer.ino | 6 +- .../examples/PostServer/PostServer.ino | 16 +- .../ServerSentEvents/ServerSentEvents.ino | 64 +- .../SimpleAuthentication.ino | 22 +- .../examples/WebServer/WebServer.ino | 170 +- .../examples/WebUpdate/WebUpdate.ino | 58 +- .../BearSSL_CertStore/BearSSL_CertStore.ino | 21 +- .../BearSSL_MaxFragmentLength.ino | 14 +- .../BearSSL_Server/BearSSL_Server.ino | 53 +- .../BearSSL_ServerClientCert.ino | 44 +- .../BearSSL_Sessions/BearSSL_Sessions.ino | 17 +- .../BearSSL_Validation/BearSSL_Validation.ino | 14 +- .../examples/HTTPSRequest/HTTPSRequest.ino | 10 +- libraries/ESP8266WiFi/examples/IPv6/IPv6.ino | 53 +- .../examples/NTPClient/NTPClient.ino | 50 +- .../examples/PagerServer/PagerServer.ino | 20 +- .../RangeExtender-NAPT/RangeExtender-NAPT.ino | 25 +- libraries/ESP8266WiFi/examples/Udp/Udp.ino | 17 +- .../WiFiAccessPoint/WiFiAccessPoint.ino | 2 +- .../examples/WiFiClient/WiFiClient.ino | 10 +- .../WiFiClientBasic/WiFiClientBasic.ino | 7 +- .../examples/WiFiEcho/WiFiEcho.ino | 54 +- .../examples/WiFiEvents/WiFiEvents.ino | 7 +- .../WiFiManualWebServer.ino | 8 +- .../examples/WiFiScan/WiFiScan.ino | 10 +- .../examples/WiFiShutdown/WiFiShutdown.ino | 15 +- .../WiFiTelnetToSerial/WiFiTelnetToSerial.ino | 32 +- .../examples/HelloEspnow/HelloEspnow.ino | 68 +- .../examples/HelloMesh/HelloMesh.ino | 54 +- .../examples/HelloTcpIp/HelloTcpIp.ino | 21 +- .../examples/httpUpdate/httpUpdate.ino | 19 +- .../httpUpdateLittleFS/httpUpdateLittleFS.ino | 16 +- .../httpUpdateSecure/httpUpdateSecure.ino | 22 +- .../httpUpdateSigned/httpUpdateSigned.ino | 23 +- .../LEAmDNS/mDNS_Clock/mDNS_Clock.ino | 39 +- .../mDNS_ServiceMonitor.ino | 69 +- .../OTA-mDNS-LittleFS/OTA-mDNS-LittleFS.ino | 27 +- .../mDNS-SD_Extended/mDNS-SD_Extended.ino | 14 +- .../mDNS_Web_Server/mDNS_Web_Server.ino | 15 +- libraries/ESP8266mDNS/src/ESP8266mDNS.cpp | 1 - libraries/ESP8266mDNS/src/ESP8266mDNS.h | 18 +- libraries/ESP8266mDNS/src/LEAmDNS.cpp | 2169 +++++----- libraries/ESP8266mDNS/src/LEAmDNS.h | 2237 +++++----- libraries/ESP8266mDNS/src/LEAmDNS_Control.cpp | 3569 ++++++++-------- libraries/ESP8266mDNS/src/LEAmDNS_Helpers.cpp | 1148 +++-- libraries/ESP8266mDNS/src/LEAmDNS_Priv.h | 79 +- libraries/ESP8266mDNS/src/LEAmDNS_Structs.cpp | 3793 ++++++++--------- .../ESP8266mDNS/src/LEAmDNS_Transfer.cpp | 2974 ++++++------- libraries/ESP8266mDNS/src/LEAmDNS_lwIPdefs.h | 2 +- libraries/Hash/examples/sha1/sha1.ino | 4 +- .../InputSerialPlotter/InputSerialPlotter.ino | 5 +- .../I2S/examples/SimpleTone/SimpleTone.ino | 14 +- .../LittleFS_Timestamp/LittleFS_Timestamp.ino | 29 +- .../LittleFS/examples/SpeedTest/SpeedTest.ino | 22 +- .../Netdump/examples/Netdump/Netdump.ino | 92 +- libraries/Netdump/src/Netdump.cpp | 82 +- libraries/Netdump/src/Netdump.h | 24 +- libraries/Netdump/src/NetdumpIP.cpp | 67 +- libraries/Netdump/src/NetdumpIP.h | 23 +- libraries/Netdump/src/NetdumpPacket.cpp | 162 +- libraries/Netdump/src/NetdumpPacket.h | 55 +- libraries/Netdump/src/PacketType.cpp | 61 +- libraries/Netdump/src/PacketType.h | 1 - .../SD/examples/Datalogger/Datalogger.ino | 17 +- libraries/SD/examples/DumpFile/DumpFile.ino | 12 +- libraries/SD/examples/Files/Files.ino | 3 - libraries/SD/examples/ReadWrite/ReadWrite.ino | 6 +- libraries/SD/examples/listfiles/listfiles.ino | 10 +- .../SPISlave_Master/SPISlave_Master.ino | 107 +- .../SPISlave_SafeMaster.ino | 118 +- .../examples/SPISlave_Test/SPISlave_Test.ino | 6 +- libraries/Servo/examples/Sweep/Sweep.ino | 13 +- .../examples/drawCircle/drawCircle.ino | 16 +- .../examples/drawLines/drawLines.ino | 14 +- .../examples/drawNumber/drawNumber.ino | 23 +- .../examples/drawRectangle/drawRectangle.ino | 4 +- .../examples/paint/paint.ino | 16 +- .../examples/shapes/shapes.ino | 8 +- .../examples/text/text.ino | 20 +- .../examples/tftbmp/tftbmp.ino | 47 +- .../examples/tftbmp2/tftbmp2.ino | 89 +- .../examples/TickerBasic/TickerBasic.ino | 7 +- .../TickerFunctional/TickerFunctional.ino | 40 +- .../TickerParameter/TickerParameter.ino | 3 +- libraries/Wire/Wire.cpp | 49 +- libraries/Wire/Wire.h | 51 +- .../examples/master_reader/master_reader.ino | 12 +- .../examples/master_writer/master_writer.ino | 10 +- .../slave_receiver/slave_receiver.ino | 21 +- .../examples/slave_sender/slave_sender.ino | 9 +- libraries/esp8266/examples/Blink/Blink.ino | 4 +- .../BlinkPolledTimeout/BlinkPolledTimeout.ino | 34 +- .../examples/CallBackList/CallBackGeneric.ino | 31 +- .../examples/CheckFlashCRC/CheckFlashCRC.ino | 11 +- .../CheckFlashConfig/CheckFlashConfig.ino | 5 +- .../examples/ConfigFile/ConfigFile.ino | 3 +- .../FadePolledTimeout/FadePolledTimeout.ino | 10 +- .../examples/HeapMetric/HeapMetric.ino | 32 +- .../examples/HelloCrypto/HelloCrypto.ino | 14 +- .../examples/HwdtStackDump/HwdtStackDump.ino | 14 +- .../examples/HwdtStackDump/ProcessKey.ino | 15 +- .../esp8266/examples/I2SInput/I2SInput.ino | 2 +- .../examples/I2STransmit/I2STransmit.ino | 17 +- .../examples/IramReserve/IramReserve.ino | 22 +- .../examples/IramReserve/ProcessKey.ino | 15 +- .../examples/LowPowerDemo/LowPowerDemo.ino | 176 +- libraries/esp8266/examples/MMU48K/MMU48K.ino | 53 +- .../examples/NTP-TZ-DST/NTP-TZ-DST.ino | 64 +- .../examples/RTCUserMemory/RTCUserMemory.ino | 25 +- .../SerialDetectBaudrate.ino | 8 +- .../examples/SerialStress/SerialStress.ino | 110 +- .../SigmaDeltaDemo/SigmaDeltaDemo.ino | 6 +- .../examples/StreamString/StreamString.ino | 7 +- .../examples/TestEspApi/TestEspApi.ino | 98 +- .../examples/UartDownload/UartDownload.ino | 25 +- .../examples/interactive/interactive.ino | 39 +- .../esp8266/examples/irammem/irammem.ino | 161 +- .../examples/virtualmem/virtualmem.ino | 36 +- .../lwIP_PPP/examples/PPPServer/PPPServer.ino | 27 +- libraries/lwIP_PPP/src/PPPServer.cpp | 64 +- libraries/lwIP_PPP/src/PPPServer.h | 18 +- libraries/lwIP_enc28j60/src/ENC28J60lwIP.h | 2 +- .../lwIP_enc28j60/src/utility/enc28j60.cpp | 158 +- .../lwIP_enc28j60/src/utility/enc28j60.h | 41 +- libraries/lwIP_w5100/src/W5100lwIP.h | 2 +- libraries/lwIP_w5100/src/utility/w5100.cpp | 50 +- libraries/lwIP_w5100/src/utility/w5100.h | 198 +- .../examples/TCPClient/TCPClient.ino | 22 +- libraries/lwIP_w5500/src/W5500lwIP.h | 2 +- libraries/lwIP_w5500/src/utility/w5500.cpp | 35 +- libraries/lwIP_w5500/src/utility/w5500.h | 265 +- tests/astyle_core.conf | 32 - tests/astyle_examples.conf | 44 - tests/ci/style_check.sh | 8 +- tests/clang-format-arduino.yaml | 149 + tests/clang-format-core.yaml | 29 + tests/device/libraries/BSTest/src/BSArduino.h | 42 +- tests/device/libraries/BSTest/src/BSArgs.h | 268 +- .../device/libraries/BSTest/src/BSProtocol.h | 186 +- tests/device/libraries/BSTest/src/BSStdio.h | 19 +- tests/device/libraries/BSTest/src/BSTest.h | 134 +- tests/device/libraries/BSTest/test/test.cpp | 20 +- tests/device/test_libc/libm_string.c | 898 ++-- tests/device/test_libc/memcpy-1.c | 178 +- tests/device/test_libc/memmove1.c | 196 +- tests/device/test_libc/strcmp-1.c | 328 +- tests/device/test_libc/tstring.c | 487 +-- tests/host/common/Arduino.cpp | 41 +- tests/host/common/ArduinoCatch.cpp | 5 +- tests/host/common/ArduinoMain.cpp | 484 +-- tests/host/common/ArduinoMainLittlefs.cpp | 13 +- tests/host/common/ArduinoMainSpiffs.cpp | 13 +- tests/host/common/ArduinoMainUdp.cpp | 38 +- tests/host/common/ClientContextSocket.cpp | 255 +- tests/host/common/ClientContextTools.cpp | 27 +- tests/host/common/EEPROM.h | 71 +- tests/host/common/HostWiring.cpp | 76 +- tests/host/common/MockEEPROM.cpp | 52 +- tests/host/common/MockEsp.cpp | 209 +- tests/host/common/MockSPI.cpp | 18 +- tests/host/common/MockTools.cpp | 111 +- tests/host/common/MockUART.cpp | 784 ++-- tests/host/common/MockWiFiServer.cpp | 25 +- tests/host/common/MockWiFiServerSocket.cpp | 143 +- tests/host/common/MocklwIP.cpp | 106 +- tests/host/common/MocklwIP.h | 7 +- tests/host/common/UdpContextSocket.cpp | 313 +- tests/host/common/WMath.cpp | 38 +- tests/host/common/c_types.h | 82 +- tests/host/common/esp8266_peri.h | 4 +- tests/host/common/flash_hal.h | 18 +- tests/host/common/flash_hal_mock.cpp | 26 +- tests/host/common/include/ClientContext.h | 88 +- tests/host/common/include/UdpContext.h | 56 +- tests/host/common/littlefs_mock.cpp | 27 +- tests/host/common/littlefs_mock.h | 23 +- tests/host/common/md5.c | 252 +- tests/host/common/mock.h | 98 +- tests/host/common/noniso.c | 77 +- tests/host/common/pins_arduino.h | 5 +- tests/host/common/queue.h | 667 +-- tests/host/common/sdfs_mock.cpp | 2 +- tests/host/common/sdfs_mock.h | 30 +- tests/host/common/spiffs_mock.cpp | 25 +- tests/host/common/spiffs_mock.h | 23 +- tests/host/common/strl.cpp | 28 +- tests/host/common/user_interface.cpp | 120 +- tests/host/core/test_PolledTimeout.cpp | 306 +- tests/host/core/test_Print.cpp | 28 +- tests/host/core/test_Updater.cpp | 5 +- tests/host/core/test_md5builder.cpp | 39 +- tests/host/core/test_pgmspace.cpp | 7 +- tests/host/core/test_string.cpp | 557 +-- tests/host/fs/test_fs.cpp | 53 +- tests/host/sys/pgmspace.h | 64 +- tests/restyle-examples-only.sh | 19 - tests/restyle.sh | 78 +- tests/run_CI_locally.sh | 3 +- 241 files changed, 15428 insertions(+), 15700 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.yaml create mode 100644 tests/clang-format-core.yaml delete mode 100755 tests/restyle-examples-only.sh diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 74f1b43063..1f3e12a3b7 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -238,11 +238,20 @@ jobs: python-version: '3.x' - name: Style check env: + LLVM_SNAPSHOT_KEY: "6084F3CF814B57C1CF12EFD515CF4D18AF4F7421" TRAVIS_BUILD_DIR: ${{ github.workspace }} TRAVIS_TAG: ${{ github.ref }} run: | + export GNUPGHOME=$(mktemp -d) + gpg --batch --keyserver keyserver.ubuntu.com --recv-keys "$LLVM_SNAPSHOT_KEY" + gpg --batch --armor --export "$LLVM_SNAPSHOT_KEY" | \ + sudo tee /etc/apt/trusted.gpg.d/llvm-snapshot.gpg.asc + rm -r $GNUPGHOME + echo "deb http://apt.llvm.org/focal/ llvm-toolchain-focal-13 main" | \ + sudo tee /etc/apt/sources.list.d/llvm.list sudo apt update - sudo apt install astyle + sudo apt install clang-format-13 + pip3 install pyyaml 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..07270bb6c2 100644 --- a/cores/esp8266/LwipDhcpServer.cpp +++ b/cores/esp8266/LwipDhcpServer.cpp @@ -34,9 +34,9 @@ // (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 @@ -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,50 +103,49 @@ 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 +#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,32 +154,41 @@ 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; + pcb_dhcps = nullptr; dns_address.addr = 0; - plist = nullptr; - offer = 0xFF; - renew = false; - dhcps_lease_time = DHCPS_LEASE_TIME_DEF; //minute + 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) { @@ -188,14 +196,13 @@ DhcpServer::DhcpServer(netif* netif): _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 + fw_has_started_softap_dhcps = 2; // not 1, ending initial boot sequence } }; @@ -217,25 +224,25 @@ 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; } 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 { @@ -245,7 +252,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; @@ -266,9 +273,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) @@ -279,7 +286,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 @@ -288,7 +295,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; @@ -303,13 +310,13 @@ 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; + uint32 end_ip = dhcps_lease.end_ip.addr; for (pback_node = plist; pback_node != nullptr; pback_node = pback_node->pnext) { @@ -335,15 +342,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; @@ -359,9 +366,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,15 +382,15 @@ 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; + // struct ipv4_addr ipadd; + // ipadd.addr = server_address.addr; #define ipadd (_netif->ip_addr) - //struct ip_info if_ip; - //bzero(&if_ip, sizeof(struct ip_info)); - //wifi_get_ip_info(SOFTAP_IF, &if_ip); + // struct ip_info if_ip; + // bzero(&if_ip, sizeof(struct ip_info)); + // wifi_get_ip_info(SOFTAP_IF, &if_ip); #define if_ip (*_netif) *optptr++ = DHCP_OPTION_SUBNET_MASK; @@ -448,19 +454,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,35 +489,34 @@ 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; client.addr = client_address.addr; - m->op = DHCP_REPLY; + m->op = DHCP_REPLY; m->htype = DHCP_HTYPE_ETHERNET; - m->hlen = 6; - m->hops = 0; - m->secs = 0; + 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)); - 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,13 +525,13 @@ 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; - 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); @@ -539,7 +544,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 +552,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 +563,6 @@ void DhcpServer::send_offer(struct dhcps_msg *m) } else { - #if DHCPS_DEBUG os_printf("dhcps: send_offer>>pbuf_alloc failed\n"); #endif @@ -586,14 +589,13 @@ 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; - 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); @@ -605,7 +607,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 +615,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 +626,6 @@ void DhcpServer::send_nak(struct dhcps_msg *m) } else { - #if DHCPS_DEBUG os_printf("dhcps: send_nak>>pbuf_alloc failed\n"); #endif @@ -647,14 +647,13 @@ 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; - 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); @@ -667,7 +666,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 +674,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,13 +685,13 @@ void DhcpServer::send_ack(struct dhcps_msg *m) } else { - #if DHCPS_DEBUG os_printf("dhcps: send_ack>>pbuf_alloc failed\n"); #endif return; } - if (!LWIP_IS_OK("dhcps send ack", udp_sendto(pcb_dhcps, p, &broadcast_dhcps, DHCPS_CLIENT_PORT))) + if (!LWIP_IS_OK("dhcps send ack", + udp_sendto(pcb_dhcps, p, &broadcast_dhcps, DHCPS_CLIENT_PORT))) { #if DHCPS_DEBUG os_printf("dhcps: send_ack>>udp_sendto\n"); @@ -718,15 +716,15 @@ 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; + struct ipv4_addr client; + bool is_dhcp_parse_end = false; struct dhcps_state s; 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,16 +734,15 @@ 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 + 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"); @@ -777,14 +774,14 @@ uint8_t DhcpServer::parse_options(uint8_t *optptr, sint16_t len) switch (type) { - case DHCPDISCOVER://1 + case DHCPDISCOVER: // 1 s.state = DHCPS_STATE_OFFER; #if DHCPS_DEBUG os_printf("dhcps: DHCPD_STATE_OFFER\n"); #endif break; - case DHCPREQUEST://3 + case DHCPREQUEST: // 3 if (!(s.state == DHCPS_STATE_ACK || s.state == DHCPS_STATE_NAK)) { if (renew == true) @@ -801,14 +798,14 @@ uint8_t DhcpServer::parse_options(uint8_t *optptr, sint16_t len) } break; - case DHCPDECLINE://4 + case DHCPDECLINE: // 4 s.state = DHCPS_STATE_IDLE; #if DHCPS_DEBUG os_printf("dhcps: DHCPD_STATE_IDLE\n"); #endif break; - case DHCPRELEASE://7 + case DHCPRELEASE: // 7 s.state = DHCPS_STATE_RELEASE; #if DHCPS_DEBUG os_printf("dhcps: DHCPD_STATE_IDLE\n"); @@ -822,11 +819,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, - &magic_cookie, - sizeof(magic_cookie)) == 0) + if (memcmp((char*)m->options, &magic_cookie, sizeof(magic_cookie)) == 0) { struct ipv4_addr ip; memcpy(&ip.addr, m->ciaddr, sizeof(ip.addr)); @@ -836,7 +831,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,32 +852,26 @@ 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, - const ip_addr_t *addr, - uint16_t port) +void DhcpServer::handle_dhcp(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; - 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"); @@ -892,15 +881,15 @@ 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; - tlen = p->tot_len; - data = (u8_t*)p->payload; + p_dhcps_msg = (u8_t*)pmsg_dhcps; + tlen = p->tot_len; + data = (u8_t*)p->payload; #if DHCPS_DEBUG os_printf("dhcps: handle_dhcp-> p->tot_len = %d\n", tlen); @@ -933,14 +922,13 @@ 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"); #endif send_offer(pmsg_dhcps); break; - case DHCPS_STATE_ACK://3 + case DHCPS_STATE_ACK: // 3 #if DHCPS_DEBUG os_printf("dhcps: handle_dhcp-> DHCPD_STATE_ACK\n"); #endif @@ -950,13 +938,13 @@ void DhcpServer::handle_dhcp( wifi_softap_set_station_info(pmsg_dhcps->chaddr, &client_address); } break; - case DHCPS_STATE_NAK://4 + case DHCPS_STATE_NAK: // 4 #if DHCPS_DEBUG os_printf("dhcps: handle_dhcp-> DHCPD_STATE_NAK\n"); #endif send_nak(pmsg_dhcps); break; - default : + default: break; } #if DHCPS_DEBUG @@ -971,12 +959,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)) { @@ -987,7 +975,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)) + || (end_ip - start_ip > DHCPS_MAX_LEASE)) { dhcps_lease.enable = false; } @@ -1005,14 +993,14 @@ void DhcpServer::init_dhcps_lease(uint32 ip) } else { - local_ip ++; + local_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); @@ -1020,7 +1008,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) { @@ -1040,7 +1028,7 @@ bool DhcpServer::begin(struct ip_info *info) broadcast_dhcps = _netif->ip_addr; ip_2_ip4(&broadcast_dhcps)->addr &= ip_2_ip4(&_netif->netmask)->addr; ip_2_ip4(&broadcast_dhcps)->addr |= ~ip_2_ip4(&_netif->netmask)->addr; - //XXXFIXMEIPV6 broadcast address? + // XXXFIXMEIPV6 broadcast address? server_address = info->ip; init_dhcps_lease(server_address.addr); @@ -1048,14 +1036,15 @@ bool DhcpServer::begin(struct ip_info *info) udp_bind(pcb_dhcps, IP_ADDR_ANY, DHCPS_SERVER_PORT); udp_recv(pcb_dhcps, S_handle_dhcp, this); #if DHCPS_DEBUG - os_printf("dhcps:dhcps_start->udp_recv function Set a receive callback handle_dhcp for UDP_PCB pcb_dhcps\n"); + os_printf("dhcps:dhcps_start->udp_recv function Set a receive callback handle_dhcp for UDP_PCB " + "pcb_dhcps\n"); #endif 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; } @@ -1076,21 +1065,21 @@ void DhcpServer::end() udp_remove(pcb_dhcps); 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; + // udp_remove(pcb_dhcps); + 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 + // dhcps_client_leave(dhcp_node->mac,&dhcp_node->ip,true); // force to delete if (_netif->num == SOFTAP_IF) { wifi_softap_set_station_info(dhcp_node->mac, &ip_zero); @@ -1107,7 +1096,6 @@ bool DhcpServer::isRunning() return !!_netif->state; } - /****************************************************************************** FunctionName : set_dhcps_lease Description : set the lease information of DHCP server @@ -1115,11 +1103,11 @@ 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; - uint32 end_ip = 0; + uint32 start_ip = 0; + uint32 end_ip = 0; if (_netif->num == SOFTAP_IF || _netif->num == STATION_IF) { @@ -1141,8 +1129,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)) { @@ -1151,8 +1139,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; } @@ -1166,7 +1153,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; @@ -1180,7 +1167,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) { @@ -1219,32 +1206,33 @@ 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; pdhcps_pool->state = DHCPS_STATE_OFFLINE; + minpre->pnext = minp->pnext; + pdhcps_pool->state = DHCPS_STATE_OFFLINE; free(minp->pnode); minp->pnode = nullptr; free(minp); @@ -1253,22 +1241,22 @@ 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; if (pdhcps_pool->type == DHCPS_TYPE_DYNAMIC) { - pdhcps_pool->lease_timer --; + pdhcps_pool->lease_timer--; } 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; @@ -1277,8 +1265,8 @@ void DhcpServer::dhcps_coarse_tmr(void) } else { - pnode = pnode ->pnext; - num_dhcps_pool ++; + pnode = pnode->pnext; + num_dhcps_pool++; } } @@ -1291,7 +1279,7 @@ void DhcpServer::dhcps_coarse_tmr(void) bool DhcpServer::set_dhcps_offer_option(uint8 level, void* optarg) { bool offer_flag = true; - //uint8 option = 0; + // uint8 option = 0; if (optarg == nullptr && !isRunning()) { return false; @@ -1305,10 +1293,10 @@ 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 : + default: offer_flag = false; break; } @@ -1358,15 +1346,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,16 +1400,16 @@ 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; - 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; + 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; if (bssid == nullptr) { return IPADDR_ANY; @@ -1447,7 +1435,7 @@ uint32 DhcpServer::dhcps_client_update(u8 *bssid, struct ipv4_addr *ip) for (pback_node = plist; pback_node != nullptr; pback_node = pback_node->pnext) { pdhcps_pool = (struct dhcps_pool*)pback_node->pnode; - //os_printf("mac:"MACSTR"bssid:"MACSTR"\r\n",MAC2STR(pdhcps_pool->mac),MAC2STR(bssid)); + // os_printf("mac:"MACSTR"bssid:"MACSTR"\r\n",MAC2STR(pdhcps_pool->mac),MAC2STR(bssid)); if (memcmp(pdhcps_pool->mac, bssid, sizeof(pdhcps_pool->mac)) == 0) { pmac_node = pback_node; @@ -1496,12 +1484,12 @@ uint32 DhcpServer::dhcps_client_update(u8 *bssid, struct ipv4_addr *ip) { return IPADDR_ANY; } - //start_ip = htonl((ntohl(start_ip) + 1)); + // start_ip = htonl((ntohl(start_ip) + 1)); flag = true; } } - if (pmac_node != nullptr) // update new ip + if (pmac_node != nullptr) // update new ip { if (pip_node != nullptr) { @@ -1525,13 +1513,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 { @@ -1544,21 +1531,21 @@ 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; } 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); } } - 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) @@ -1567,12 +1554,12 @@ 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 { - 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 +1568,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; @@ -1593,11 +1580,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 e93166981d..d5eb6410ef 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: - DhcpServer(netif* netif); ~DhcpServer(); @@ -53,72 +52,64 @@ 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); 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, - 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 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 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; + uint32 dhcps_lease_time; struct dhcps_lease dhcps_lease; - list_node *plist; - uint8 offer; - bool renew; + 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__ +#endif // __DHCPS_H__ diff --git a/cores/esp8266/LwipIntf.cpp b/cores/esp8266/LwipIntf.cpp index b4a4807b9a..6b84aab16d 100644 --- a/cores/esp8266/LwipIntf.cpp +++ b/cores/esp8266/LwipIntf.cpp @@ -1,12 +1,13 @@ -extern "C" { +extern "C" +{ #include "lwip/err.h" #include "lwip/ip_addr.h" #include "lwip/dns.h" #include "lwip/dhcp.h" -#include "lwip/init.h" // LWIP_VERSION_ +#include "lwip/init.h" // LWIP_VERSION_ #if LWIP_IPV6 -#include "lwip/netif.h" // struct netif +#include "lwip/netif.h" // struct netif #endif #include @@ -24,19 +25,23 @@ 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. + // 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 + // 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; } @@ -46,7 +51,7 @@ bool LwipIntf::ipAddressReorder(const IPAddress& local_ip, const IPAddress& arg1 return false; } - //ip and gateway must be in the same netmask + // ip and gateway must be in the same netmask if (gateway.isSet() && (local_ip.v4() & netmask.v4()) != (gateway.v4() & netmask.v4())) { return false; @@ -143,7 +148,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 +166,3 @@ bool LwipIntf::hostname(const char* aHostname) return ret && compliant; } - diff --git a/cores/esp8266/LwipIntf.h b/cores/esp8266/LwipIntf.h index d73c2d825a..1eee25cce5 100644 --- a/cores/esp8266/LwipIntf.h +++ b/cores/esp8266/LwipIntf.h @@ -10,8 +10,7 @@ class LwipIntf { public: - - using CBType = std::function ; + using CBType = std::function; static bool stateUpCB(LwipIntf::CBType&& cb); @@ -24,12 +23,12 @@ 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) + bool hostname(const String& aHostname) { return hostname(aHostname.c_str()); } @@ -42,8 +41,7 @@ class LwipIntf const char* getHostname(); 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..9d0f9feb22 100644 --- a/cores/esp8266/LwipIntfCB.cpp +++ b/cores/esp8266/LwipIntfCB.cpp @@ -5,8 +5,8 @@ #define NETIF_STATUS_CB_SIZE 3 -static int netifStatusChangeListLength = 0; -LwipIntf::CBType netifStatusChangeList [NETIF_STATUS_CB_SIZE]; +static int netifStatusChangeListLength = 0; +LwipIntf::CBType netifStatusChangeList[NETIF_STATUS_CB_SIZE]; extern "C" void netif_status_changed(struct netif* netif) { @@ -33,12 +33,14 @@ 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]() + return stateChangeSysCB( + [cb](netif* 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 f8290d7cd6..e105e36942 100644 --- a/cores/esp8266/LwipIntfDev.h +++ b/cores/esp8266/LwipIntfDev.h @@ -14,7 +14,7 @@ #include #include -#include // wifi_get_macaddr() +#include // wifi_get_macaddr() #include "SPI.h" #include "Schedule.h" @@ -25,41 +25,36 @@ #define DEFAULT_MTU 1500 #endif -template +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 { 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))); } @@ -77,12 +72,11 @@ class LwipIntfDev: public LwipIntf, public RawDev wl_status_t status(); protected: - 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 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 @@ -90,18 +84,19 @@ class LwipIntfDev: public LwipIntf, public RawDev // 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 -boolean LwipIntfDev::config(const IPAddress& localIP, const IPAddress& gateway, const IPAddress& netmask, const IPAddress& dns1, const IPAddress& dns2) +template +boolean LwipIntfDev::config(const IPAddress& localIP, const IPAddress& gateway, + const IPAddress& netmask, const IPAddress& dns1, + const IPAddress& dns2) { if (_started) { @@ -132,7 +127,7 @@ boolean LwipIntfDev::config(const IPAddress& localIP, const IPAddress& g return true; } -template +template boolean LwipIntfDev::begin(const uint8_t* macAddress, const uint16_t mtu) { if (mtu) @@ -162,9 +157,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)) @@ -183,7 +178,8 @@ boolean LwipIntfDev::begin(const uint8_t* macAddress, const uint16_t mtu ip_addr_copy(netmask, _netif.netmask); ip_addr_copy(gw, _netif.gw); - if (!netif_add(&_netif, ip_2_ip4(&ip_addr), ip_2_ip4(&netmask), ip_2_ip4(&gw), this, netif_init_s, ethernet_input)) + if (!netif_add(&_netif, ip_2_ip4(&ip_addr), ip_2_ip4(&netmask), ip_2_ip4(&gw), this, + netif_init_s, ethernet_input)) { return false; } @@ -212,20 +208,24 @@ boolean LwipIntfDev::begin(const uint8_t* macAddress, const uint16_t mtu { if (RawDev::interruptIsPossible()) { - //attachInterrupt(_intrPin, [&]() { this->handlePackets(); }, FALLING); + // attachInterrupt(_intrPin, [&]() { this->handlePackets(); }, FALLING); } else { - ::printf((PGM_P)F("lwIP_Intf: Interrupt not implemented yet, enabling transparent polling\r\n")); + ::printf((PGM_P)F( + "lwIP_Intf: Interrupt not implemented yet, enabling transparent polling\r\n")); _intrPin = -1; } } - if (_intrPin < 0 && !schedule_recurrent_function_us([&]() -{ - this->handlePackets(); - return true; - }, 100)) + if (_intrPin < 0 + && !schedule_recurrent_function_us( + [&]() + { + this->handlePackets(); + return true; + }, + 100)) { netif_remove(&_netif); return false; @@ -234,14 +234,14 @@ boolean LwipIntfDev::begin(const uint8_t* macAddress, const uint16_t mtu return true; } -template +template wl_status_t LwipIntfDev::status() { return _started ? (connected() ? WL_CONNECTED : WL_DISCONNECTED) : WL_NO_SHIELD; } -template -err_t LwipIntfDev::linkoutput_s(netif *netif, struct pbuf *pbuf) +template +err_t LwipIntfDev::linkoutput_s(netif* netif, struct pbuf* pbuf) { LwipIntfDev* ths = (LwipIntfDev*)netif->state; @@ -255,37 +255,34 @@ 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 return len == pbuf->len ? ERR_OK : ERR_MEM; } -template +template err_t LwipIntfDev::netif_init_s(struct netif* netif) { return ((LwipIntfDev*)netif->state)->netif_init(); } -template +template void LwipIntfDev::netif_status_callback_s(struct netif* netif) { ((LwipIntfDev*)netif->state)->netif_status_callback(); } -template +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_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 @@ -301,7 +298,7 @@ err_t LwipIntfDev::netif_init() return ERR_OK; } -template +template void LwipIntfDev::netif_status_callback() { if (connected()) @@ -321,14 +318,14 @@ void LwipIntfDev::netif_status_callback() } } -template +template err_t LwipIntfDev::handlePackets() { int pkt = 0; while (1) { if (++pkt == 10) - // prevent starvation + // prevent starvation { return ERR_OK; } @@ -374,7 +371,8 @@ 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,11 +382,10 @@ err_t LwipIntfDev::handlePackets() return err; } // (else) allocated pbuf is now lwIP's responsibility - } } -template +template void LwipIntfDev::setDefault() { _default = true; @@ -398,4 +395,4 @@ void LwipIntfDev::setDefault() } } -#endif // _LWIPINTFDEV_H +#endif // _LWIPINTFDEV_H diff --git a/cores/esp8266/StreamSend.cpp b/cores/esp8266/StreamSend.cpp index 693e340cff..bf07f397b8 100644 --- a/cores/esp8266/StreamSend.cpp +++ b/cores/esp8266/StreamSend.cpp @@ -19,20 +19,17 @@ parsing functions based on TextFinder library by Michael Margolis */ - #include #include -size_t Stream::sendGeneric(Print* to, - const ssize_t len, - const int readUntilChar, +size_t Stream::sendGeneric(Print* to, const ssize_t len, const int readUntilChar, const esp8266::polledTimeout::oneShotFastMs::timeType timeoutMs) { setReport(Report::Success); 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,14 +54,17 @@ 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) +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 - esp8266::polledTimeout::oneShotFastMs timedOut(timeoutMs >= esp8266::polledTimeout::oneShotFastMs::neverExpires ? getTimeout() : timeoutMs); + 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) { @@ -90,13 +90,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; } } @@ -104,7 +104,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) { @@ -145,16 +145,20 @@ size_t Stream::SendGenericPeekBuffer(Print* to, const ssize_t len, const int rea return written; } -size_t Stream::SendGenericRegularUntil(Print* to, const ssize_t len, const int readUntilChar, const esp8266::polledTimeout::oneShotFastMs::timeType timeoutMs) +size_t +Stream::SendGenericRegularUntil(Print* to, const ssize_t len, const int readUntilChar, + const esp8266::polledTimeout::oneShotFastMs::timeType timeoutMs) { // regular Stream API // no other choice than reading byte by byte // "neverExpires (default, impossible)" is translated to default timeout - esp8266::polledTimeout::oneShotFastMs timedOut(timeoutMs >= esp8266::polledTimeout::oneShotFastMs::neverExpires ? getTimeout() : timeoutMs); + 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) { @@ -186,7 +190,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) @@ -221,16 +225,19 @@ size_t Stream::SendGenericRegularUntil(Print* to, const ssize_t len, const int r return written; } -size_t Stream::SendGenericRegular(Print* to, const ssize_t len, const esp8266::polledTimeout::oneShotFastMs::timeType timeoutMs) +size_t Stream::SendGenericRegular(Print* to, const ssize_t len, + const esp8266::polledTimeout::oneShotFastMs::timeType timeoutMs) { // regular Stream API // use an intermediary buffer // "neverExpires (default, impossible)" is translated to default timeout - esp8266::polledTimeout::oneShotFastMs timedOut(timeoutMs >= esp8266::polledTimeout::oneShotFastMs::neverExpires ? getTimeout() : timeoutMs); + 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) { @@ -243,7 +250,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; } @@ -256,7 +263,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) { @@ -270,7 +277,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 +312,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 +346,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..2331a3c51a 100644 --- a/cores/esp8266/StreamString.h +++ b/cores/esp8266/StreamString.h @@ -35,16 +35,9 @@ 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) { } virtual int available() override { @@ -207,18 +200,15 @@ 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 class StreamString: public String, public S2Stream { protected: - void resetpp() { if (peekPointer > 0) @@ -228,55 +218,68 @@ 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& 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 +287,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..98f8115b8b 100644 --- a/cores/esp8266/core_esp8266_si2c.cpp +++ b/cores/esp8266/core_esp8266_si2c.cpp @@ -24,9 +24,8 @@ #include "wiring_private.h" #include "PolledTimeout.h" - - -extern "C" { +extern "C" +{ #include "twi_util.h" #include "ets_sys.h" }; @@ -57,78 +56,113 @@ 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 +// Implement as a class to reduce code size by allowing access to many global variables with a +// single base pointer 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; - - // 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; - 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; + 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; + 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; + 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_READY; - volatile uint8_t twi_error = 0xFF; + volatile uint8_t twi_error = 0xFF; - uint8_t twi_txBuffer[TWI_BUFFER_LENGTH]; - volatile int twi_txBufferIndex = 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]; + uint8_t twi_rxBuffer[TWI_BUFFER_LENGTH]; volatile int twi_rxBufferIndex = 0; void (*twi_onSlaveTransmit)(void); 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; // 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); + 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() { - 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 + 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(); } @@ -139,19 +173,21 @@ 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; @@ -176,7 +212,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 + = (1000 * (twi_dcount - 1120)) / 62500; // (half cycle - overhead) / busywait loop time #else @@ -185,7 +222,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 + = (1000 * (twi_dcount - 560)) / 31250; // (half cycle - overhead) / busywait loop time #endif } @@ -195,8 +233,6 @@ void Twi::setClockStretchLimit(uint32_t limit) twi_clockStretchLimit = limit; } - - void Twi::init(unsigned char sda, unsigned char scl) { // set timer function @@ -210,7 +246,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 +270,8 @@ 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. } } @@ -250,7 +287,8 @@ bool Twi::write_start(void) // A high-to-low transition on the SDA line while the SCL is high defines a START condition. SDA_LOW(twi_sda); busywait(twi_dcount); - // An additional delay between the SCL line high-to-low transition and setting up the SDA line to prevent a STOP condition execute. + // An additional delay between the SCL line high-to-low transition and setting up the SDA line + // to prevent a STOP condition execute. SCL_LOW(twi_scl); busywait(twi_dcount); return true; @@ -308,7 +346,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,12 +361,13 @@ 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()) { - return 4; //line busy + return 4; // line busy } if (!write_byte(((address << 1) | 0) & 0xFF)) { @@ -336,7 +375,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 +385,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) @@ -368,12 +407,13 @@ unsigned char Twi::writeTo(unsigned char address, unsigned char * buf, unsigned return 0; } -unsigned char Twi::readFrom(unsigned char address, unsigned char* buf, unsigned int len, unsigned char sendStop) +unsigned char Twi::readFrom(unsigned char address, unsigned char* buf, unsigned int len, + unsigned char sendStop) { unsigned int i; if (!write_start()) { - return 4; //line busy + return 4; // line busy } if (!write_byte(((address << 1) | 1) & 0xFF)) { @@ -381,7 +421,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++) { @@ -420,21 +460,25 @@ uint8_t Twi::status() WAIT_CLOCK_STRETCH(); // wait for a slow slave to finish if (!SCL_READ(twi_scl)) { - return I2C_SCL_HELD_LOW; // SCL held low by another device, no procedure available to recover + return I2C_SCL_HELD_LOW; // SCL held low by another device, no procedure available to + // recover } 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)) { - return I2C_SDA_HELD_LOW; // I2C bus error. SDA line held low by slave/another_master after n bits. + return I2C_SDA_HELD_LOW; // I2C bus error. SDA line held low by slave/another_master after + // n bits. } return I2C_OK; @@ -476,58 +520,57 @@ void Twi::attachSlaveTxEvent(void (*function)(void)) twi_onSlaveTransmit = function; } -// DO NOT INLINE, inlining reply() in combination with compiler optimizations causes function breakup into -// parts and the IRAM_ATTR isn't propagated correctly to all parts, which of course causes crashes. +// DO NOT INLINE, inlining reply() in combination with compiler optimizations causes function +// breakup into parts and the IRAM_ATTR isn't propagated correctly to all parts, which of course +// causes crashes. // TODO: test with gcc 9.x and if it still fails, disable optimization with -fdisable-ipa-fnsplit void IRAM_ATTR Twi::reply(uint8_t ack) { // transmit master read ready signal, with or without ack if (ack) { - //TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT) | _BV(TWEA); - SCL_HIGH(twi.twi_scl); // _BV(TWINT) - twi_ack = 1; // _BV(TWEA) + // TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT) | _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) + // TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT); + 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) + // TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT); + 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 + 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 + 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) { @@ -541,29 +584,29 @@ void IRAM_ATTR Twi::onTwipEvent(uint8_t status) reply(0); } break; - case TW_SR_STOP: // stop or repeated start condition received + 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 + // 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 + 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 + 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 @@ -576,7 +619,7 @@ void IRAM_ATTR Twi::onTwipEvent(uint8_t status) ets_post(EVENTTASK_QUEUE_PRIO, TWI_SIG_TX, 0); break; - case TW_ST_DATA_ACK: // byte sent, ack returned + case TW_ST_DATA_ACK: // byte sent, ack returned // copy data to output register twi_data = twi_txBuffer[twi_txBufferIndex++]; @@ -602,33 +645,32 @@ void IRAM_ATTR Twi::onTwipEvent(uint8_t status) 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! + 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 + case TW_NO_INFO: // no state information break; - case TW_BUS_ERROR: // bus error, illegal stop/start + 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(); twi.onTwipEvent(TW_BUS_ERROR); - twi.twip_mode = TWIPM_WAIT; + twi.twip_mode = TWIPM_WAIT; twi.twip_state = TWIP_BUS_ERR; } -void Twi::eventTask(ETSEvent *e) +void Twi::eventTask(ETSEvent* e) { - if (e == NULL) { return; @@ -643,7 +685,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 @@ -663,7 +705,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 +719,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,13 +794,13 @@ 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)) { twi.onTwipEvent(TW_SR_SLA_ACK); - twi.bitCount = 8; + twi.bitCount = 8; twi.twip_state = TWIP_SLA_W; } else @@ -770,18 +812,18 @@ 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) { 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; } } @@ -837,7 +879,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)) @@ -848,7 +890,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); @@ -858,7 +900,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; } } @@ -875,7 +917,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)) { @@ -886,17 +928,19 @@ 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 + 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)) + 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_mode = TWIPM_WAIT; twi.twip_state = TWIP_BUS_ERR; } else IFSTATE(S2M(TWIP_WAIT_STOP) | S2M(TWIP_BUS_ERR)) @@ -904,10 +948,10 @@ 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; + twi.twip_mode = TWIPM_IDLE; SCL_HIGH(twi.twi_scl); } else @@ -919,9 +963,9 @@ 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 + ets_timer_arm_new(&twi.timer, twi.twi_timeout_ms, false, true); // Once, ms } } } @@ -932,28 +976,28 @@ 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 { // 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) { // STOP ets_timer_disarm(&twi.timer); twi.twip_state = TWIP_IDLE; - twi.twip_mode = TWIPM_IDLE; + twi.twip_mode = TWIPM_IDLE; } else { // 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; + twi.twip_mode = TWIPM_IDLE; } } } @@ -961,8 +1005,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 +1027,14 @@ 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 +1044,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 +1073,4 @@ extern "C" { { twi.enableSlave(); } - }; diff --git a/cores/esp8266/debug.cpp b/cores/esp8266/debug.cpp index 06af1e424b..327aace64e 100644 --- a/cores/esp8266/debug.cpp +++ b/cores/esp8266/debug.cpp @@ -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..c6ea8230ef 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; \ - __iamslow((PGM_P)FPSTR(__FUNCTION__)); \ - } \ + 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/ArduinoOTA/examples/BasicOTA/BasicOTA.ino b/libraries/ArduinoOTA/examples/BasicOTA/BasicOTA.ino index ddc5629741..6f175ccaff 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; @@ -39,7 +39,7 @@ void setup() { String type; if (ArduinoOTA.getCommand() == U_FLASH) { type = "sketch"; - } else { // U_FS + } else { // U_FS type = "filesystem"; } diff --git a/libraries/ArduinoOTA/examples/OTALeds/OTALeds.ino b/libraries/ArduinoOTA/examples/OTALeds/OTALeds.ino index 7d05074e15..57b1b75a22 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); @@ -45,14 +45,14 @@ void setup() { } ArduinoOTA.setHostname(host); - ArduinoOTA.onStart([]() { // switch off all the PWMs during upgrade + 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 + 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); @@ -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..55222fbc7b 100644 --- a/libraries/DNSServer/examples/CaptivePortalAdvanced/CaptivePortalAdvanced.ino +++ b/libraries/DNSServer/examples/CaptivePortalAdvanced/CaptivePortalAdvanced.ino @@ -20,7 +20,7 @@ /* 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; @@ -62,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()); @@ -74,13 +74,13 @@ 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() { @@ -106,7 +106,7 @@ void loop() { /* 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; @@ -130,13 +130,11 @@ void loop() { WiFi.disconnect(); } } - if (s == WL_CONNECTED) { - MDNS.update(); - } + if (s == WL_CONNECTED) { MDNS.update(); } } // Do work: - //DNS + // DNS dnsServer.processNextRequest(); - //HTTP + // HTTP server.handleClient(); } diff --git a/libraries/DNSServer/examples/CaptivePortalAdvanced/handleHttp.ino b/libraries/DNSServer/examples/CaptivePortalAdvanced/handleHttp.ino index dc286c1840..aec2556a48 100644 --- a/libraries/DNSServer/examples/CaptivePortalAdvanced/handleHttp.ino +++ b/libraries/DNSServer/examples/CaptivePortalAdvanced/handleHttp.ino @@ -1,6 +1,6 @@ /** Handle root or redirect to captive portal */ void handleRoot() { - if (captivePortal()) { // If caprive portal redirect instead of displaying the page. + if (captivePortal()) { // If caprive portal redirect instead of displaying the page. return; } server.sendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); @@ -8,8 +8,7 @@ void handleRoot() { server.sendHeader("Expires", "-1"); String Page; - Page += F( - "" + Page += F("" "" "CaptivePortal" "

HELLO WORLD!!

"); @@ -18,8 +17,7 @@ void handleRoot() { } else { Page += String(F("

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

"); } - Page += F( - "

You may want to config the wifi connection.

" + Page += F("

You may want to config the wifi connection.

" ""); server.send(200, "text/html", Page); @@ -30,8 +28,8 @@ 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; @@ -44,8 +42,7 @@ void handleWifi() { server.sendHeader("Expires", "-1"); String Page; - Page += F( - "" + Page += F("" "" "CaptivePortal" "

Wifi config

"); @@ -54,40 +51,31 @@ void handleWifi() { } 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"); if (n > 0) { - for (int i = 0; i < n; i++) { - Page += String(F("\r\n"); - } + for (int i = 0; i < n; i++) { Page += String(F("\r\n"); } } else { Page += F(""); } - Page += F( - "
WLAN list (refresh if any missing)
SSID ")) + WiFi.SSID(i) + ((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? F(" ") : F(" *")) + F(" (") + WiFi.RSSI(i) + F(")
SSID ")) + WiFi.SSID(i) + ((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? F(" ") : F(" *")) + F(" (") + WiFi.RSSI(i) + F(")
No WLAN found
" + Page += F("" "\r\n

Connect to network:

" "" "
" @@ -95,7 +83,7 @@ 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 */ @@ -107,14 +95,14 @@ 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. + if (captivePortal()) { // If caprive portal redirect instead of displaying the error page. return; } String message = F("File Not Found\n\n"); @@ -126,9 +114,7 @@ void handleNotFound() { message += server.args(); message += F("\n"); - for (uint8_t i = 0; i < server.args(); i++) { - message += String(F(" ")) + server.argName(i) + F(": ") + server.arg(i) + F("\n"); - } + 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"); server.sendHeader("Pragma", "no-cache"); server.sendHeader("Expires", "-1"); diff --git a/libraries/DNSServer/examples/CaptivePortalAdvanced/tools.ino b/libraries/DNSServer/examples/CaptivePortalAdvanced/tools.ino index e4840a1c12..65219bdccb 100644 --- a/libraries/DNSServer/examples/CaptivePortalAdvanced/tools.ino +++ b/libraries/DNSServer/examples/CaptivePortalAdvanced/tools.ino @@ -2,9 +2,7 @@ boolean isIp(String str) { for (size_t i = 0; i < str.length(); i++) { int c = str.charAt(i); - if (c != '.' && (c < '0' || c > '9')) { - return false; - } + if (c != '.' && (c < '0' || c > '9')) { return false; } } return true; } @@ -12,10 +10,7 @@ boolean isIp(String str) { /** IP to String? */ String toStringIp(IPAddress ip) { String res = ""; - for (int i = 0; i < 3; i++) { - res += String((ip >> (8 * i)) & 0xFF) + "."; - } + for (int i = 0; i < 3; i++) { res += String((ip >> (8 * i)) & 0xFF) + "."; } res += String(((ip >> 8 * 3)) & 0xFF); return res; } - diff --git a/libraries/EEPROM/examples/eeprom_clear/eeprom_clear.ino b/libraries/EEPROM/examples/eeprom_clear/eeprom_clear.ino index bb7d887c57..99ec3d98de 100644 --- a/libraries/EEPROM/examples/eeprom_clear/eeprom_clear.ino +++ b/libraries/EEPROM/examples/eeprom_clear/eeprom_clear.ino @@ -11,9 +11,7 @@ void setup() { EEPROM.begin(512); // write a 0 to all 512 bytes of the EEPROM - for (int i = 0; i < 512; i++) { - EEPROM.write(i, 0); - } + for (int i = 0; i < 512; i++) { EEPROM.write(i, 0); } // turn the LED on when we're done pinMode(13, OUTPUT); @@ -21,5 +19,4 @@ void setup() { EEPROM.end(); } -void loop() { -} +void loop() {} diff --git a/libraries/EEPROM/examples/eeprom_read/eeprom_read.ino b/libraries/EEPROM/examples/eeprom_read/eeprom_read.ino index 3295fecf9f..30d25a67de 100644 --- a/libraries/EEPROM/examples/eeprom_read/eeprom_read.ino +++ b/libraries/EEPROM/examples/eeprom_read/eeprom_read.ino @@ -32,9 +32,7 @@ void loop() { // there are only 512 bytes of EEPROM, from 0 to 511, so if we're // on address 512, wrap around to address 0 - if (address == 512) { - address = 0; - } + if (address == 512) { address = 0; } delay(500); } 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..b86a4fc021 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"; @@ -20,7 +20,7 @@ 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); @@ -51,17 +51,20 @@ void loop() { AVRISPState_t new_state = avrprog.update(); if (last_state != new_state) { switch (new_state) { - case AVRISP_STATE_IDLE: { + 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 +73,7 @@ void loop() { last_state = new_state; } // Serve the client - if (last_state != AVRISP_STATE_IDLE) { - avrprog.serve(); - } + if (last_state != AVRISP_STATE_IDLE) { avrprog.serve(); } - if (WiFi.status() == WL_CONNECTED) { - MDNS.update(); - } + if (WiFi.status() == WL_CONNECTED) { MDNS.update(); } } diff --git a/libraries/ESP8266HTTPClient/examples/Authorization/Authorization.ino b/libraries/ESP8266HTTPClient/examples/Authorization/Authorization.ino index 9de3077ff4..459bc78e92 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() { diff --git a/libraries/ESP8266HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino b/libraries/ESP8266HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino index 21a97172ef..8d4f9c3015 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() { diff --git a/libraries/ESP8266HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino b/libraries/ESP8266HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino index aaa4af2b4d..b8c4c5b328 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: diff --git a/libraries/ESP8266HTTPClient/examples/DigestAuthorization/DigestAuthorization.ino b/libraries/ESP8266HTTPClient/examples/DigestAuthorization/DigestAuthorization.ino index db8fe8cbd4..b71e3baf7a 100644 --- a/libraries/ESP8266HTTPClient/examples/DigestAuthorization/DigestAuthorization.ino +++ b/libraries/ESP8266HTTPClient/examples/DigestAuthorization/DigestAuthorization.ino @@ -13,36 +13,31 @@ #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); - if (_begin == -1) { - return ""; - } + if (_begin == -1) { return ""; } return authReq.substring(_begin + param.length(), authReq.indexOf(delimit, _begin + param.length())); } 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) { - s += alphanum[rand() % (sizeof(alphanum) - 1)]; - } + for (int i = 0; i < len; ++i) { s += alphanum[rand() % (sizeof(alphanum) - 1)]; } return s; } @@ -73,8 +68,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; @@ -100,7 +94,7 @@ void setup() { 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"); @@ -108,7 +102,7 @@ void loop() { 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..72d51142c7 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() { @@ -52,7 +51,7 @@ void loop() { 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"); diff --git a/libraries/ESP8266HTTPClient/examples/ReuseConnectionV2/ReuseConnectionV2.ino b/libraries/ESP8266HTTPClient/examples/ReuseConnectionV2/ReuseConnectionV2.ino index 42a89beced..24d7e3a4cf 100644 --- a/libraries/ESP8266HTTPClient/examples/ReuseConnectionV2/ReuseConnectionV2.ino +++ b/libraries/ESP8266HTTPClient/examples/ReuseConnectionV2/ReuseConnectionV2.ino @@ -13,7 +13,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif ESP8266WiFiMulti WiFiMulti; @@ -45,7 +45,7 @@ void setup() { http.begin(client, "http://jigsaw.w3.org/HTTP/connection.html"); - //http.begin(client, "jigsaw.w3.org", 80, "/HTTP/connection.html"); + // http.begin(client, "jigsaw.w3.org", 80, "/HTTP/connection.html"); } int pass = 0; @@ -60,15 +60,13 @@ void loop() { Serial.printf("[HTTP] GET... code: %d\n", httpCode); // file found at server - if (httpCode == HTTP_CODE_OK) { - http.writeToStream(&Serial); - } + if (httpCode == HTTP_CODE_OK) { http.writeToStream(&Serial); } } 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(); http.begin(client, "http://jigsaw.w3.org/HTTP/connection.html"); - //http.begin(client, "jigsaw.w3.org", 80, "/HTTP/connection.html"); + // http.begin(client, "jigsaw.w3.org", 80, "/HTTP/connection.html"); } if (pass == 10) { diff --git a/libraries/ESP8266HTTPClient/examples/StreamHttpClient/StreamHttpClient.ino b/libraries/ESP8266HTTPClient/examples/StreamHttpClient/StreamHttpClient.ino index 7e1593f52b..ca9bcbc5df 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() { @@ -39,13 +38,13 @@ void loop() { 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"); // configure server and url http.begin(client, "http://jigsaw.w3.org/HTTP/connection.html"); - //http.begin(client, "jigsaw.w3.org", 80, "/HTTP/connection.html"); + // http.begin(client, "jigsaw.w3.org", 80, "/HTTP/connection.html"); Serial.print("[HTTP] GET...\n"); // start connection and send HTTP header @@ -70,23 +69,19 @@ 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)) { // 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) { - Serial.println("read timeout"); - } + if (!c) { Serial.println("read timeout"); } // write it to Serial Serial.write(buff, c); - if (len > 0) { - len -= c; - } + if (len > 0) { len -= c; } } #endif diff --git a/libraries/ESP8266HTTPClient/examples/StreamHttpsClient/StreamHttpsClient.ino b/libraries/ESP8266HTTPClient/examples/StreamHttpsClient/StreamHttpsClient.ino index 8098986650..5c80a1eeb8 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() { @@ -43,14 +42,12 @@ void loop() { 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) { - client->setBufferSizes(1024, 1024); - } + if (mfln) { client->setBufferSizes(1024, 1024); } 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); @@ -86,16 +83,13 @@ void loop() { // write it to Serial Serial.write(buff, c); - if (len > 0) { - len -= c; - } + if (len > 0) { len -= c; } } delay(1); } 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..f8829120ef 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 @@ -88,8 +88,7 @@ gz5JWYhbD6c38khSzJb0pNXCo3EuYAVa36kDM96k1BtWuhRS10Q1VXk= )EOF"; -void setup() -{ +void setup() { Serial.begin(115200); Serial.println(); @@ -97,7 +96,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 +110,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..31d9327883 --- 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; diff --git a/libraries/ESP8266SSDP/examples/SSDP/SSDP.ino b/libraries/ESP8266SSDP/examples/SSDP/SSDP.ino index 28b0ca977b..c55afacf72 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; @@ -46,9 +46,7 @@ void setup() { Serial.printf("Ready!\n"); } else { Serial.printf("WiFi Failed\n"); - while (1) { - delay(100); - } + while (1) { delay(100); } } } diff --git a/libraries/ESP8266WebServer/examples/AdvancedWebServer/AdvancedWebServer.ino b/libraries/ESP8266WebServer/examples/AdvancedWebServer/AdvancedWebServer.ino index 2fc8508ca0..36511917db 100644 --- a/libraries/ESP8266WebServer/examples/AdvancedWebServer/AdvancedWebServer.ino +++ b/libraries/ESP8266WebServer/examples/AdvancedWebServer/AdvancedWebServer.ino @@ -35,7 +35,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char *ssid = STASSID; @@ -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); } @@ -86,9 +85,7 @@ void handleNotFound() { message += server.args(); message += "\n"; - for (uint8_t i = 0; i < server.args(); i++) { - message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; - } + 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); @@ -133,9 +130,7 @@ void setup(void) { Serial.print("IP address: "); Serial.println(WiFi.localIP()); - if (MDNS.begin("esp8266")) { - Serial.println("MDNS responder started"); - } + if (MDNS.begin("esp8266")) { Serial.println("MDNS responder started"); } server.on("/", handleRoot); server.on("/test.svg", drawGraph); @@ -151,4 +146,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..5a0937df0c 100644 --- a/libraries/ESP8266WebServer/examples/FSBrowser/FSBrowser.ino +++ b/libraries/ESP8266WebServer/examples/FSBrowser/FSBrowser.ino @@ -72,7 +72,7 @@ SDFSConfig fileSystemConfig = SDFSConfig(); #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* ssid = STASSID; @@ -122,15 +122,9 @@ void replyServerError(String msg) { */ String checkForUnsupportedPath(String filename) { String error = String(); - if (!filename.startsWith("/")) { - error += F("!NO_LEADING_SLASH! "); - } - if (filename.indexOf("//") != -1) { - error += F("!DOUBLE_SLASH! "); - } - if (filename.endsWith("/")) { - error += F("!TRAILING_SLASH! "); - } + if (!filename.startsWith("/")) { error += F("!NO_LEADING_SLASH! "); } + if (filename.indexOf("//") != -1) { error += F("!DOUBLE_SLASH! "); } + if (filename.endsWith("/")) { error += F("!TRAILING_SLASH! "); } return error; } #endif @@ -174,18 +168,12 @@ void handleStatus() { Also demonstrates the use of chunked responses. */ void handleFileList() { - if (!fsOK) { - return replyServerError(FPSTR(FS_INIT_ERROR)); - } + if (!fsOK) { return replyServerError(FPSTR(FS_INIT_ERROR)); } - if (!server.hasArg("dir")) { - return replyBadRequest(F("DIR ARG MISSING")); - } + if (!server.hasArg("dir")) { return replyBadRequest(F("DIR ARG MISSING")); } String path = server.arg("dir"); - if (path != "/" && !fileSystem->exists(path)) { - return replyBadRequest("BAD PATH"); - } + if (path != "/" && !fileSystem->exists(path)) { return replyBadRequest("BAD PATH"); } DBG_OUTPUT_PORT.println(String("handleFileList: ") + path); Dir dir = fileSystem->openDir(path); @@ -253,9 +241,7 @@ bool handleFileRead(String path) { return true; } - if (path.endsWith("/")) { - path += "index.htm"; - } + if (path.endsWith("/")) { path += "index.htm"; } String contentType; if (server.hasArg("download")) { @@ -270,9 +256,7 @@ bool handleFileRead(String path) { } if (fileSystem->exists(path)) { File file = fileSystem->open(path, "r"); - if (server.streamFile(file, contentType) != file.size()) { - DBG_OUTPUT_PORT.println("Sent less data than expected!"); - } + if (server.streamFile(file, contentType) != file.size()) { DBG_OUTPUT_PORT.println("Sent less data than expected!"); } file.close(); return true; } @@ -309,27 +293,17 @@ String lastExistingParent(String path) { Move folder | parent of source folder, or remaining ancestor */ void handleFileCreate() { - if (!fsOK) { - return replyServerError(FPSTR(FS_INIT_ERROR)); - } + if (!fsOK) { return replyServerError(FPSTR(FS_INIT_ERROR)); } String path = server.arg("path"); - if (path.isEmpty()) { - return replyBadRequest(F("PATH ARG MISSING")); - } + if (path.isEmpty()) { return replyBadRequest(F("PATH ARG MISSING")); } #ifdef USE_SPIFFS - if (checkForUnsupportedPath(path).length() > 0) { - return replyServerError(F("INVALID FILENAME")); - } + if (checkForUnsupportedPath(path).length() > 0) { return replyServerError(F("INVALID FILENAME")); } #endif - if (path == "/") { - return replyBadRequest("BAD PATH"); - } - if (fileSystem->exists(path)) { - return replyBadRequest(F("PATH FILE EXISTS")); - } + if (path == "/") { return replyBadRequest("BAD PATH"); } + if (fileSystem->exists(path)) { return replyBadRequest(F("PATH FILE EXISTS")); } String src = server.arg("src"); if (src.isEmpty()) { @@ -338,43 +312,29 @@ void handleFileCreate() { if (path.endsWith("/")) { // Create a folder path.remove(path.length() - 1); - if (!fileSystem->mkdir(path)) { - return replyServerError(F("MKDIR FAILED")); - } + if (!fileSystem->mkdir(path)) { return replyServerError(F("MKDIR FAILED")); } } else { // 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")); } } - if (path.lastIndexOf('/') > -1) { - path = path.substring(0, path.lastIndexOf('/')); - } + if (path.lastIndexOf('/') > -1) { path = path.substring(0, path.lastIndexOf('/')); } replyOKWithMsg(path); } else { // Source specified: rename - if (src == "/") { - return replyBadRequest("BAD SRC"); - } - if (!fileSystem->exists(src)) { - return replyBadRequest(F("SRC FILE NOT FOUND")); - } + if (src == "/") { return replyBadRequest("BAD SRC"); } + if (!fileSystem->exists(src)) { return replyBadRequest(F("SRC FILE NOT FOUND")); } DBG_OUTPUT_PORT.println(String("handleFileCreate: ") + path + " from " + src); - if (path.endsWith("/")) { - path.remove(path.length() - 1); - } - if (src.endsWith("/")) { - src.remove(src.length() - 1); - } - if (!fileSystem->rename(src, path)) { - return replyServerError(F("RENAME FAILED")); - } + if (path.endsWith("/")) { path.remove(path.length() - 1); } + if (src.endsWith("/")) { src.remove(src.length() - 1); } + if (!fileSystem->rename(src, path)) { return replyServerError(F("RENAME FAILED")); } replyOKWithMsg(lastExistingParent(src)); } } @@ -403,9 +363,7 @@ void deleteRecursive(String path) { // Otherwise delete its contents first Dir dir = fileSystem->openDir(path); - while (dir.next()) { - deleteRecursive(path + '/' + dir.fileName()); - } + while (dir.next()) { deleteRecursive(path + '/' + dir.fileName()); } // Then delete the folder itself fileSystem->rmdir(path); @@ -420,19 +378,13 @@ void deleteRecursive(String path) { Delete folder | parent of deleted folder, or remaining ancestor */ void handleFileDelete() { - if (!fsOK) { - return replyServerError(FPSTR(FS_INIT_ERROR)); - } + if (!fsOK) { return replyServerError(FPSTR(FS_INIT_ERROR)); } String path = server.arg(0); - if (path.isEmpty() || path == "/") { - return replyBadRequest("BAD PATH"); - } + if (path.isEmpty() || path == "/") { return replyBadRequest("BAD PATH"); } DBG_OUTPUT_PORT.println(String("handleFileDelete: ") + path); - if (!fileSystem->exists(path)) { - return replyNotFound(FPSTR(FILE_NOT_FOUND)); - } + if (!fileSystem->exists(path)) { return replyNotFound(FPSTR(FILE_NOT_FOUND)); } deleteRecursive(path); replyOKWithMsg(lastExistingParent(path)); @@ -442,37 +394,25 @@ void handleFileDelete() { Handle a file upload request */ void handleFileUpload() { - if (!fsOK) { - return replyServerError(FPSTR(FS_INIT_ERROR)); - } - if (server.uri() != "/edit") { - return; - } + if (!fsOK) { return replyServerError(FPSTR(FS_INIT_ERROR)); } + if (server.uri() != "/edit") { return; } HTTPUpload& upload = server.upload(); if (upload.status == UPLOAD_FILE_START) { String filename = upload.filename; // Make sure paths always start with "/" - if (!filename.startsWith("/")) { - filename = "/" + filename; - } + if (!filename.startsWith("/")) { filename = "/" + filename; } DBG_OUTPUT_PORT.println(String("handleFileUpload Name: ") + filename); uploadFile = fileSystem->open(filename, "w"); - if (!uploadFile) { - return replyServerError(F("CREATE FAILED")); - } + 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) { size_t bytesWritten = uploadFile.write(upload.buf, upload.currentSize); - if (bytesWritten != upload.currentSize) { - return replyServerError(F("WRITE FAILED")); - } + 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) { - uploadFile.close(); - } + if (uploadFile) { uploadFile.close(); } DBG_OUTPUT_PORT.println(String("Upload: END, Size: ") + upload.totalSize); } } @@ -484,15 +424,11 @@ void handleFileUpload() { and if it fails, return a 404 page with debug information */ void handleNotFound() { - if (!fsOK) { - return replyServerError(FPSTR(FS_INIT_ERROR)); - } + 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)) { - return; - } + if (handleFileRead(uri)) { return; } // Dump debug data String message; @@ -526,9 +462,7 @@ void handleNotFound() { Otherwise, fails with a 404 page with debug information */ void handleGetEdit() { - if (handleFileRead(F("/edit/index.htm"))) { - return; - } + if (handleFileRead(F("/edit/index.htm"))) { return; } #ifdef INCLUDE_FALLBACK_INDEX_HTM server.sendHeader(F("Content-Encoding"), "gzip"); @@ -536,7 +470,6 @@ void handleGetEdit() { #else replyNotFound(FPSTR(FILE_NOT_FOUND)); #endif - } void setup(void) { @@ -562,9 +495,7 @@ void setup(void) { 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) { - unsupportedFiles += error + fileInfo + '\n'; - } + if (error.length() > 0) { unsupportedFiles += error + fileInfo + '\n'; } } DBG_OUTPUT_PORT.println(); @@ -609,15 +540,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 diff --git a/libraries/ESP8266WebServer/examples/Graph/Graph.ino b/libraries/ESP8266WebServer/examples/Graph/Graph.ino index b0eb5f847b..0d6f724bae 100644 --- a/libraries/ESP8266WebServer/examples/Graph/Graph.ino +++ b/libraries/ESP8266WebServer/examples/Graph/Graph.ino @@ -58,7 +58,7 @@ SDFSConfig fileSystemConfig = SDFSConfig(); #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. @@ -110,9 +110,7 @@ void replyServerError(String msg) { bool handleFileRead(String path) { DBG_OUTPUT_PORT.println(String("handleFileRead: ") + path); - if (path.endsWith("/")) { - path += "index.htm"; - } + if (path.endsWith("/")) { path += "index.htm"; } String contentType = mime::getContentType(path); @@ -122,9 +120,7 @@ bool handleFileRead(String path) { } if (fileSystem->exists(path)) { File file = fileSystem->open(path, "r"); - if (server.streamFile(file, contentType) != file.size()) { - DBG_OUTPUT_PORT.println("Sent less data than expected!"); - } + if (server.streamFile(file, contentType) != file.size()) { DBG_OUTPUT_PORT.println("Sent less data than expected!"); } file.close(); return true; } @@ -139,11 +135,9 @@ bool handleFileRead(String path) { 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 + String uri = ESP8266WebServer::urlDecode(server.uri()); // required to read paths with blanks - if (handleFileRead(uri)) { - return; - } + if (handleFileRead(uri)) { return; } // Dump debug data String message; @@ -218,7 +212,7 @@ void setup(void) { //////////////////////////////// // WEB SERVER INIT - //get heap status, analog input value and all GPIO statuses in one json call + // get heap status, analog input value and all GPIO statuses in one json call server.on("/espData", HTTP_GET, []() { String json; json.reserve(88); @@ -249,21 +243,18 @@ 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 unsigned int defaultMask() { unsigned int mask = 0b11111111111111111; for (auto pin = 0; pin <= 16; pin++) { - if (isFlashInterfacePin(pin)) { - mask &= ~(1 << pin); - } + if (isFlashInterfacePin(pin)) { mask &= ~(1 << pin); } } return mask; } -int rgbMode = 1; // 0=off - 1=auto - 2=manual +int rgbMode = 1; // 0=off - 1=auto - 2=manual int rgbValue = 0; esp8266::polledTimeout::periodicMs timeToChange(1000); bool modeChangeRequested = false; @@ -278,28 +269,24 @@ void loop(void) { } // see if one second has passed since last change, otherwise stop here - if (!timeToChange) { - return; - } + if (!timeToChange) { return; } // see if a mode change was requested if (modeChangeRequested) { // increment mode (reset after 2) rgbMode++; - if (rgbMode > 2) { - rgbMode = 0; - } + if (rgbMode > 2) { rgbMode = 0; } modeChangeRequested = false; } // act according to mode switch (rgbMode) { - case 0: // off + 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); @@ -307,14 +294,12 @@ void loop(void) { digitalWrite(15, 0); break; - case 1: // auto + case 1: // auto gpioMask = defaultMask(); // increment value (reset after 7) rgbValue++; - if (rgbValue > 7) { - rgbValue = 0; - } + if (rgbValue > 7) { rgbValue = 0; } // output new values digitalWrite(12, rgbValue & 0b001); @@ -322,11 +307,10 @@ void loop(void) { digitalWrite(15, rgbValue & 0b100); break; - case 2: // manual + case 2: // manual gpioMask = defaultMask(); // keep outputs unchanged break; } } - diff --git a/libraries/ESP8266WebServer/examples/HelloServer/HelloServer.ino b/libraries/ESP8266WebServer/examples/HelloServer/HelloServer.ino index 7fdee1667a..16b6ac20f0 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; @@ -31,9 +31,7 @@ void handleNotFound() { message += "\nArguments: "; message += server.args(); message += "\n"; - for (uint8_t i = 0; i < server.args(); i++) { - message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; - } + 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); } @@ -57,9 +55,7 @@ void setup(void) { Serial.print("IP address: "); Serial.println(WiFi.localIP()); - if (MDNS.begin("esp8266")) { - Serial.println("MDNS responder started"); - } + if (MDNS.begin("esp8266")) { Serial.println("MDNS responder started"); } server.on("/", handleRoot); @@ -89,17 +85,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 - (void)contentType; // contentType(".html") => "text/html" + 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 +103,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"); @@ -137,7 +133,7 @@ void setup(void) { // 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 + static WiFiClient forgetme = *client; // stop previous one if present and transfer client refcounter return ESP8266WebServer::CLIENT_IS_GIVEN; } return ESP8266WebServer::CLIENT_REQUEST_CAN_CONTINUE; diff --git a/libraries/ESP8266WebServer/examples/HelloServerBearSSL/HelloServerBearSSL.ino b/libraries/ESP8266WebServer/examples/HelloServerBearSSL/HelloServerBearSSL.ino index 185914f305..14dc1d3417 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 @@ -89,24 +89,22 @@ 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")); @@ -211,7 +208,7 @@ void processKey(Print& out, int hotKey) { } -void loop(void){ +void loop(void) { server.handleClient(); MDNS.update(); if (Serial.available() > 0) { diff --git a/libraries/ESP8266WebServer/examples/HttpAdvancedAuth/HttpAdvancedAuth.ino b/libraries/ESP8266WebServer/examples/HttpAdvancedAuth/HttpAdvancedAuth.ino index 857048cf0b..8fc4b0f5b7 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..86cbf1f369 100644 --- a/libraries/ESP8266WebServer/examples/HttpHashCredAuth/HttpHashCredAuth.ino +++ b/libraries/ESP8266WebServer/examples/HttpHashCredAuth/HttpHashCredAuth.ino @@ -15,21 +15,21 @@ #include #include -//Unfortunately it is not possible to have persistent WiFi credentials stored as anything but plain text. Obfuscation would be the only feasible barrier. +// 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 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. +// 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( -----BEGIN CERTIFICATE----- MIIDSzCCAjMCCQD2ahcfZAwXxDANBgkqhkiG9w0BAQsFADCBiTELMAkGA1UEBhMC @@ -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 @@ -84,7 +84,7 @@ gz5JWYhbD6c38khSzJb0pNXCo3EuYAVa36kDM96k1BtWuhRS10Q1VXk= ESP8266WebServerSecure server(443); -//These are temporary credentials that will only be used if none are found saved in LittleFS. +// 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 = ""; @@ -93,16 +93,16 @@ String authentication_failed = "User authentication has failed."; void setup() { Serial.begin(115200); - //Initialize LittleFS to save credentials - if(!LittleFS.begin()){ - Serial.println("LittleFS initialization error, programmer flash configured?"); + // Initialize LittleFS to save credentials + 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 + // Attempt to load credentials. If the file does not yet exist, they will be set to the default values above loadcredentials(); - //Initialize wifi + // Initialize wifi WiFi.mode(WIFI_STA); WiFi.begin(ssid, wifi_pw); if (WiFi.waitForConnectResult() != WL_CONNECTED) { @@ -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(); @@ -127,49 +127,48 @@ void loop() { server.handleClient(); } -//This function redirects home -void redirect(){ +// This function redirects home +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. +// 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(){ +// This function sends a simple webpage for changing login credentials to the client +void showcredentialpage() { Serial.println("Show credential page called."); - if(!session_authenticated()){ - return; - } + if (!session_authenticated()) { return; } Serial.println("Forming credential modification page."); String page; page = R"()"; - page+= - R"( + page += + R"(

Login Credentials


- + Login:

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


- )" - ; + )"; page += R"()"; @@ -188,17 +186,16 @@ void showcredentialpage(){ server.send(200, "text/html", page); } -//Saves credentials to LittleFS -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); +// Saves credentials to LittleFS +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); - //Save new values to LittleFS for loading on next reboot + // 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,19 +206,18 @@ void savecredentials(String new_login, String new_password) Serial.println("Credentials saved."); } -//loads credentials from LittleFS -void loadcredentials() -{ +// loads credentials from LittleFS +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,17 +225,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. +// This function handles a credential change from a client. void handlecredentialchange() { Serial.println("Handle credential change called."); - if(!session_authenticated()){ - return; - } + if (!session_authenticated()) { return; } Serial.println("Handling credential change request from client."); @@ -247,9 +241,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..4e2ef12ce0 100644 --- a/libraries/ESP8266WebServer/examples/PathArgServer/PathArgServer.ino +++ b/libraries/ESP8266WebServer/examples/PathArgServer/PathArgServer.ino @@ -8,7 +8,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char *ssid = STASSID; @@ -33,9 +33,7 @@ void setup(void) { Serial.print("IP address: "); Serial.println(WiFi.localIP()); - if (MDNS.begin("esp8266")) { - Serial.println("MDNS responder started"); - } + if (MDNS.begin("esp8266")) { Serial.println("MDNS responder started"); } server.on(F("/"), []() { server.send(200, "text/plain", "hello from esp8266!"); diff --git a/libraries/ESP8266WebServer/examples/PostServer/PostServer.ino b/libraries/ESP8266WebServer/examples/PostServer/PostServer.ino index da1703807a..2785e37979 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); @@ -62,9 +62,7 @@ void handleForm() { } else { digitalWrite(led, 1); String message = "POST form was:\n"; - for (uint8_t i = 0; i < server.args(); i++) { - message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; - } + for (uint8_t i = 0; i < server.args(); i++) { message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; } server.send(200, "text/plain", message); digitalWrite(led, 0); } @@ -80,9 +78,7 @@ void handleNotFound() { message += "\nArguments: "; message += server.args(); message += "\n"; - for (uint8_t i = 0; i < server.args(); i++) { - message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; - } + 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); } @@ -105,9 +101,7 @@ void setup(void) { Serial.print("IP address: "); Serial.println(WiFi.localIP()); - if (MDNS.begin("esp8266")) { - Serial.println("MDNS responder started"); - } + if (MDNS.begin("esp8266")) { Serial.println("MDNS responder started"); } server.on("/", handleRoot); diff --git a/libraries/ESP8266WebServer/examples/ServerSentEvents/ServerSentEvents.ino b/libraries/ESP8266WebServer/examples/ServerSentEvents/ServerSentEvents.ino index 77ae1e958e..7c462295cd 100644 --- a/libraries/ESP8266WebServer/examples/ServerSentEvents/ServerSentEvents.ino +++ b/libraries/ESP8266WebServer/examples/ServerSentEvents/ServerSentEvents.ino @@ -42,11 +42,11 @@ extern "C" { #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; const unsigned int port = 80; ESP8266WebServer server(port); @@ -76,20 +76,16 @@ void handleNotFound() { message += "\nArguments: "; message += server.args(); message += "\n"; - for (uint8_t i = 0; i < server.args(); i++) { - message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; - } + for (uint8_t i = 0; i < server.args(); i++) { message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; } server.send(404, "text/plain", message); } void SSEKeepAlive() { for (uint8_t i = 0; i < SSE_MAX_CHANNELS; i++) { - if (!(subscription[i].clientIP)) { - continue; - } + if (!(subscription[i].clientIP)) { continue; } 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(); @@ -106,15 +102,15 @@ void SSEKeepAlive() { void SSEHandler(uint8_t channel) { WiFiClient client = server.client(); SSESubscription &s = subscription[channel]; - if (s.clientIP != client.remoteIP()) { // IP addresses don't match, reject this client + 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(); } client.setNoDelay(true); client.setSync(true); Serial.printf_P(PSTR("SSEHandler - registered client with IP %s is listening\n"), IPAddress(s.clientIP).toString().c_str()); - s.client = client; // capture SSE server client connection - server.setContentLength(CONTENT_LENGTH_UNKNOWN); // the payload can go on forever + 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 } @@ -122,28 +118,20 @@ void SSEHandler(uint8_t channel) { void handleAll() { const char *uri = server.uri().c_str(); const char *restEvents = PSTR("/rest/events/"); - if (strncmp_P(uri, restEvents, strlen_P(restEvents))) { - return handleNotFound(); - } - uri += strlen_P(restEvents); // Skip the "/rest/events/" and get to the channel number + if (strncmp_P(uri, restEvents, strlen_P(restEvents))) { return handleNotFound(); } + uri += strlen_P(restEvents); // Skip the "/rest/events/" and get to the channel number unsigned int channel = atoi(uri); - if (channel < SSE_MAX_CHANNELS) { - return SSEHandler(channel); - } + if (channel < SSE_MAX_CHANNELS) { return SSEHandler(channel); } handleNotFound(); }; 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; - } + if (!(subscription[i].clientIP)) { continue; } 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); - subscription[i].client.printf_P(PSTR("event: event\ndata: {\"TYPE\":\"STATE\", \"%s\":{\"state\":%d, \"prevState\":%d}}\n\n"), - sensorName, sensorValue, prevSensorValue); + 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); + subscription[i].client.printf_P(PSTR("event: event\ndata: {\"TYPE\":\"STATE\", \"%s\":{\"state\":%d, \"prevState\":%d}}\n\n"), sensorName, sensorValue, prevSensorValue); } else { Serial.printf_P(PSTR("SSEBroadcastState - client %s registered on channel %d but not listening\n"), IPaddrstr.c_str(), i); } @@ -152,7 +140,7 @@ void SSEBroadcastState(const char *sensorName, unsigned short prevSensorValue, u // Simulate sensors void updateSensor(sensorType &sensor) { - unsigned short newVal = (unsigned short)RANDOM_REG32; // (not so good) random value for the 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 @@ -167,7 +155,7 @@ void handleSubscribe() { } 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(":"); @@ -176,14 +164,12 @@ void handleSubscribe() { SSEurl += F("/rest/events/"); ++subscriptionCount; - for (channel = 0; channel < SSE_MAX_CHANNELS; channel++) // Find first free slot - if (!subscription[channel].clientIP) { - break; - } - subscription[channel] = {clientIP, server.client(), Ticker()}; + for (channel = 0; channel < SSE_MAX_CHANNELS; channel++) // Find first free slot + if (!subscription[channel].clientIP) { break; } + 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]))); + // server.on(SSEurl.substring(offset), std::bind(SSEHandler, &(subscription[channel]))); Serial.printf_P(PSTR("subscription for client IP %s: event bus location: %s\n"), clientIP.toString().c_str(), SSEurl.c_str()); server.send_P(200, "text/plain", SSEurl.c_str()); } @@ -200,16 +186,14 @@ 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("."); } Serial.printf_P(PSTR("\nConnected to %s with IP address: %s\n"), ssid, WiFi.localIP().toString().c_str()); - if (MDNS.begin("esp8266")) { - Serial.println("MDNS responder started"); - } + if (MDNS.begin("esp8266")) { 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..aaea090ed9 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; @@ -12,7 +12,7 @@ const char* password = STAPSK; ESP8266WebServer server(80); -//Check if header is present and correct +// Check if header is present and correct bool is_authenticated() { Serial.println("Enter is_authenticated"); if (server.hasHeader("Cookie")) { @@ -28,7 +28,7 @@ bool is_authenticated() { return false; } -//login page, also called for disconnect +// login page, also called for disconnect void handleLogin() { String msg; if (server.hasHeader("Cookie")) { @@ -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"); @@ -64,7 +64,7 @@ void handleLogin() { server.send(200, "text/html", content); } -//root page can be accessed only if authentication is ok +// root page can be accessed only if authentication is ok void handleRoot() { Serial.println("Enter handleRoot"); String header; @@ -75,14 +75,12 @@ void handleRoot() { return; } String content = "

hello, you successfully connected to esp8266!


"; - if (server.hasHeader("User-Agent")) { - content += "the user agent used is : " + server.header("User-Agent") + "

"; - } + if (server.hasHeader("User-Agent")) { content += "the user agent used is : " + server.header("User-Agent") + "

"; } content += "You can access this page until you disconnect"; server.send(200, "text/html", content); } -//no need authentication +// no need authentication void handleNotFound() { String message = "File Not Found\n\n"; message += "URI: "; @@ -92,9 +90,7 @@ void handleNotFound() { message += "\nArguments: "; message += server.args(); message += "\n"; - for (uint8_t i = 0; i < server.args(); i++) { - message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; - } + for (uint8_t i = 0; i < server.args(); i++) { message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; } server.send(404, "text/plain", message); } @@ -123,7 +119,7 @@ void setup(void) { }); server.onNotFound(handleNotFound); - //ask server to track these headers + // ask server to track these headers server.collectHeaders("User-Agent", "Cookie"); server.begin(); Serial.println("HTTP server started"); diff --git a/libraries/ESP8266WebServer/examples/WebServer/WebServer.ino b/libraries/ESP8266WebServer/examples/WebServer/WebServer.ino index 08107586fd..81a58478f9 100644 --- a/libraries/ESP8266WebServer/examples/WebServer/WebServer.ino +++ b/libraries/ESP8266WebServer/examples/WebServer/WebServer.ino @@ -9,10 +9,10 @@ #include #include -#include "secrets.h" // add WLAN Credentials in here. +#include "secrets.h" // add WLAN Credentials in here. -#include // File System for Web Server Files -#include // This file system is used. +#include // File System for Web Server Files +#include // This file system is used. // mark parameters not used in example #define UNUSED __attribute__((unused)) @@ -41,13 +41,11 @@ void handleRedirect() { TRACE("Redirect..."); String url = "/index.htm"; - if (!LittleFS.exists(url)) { - url = "/$update.htm"; - } + if (!LittleFS.exists(url)) { url = "/$update.htm"; } server.sendHeader("Location", url, true); server.send(302); -} // handleRedirect() +} // handleRedirect() // This function is called when the WebServer was requested to list all existing files in the filesystem. @@ -58,20 +56,18 @@ void handleListFiles() { result += "[\n"; while (dir.next()) { - if (result.length() > 4) { - result += ","; - } + if (result.length() > 4) { result += ","; } result += " {"; result += " \"name\": \"" + dir.fileName() + "\", "; result += " \"size\": " + String(dir.fileSize()) + ", "; result += " \"time\": " + String(dir.fileTime()); result += " }\n"; // jc.addProperty("size", dir.fileSize()); - } // while + } // while result += "]"; server.sendHeader("Cache-Control", "no-cache"); server.send(200, "text/javascript; charset=utf-8", result); -} // handleListFiles() +} // handleListFiles() // This function is called when the sysInfo service was requested. @@ -90,96 +86,84 @@ void handleSysInfo() { server.sendHeader("Cache-Control", "no-cache"); server.send(200, "text/javascript; charset=utf-8", result); -} // handleSysInfo() +} // 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() - - - 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. - - } 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 (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() - - protected: - File _fsUploadFile; +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() + + + 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. + + } 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 (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() + +protected: + File _fsUploadFile; }; // Setup everything to make the webserver work. void setup(void) { - delay(3000); // wait for serial monitor to start completely. + delay(3000); // wait for serial monitor to start completely. // Use Serial port for some trace information from the example Serial.begin(115200); @@ -250,12 +234,12 @@ void setup(void) { server.begin(); TRACE("hostname=%s\n", WiFi.getHostname()); -} // setup +} // setup // run the server... void loop(void) { server.handleClient(); -} // loop() +} // loop() // end. diff --git a/libraries/ESP8266WebServer/examples/WebUpdate/WebUpdate.ino b/libraries/ESP8266WebServer/examples/WebUpdate/WebUpdate.ino index 17646fd172..728889a916 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,34 +31,36 @@ void setup(void) { server.sendHeader("Connection", "close"); server.send(200, "text/html", serverIndex); }); - server.on("/update", HTTP_POST, []() { - server.sendHeader("Connection", "close"); - server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK"); - ESP.restart(); - }, []() { - HTTPUpload& upload = server.upload(); - if (upload.status == UPLOAD_FILE_START) { - Serial.setDebugOutput(true); - WiFiUDP::stopAll(); - Serial.printf("Update: %s\n", upload.filename.c_str()); - uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000; - if (!Update.begin(maxSketchSpace)) { //start with max available size - Update.printError(Serial); - } - } else if (upload.status == UPLOAD_FILE_WRITE) { - if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) { - Update.printError(Serial); + server.on( + "/update", HTTP_POST, []() { + server.sendHeader("Connection", "close"); + server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK"); + ESP.restart(); + }, + []() { + HTTPUpload& upload = server.upload(); + if (upload.status == UPLOAD_FILE_START) { + Serial.setDebugOutput(true); + WiFiUDP::stopAll(); + Serial.printf("Update: %s\n", upload.filename.c_str()); + uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000; + if (!Update.begin(maxSketchSpace)) { // start with max available size + Update.printError(Serial); + } + } else if (upload.status == UPLOAD_FILE_WRITE) { + if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) { + Update.printError(Serial); + } + } else if (upload.status == UPLOAD_FILE_END) { + if (Update.end(true)) { // true to set the size to the current progress + Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize); + } else { + Update.printError(Serial); + } + Serial.setDebugOutput(false); } - } else if (upload.status == UPLOAD_FILE_END) { - if (Update.end(true)) { //true to set the size to the current progress - Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize); - } else { - Update.printError(Serial); - } - 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..fd543933b4 100644 --- a/libraries/ESP8266WiFi/examples/BearSSL_CertStore/BearSSL_CertStore.ino +++ b/libraries/ESP8266WiFi/examples/BearSSL_CertStore/BearSSL_CertStore.ino @@ -41,7 +41,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char *ssid = STASSID; @@ -72,9 +72,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) { - if (!path) { - path = "/"; - } + if (!path) { path = "/"; } Serial.printf("Trying: %s:443...", host); client->connect(host, port); @@ -94,11 +92,9 @@ void fetchURL(BearSSL::WiFiClientSecure *client, const char *host, const uint16_ do { char tmp[32]; memset(tmp, 0, 32); - int rlen = client->read((uint8_t*)tmp, sizeof(tmp) - 1); + int rlen = client->read((uint8_t *)tmp, sizeof(tmp) - 1); yield(); - if (rlen < 0) { - break; - } + if (rlen < 0) { break; } // Only print out first line up to \r, then abort connection char *nl = strchr(tmp, '\r'); if (nl) { @@ -136,13 +132,13 @@ void setup() { Serial.println("IP address: "); Serial.println(WiFi.localIP()); - setClock(); // Required for X.509 validation + setClock(); // Required for X.509 validation int numCerts = certStore.initCertStore(LittleFS, PSTR("/certs.idx"), PSTR("/certs.ar")); Serial.printf("Number of CA certs read: %d\n", numCerts); if (numCerts == 0) { Serial.printf("No certs found. Did you run certs-from-mozilla.py and upload the LittleFS directory before running?\n"); - return; // Can't connect to anything w/o certs! + return; // Can't connect to anything w/o certs! } BearSSL::WiFiClientSecure *bear = new BearSSL::WiFiClientSecure(); @@ -156,9 +152,7 @@ void setup() { void loop() { Serial.printf("\nPlease enter a website address (www.blah.com) to connect to: "); String site; - do { - site = Serial.readString(); - } while (site == ""); + do { site = Serial.readString(); } while (site == ""); // Strip newline if present site.replace(String("\r"), emptyString); site.replace(String("\n"), emptyString); @@ -170,4 +164,3 @@ void loop() { 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..03b619f932 100644 --- a/libraries/ESP8266WiFi/examples/BearSSL_MaxFragmentLength/BearSSL_MaxFragmentLength.ino +++ b/libraries/ESP8266WiFi/examples/BearSSL_MaxFragmentLength/BearSSL_MaxFragmentLength.ino @@ -9,7 +9,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char *ssid = STASSID; @@ -22,13 +22,11 @@ void fetch(BearSSL::WiFiClientSecure *client) { oneShot timeout(5000); do { char tmp[32]; - int rlen = client->read((uint8_t*)tmp, sizeof(tmp) - 1); + int rlen = client->read((uint8_t *)tmp, sizeof(tmp) - 1); yield(); - if (rlen < 0) { - break; - } + if (rlen < 0) { break; } if (rlen == 0) { - delay(10); // Give background processes some time + delay(10); // Give background processes some time continue; } tmp[rlen] = '\0'; @@ -82,9 +80,7 @@ int fetchMaxFragmentLength() { bool mfln = client.probeMaxFragmentLength("tls.mbed.org", 443, 512); Serial.printf("\nConnecting to https://tls.mbed.org\n"); Serial.printf("MFLN supported: %s\n", mfln ? "yes" : "no"); - if (mfln) { - client.setBufferSizes(512, 512); - } + if (mfln) { client.setBufferSizes(512, 512); } client.connect("tls.mbed.org", 443); if (client.connected()) { Serial.printf("MFLN status: %s\n", client.getMFLNStatus() ? "true" : "false"); diff --git a/libraries/ESP8266WiFi/examples/BearSSL_Server/BearSSL_Server.ino b/libraries/ESP8266WiFi/examples/BearSSL_Server/BearSSL_Server.ino index 160b6a981e..299324af31 100644 --- a/libraries/ESP8266WiFi/examples/BearSSL_Server/BearSSL_Server.ino +++ b/libraries/ESP8266WiFi/examples/BearSSL_Server/BearSSL_Server.ino @@ -39,7 +39,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char *ssid = STASSID; @@ -138,11 +138,11 @@ 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 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 DYNAMIC_CACHE // Whether to dynamically allocate the cache. #if defined(USE_CACHE) && defined(DYNAMIC_CACHE) @@ -181,7 +181,7 @@ void setup() { #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,31 +193,28 @@ 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; BearSSL::WiFiClientSecure incoming = server.accept(); - if (!incoming) { - return; - } - Serial.printf("Incoming connection...%d\n",cnt++); - + if (!incoming) { return; } + 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"); @@ -228,14 +225,12 @@ void loop() { } else if (x == 0x0D) { continue; } else if (x == 0x0A) { - if (lcwn) { - break; - } + if (lcwn) { break; } lcwn = 1; } else lcwn = 0; } - incoming.write((uint8_t*)HTTP_RES, strlen(HTTP_RES)); + incoming.write((uint8_t *)HTTP_RES, strlen(HTTP_RES)); incoming.flush(); incoming.stop(); Serial.printf("Connection closed.\n"); diff --git a/libraries/ESP8266WiFi/examples/BearSSL_ServerClientCert/BearSSL_ServerClientCert.ino b/libraries/ESP8266WiFi/examples/BearSSL_ServerClientCert/BearSSL_ServerClientCert.ino index 3e88019cf4..d05ccb3dd3 100644 --- a/libraries/ESP8266WiFi/examples/BearSSL_ServerClientCert/BearSSL_ServerClientCert.ino +++ b/libraries/ESP8266WiFi/examples/BearSSL_ServerClientCert/BearSSL_ServerClientCert.ino @@ -67,7 +67,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char *ssid = STASSID; @@ -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: "); @@ -199,7 +198,7 @@ void setup() { Serial.println("IP address: "); Serial.println(WiFi.localIP()); - setClock(); // Required for X.509 validation + setClock(); // Required for X.509 validation // Attach the server private cert/key combo BearSSL::X509List *serverCertList = new BearSSL::X509List(server_cert); @@ -214,30 +213,27 @@ void setup() { 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(); - if (!incoming) { - return; - } + if (!incoming) { 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"); @@ -248,14 +244,12 @@ void loop() { } else if (x == 0x0D) { continue; } else if (x == 0x0A) { - if (lcwn) { - break; - } + if (lcwn) { break; } lcwn = 1; } else lcwn = 0; } - incoming.write((uint8_t*)HTTP_RES, strlen(HTTP_RES)); + incoming.write((uint8_t *)HTTP_RES, strlen(HTTP_RES)); incoming.flush(); incoming.stop(); Serial.printf("Connection closed.\n"); diff --git a/libraries/ESP8266WiFi/examples/BearSSL_Sessions/BearSSL_Sessions.ino b/libraries/ESP8266WiFi/examples/BearSSL_Sessions/BearSSL_Sessions.ino index fa03c7fa38..f147b361d9 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 * path = "/"; +const char *path = "/"; void setup() { Serial.begin(115200); @@ -53,9 +53,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) { - if (!path) { - path = "/"; - } + if (!path) { path = "/"; } Serial.printf("Trying: %s:443...", host); client->connect(host, port); @@ -75,11 +73,9 @@ void fetchURL(BearSSL::WiFiClientSecure *client, const char *host, const uint16_ do { char tmp[32]; memset(tmp, 0, 32); - int rlen = client->read((uint8_t*)tmp, sizeof(tmp) - 1); + int rlen = client->read((uint8_t *)tmp, sizeof(tmp) - 1); yield(); - if (rlen < 0) { - break; - } + if (rlen < 0) { break; } // Only print out first line up to \r, then abort connection char *nl = strchr(tmp, '\r'); if (nl) { @@ -130,6 +126,5 @@ void loop() { finish = millis(); Serial.printf("Total time: %dms\n", finish - start); - delay(10000); // Avoid DDOSing github + 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..7667579157 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 * path = "/"; +const char *path = "/"; // Set time via NTP, as required for x.509 validation void setClock() { @@ -40,9 +40,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) { - if (!path) { - path = "/"; - } + if (!path) { path = "/"; } ESP.resetFreeContStack(); uint32_t freeStackStart = ESP.getFreeContStack(); @@ -64,11 +62,9 @@ void fetchURL(BearSSL::WiFiClientSecure *client, const char *host, const uint16_ do { char tmp[32]; memset(tmp, 0, 32); - int rlen = client->read((uint8_t*)tmp, sizeof(tmp) - 1); + int rlen = client->read((uint8_t *)tmp, sizeof(tmp) - 1); yield(); - if (rlen < 0) { - break; - } + if (rlen < 0) { break; } // Only print out first line up to \r, then abort connection char *nl = strchr(tmp, '\r'); if (nl) { diff --git a/libraries/ESP8266WiFi/examples/HTTPSRequest/HTTPSRequest.ino b/libraries/ESP8266WiFi/examples/HTTPSRequest/HTTPSRequest.ino index 9ccf3b6b37..5b25b40559 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()) { @@ -100,5 +97,4 @@ void setup() { Serial.println("Closing connection"); } -void loop() { -} +void loop() {} diff --git a/libraries/ESP8266WiFi/examples/IPv6/IPv6.ino b/libraries/ESP8266WiFi/examples/IPv6/IPv6.ino index 560d9bfe46..a3d6d58751 100644 --- a/libraries/ESP8266WiFi/examples/IPv6/IPv6.ino +++ b/libraries/ESP8266WiFi/examples/IPv6/IPv6.ino @@ -23,12 +23,12 @@ #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 FQDN6 F("ipv6.google.com") // does not resolve in IPv4 +#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 #define UDP_PORT 23 @@ -71,29 +71,17 @@ void status(Print& out) { for (int i = 0; i < DNS_MAX_SERVERS; i++) { IPAddress dns = WiFi.dnsIP(i); - if (dns.isSet()) { - out.printf("dns%d: %s\n", i, dns.toString().c_str()); - } + if (dns.isSet()) { out.printf("dns%d: %s\n", i, dns.toString().c_str()); } } out.println(F("Try me at these addresses:")); 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()); - - if (a.isLegacy()) { - out.printf(" / mask:%s / gw:%s", - a.netmask().toString().c_str(), - a.gw().toString().c_str()); - } + 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()); - out.println(); + if (a.isLegacy()) { out.printf(" / mask:%s / gw:%s", a.netmask().toString().c_str(), a.gw().toString().c_str()); } + out.println(); } // lwIP's dns client will ask for IPv4 first (by default) @@ -101,8 +89,8 @@ 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, FQDN2, DNSResolveType::DNS_AddrType_IPv6_IPv4); // IPv6 before IPv4 + 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("------------------------------")); } @@ -125,7 +113,7 @@ void setup() { status(Serial); -#if 0 // 0: legacy connecting loop - 1: wait for IPv6 +#if 0 // 0: legacy connecting loop - 1: wait for IPv6 // legacy loop (still valid with IPv4 only) @@ -146,11 +134,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 - )) { - break; - } + // && addr.isV6() // uncomment when IPv6 is mandatory + // && addr.ifnumber() == STATION_IF + )) { break; } Serial.print('.'); delay(500); } @@ -188,10 +174,8 @@ void loop() { udp.remoteIP().printTo(Serial); Serial.print(F(" :")); Serial.println(udp.remotePort()); - int c; - while ((c = udp.read()) >= 0) { - Serial.write(c); - } + int c; + while ((c = udp.read()) >= 0) { Serial.write(c); } // send a reply, to the IP address and port that sent us the packet we received udp.beginPacket(udp.remoteIP(), udp.remotePort()); @@ -200,8 +184,5 @@ void loop() { } - if (showStatusOnSerialNow) { - status(Serial); - } - + if (showStatusOnSerialNow) { status(Serial); } } diff --git a/libraries/ESP8266WiFi/examples/NTPClient/NTPClient.ino b/libraries/ESP8266WiFi/examples/NTPClient/NTPClient.ino index 927e78fee9..0ef1203667 100644 --- a/libraries/ESP8266WiFi/examples/NTPClient/NTPClient.ino +++ b/libraries/ESP8266WiFi/examples/NTPClient/NTPClient.ino @@ -23,24 +23,24 @@ #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 */ -//IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server -IPAddress timeServerIP; // time.nist.gov NTP server address +// IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server +IPAddress timeServerIP; // time.nist.gov NTP server address const char* ntpServerName = "time.nist.gov"; -const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message +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; @@ -73,10 +73,10 @@ void setup() { } void loop() { - //get a random server from the pool + // get a random server from the pool WiFi.hostByName(ntpServerName, timeServerIP); - sendNTPpacket(timeServerIP); // send an NTP packet to a time server + sendNTPpacket(timeServerIP); // send an NTP packet to a time server // wait to see if a reply is available delay(1000); @@ -87,10 +87,10 @@ void loop() { Serial.print("packet received, length="); Serial.println(cb); // We've received a packet, read the data from it - udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer + udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer - //the timestamp starts at byte 40 of the received packet and is four bytes, - // or two words, long. First, esxtract the two words: + // the timestamp starts at byte 40 of the received packet and is four bytes, + // or two words, long. First, esxtract the two words: unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]); @@ -112,19 +112,19 @@ void loop() { // 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((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' Serial.print('0'); } - Serial.println(epoch % 60); // print the second + Serial.println(epoch % 60); // print the second } // wait ten seconds before asking for the time again delay(10000); @@ -137,19 +137,19 @@ 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: - udp.beginPacket(address, 123); //NTP requests are to port 123 + udp.beginPacket(address, 123); // NTP requests are to port 123 udp.write(packetBuffer, NTP_PACKET_SIZE); udp.endPacket(); } diff --git a/libraries/ESP8266WiFi/examples/PagerServer/PagerServer.ino b/libraries/ESP8266WiFi/examples/PagerServer/PagerServer.ino index 43f8fe981c..a19ffa42f7 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); @@ -60,13 +60,13 @@ void setup() { void loop() { - WiFiClient client = server.available(); // returns first client which has data to read or a 'false' client - if (client) { // client is true only if it is connected and has data to read - String s = client.readStringUntil('\n'); // read the message incoming from one of the clients - s.trim(); // trim eventual \r - Serial.println(s); // print the message to Serial Monitor - client.print("echo: "); // this is only for the sending client - server.println(s); // send the message to all connected clients - server.flush(); // flush the buffers + WiFiClient client = server.available(); // returns first client which has data to read or a 'false' client + if (client) { // client is true only if it is connected and has data to read + String s = client.readStringUntil('\n'); // read the message incoming from one of the clients + s.trim(); // trim eventual \r + Serial.println(s); // print the message to Serial Monitor + client.print("echo: "); // this is only for the sending client + server.println(s); // send the message to all connected clients + server.flush(); // flush the buffers } } diff --git a/libraries/ESP8266WiFi/examples/RangeExtender-NAPT/RangeExtender-NAPT.ino b/libraries/ESP8266WiFi/examples/RangeExtender-NAPT/RangeExtender-NAPT.ino index a98e894873..2c62ded038 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 @@ -30,7 +30,7 @@ void dump(int netif_idx, const char* data, size_t len, int out, int success) { // optional filter example: if (netDump_is_ARP(data)) { netDump(Serial, data, len); - //netDumpHex(Serial, data, len); + // netDumpHex(Serial, data, len); } } #endif @@ -51,19 +51,14 @@ void setup() { Serial.print('.'); 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()); + 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()); // 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)); + 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()); @@ -73,14 +68,10 @@ void setup() { if (ret == ERR_OK) { ret = ip_napt_enable_no(SOFTAP_IF, 1); Serial.printf("ip_napt_enable_no(SOFTAP_IF): ret=%d (OK=%d)\n", (int)ret, (int)ERR_OK); - if (ret == ERR_OK) { - Serial.printf("WiFi Network '%s' with same password is now NATed behind '%s'\n", STASSID "extender", STASSID); - } + if (ret == ERR_OK) { Serial.printf("WiFi Network '%s' with same password is now NATed behind '%s'\n", STASSID "extender", STASSID); } } Serial.printf("Heap after napt init: %d\n", ESP.getFreeHeap()); - if (ret != ERR_OK) { - Serial.printf("NAPT initialization failed\n"); - } + if (ret != ERR_OK) { Serial.printf("NAPT initialization failed\n"); } } #else @@ -92,6 +83,4 @@ void setup() { #endif -void loop() { -} - +void loop() {} diff --git a/libraries/ESP8266WiFi/examples/Udp/Udp.ino b/libraries/ESP8266WiFi/examples/Udp/Udp.ino index 7ec287b392..23d6af8de1 100644 --- a/libraries/ESP8266WiFi/examples/Udp/Udp.ino +++ b/libraries/ESP8266WiFi/examples/Udp/Udp.ino @@ -20,14 +20,14 @@ #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 packetBuffer[UDP_TX_PACKET_MAX_SIZE + 1]; // buffer to hold incoming packet, +char ReplyBuffer[] = "acknowledged\r\n"; // a string to send back WiFiUDP Udp; @@ -49,11 +49,7 @@ void loop() { // if there's data available, read a packet 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()); + 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()); // read the packet into packetBufffer int n = Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE); @@ -66,11 +62,10 @@ void loop() { Udp.write(ReplyBuffer); Udp.endPacket(); } - } /* test (shell/netcat): -------------------- - nc -u 192.168.esp.address 8888 + nc -u 192.168.esp.address 8888 */ diff --git a/libraries/ESP8266WiFi/examples/WiFiAccessPoint/WiFiAccessPoint.ino b/libraries/ESP8266WiFi/examples/WiFiAccessPoint/WiFiAccessPoint.ino index 6fea68f590..15dd93c83d 100644 --- a/libraries/ESP8266WiFi/examples/WiFiAccessPoint/WiFiAccessPoint.ino +++ b/libraries/ESP8266WiFi/examples/WiFiAccessPoint/WiFiAccessPoint.ino @@ -36,7 +36,7 @@ #ifndef APSSID #define APSSID "ESPap" -#define APPSK "thereisnospoon" +#define APPSK "thereisnospoon" #endif /* Set these to your desired credentials. */ diff --git a/libraries/ESP8266WiFi/examples/WiFiClient/WiFiClient.ino b/libraries/ESP8266WiFi/examples/WiFiClient/WiFiClient.ino index ef9016063b..cddb262a77 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"; @@ -61,9 +61,7 @@ void loop() { // This will send a string to the server Serial.println("sending data to server"); - if (client.connected()) { - client.println("hello from ESP8266"); - } + if (client.connected()) { client.println("hello from ESP8266"); } // wait for data to be available unsigned long timeout = millis(); @@ -90,7 +88,7 @@ void loop() { client.stop(); if (wait) { - delay(300000); // execute once every 5 minutes, don't flood remote service + delay(300000); // execute once every 5 minutes, don't flood remote service } wait = true; } diff --git a/libraries/ESP8266WiFi/examples/WiFiClientBasic/WiFiClientBasic.ino b/libraries/ESP8266WiFi/examples/WiFiClientBasic/WiFiClientBasic.ino index e442282e37..4be0d2b9d0 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"; @@ -64,7 +64,7 @@ void loop() { // This will send the request to the server client.println("hello from ESP8266"); - //read back one line from server + // read back one line from server Serial.println("receiving from remote server"); String line = client.readStringUntil('\r'); Serial.println(line); @@ -75,4 +75,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..c4a6cb788d 100644 --- a/libraries/ESP8266WiFi/examples/WiFiEcho/WiFiEcho.ino +++ b/libraries/ESP8266WiFi/examples/WiFiEcho/WiFiEcho.ino @@ -7,11 +7,11 @@ #include #include #include -#include // std::min +#include // std::min #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif constexpr int port = 23; @@ -19,12 +19,12 @@ 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); -int t = 1; // test (1, 2 or 3, see below) -int s = 0; // sizes[] index +int t = 1; // test (1, 2 or 3, see below) +int s = 0; // sizes[] index void setup() { @@ -63,19 +63,13 @@ void loop() { static uint32_t cnt = 0; if (test && cnt) { Serial.printf("measured-block-size=%u min-free-stack=%u", tot / cnt, ESP.getFreeContStack()); - if (t == 2 && sizes[s]) { - Serial.printf(" (blocks: at most %d bytes)", sizes[s]); - } - if (t == 3 && sizes[s]) { - Serial.printf(" (blocks: exactly %d bytes)", sizes[s]); - } - if (t == 3 && !sizes[s]) { - Serial.printf(" (blocks: any size)"); - } + if (t == 2 && sizes[s]) { Serial.printf(" (blocks: at most %d bytes)", sizes[s]); } + if (t == 3 && sizes[s]) { Serial.printf(" (blocks: exactly %d bytes)", sizes[s]); } + if (t == 3 && !sizes[s]) { Serial.printf(" (blocks: any size)"); } Serial.printf("\n"); } - //check if there are any new clients + // check if there are any new clients if (server.hasClient()) { client = server.accept(); Serial.println("New client"); @@ -84,10 +78,25 @@ 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(); @@ -113,9 +122,7 @@ void loop() { uint8_t buf[maxTo]; size_t tcp_got = client.read(buf, maxTo); size_t tcp_sent = client.write(buf, tcp_got); - if (tcp_sent != maxTo) { - Serial.printf("len mismatch: available:%zd tcp-read:%zd serial-write:%zd\n", maxTo, tcp_got, tcp_sent); - } + if (tcp_sent != maxTo) { Serial.printf("len mismatch: available:%zd tcp-read:%zd serial-write:%zd\n", maxTo, tcp_got, tcp_sent); } tot += tcp_sent; cnt++; } @@ -141,7 +148,7 @@ void loop() { else if (t == 4) { // stream to print, possibly with only one copy - tot += client.sendAll(&client); // this one might not exit until peer close + tot += client.sendAll(&client); // this one might not exit until peer close cnt++; switch (client.getLastSendReport()) { @@ -152,5 +159,4 @@ void loop() { 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..dddfde9f5b 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; @@ -98,7 +98,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]); + snprintf(buf, sizeof(buf), "%02x:%02x:%02x:%02x:%02x:%02x", 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..0526908a34 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; @@ -55,12 +55,10 @@ void setup() { void loop() { // Check if a client has connected WiFiClient client = server.accept(); - if (!client) { - return; - } + if (!client) { return; } Serial.println(F("new client")); - client.setTimeout(5000); // default is 1000 + client.setTimeout(5000); // default is 1000 // Read the first line of the request String req = client.readStringUntil('\r'); diff --git a/libraries/ESP8266WiFi/examples/WiFiScan/WiFiScan.ino b/libraries/ESP8266WiFi/examples/WiFiScan/WiFiScan.ino index b546df4a7d..7cb8fa9dd6 100644 --- a/libraries/ESP8266WiFi/examples/WiFiScan/WiFiScan.ino +++ b/libraries/ESP8266WiFi/examples/WiFiScan/WiFiScan.ino @@ -40,15 +40,7 @@ void loop() { for (int8_t i = 0; i < scanResult; i++) { 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()); + 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()); yield(); } } else { diff --git a/libraries/ESP8266WiFi/examples/WiFiShutdown/WiFiShutdown.ino b/libraries/ESP8266WiFi/examples/WiFiShutdown/WiFiShutdown.ino index b03357c143..69502de862 100644 --- a/libraries/ESP8266WiFi/examples/WiFiShutdown/WiFiShutdown.ino +++ b/libraries/ESP8266WiFi/examples/WiFiShutdown/WiFiShutdown.ino @@ -17,7 +17,7 @@ #endif #include -#include // WiFiState structure details +#include // WiFiState structure details WiFiState state; @@ -26,7 +26,7 @@ const char* password = STAPSK; void setup() { Serial.begin(74880); - //Serial.setDebugOutput(true); // If you need debug output + // Serial.setDebugOutput(true); // If you need debug output Serial.println("Trying to resume WiFi connection..."); // May be necessary after deepSleep. Otherwise you may get "error: pll_cal exceeds 2ms!!!" when trying to connect @@ -36,17 +36,14 @@ 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) - || (WiFi.waitForConnectResult(10000) != WL_CONNECTED)) { + if (!WiFi.resumeFromShutdown(state) || (WiFi.waitForConnectResult(10000) != WL_CONNECTED)) { Serial.println("Cannot resume WiFi connection, connecting via begin..."); WiFi.persistent(false); - if (!WiFi.mode(WIFI_STA) - || !WiFi.begin(ssid, password) - || (WiFi.waitForConnectResult(10000) != WL_CONNECTED)) { + if (!WiFi.mode(WIFI_STA) || !WiFi.begin(ssid, password) || (WiFi.waitForConnectResult(10000) != WL_CONNECTED)) { WiFi.mode(WIFI_OFF); Serial.println("Cannot connect!"); Serial.flush(); @@ -64,7 +61,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..05bdb94aa9 100644 --- a/libraries/ESP8266WiFi/examples/WiFiTelnetToSerial/WiFiTelnetToSerial.ino +++ b/libraries/ESP8266WiFi/examples/WiFiTelnetToSerial/WiFiTelnetToSerial.ino @@ -20,11 +20,11 @@ */ #include -#include // std::min +#include // std::min #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif /* @@ -64,9 +64,9 @@ 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 +// how many clients should be able to telnet to this ESP8266 #define MAX_SRV_CLIENTS 2 const char* ssid = STASSID; const char* password = STAPSK; @@ -98,7 +98,7 @@ void setup() { logger->printf("Serial receive buffer size: %d bytes\n", RXBUFFERSIZE); #if SERIAL_LOOPBACK - USC0(0) |= (1 << UCLBE); // incomplete HardwareSerial API + USC0(0) |= (1 << UCLBE); // incomplete HardwareSerial API logger->println("Serial Internal Loopback enabled"); #endif @@ -114,7 +114,7 @@ void setup() { logger->print("connected, address="); logger->println(WiFi.localIP()); - //start server + // start server server.begin(); server.setNoDelay(true); @@ -124,19 +124,19 @@ void setup() { } void loop() { - //check if there are any new clients + // check if there are any new clients if (server.hasClient()) { - //find free/disconnected spot + // find free/disconnected spot int i; for (i = 0; i < MAX_SRV_CLIENTS; i++) - if (!serverClients[i]) { // equivalent to !serverClients[i].connected() + if (!serverClients[i]) { // equivalent to !serverClients[i].connected() serverClients[i] = server.accept(); logger->print("New client: index "); logger->print(i); break; } - //no free/disconnected spot so reject + // no free/disconnected spot so reject if (i == MAX_SRV_CLIENTS) { server.accept().println("busy"); // hints: server.accept() is a WiFiClient with short-term scope @@ -147,7 +147,7 @@ void loop() { } } - //check TCP clients for data + // check TCP clients for data #if 1 // Incredibly, this code is faster than the buffered one below - #4620 is needed // loopback/3000000baud average 348KB/s @@ -165,9 +165,7 @@ void loop() { uint8_t buf[maxToSerial]; size_t tcp_got = serverClients[i].read(buf, maxToSerial); size_t serial_sent = Serial.write(buf, tcp_got); - if (serial_sent != maxToSerial) { - logger->printf("len mismatch: available:%zd tcp-read:%zd serial-write:%zd\n", maxToSerial, tcp_got, serial_sent); - } + if (serial_sent != maxToSerial) { logger->printf("len mismatch: available:%zd tcp-read:%zd serial-write:%zd\n", maxToSerial, tcp_got, serial_sent); } } #endif @@ -189,7 +187,7 @@ void loop() { } } - //check UART for data + // check UART for data size_t len = std::min(Serial.available(), maxToTcp); len = std::min(len, (size_t)STACK_PROTECTOR); if (len) { @@ -202,9 +200,7 @@ void loop() { // ensure write space is sufficient: if (serverClients[i].availableForWrite() >= serial_got) { size_t tcp_sent = serverClients[i].write(sbuf, serial_got); - if (tcp_sent != len) { - logger->printf("len mismatch: available:%zd serial-read:%zd tcp-write:%zd\n", len, serial_got, tcp_sent); - } + if (tcp_sent != len) { logger->printf("len mismatch: available:%zd serial-read:%zd tcp-write:%zd\n", len, serial_got, tcp_sent); } } } } diff --git a/libraries/ESP8266WiFiMesh/examples/HelloEspnow/HelloEspnow.ino b/libraries/ESP8266WiFiMesh/examples/HelloEspnow/HelloEspnow.ino index 443d52e2bb..427084e312 100644 --- a/libraries/ESP8266WiFiMesh/examples/HelloEspnow/HelloEspnow.ino +++ b/libraries/ESP8266WiFiMesh/examples/HelloEspnow/HelloEspnow.ino @@ -1,4 +1,4 @@ -#define ESP8266WIFIMESH_DISABLE_COMPATIBILITY // Excludes redundant compatibility code. TODO: Should be used for new code until the compatibility code is removed with release 3.0.0 of the Arduino core. +#define ESP8266WIFIMESH_DISABLE_COMPATIBILITY // Excludes redundant compatibility code. TODO: Should be used for new code until the compatibility code is removed with release 3.0.0 of the Arduino core. #include #include @@ -19,26 +19,23 @@ namespace TypeCast = MeshTypeConversionFunctions; https://github.com/esp8266/Arduino/issues/1143 https://arduino-esp8266.readthedocs.io/en/latest/PROGMEM.html */ -constexpr char exampleMeshName[] PROGMEM = "MeshNode_"; // The name of the mesh network. Used as prefix for the node SSID and to find other network nodes in the example networkFilter and broadcastFilter functions below. -constexpr char exampleWiFiPassword[] PROGMEM = "ChangeThisWiFiPassword_TODO"; // Note: " is an illegal character. The password has to be min 8 and max 64 characters long, otherwise an AP which uses it will not be found during scans. +constexpr char exampleMeshName[] PROGMEM = "MeshNode_"; // The name of the mesh network. Used as prefix for the node SSID and to find other network nodes in the example networkFilter and broadcastFilter functions below. +constexpr char exampleWiFiPassword[] PROGMEM = "ChangeThisWiFiPassword_TODO"; // Note: " is an illegal character. The password has to be min 8 and max 64 characters long, otherwise an AP which uses it will not be found during scans. // 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 +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); @@ -61,7 +58,7 @@ String manageRequest(const String &request, MeshBackendBase &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)) { - (void)tcpIpInstance; // This is useful to remove a "unused parameter" compiler warning. Does nothing else. + (void)tcpIpInstance; // This is useful to remove a "unused parameter" compiler warning. Does nothing else. Serial.print(F("TCP/IP: ")); } else { Serial.print(F("UNKNOWN!: ")); @@ -174,7 +171,7 @@ bool broadcastFilter(String &firstTransmission, EspnowMeshBackend &meshInstance) String targetMeshName = firstTransmission.substring(0, metadataEndIndex); if (!targetMeshName.isEmpty() && meshInstance.getMeshName() != targetMeshName) { - return false; // Broadcast is for another mesh network + return false; // Broadcast is for another mesh network } else { // Remove metadata from message and mark as accepted broadcast. // Note that when you modify firstTransmission it is best to avoid using substring or other String methods that rely on null values for String length determination. @@ -198,7 +195,7 @@ bool broadcastFilter(String &firstTransmission, EspnowMeshBackend &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. + (void)meshInstance; // This is useful to remove a "unused parameter" compiler warning. Does nothing else. return true; } @@ -221,7 +218,7 @@ bool exampleTransmissionOutcomesUpdateHook(MeshBackendBase &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. + (void)transmissionSuccessful; // This is useful to remove a "unused parameter" compiler warning. Does nothing else. (void)response; (void)recipientMac; (void)responseIndex; @@ -281,8 +278,8 @@ void setup() { // Uncomment the lines below to use automatic AEAD encryption/decryption of messages sent/received. // All nodes this node wishes to communicate with must then also use encrypted messages with the same getEspnowMessageEncryptionKey(), or messages will not be accepted. // Note that using AEAD encrypted messages will reduce the number of message bytes that can be transmitted. - //espnowNode.setEspnowMessageEncryptionKey(F("ChangeThisKeySeed_TODO")); // The message encryption key should always be set manually. Otherwise a default key (all zeroes) is used. - //espnowNode.setUseEncryptedMessages(true); + // espnowNode.setEspnowMessageEncryptionKey(F("ChangeThisKeySeed_TODO")); // The message encryption key should always be set manually. Otherwise a default key (all zeroes) is used. + // espnowNode.setUseEncryptedMessages(true); } int32_t timeOfLastScan = -10000; @@ -293,10 +290,10 @@ void loop() { // Note that depending on the amount of responses to send and their length, this method can take tens or even hundreds of milliseconds to complete. // More intense transmission activity and less frequent calls to performEspnowMaintenance will likely cause the method to take longer to complete, so plan accordingly. - //Should not be used inside responseHandler, requestHandler, networkFilter or broadcastFilter callbacks since performEspnowMaintenance() can alter the ESP-NOW state. + // Should not be used inside responseHandler, requestHandler, networkFilter or broadcastFilter callbacks since performEspnowMaintenance() can alter the ESP-NOW state. EspnowMeshBackend::performEspnowMaintenance(); - if (millis() - timeOfLastScan > 10000) { // Give other nodes some time to connect between data transfers. + if (millis() - timeOfLastScan > 10000) { // Give other nodes some time to connect between data transfers. Serial.println(F("\nPerforming unencrypted ESP-NOW transmissions.")); uint32_t startTime = millis(); @@ -310,9 +307,7 @@ void loop() { espnowDelay(100); // One way to check how attemptTransmission worked out - if (espnowNode.latestTransmissionSuccessful()) { - Serial.println(F("Transmission successful.")); - } + if (espnowNode.latestTransmissionSuccessful()) { Serial.println(F("Transmission successful.")); } // Another way to check how attemptTransmission worked out if (espnowNode.latestTransmissionOutcomes().empty()) { @@ -343,20 +338,20 @@ void loop() { espnowNode.broadcast(broadcastMetadata + broadcastMessage); Serial.println(String(F("Broadcast to all mesh nodes done in ")) + String(millis() - startTime) + F(" ms.")); - espnowDelay(100); // Wait for responses (broadcasts can receive an unlimited number of responses, other transmissions can only receive one response). + espnowDelay(100); // Wait for responses (broadcasts can receive an unlimited number of responses, other transmissions can only receive one response). // 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); - espnowDelay(100); // Wait for response. + espnowDelay(100); // Wait for response. 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) { @@ -369,7 +364,7 @@ void loop() { String espnowMessage = String(F("This message is encrypted only when received by node ")) + peerMac; Serial.println(String(F("\nTransmitting: ")) + espnowMessage); espnowNode.attemptTransmission(espnowMessage, false); - espnowDelay(100); // Wait for response. + espnowDelay(100); // Wait for response. // A connection can be serialized and stored for later use. // Note that this saves the current state only, so if encrypted communication between the nodes happen after this, the stored state is invalid. @@ -383,7 +378,7 @@ void loop() { espnowMessage = String(F("This message is no longer encrypted when received by node ")) + peerMac; Serial.println(String(F("\nTransmitting: ")) + espnowMessage); espnowNode.attemptTransmission(espnowMessage, false); - espnowDelay(100); // Wait for response. + espnowDelay(100); // Wait for response. Serial.println(F("Cannot read the encrypted response...")); // Let's re-add our stored connection so we can communicate properly with targetBSSID again! @@ -392,7 +387,7 @@ void loop() { espnowMessage = String(F("This message is once again encrypted when received by node ")) + peerMac; Serial.println(String(F("\nTransmitting: ")) + espnowMessage); espnowNode.attemptTransmission(espnowMessage, false); - espnowDelay(100); // Wait for response. + espnowDelay(100); // Wait for response. Serial.println(); // If we want to remove the encrypted connection on both nodes, we can do it like this. @@ -403,7 +398,7 @@ void loop() { espnowMessage = String(F("This message is only received by node ")) + peerMac + F(". Transmitting in this way will not change the transmission state of the sender."); Serial.println(String(F("Transmitting: ")) + espnowMessage); espnowNode.attemptTransmission(espnowMessage, EspnowNetworkInfo(targetBSSID)); - espnowDelay(100); // Wait for response. + espnowDelay(100); // Wait for response. Serial.println(); @@ -423,7 +418,7 @@ void loop() { espnowMessage = String(F("Due to encrypted connection expiration, this message is no longer encrypted when received by node ")) + peerMac; Serial.println(String(F("\nTransmitting: ")) + espnowMessage); espnowNode.attemptTransmission(espnowMessage, false); - espnowDelay(100); // Wait for response. + espnowDelay(100); // Wait for response. } // Or if we prefer we can just let the library automatically create brief encrypted connections which are long enough to transmit an encrypted message. @@ -432,9 +427,9 @@ void loop() { espnowMessage = F("This message is always encrypted, regardless of receiver."); Serial.println(String(F("\nTransmitting: ")) + espnowMessage); espnowNode.attemptAutoEncryptingTransmission(espnowMessage); - espnowDelay(100); // Wait for response. + 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 @@ -445,8 +440,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.setMessage(String(F("Hello world request #")) + String(++requestNumber) + F(" from ") + 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..4129882acf 100644 --- a/libraries/ESP8266WiFiMesh/examples/HelloMesh/HelloMesh.ino +++ b/libraries/ESP8266WiFiMesh/examples/HelloMesh/HelloMesh.ino @@ -8,7 +8,7 @@ Or "floodingMesh.getEspnowMeshBackend().setBroadcastTransmissionRedundancy(uint8_t redundancy)" (default 1) at the cost of longer transmission times. */ -#define ESP8266WIFIMESH_DISABLE_COMPATIBILITY // Excludes redundant compatibility code. TODO: Should be used for new code until the compatibility code is removed with release 3.0.0 of the Arduino core. +#define ESP8266WIFIMESH_DISABLE_COMPATIBILITY // Excludes redundant compatibility code. TODO: Should be used for new code until the compatibility code is removed with release 3.0.0 of the Arduino core. #include #include @@ -28,18 +28,16 @@ namespace TypeCast = MeshTypeConversionFunctions; https://github.com/esp8266/Arduino/issues/1143 https://arduino-esp8266.readthedocs.io/en/latest/PROGMEM.html */ -constexpr char exampleMeshName[] PROGMEM = "MeshNode_"; // The name of the mesh network. Used as prefix for the node SSID and to find other network nodes in the example networkFilter and broadcastFilter functions below. -constexpr char exampleWiFiPassword[] PROGMEM = "ChangeThisWiFiPassword_TODO"; // Note: " is an illegal character. The password has to be min 8 and max 64 characters long, otherwise an AP which uses it will not be found during scans. +constexpr char exampleMeshName[] PROGMEM = "MeshNode_"; // The name of the mesh network. Used as prefix for the node SSID and to find other network nodes in the example networkFilter and broadcastFilter functions below. +constexpr char exampleWiFiPassword[] PROGMEM = "ChangeThisWiFiPassword_TODO"; // Note: " is an illegal character. The password has to be min 8 and max 64 characters long, otherwise an AP which uses it will not be found during scans. // 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); @@ -49,7 +47,7 @@ FloodingMesh floodingMesh = FloodingMesh(meshMessageHandler, FPSTR(exampleWiFiPa bool theOne = true; String theOneMac; -bool useLED = false; // Change this to true if you wish the onboard LED to mark The One. +bool useLED = false; // Change this to true if you wish the onboard LED to mark The One. /** Callback for when a message is received from the mesh network. @@ -78,7 +76,7 @@ bool meshMessageHandler(String &message, FloodingMesh &meshInstance) { if (useLED && !theOne) { bool ledState = message.charAt(1) == '1'; - digitalWrite(LED_BUILTIN, ledState); // Turn LED on/off (LED_BUILTIN is active low) + digitalWrite(LED_BUILTIN, ledState); // Turn LED on/off (LED_BUILTIN is active low) } return true; @@ -87,26 +85,22 @@ bool meshMessageHandler(String &message, FloodingMesh &meshInstance) { } } else if (delimiterIndex > 0) { if (meshInstance.getOriginMac() == theOneMac) { - uint32_t totalBroadcasts = strtoul(message.c_str(), nullptr, 0); // strtoul stops reading input when an invalid character is discovered. + uint32_t totalBroadcasts = strtoul(message.c_str(), nullptr, 0); // strtoul stops reading input when an invalid character is discovered. // Static variables are only initialized once. static uint32_t firstBroadcast = totalBroadcasts; - if (totalBroadcasts - firstBroadcast >= 100) { // Wait a little to avoid start-up glitches - static uint32_t missedBroadcasts = 1; // Starting at one to compensate for initial -1 below. + if (totalBroadcasts - firstBroadcast >= 100) { // Wait a little to avoid start-up glitches + static uint32_t missedBroadcasts = 1; // Starting at one to compensate for initial -1 below. static uint32_t previousTotalBroadcasts = totalBroadcasts; static uint32_t totalReceivedBroadcasts = 0; totalReceivedBroadcasts++; - missedBroadcasts += totalBroadcasts - previousTotalBroadcasts - 1; // We expect an increment by 1. + missedBroadcasts += totalBroadcasts - previousTotalBroadcasts - 1; // We expect an increment by 1. previousTotalBroadcasts = totalBroadcasts; - if (totalReceivedBroadcasts % 50 == 0) { - Serial.println(String(F("missed/total: ")) + String(missedBroadcasts) + '/' + String(totalReceivedBroadcasts)); - } - if (totalReceivedBroadcasts % 500 == 0) { - Serial.println(String(F("Benchmark message: ")) + message.substring(0, 100)); - } + if (totalReceivedBroadcasts % 50 == 0) { Serial.println(String(F("missed/total: ")) + String(missedBroadcasts) + '/' + String(totalReceivedBroadcasts)); } + if (totalReceivedBroadcasts % 500 == 0) { Serial.println(String(F("Benchmark message: ")) + message.substring(0, 100)); } } } } else { @@ -136,24 +130,24 @@ void setup() { Serial.println(F("Setting up mesh node...")); floodingMesh.begin(); - floodingMesh.activateAP(); // Required to receive messages + floodingMesh.activateAP(); // Required to receive messages - uint8_t apMacArray[6] {0}; + uint8_t apMacArray[6]{ 0 }; theOneMac = TypeCast::macToString(WiFi.softAPmacAddress(apMacArray)); if (useLED) { - pinMode(LED_BUILTIN, OUTPUT); // Initialize the LED_BUILTIN pin as an output - digitalWrite(LED_BUILTIN, LOW); // Turn LED on (LED_BUILTIN is active low) + pinMode(LED_BUILTIN, OUTPUT); // Initialize the LED_BUILTIN pin as an output + digitalWrite(LED_BUILTIN, LOW); // Turn LED on (LED_BUILTIN is active low) } // Uncomment the lines below to use automatic AEAD encryption/decryption of messages sent/received via broadcast() and encryptedBroadcast(). // The main benefit of AEAD encryption is that it can be used with normal broadcasts (which are substantially faster than encryptedBroadcasts). // The main drawbacks are that AEAD only encrypts the message data (not transmission metadata), transfers less data per message and lacks replay attack protection. // When using AEAD, potential replay attacks must thus be handled manually. - //floodingMesh.getEspnowMeshBackend().setEspnowMessageEncryptionKey(F("ChangeThisKeySeed_TODO")); // The message encryption key should always be set manually. Otherwise a default key (all zeroes) is used. - //floodingMesh.getEspnowMeshBackend().setUseEncryptedMessages(true); + // floodingMesh.getEspnowMeshBackend().setEspnowMessageEncryptionKey(F("ChangeThisKeySeed_TODO")); // The message encryption key should always be set manually. Otherwise a default key (all zeroes) is used. + // floodingMesh.getEspnowMeshBackend().setUseEncryptedMessages(true); - floodingMeshDelay(5000); // Give some time for user to start the nodes + floodingMeshDelay(5000); // Give some time for user to start the nodes } int32_t timeOfLastProclamation = -10000; @@ -177,7 +171,7 @@ void loop() { if (theOne) { if (millis() - timeOfLastProclamation > 10000) { uint32_t startTime = millis(); - ledState = ledState ^ bool(benchmarkCount); // Make other nodes' LEDs alternate between on and off once benchmarking begins. + ledState = ledState ^ bool(benchmarkCount); // Make other nodes' LEDs alternate between on and off once benchmarking begins. // Note: The maximum length of an unencrypted broadcast message is given by floodingMesh.maxUnencryptedMessageLength(). It is around 670 bytes by default. floodingMesh.broadcast(String(floodingMesh.metadataDelimiter()) + String(ledState) + theOneMac + F(" is The One.")); @@ -187,7 +181,7 @@ void loop() { floodingMeshDelay(20); } - if (millis() - loopStart > 23000) { // Start benchmarking the mesh once three proclamations have been made + if (millis() - loopStart > 23000) { // Start benchmarking the mesh once three proclamations have been made uint32_t startTime = millis(); floodingMesh.broadcast(String(benchmarkCount++) + String(floodingMesh.metadataDelimiter()) + F(": Not a spoon in sight.")); Serial.println(String(F("Benchmark broadcast done in ")) + String(millis() - startTime) + F(" ms.")); diff --git a/libraries/ESP8266WiFiMesh/examples/HelloTcpIp/HelloTcpIp.ino b/libraries/ESP8266WiFiMesh/examples/HelloTcpIp/HelloTcpIp.ino index f68b81f181..f59ce2a753 100644 --- a/libraries/ESP8266WiFiMesh/examples/HelloTcpIp/HelloTcpIp.ino +++ b/libraries/ESP8266WiFiMesh/examples/HelloTcpIp/HelloTcpIp.ino @@ -1,4 +1,4 @@ -#define ESP8266WIFIMESH_DISABLE_COMPATIBILITY // Excludes redundant compatibility code. TODO: Should be used for new code until the compatibility code is removed with release 3.0.0 of the Arduino core. +#define ESP8266WIFIMESH_DISABLE_COMPATIBILITY // Excludes redundant compatibility code. TODO: Should be used for new code until the compatibility code is removed with release 3.0.0 of the Arduino core. #include #include @@ -20,7 +20,7 @@ namespace TypeCast = MeshTypeConversionFunctions; https://arduino-esp8266.readthedocs.io/en/latest/PROGMEM.html */ constexpr char exampleMeshName[] PROGMEM = "MeshNode_"; -constexpr char exampleWiFiPassword[] PROGMEM = "ChangeThisWiFiPassword_TODO"; // Note: " is an illegal character. The password has to be min 8 and max 64 characters long, otherwise an AP which uses it will not be found during scans. +constexpr char exampleWiFiPassword[] PROGMEM = "ChangeThisWiFiPassword_TODO"; // Note: " is an illegal character. The password has to be min 8 and max 64 characters long, otherwise an AP which uses it will not be found during scans. unsigned int requestNumber = 0; unsigned int responseNumber = 0; @@ -45,7 +45,7 @@ String manageRequest(const String &request, MeshBackendBase &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)) { - (void)tcpIpInstance; // This is useful to remove a "unused parameter" compiler warning. Does nothing else. + (void)tcpIpInstance; // This is useful to remove a "unused parameter" compiler warning. Does nothing else. Serial.print(F("TCP/IP: ")); } else { Serial.print(F("UNKNOWN!: ")); @@ -145,8 +145,7 @@ bool exampleTransmissionOutcomesUpdateHook(MeshBackendBase &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.setMessage(String(F("Hello world request #")) + String(++requestNumber) + F(" from ") + meshInstance.getMeshName() + meshInstance.getNodeID() + String('.')); } } else { Serial.println(F("Invalid mesh backend!")); @@ -174,8 +173,8 @@ void setup() { /* Initialise the mesh node */ tcpIpNode.begin(); - tcpIpNode.activateAP(); // Each AP requires a separate server port. - tcpIpNode.setStaticIP(IPAddress(192, 168, 4, 22)); // Activate static IP mode to speed up connection times. + tcpIpNode.activateAP(); // Each AP requires a separate server port. + tcpIpNode.setStaticIP(IPAddress(192, 168, 4, 22)); // Activate static IP mode to speed up connection times. // Storing our message in the TcpIpMeshBackend instance is not required, but can be useful for organizing code, especially when using many TcpIpMeshBackend instances. // Note that calling the multi-recipient tcpIpNode.attemptTransmission will replace the stored message with whatever message is transmitted. @@ -186,17 +185,15 @@ void setup() { int32_t timeOfLastScan = -10000; void loop() { - if (millis() - timeOfLastScan > 3000 // Give other nodes some time to connect between data transfers. - || (WiFi.status() != WL_CONNECTED && millis() - timeOfLastScan > 2000)) { // Scan for networks with two second intervals when not already connected. + if (millis() - timeOfLastScan > 3000 // Give other nodes some time to connect between data transfers. + || (WiFi.status() != WL_CONNECTED && millis() - timeOfLastScan > 2000)) { // Scan for networks with two second intervals when not already connected. // attemptTransmission(message, scan, scanAllWiFiChannels, concludingDisconnect, initialDisconnect = false) tcpIpNode.attemptTransmission(tcpIpNode.getMessage(), true, false, false); timeOfLastScan = millis(); // One way to check how attemptTransmission worked out - if (tcpIpNode.latestTransmissionSuccessful()) { - Serial.println(F("Transmission successful.")); - } + if (tcpIpNode.latestTransmissionSuccessful()) { Serial.println(F("Transmission successful.")); } // Another way to check how attemptTransmission worked out if (tcpIpNode.latestTransmissionOutcomes().empty()) { diff --git a/libraries/ESP8266httpUpdate/examples/httpUpdate/httpUpdate.ino b/libraries/ESP8266httpUpdate/examples/httpUpdate/httpUpdate.ino index 19c555a235..f245d2363d 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() { @@ -80,21 +78,14 @@ void loop() { t_httpUpdate_return ret = ESPhttpUpdate.update(client, "http://server/file.bin"); // Or: - //t_httpUpdate_return ret = ESPhttpUpdate.update(client, "server", 80, "file.bin"); + // t_httpUpdate_return ret = ESPhttpUpdate.update(client, "server", 80, "file.bin"); switch (ret) { - case HTTP_UPDATE_FAILED: - Serial.printf("HTTP_UPDATE_FAILD Error (%d): %s\n", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str()); - break; + case HTTP_UPDATE_FAILED: Serial.printf("HTTP_UPDATE_FAILD Error (%d): %s\n", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str()); break; - case HTTP_UPDATE_NO_UPDATES: - Serial.println("HTTP_UPDATE_NO_UPDATES"); - break; + case HTTP_UPDATE_NO_UPDATES: Serial.println("HTTP_UPDATE_NO_UPDATES"); break; - case HTTP_UPDATE_OK: - Serial.println("HTTP_UPDATE_OK"); - break; + case HTTP_UPDATE_OK: Serial.println("HTTP_UPDATE_OK"); break; } } } - diff --git a/libraries/ESP8266httpUpdate/examples/httpUpdateLittleFS/httpUpdateLittleFS.ino b/libraries/ESP8266httpUpdate/examples/httpUpdateLittleFS/httpUpdateLittleFS.ino index 6541d047fd..1a4c9ff1b4 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() { @@ -62,19 +61,12 @@ void loop() { ret = ESPhttpUpdate.update(client, "http://server/file.bin"); switch (ret) { - case HTTP_UPDATE_FAILED: - Serial.printf("HTTP_UPDATE_FAILED Error (%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str()); - break; + case HTTP_UPDATE_FAILED: Serial.printf("HTTP_UPDATE_FAILED Error (%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str()); break; - case HTTP_UPDATE_NO_UPDATES: - Serial.println("HTTP_UPDATE_NO_UPDATES"); - break; + case HTTP_UPDATE_NO_UPDATES: Serial.println("HTTP_UPDATE_NO_UPDATES"); break; - case HTTP_UPDATE_OK: - Serial.println("HTTP_UPDATE_OK"); - break; + case HTTP_UPDATE_OK: Serial.println("HTTP_UPDATE_OK"); break; } } } } - diff --git a/libraries/ESP8266httpUpdate/examples/httpUpdateSecure/httpUpdateSecure.ino b/libraries/ESP8266httpUpdate/examples/httpUpdateSecure/httpUpdateSecure.ino index beb613897c..f7896a22f6 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; @@ -74,7 +74,7 @@ void setup() { Serial.println(numCerts); if (numCerts == 0) { Serial.println(F("No certs found. Did you run certs-from-mozill.py and upload the LittleFS directory before running?")); - return; // Can't connect to anything w/o certs! + return; // Can't connect to anything w/o certs! } } @@ -87,9 +87,7 @@ void loop() { BearSSL::WiFiClientSecure client; 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); - } + if (mfln) { client.setBufferSizes(1024, 1024); } client.setCertStore(&certStore); // The line below is optional. It can be used to blink the LED on the board during flashing @@ -102,21 +100,15 @@ void loop() { t_httpUpdate_return ret = ESPhttpUpdate.update(client, "https://server/file.bin"); // Or: - //t_httpUpdate_return ret = ESPhttpUpdate.update(client, "server", 443, "file.bin"); + // 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()); - break; + case HTTP_UPDATE_FAILED: Serial.printf("HTTP_UPDATE_FAILED Error (%d): %s\n", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str()); break; - case HTTP_UPDATE_NO_UPDATES: - Serial.println("HTTP_UPDATE_NO_UPDATES"); - break; + case HTTP_UPDATE_NO_UPDATES: Serial.println("HTTP_UPDATE_NO_UPDATES"); break; - case HTTP_UPDATE_OK: - Serial.println("HTTP_UPDATE_OK"); - break; + case HTTP_UPDATE_OK: Serial.println("HTTP_UPDATE_OK"); break; } } } diff --git a/libraries/ESP8266httpUpdate/examples/httpUpdateSigned/httpUpdateSigned.ino b/libraries/ESP8266httpUpdate/examples/httpUpdateSigned/httpUpdateSigned.ino index e196ef6419..285d077f05 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; @@ -73,11 +73,11 @@ 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 } @@ -87,10 +87,10 @@ void loop() { 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 @@ -99,19 +99,12 @@ void loop() { t_httpUpdate_return ret = ESPhttpUpdate.update(client, "http://192.168.1.8/esp8266.bin"); switch (ret) { - case HTTP_UPDATE_FAILED: - Serial.printf("HTTP_UPDATE_FAILED Error (%d): %s\n", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str()); - break; + case HTTP_UPDATE_FAILED: Serial.printf("HTTP_UPDATE_FAILED Error (%d): %s\n", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str()); break; - case HTTP_UPDATE_NO_UPDATES: - Serial.println("HTTP_UPDATE_NO_UPDATES"); - break; + case HTTP_UPDATE_NO_UPDATES: Serial.println("HTTP_UPDATE_NO_UPDATES"); break; - case HTTP_UPDATE_OK: - Serial.println("HTTP_UPDATE_OK"); - break; + case HTTP_UPDATE_OK: Serial.println("HTTP_UPDATE_OK"); break; } } 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..6234e9f109 100644 --- a/libraries/ESP8266mDNS/examples/LEAmDNS/mDNS_Clock/mDNS_Clock.ino +++ b/libraries/ESP8266mDNS/examples/LEAmDNS/mDNS_Clock/mDNS_Clock.ino @@ -43,39 +43,38 @@ 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])) { - acTimeString[stLength - 1] = 0; // Remove trailing line break... + size_t stLength; + while (((stLength = strlen(acTimeString))) && ('\n' == acTimeString[stLength - 1])) { + acTimeString[stLength - 1] = 0; // Remove trailing line break... } return acTimeString; } @@ -186,7 +185,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,10 +231,9 @@ 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 + 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..1773b590b0 100644 --- a/libraries/ESP8266mDNS/examples/LEAmDNS/mDNS_ServiceMonitor/mDNS_ServiceMonitor.ino +++ b/libraries/ESP8266mDNS/examples/LEAmDNS/mDNS_ServiceMonitor/mDNS_ServiceMonitor.ino @@ -39,26 +39,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); /* @@ -80,26 +80,17 @@ 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 : - answerInfo = "ServiceDomain " + String(serviceInfo.serviceDomain()); - break; - case MDNSResponder::AnswerType::HostDomainAndPort : - answerInfo = "HostDomainAndPort " + String(serviceInfo.hostDomain()) + ":" + String(serviceInfo.hostPort()); - break; - case MDNSResponder::AnswerType::IP4Address : + case MDNSResponder::AnswerType::ServiceDomain: answerInfo = "ServiceDomain " + String(serviceInfo.serviceDomain()); break; + case MDNSResponder::AnswerType::HostDomainAndPort: answerInfo = "HostDomainAndPort " + String(serviceInfo.hostDomain()) + ":" + String(serviceInfo.hostPort()); break; + case MDNSResponder::AnswerType::IP4Address: answerInfo = "IP4Address "; - for (IPAddress ip : serviceInfo.IP4Adresses()) { - answerInfo += "- " + ip.toString(); - }; + 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); - } + for (auto kv : serviceInfo.keyValues()) { answerInfo += "\nkv : " + String(kv.first) + " : " + String(kv.second); } break; - default : - answerInfo = "Unknown Answertype"; + default: answerInfo = "Unknown Answertype"; } Serial.printf("Answer %s %s\n", answerInfo.c_str(), p_bSetContent ? "Modified" : "Deleted"); } @@ -109,10 +100,8 @@ void MDNSServiceQueryCallback(MDNSResponder::MDNSServiceInfo serviceInfo, MDNSRe Probe result callback for Services */ -void serviceProbeResult(String p_pcServiceName, - const MDNSResponder::hMDNSService p_hMDNSService, - bool p_bProbeResult) { - (void) p_hMDNSService; +void serviceProbeResult(String p_pcServiceName, 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 +175,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()) { @@ -196,15 +185,11 @@ void handleHTTPRequest() { } if (info.IP4AddressAvailable()) { s += "
    IP4:"; - for (auto ip : info.IP4Adresses()) { - s += " " + ip.toString(); - } + for (auto ip : info.IP4Adresses()) { s += " " + ip.toString(); } } if (info.txtAvailable()) { s += "
    TXT:
    "; - for (auto kv : info.keyValues()) { - s += "\t" + String(kv.first) + " : " + String(kv.second) + "
    "; - } + for (auto kv : info.keyValues()) { s += "\t" + String(kv.first) + " : " + String(kv.second) + "
    "; } } s += "
  2. "; } @@ -245,10 +230,9 @@ 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 + while (1) { // STOP delay(1000); } } @@ -265,6 +249,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..d94d96077c 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 @@ -35,15 +35,15 @@ @brief mDNS and OTA Constants @{ */ -#define HOSTNAME "ESP8266-OTA-" ///< Hostname. The setup function adds the Chip ID at the end. +#define HOSTNAME "ESP8266-OTA-" ///< Hostname. The setup function adds the Chip ID at the end. /// @} /** @brief Default WiFi connection information. @{ */ -const char* ap_default_ssid = APSSID; ///< Default SSID. -const char* ap_default_psk = APPSK; ///< Default PSK. +const char *ap_default_ssid = APSSID; ///< Default SSID. +const char *ap_default_psk = APPSK; ///< Default PSK. /// @} /// Uncomment the next line for verbose output over UART. @@ -81,9 +81,7 @@ bool loadConfig(String *ssid, String *pass) { if (pos == -1) { le = 1; pos = content.indexOf("\n"); - if (pos == -1) { - pos = content.indexOf("\r"); - } + if (pos == -1) { pos = content.indexOf("\r"); } } // If there is no second line: Some information is missing. @@ -110,7 +108,7 @@ bool loadConfig(String *ssid, String *pass) { #endif return true; -} // loadConfig +} // loadConfig /** @@ -135,7 +133,7 @@ bool saveConfig(String *ssid, String *pass) { configFile.close(); return true; -} // saveConfig +} // saveConfig /** @@ -160,7 +158,7 @@ void setup() { // Print hostname. Serial.println("Hostname: " + hostname); - //Serial.println(WiFi.hostname()); + // Serial.println(WiFi.hostname()); // Initialize file system. @@ -170,7 +168,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; @@ -196,7 +194,7 @@ void setup() { Serial.println(WiFi.SSID()); // ... Uncomment this for debugging output. - //WiFi.printDiag(Serial); + // WiFi.printDiag(Serial); } else { // ... Begin with sdk config. WiFi.begin(); @@ -208,7 +206,7 @@ void setup() { unsigned long startTime = millis(); while (WiFi.status() != WL_CONNECTED && millis() - startTime < 10000) { Serial.write('.'); - //Serial.print(WiFi.status()); + // Serial.print(WiFi.status()); delay(500); } Serial.println(); @@ -245,4 +243,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..20e1fa2146 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); @@ -43,14 +43,12 @@ void setup() { Serial.print("IP address: "); Serial.println(WiFi.localIP()); - if (!MDNS.begin(hostString)) { - Serial.println("Error setting up MDNS responder!"); - } + if (!MDNS.begin(hostString)) { Serial.println("Error setting up MDNS responder!"); } Serial.println("mDNS responder started"); - MDNS.addService("esp", "tcp", 8080); // Announce esp tcp service on port 8080 + MDNS.addService("esp", "tcp", 8080); // Announce esp tcp service on port 8080 Serial.println("Sending mDNS query"); - int n = MDNS.queryService("esp", "tcp"); // Send out query for esp tcp services + int n = MDNS.queryService("esp", "tcp"); // Send out query for esp tcp services Serial.println("mDNS query done"); if (n == 0) { Serial.println("no services found"); 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..fe625e5432 100644 --- a/libraries/ESP8266mDNS/examples/mDNS_Web_Server/mDNS_Web_Server.ino +++ b/libraries/ESP8266mDNS/examples/mDNS_Web_Server/mDNS_Web_Server.ino @@ -22,7 +22,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* ssid = STASSID; @@ -57,9 +57,7 @@ void setup(void) { // we send our IP address on the WiFi network if (!MDNS.begin("esp8266")) { Serial.println("Error setting up MDNS responder!"); - while (1) { - delay(1000); - } + while (1) { delay(1000); } } Serial.println("mDNS responder started"); @@ -77,16 +75,12 @@ void loop(void) { // Check if a client has connected WiFiClient client = server.accept(); - if (!client) { - return; - } + if (!client) { return; } Serial.println(""); Serial.println("New client"); // Wait for data from client to become available - while (client.connected() && !client.available()) { - delay(1); - } + while (client.connected() && !client.available()) { delay(1); } // Read the first line of HTTP request String req = client.readStringUntil('\r'); @@ -121,4 +115,3 @@ void loop(void) { Serial.println("Done with client"); } - 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..840577b6d2 100644 --- a/libraries/ESP8266mDNS/src/ESP8266mDNS.h +++ b/libraries/ESP8266mDNS/src/ESP8266mDNS.h @@ -3,15 +3,19 @@ This file is part of the esp8266 core for Arduino environment. mDNS implementation, that supports many mDNS features like: - - Presenting a DNS-SD service to interested observers, eg. a http server by presenting _http._tcp service - - Support for multi-level compressed names in input; in output only a very simple one-leven full-name compression is implemented + - Presenting a DNS-SD service to interested observers, eg. a http server by presenting + _http._tcp service + - Support for multi-level compressed names in input; in output only a very simple one-leven + full-name compression is implemented - Probing host and service domains for uniqueness in the local network - - Tiebreaking while probing is supported in a very minimalistic way (the 'higher' IP address wins the tiebreak) + - Tiebreaking while probing is supported in a very minimalistic way (the 'higher' IP address + wins the tiebreak) - Announcing available services after successful probing - Using fixed service TXT items or - Using dynamic service TXT items for presented services (via callback) - Remove services (and un-announcing them to the observers by sending goodbye-messages) - - Static queries for DNS-SD services (creating a fixed answer set after a certain timeout period) + - Static queries for DNS-SD services (creating a fixed answer set after a certain timeout + period) - Dynamic queries for DNS-SD services with cached and updated answers and user notifications - Support for multi-homed client host domains @@ -41,13 +45,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..68d71efc4a 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS.cpp +++ b/libraries/ESP8266mDNS/src/LEAmDNS.cpp @@ -27,7 +27,7 @@ #include "ESP8266mDNS.h" #include "LEAmDNS_Priv.h" -#include // LwipIntf::stateUpCB() +#include // LwipIntf::stateUpCB() #include #include @@ -50,1335 +50,1322 @@ namespace MDNSImplementation #define STRINGIZE_VALUE_OF(x) STRINGIZE(x) #endif + /** + INTERFACE + */ -/** - INTERFACE -*/ - -/** - MDNSResponder::MDNSResponder -*/ -MDNSResponder::MDNSResponder(void) - : m_pServices(0), - m_pUDPContext(0), - m_pcHostname(0), - m_pServiceQueries(0), + /** + MDNSResponder::MDNSResponder + */ + 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::begin - - Set the host domain (for probing) and install WiFi event handlers for - IP assignment and disconnection management. In both cases, the MDNS responder - is restarted (reset and restart probe status) - 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)) { - bResult = _restart(); } - LwipIntf::stateUpCB - ( - [this](netif * intf) + /* + MDNSResponder::~MDNSResponder + */ + MDNSResponder::~MDNSResponder(void) { - (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) - { - _announce(false, true); - _resetProbeStatus(false); // Stop probing + _resetProbeStatus(false); _releaseServiceQueries(); - _releaseServices(); - _releaseUDPContext(); _releaseHostname(); - - bResult = true; - } - else - { - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] close: Ignoring call to close!\n"));); + _releaseUDPContext(); + _releaseServices(); } - return bResult; -} - -/* - MDNSResponder::end - Ends the MDNS responder. - for compatibility with esp32 + /* + MDNSResponder::begin -*/ + Set the host domain (for probing) and install WiFi event handlers for + IP assignment and disconnection management. In both cases, the MDNS responder + is restarted (reset and restart probe status) + Finally the responder is (re)started -bool MDNSResponder::end(void) -{ - return close(); -} + */ + bool MDNSResponder::begin(const char* p_pcHostname, const IPAddress& /*p_IPAddress*/, + uint32_t /*p_u32TTL*/) + { + bool bResult = false; -/* - MDNSResponder::setHostname + if (_setHostname(p_pcHostname)) + { + bResult = _restart(); + } - Replaces the current hostname and restarts probing. - For services without own instance name (when the host name was used a instance - name), the instance names are replaced also (and the probing is restarted). + 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; + } -*/ -bool MDNSResponder::setHostname(const char* p_pcHostname) -{ + /* + MDNSResponder::close - bool bResult = false; + Ends the MDNS responder. + Announced services are unannounced (by multicasting a goodbye message) - if (_setHostname(p_pcHostname)) + */ + bool MDNSResponder::close(void) { - 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 (0 != m_pUDPContext) { - if (pService->m_bAutoName) - { - bResult = pService->setName(p_pcHostname); - pService->m_ProbeInformation.m_ProbingStatus = ProbingStatus_ReadyToStart; - } + _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; } - 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) -{ + /* + MDNSResponder::end - return setHostname(p_strHostname.c_str()); -} + Ends the MDNS responder. + for compatibility with esp32 + */ -/* - SERVICES -*/ - -/* - MDNSResponder::addService - - Add service; using hostname if no name is explicitly provided for the service - The usual '_' underline, which is prepended to service and protocol, eg. _http, - may be given. If not, it is added automatically. + bool MDNSResponder::end(void) + { + return close(); + } -*/ -MDNSResponder::hMDNSService MDNSResponder::addService(const char* p_pcName, - const char* p_pcService, - const char* p_pcProtocol, - uint16_t p_u16Port) -{ + /* + MDNSResponder::setHostname - hMDNSService hResult = 0; + Replaces the current hostname and restarts probing. + For services without own instance name (when the host name was used a instance + name), the instance names are replaced also (and the probing is restarted). - 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)) + */ + bool MDNSResponder::setHostname(const char* p_pcHostname) { + bool bResult = false; - if (!_findService((p_pcName ? : m_pcHostname), p_pcService, p_pcProtocol)) // Not already used + if (_setHostname(p_pcHostname)) { - if (0 != (hResult = (hMDNSService)_allocService(p_pcName, p_pcService, p_pcProtocol, p_u16Port))) - { + m_HostProbeInformation.m_ProbingStatus = ProbingStatus_ReadyToStart; - // Start probing - ((stcMDNSService*)hResult)->m_ProbeInformation.m_ProbingStatus = ProbingStatus_ReadyToStart; + // Replace 'auto-set' service names + bResult = true; + for (stcMDNSService* pService = m_pServices; ((bResult) && (pService)); + pService = pService->m_pNext) + { + if (pService->m_bAutoName) + { + bResult = pService->setName(p_pcHostname); + pService->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; -} + DEBUG_EX_ERR(if (!bResult) { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] setHostname: FAILED for '%s'!\n"), + (p_pcHostname ?: "-")); + }); + return bResult; + } -/* - MDNSResponder::removeService + /* + MDNSResponder::setHostname (LEGACY) + */ + bool MDNSResponder::setHostname(const String& p_strHostname) + { + return setHostname(p_strHostname.c_str()); + } - Unanounce a service (by sending a goodbye message) and remove it - from the MDNS responder + /* + SERVICES + */ -*/ -bool MDNSResponder::removeService(const MDNSResponder::hMDNSService p_hService) -{ + /* + MDNSResponder::addService - 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; -} + Add service; using hostname if no name is explicitly provided for the service + The usual '_' underline, which is prepended to service and protocol, eg. _http, + may be given. If not, it is added automatically. -/* - MDNSResponder::removeService -*/ -bool MDNSResponder::removeService(const char* p_pcName, - const char* p_pcService, - const char* p_pcProtocol) -{ + */ + MDNSResponder::hMDNSService MDNSResponder::addService(const char* p_pcName, + const char* p_pcService, + const char* p_pcProtocol, + uint16_t p_u16Port) + { + hMDNSService hResult = 0; - return removeService((hMDNSService)_findService((p_pcName ? : m_pcHostname), p_pcService, p_pcProtocol)); -} + 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 (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; + } -/* - MDNSResponder::addService (LEGACY) -*/ -bool MDNSResponder::addService(const String& p_strService, - const String& p_strProtocol, - uint16_t p_u16Port) -{ + /* + MDNSResponder::removeService - return (0 != addService(m_pcHostname, p_strService.c_str(), p_strProtocol.c_str(), p_u16Port)); -} + Unanounce a service (by sending a goodbye message) and remove it + from the MDNS responder -/* - MDNSResponder::setServiceName -*/ -bool MDNSResponder::setServiceName(const MDNSResponder::hMDNSService p_hService, - const char* p_pcInstanceName) -{ + */ + 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; + } - 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; -} + /* + 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)); + } -/* - SERVICE TXT -*/ + /* + 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)); + } -/* - MDNSResponder::addServiceTxt + /* + 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; + } - Add a static service TXT item ('Key'='Value') to a service. + /* + SERVICE TXT + */ -*/ -MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - const char* p_pcValue) -{ + /* + MDNSResponder::addServiceTxt - hMDNSTxt hTxt = 0; - stcMDNSService* pService = _findService(p_hService); - if (pService) + 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) { - 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); - return addServiceTxt(p_hService, p_pcKey, acBuffer); -} + /* + MDNSResponder::addServiceTxt (uint32_t) -/* - 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); + 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); - 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::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); - 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::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); - 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::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); - 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::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); - return addServiceTxt(p_hService, p_pcKey, acBuffer); -} + return addServiceTxt(p_hService, p_pcKey, acBuffer); + } -/* - MDNSResponder::removeServiceTxt + /* + 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); - Remove a static service TXT item from a service. -*/ -bool MDNSResponder::removeServiceTxt(const MDNSResponder::hMDNSService p_hService, - const MDNSResponder::hMDNSTxt p_hTxt) -{ + return addServiceTxt(p_hService, p_pcKey, acBuffer); + } - bool bResult = false; + /* + MDNSResponder::removeServiceTxt - stcMDNSService* pService = _findService(p_hService); - if (pService) + Remove a static service TXT item from a service. + */ + 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) + /* + MDNSResponder::removeServiceTxt + */ + 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) + /* + MDNSResponder::removeServiceTxt + */ + 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)); -} - -/* - 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)); -} - -/* - 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; - - 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) + /* + MDNSResponder::addServiceTxt (LEGACY) + */ + bool MDNSResponder::addServiceTxt(const char* p_pcService, const char* p_pcProtocol, + const char* p_pcKey, const char* p_pcValue) { - pService->m_fnTxtCallback = p_fnCallback; - - bResult = true; + return (0 + != _addServiceTxt(_findService(m_pcHostname, p_pcService, p_pcProtocol), p_pcKey, + p_pcValue, false)); } - 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);); - - hMDNSTxt hTxt = 0; - stcMDNSService* pService = _findService(p_hService); - if (pService) + /* + MDNSResponder::addServiceTxt (LEGACY) + */ + bool MDNSResponder::addServiceTxt(const String& p_strService, const String& p_strProtocol, + const String& p_strKey, const String& p_strValue) { - hTxt = _addServiceTxt(pService, p_pcKey, p_pcValue, true); + return (0 + != _addServiceTxt( + _findService(m_pcHostname, p_strService.c_str(), p_strProtocol.c_str()), + p_strKey.c_str(), p_strValue.c_str(), false)); } - 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); - - 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); - - 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); - - 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); - - 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); - - 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::setDynamicServiceTxtCallback (global) - return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); -} + Set a global callback for dynamic service TXT items. The callback is called, whenever + service TXT items are needed. - -/** - STATIC SERVICE QUERY (LEGACY) -*/ - -/* - MDNSResponder::queryService - - Perform a (blocking) static service query. - The arrived answers can be queried by calling: - - answerHostname (or 'hostname') - - answerIP (or 'IP') - - 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) + */ + bool MDNSResponder::setDynamicServiceTxtCallback( + MDNSResponder::MDNSDynamicServiceTxtCallbackFunc p_fnCallback) { - // safeguard against misuse - return 0; + m_fnServiceTxtCallback = p_fnCallback; + + return true; } - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] queryService '%s.%s'\n"), p_pcService, p_pcProtocol);); + /* + MDNSResponder::setDynamicServiceTxtCallback (service specific) - uint32_t u32Result = 0; + Set a service specific callback for dynamic service TXT items. The callback is called, + whenever service TXT items are needed for the given service. - 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))) + */ + bool MDNSResponder::setDynamicServiceTxtCallback( + MDNSResponder::hMDNSService p_hService, + MDNSResponder::MDNSDynamicServiceTxtCallbackFunc p_fnCallback) { + bool bResult = false; - pServiceQuery->m_bLegacyQuery = true; - - if (_sendMDNSServiceQuery(*pServiceQuery)) + stcMDNSService* pService = _findService(p_hService); + if (pService) { - // 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); + pService->m_fnTxtCallback = p_fnCallback; - // 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); + bResult = true; } + DEBUG_EX_ERR(if (!bResult) { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] setDynamicServiceTxtCallback: FAILED!\n")); + }); + return bResult; } - 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(); -} - -/* - 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()); -} - -/* - 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)) + /* + 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);); + + hMDNSTxt hTxt = 0; - char* pcHostDomain = pSQAnswer->allocHostDomain(pSQAnswer->m_HostDomain.c_strLength()); - if (pcHostDomain) + stcMDNSService* pService = _findService(p_hService); + if (pService) { - pSQAnswer->m_HostDomain.c_str(pcHostDomain); + 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; } - 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()); -} -#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()); -} -#endif + /* + 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::answerPort -*/ -uint16_t MDNSResponder::answerPort(const uint32_t p_u32AnswerIndex) -{ + return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); + } - const stcMDNSServiceQuery* pServiceQuery = _findLegacyServiceQuery(); - const stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - return (pSQAnswer ? pSQAnswer->m_u16Port : 0); -} + /* + 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::hostname (LEGACY) -*/ -String MDNSResponder::hostname(const uint32_t p_u32AnswerIndex) -{ + return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); + } - return String(answerHostname(p_u32AnswerIndex)); -} + /* + 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::IP (LEGACY) -*/ -IPAddress MDNSResponder::IP(const uint32_t p_u32AnswerIndex) -{ + return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); + } - return answerIP(p_u32AnswerIndex); -} + /* + 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::port (LEGACY) -*/ -uint16_t MDNSResponder::port(const uint32_t p_u32AnswerIndex) -{ + 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); - return answerPort(p_u32AnswerIndex); -} + 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); -/** - DYNAMIC SERVICE QUERY -*/ + return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); + } -/* - MDNSResponder::installServiceQuery + /** + STATIC SERVICE QUERY (LEGACY) + */ - Add a dynamic service query and a corresponding callback to the MDNS responder. - The callback will be called for every answer update. - The answers can also be queried by calling: - - answerServiceDomain - - answerHostDomain - - answerIP4Address/answerIP6Address - - answerPort - - answerTxts + /* + MDNSResponder::queryService -*/ -MDNSResponder::hMDNSServiceQuery MDNSResponder::installServiceQuery(const char* p_pcService, - const char* p_pcProtocol, - MDNSResponder::MDNSServiceQueryCallbackFunc p_fnCallback) -{ - hMDNSServiceQuery hResult = 0; + Perform a (blocking) static service query. + The arrived answers can be queried by calling: + - answerHostname (or 'hostname') + - answerIP (or 'IP') + - answerPort (or 'port') - 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))) + */ + 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) + { + // safeguard against misuse + return 0; + } + + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] queryService '%s.%s'\n"), + p_pcService, p_pcProtocol);); - pServiceQuery->m_fnCallback = p_fnCallback; - pServiceQuery->m_bLegacyQuery = false; + 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))) { - pServiceQuery->m_u8SentCount = 1; - pServiceQuery->m_ResendTimeout.reset(MDNS_DYNAMIC_QUERY_RESEND_DELAY); + pServiceQuery->m_bLegacyQuery = true; - hResult = (hMDNSServiceQuery)pServiceQuery; + 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(); + } + else // FAILED to send query + { + _removeServiceQuery(pServiceQuery); + } } else { - _removeServiceQuery(pServiceQuery); + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P( + PSTR("[MDNSResponder] queryService: INVALID input data!\n"));); } + return u32Result; } - 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 + /* + MDNSResponder::removeQuery - Remove a dynamic service query (and all collected answers) from the MDNS responder + Remove the last static service query (and all answers). -*/ -bool MDNSResponder::removeServiceQuery(MDNSResponder::hMDNSServiceQuery p_hServiceQuery) -{ + */ + bool MDNSResponder::removeQuery(void) + { + return _removeLegacyServiceQuery(); + } - 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::queryService (LEGACY) + */ + uint32_t MDNSResponder::queryService(const String& p_strService, const String& p_strProtocol) + { + return queryService(p_strService.c_str(), p_strProtocol.c_str()); + } -/* - MDNSResponder::answerCount -*/ -uint32_t MDNSResponder::answerCount(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery) -{ + /* + MDNSResponder::answerHostname + */ + const char* MDNSResponder::answerHostname(const uint32_t p_u32AnswerIndex) + { + stcMDNSServiceQuery* pServiceQuery = _findLegacyServiceQuery(); + stcMDNSServiceQuery::stcAnswer* pSQAnswer + = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); - return (pServiceQuery ? pServiceQuery->answerCount() : 0); -} + if ((pSQAnswer) && (pSQAnswer->m_HostDomain.m_u16NameLength) + && (!pSQAnswer->m_pcHostDomain)) + { + char* pcHostDomain = pSQAnswer->allocHostDomain(pSQAnswer->m_HostDomain.c_strLength()); + if (pcHostDomain) + { + pSQAnswer->m_HostDomain.c_str(pcHostDomain); + } + } + return (pSQAnswer ? pSQAnswer->m_pcHostDomain : 0); + } -std::vector MDNSResponder::answerInfo(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery) -{ - std::vector tempVector; - for (uint32_t i = 0; i < answerCount(p_hServiceQuery); i++) +#ifdef MDNS_IP4_SUPPORT + /* + MDNSResponder::answerIP + */ + IPAddress MDNSResponder::answerIP(const uint32_t p_u32AnswerIndex) { - tempVector.emplace_back(*this, p_hServiceQuery, i); + 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()); } - return tempVector; -} +#endif -/* - MDNSResponder::answerServiceDomain +#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()); + } +#endif - Returns the domain for the given service. - If not already existing, the string is allocated, filled and attached to the answer. + /* + 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); + } -*/ -const char* MDNSResponder::answerServiceDomain(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) -{ + /* + MDNSResponder::hostname (LEGACY) + */ + String MDNSResponder::hostname(const uint32_t p_u32AnswerIndex) + { + return String(answerHostname(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)) + /* + MDNSResponder::IP (LEGACY) + */ + IPAddress MDNSResponder::IP(const uint32_t p_u32AnswerIndex) { + return answerIP(p_u32AnswerIndex); + } - pSQAnswer->m_pcServiceDomain = pSQAnswer->allocServiceDomain(pSQAnswer->m_ServiceDomain.c_strLength()); - if (pSQAnswer->m_pcServiceDomain) - { - pSQAnswer->m_ServiceDomain.c_str(pSQAnswer->m_pcServiceDomain); - } + /* + MDNSResponder::port (LEGACY) + */ + uint16_t MDNSResponder::port(const uint32_t p_u32AnswerIndex) + { + return answerPort(p_u32AnswerIndex); } - return (pSQAnswer ? pSQAnswer->m_pcServiceDomain : 0); -} -/* - MDNSResponder::hasAnswerHostDomain -*/ -bool MDNSResponder::hasAnswerHostDomain(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) -{ + /** + DYNAMIC SERVICE QUERY + */ + + /* + MDNSResponder::installServiceQuery + + Add a dynamic service query and a corresponding callback to the MDNS responder. + The callback will be called for every answer update. + The answers can also be queried by calling: + - answerServiceDomain + - answerHostDomain + - answerIP4Address/answerIP6Address + - answerPort + - answerTxts + + */ + MDNSResponder::hMDNSServiceQuery + MDNSResponder::installServiceQuery(const char* p_pcService, const char* p_pcProtocol, + MDNSResponder::MDNSServiceQueryCallbackFunc p_fnCallback) + { + hMDNSServiceQuery hResult = 0; - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); - stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - return ((pSQAnswer) && - (pSQAnswer->m_u32ContentFlags & ServiceQueryAnswerType_HostDomainAndPort)); -} + 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_fnCallback = p_fnCallback; + pServiceQuery->m_bLegacyQuery = false; -/* - MDNSResponder::answerHostDomain + 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; + } - Returns the host domain for the given service. - If not already existing, the string is allocated, filled and attached to the answer. + /* + MDNSResponder::removeServiceQuery -*/ -const char* MDNSResponder::answerHostDomain(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) -{ + Remove a dynamic service query (and all collected answers) from the MDNS responder - 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)) + */ + 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); + } - pSQAnswer->m_pcHostDomain = pSQAnswer->allocHostDomain(pSQAnswer->m_HostDomain.c_strLength()); - if (pSQAnswer->m_pcHostDomain) + std::vector + MDNSResponder::answerInfo(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery) + { + std::vector tempVector; + for (uint32_t i = 0; i < answerCount(p_hServiceQuery); i++) { - pSQAnswer->m_HostDomain.c_str(pSQAnswer->m_pcHostDomain); + tempVector.emplace_back(*this, p_hServiceQuery, i); } + return tempVector; } - 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)); -} - -/* - MDNSResponder::answerIP4AddressCount -*/ -uint32_t MDNSResponder::answerIP4AddressCount(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) -{ + /* + MDNSResponder::answerServiceDomain - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); - stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - return (pSQAnswer ? pSQAnswer->IP4AddressCount() : 0); -} + Returns the domain for the given service. + If not already existing, the string is allocated, filled and attached to the answer. -/* - MDNSResponder::answerIP4Address -*/ -IPAddress MDNSResponder::answerIP4Address(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex, - const uint32_t p_u32AddressIndex) -{ + */ + 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) + { + pSQAnswer->m_ServiceDomain.c_str(pSQAnswer->m_pcServiceDomain); + } + } + return (pSQAnswer ? pSQAnswer->m_pcServiceDomain : 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 + /* + 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)); + } -#ifdef MDNS_IP6_SUPPORT -/* - MDNSResponder::hasAnswerIP6Address -*/ -bool MDNSResponder::hasAnswerIP6Address(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) -{ + /* + MDNSResponder::answerHostDomain - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); - stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - return ((pSQAnswer) && - (pSQAnswer->m_u32ContentFlags & ServiceQueryAnswerType_HostIP6Address)); -} + Returns the host domain for the given service. + If not already existing, the string is allocated, filled and attached to the answer. -/* - MDNSResponder::answerIP6AddressCount -*/ -uint32_t MDNSResponder::answerIP6AddressCount(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) -{ + */ + 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) + { + pSQAnswer->m_HostDomain.c_str(pSQAnswer->m_pcHostDomain); + } + } + return (pSQAnswer ? pSQAnswer->m_pcHostDomain : 0); + } - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); - stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - return (pSQAnswer ? pSQAnswer->IP6AddressCount() : 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)); + } -/* - MDNSResponder::answerIP6Address -*/ -IPAddress MDNSResponder::answerIP6Address(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex, - const uint32_t p_u32AddressIndex) -{ + /* + 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); + } - 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()); -} + /* + 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()); + } #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)); -} +#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)); + } -/* - MDNSResponder::answerPort -*/ -uint16_t MDNSResponder::answerPort(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) -{ + /* + 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); + } - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); - stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - return (pSQAnswer ? pSQAnswer->m_u16Port : 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()); + } +#endif -/* - MDNSResponder::hasAnswerTxts -*/ -bool MDNSResponder::hasAnswerTxts(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) -{ + /* + 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)); + } - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); - stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - return ((pSQAnswer) && - (pSQAnswer->m_u32ContentFlags & ServiceQueryAnswerType_Txts)); -} + /* + 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); + } -/* - MDNSResponder::answerTxts + /* + 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)); + } - 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. + /* + MDNSResponder::answerTxts -*/ -const char* MDNSResponder::answerTxts(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) -{ + 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. - 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)) + */ + const char* MDNSResponder::answerTxts(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex) { - - pSQAnswer->m_pcTxts = pSQAnswer->allocTxts(pSQAnswer->m_Txts.c_strLength()); - if (pSQAnswer->m_pcTxts) + 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 - for the host domain (or a service domain, without specific probe result callback) - fails or succeeds. - In the case of failure, the domain name should be changed via 'setHostname' or 'setServiceName'. - When succeeded, the host or service domain will be announced by the MDNS responder. + /* + PROBING + */ -*/ -bool MDNSResponder::setHostProbeResultCallback(MDNSResponder::MDNSHostProbeFn p_fnCallback) -{ + /* + MDNSResponder::setProbeResultCallback - m_HostProbeInformation.m_fnHostProbeResultCallback = p_fnCallback; + Set a global callback for probe results. The callback is called, when probing + for the host domain (or a service domain, without specific probe result callback) + fails or succeeds. + In the case of failure, the domain name should be changed via 'setHostname' or + 'setServiceName'. When succeeded, the host or service domain will be announced by the MDNS + responder. - return true; -} - -bool MDNSResponder::setHostProbeResultCallback(MDNSHostProbeFn1 pfn) -{ - using namespace std::placeholders; - return setHostProbeResultCallback([this, pfn](const char* p_pcDomainName, bool p_bProbeResult) + */ + bool MDNSResponder::setHostProbeResultCallback(MDNSResponder::MDNSHostProbeFn p_fnCallback) { - pfn(*this, p_pcDomainName, p_bProbeResult); - }); -} + m_HostProbeInformation.m_fnHostProbeResultCallback = p_fnCallback; -/* - MDNSResponder::setServiceProbeResultCallback + return true; + } - Set a service specific callback for probe results. The callback is called, when probing - for the service domain fails or succeeds. - In the case of failure, the service name should be changed via 'setServiceName'. - When succeeded, the service domain will be announced by the MDNS responder. + 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::setServiceProbeResultCallback(const MDNSResponder::hMDNSService p_hService, - MDNSResponder::MDNSServiceProbeFn p_fnCallback) -{ + /* + MDNSResponder::setServiceProbeResultCallback - bool bResult = false; + Set a service specific callback for probe results. The callback is called, when probing + for the service domain fails or succeeds. + In the case of failure, the service name should be changed via 'setServiceName'. + When succeeded, the service domain will be announced by the MDNS responder. - 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) + bool + MDNSResponder::setServiceProbeResultCallback(const MDNSResponder::hMDNSService p_hService, + MDNSResponder::MDNSServiceProbeFn1 p_fnCallback) { - 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. + 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::notifyAPChange(void) -{ + /* + MISC + */ - return _restart(); -} + /* + MDNSResponder::notifyAPChange -/* - MDNSResponder::update + 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. - Should be called in every 'loop'. + */ + bool MDNSResponder::notifyAPChange(void) + { + return _restart(); + } -*/ -bool MDNSResponder::update(void) -{ - return _process(true); -} + /* + MDNSResponder::update -/* - MDNSResponder::announce + Should be called in every 'loop'. - Should be called, if the 'configuration' changes. Mainly this will be changes in the TXT items... -*/ -bool MDNSResponder::announce(void) -{ + */ + bool MDNSResponder::update(void) + { + return _process(true); + } - return (_announce(true, true)); -} + /* + MDNSResponder::announce -/* - MDNSResponder::enableArduino + Should be called, if the 'configuration' changes. Mainly this will be changes in the TXT + items... + */ + bool MDNSResponder::announce(void) + { + return (_announce(true, true)); + } - Enable the OTA update service. + /* + MDNSResponder::enableArduino -*/ -MDNSResponder::hMDNSService MDNSResponder::enableArduino(uint16_t p_u16Port, - bool p_bAuthUpload /*= false*/) -{ + Enable the OTA update service. - 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 + /* -*/ + MULTICAST GROUPS -/* - MDNSResponder::_joinMulticastGroups -*/ -bool MDNSResponder::_joinMulticastGroups(void) -{ - bool bResult = false; + */ - // Join multicast group(s) - for (netif* pNetIf = netif_list; pNetIf; pNetIf = pNetIf->next) + /* + MDNSResponder::_joinMulticastGroups + */ + 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) + /* + clsLEAmDNS2_Host::_leaveMulticastGroups + */ + 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 - -} //namespace esp8266 +} // namespace MDNSImplementation +} // namespace esp8266 diff --git a/libraries/ESP8266mDNS/src/LEAmDNS.h b/libraries/ESP8266mDNS/src/LEAmDNS.h index 670de02ed0..92c688421f 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS.h +++ b/libraries/ESP8266mDNS/src/LEAmDNS.h @@ -11,15 +11,19 @@ A lot of the additions were basically taken from Erik Ekman's lwIP mdns app code. Supported mDNS features (in some cases somewhat limited): - - Presenting a DNS-SD service to interested observers, eg. a http server by presenting _http._tcp service - - Support for multi-level compressed names in input; in output only a very simple one-leven full-name compression is implemented + - Presenting a DNS-SD service to interested observers, eg. a http server by presenting + _http._tcp service + - Support for multi-level compressed names in input; in output only a very simple one-leven + full-name compression is implemented - Probing host and service domains for uniqueness in the local network - - Tiebreaking while probing is supported in a very minimalistic way (the 'higher' IP address wins the tiebreak) + - Tiebreaking while probing is supported in a very minimalistic way (the 'higher' IP address + wins the tiebreak) - Announcing available services after successful probing - Using fixed service TXT items or - Using dynamic service TXT items for presented services (via callback) - Remove services (and un-announcing them to the observers by sending goodbye-messages) - - Static queries for DNS-SD services (creating a fixed answer set after a certain timeout period) + - Static queries for DNS-SD services (creating a fixed answer set after a certain timeout + period) - Dynamic queries for DNS-SD services with cached and updated answers and user notifications @@ -30,19 +34,23 @@ For presenting services: In 'setup()': - Install a callback for the probing of host (and service) domains via 'MDNS.setProbeResultCallback(probeResultCallback, &userData);' - Register DNS-SD services with 'MDNSResponder::hMDNSService hService = MDNS.addService("MyESP", "http", "tcp", 5000);' - (Install additional callbacks for the probing of these service domains via 'MDNS.setServiceProbeResultCallback(hService, probeResultCallback, &userData);') - Add service TXT items with 'MDNS.addServiceTxt(hService, "c#", "1");' or by installing a service TXT callback - using 'MDNS.setDynamicServiceTxtCallback(dynamicServiceTxtCallback, &userData);' or service specific - 'MDNS.setDynamicServiceTxtCallback(hService, dynamicServiceTxtCallback, &userData);' + Install a callback for the probing of host (and service) domains via + 'MDNS.setProbeResultCallback(probeResultCallback, &userData);' Register DNS-SD services with + 'MDNSResponder::hMDNSService hService = MDNS.addService("MyESP", "http", "tcp", 5000);' (Install + additional callbacks for the probing of these service domains via + 'MDNS.setServiceProbeResultCallback(hService, probeResultCallback, &userData);') Add service TXT + items with 'MDNS.addServiceTxt(hService, "c#", "1");' or by installing a service TXT callback + using 'MDNS.setDynamicServiceTxtCallback(dynamicServiceTxtCallback, &userData);' or service + specific 'MDNS.setDynamicServiceTxtCallback(hService, dynamicServiceTxtCallback, &userData);' Call MDNS.begin("MyHostname"); - In 'probeResultCallback(MDNSResponder* p_MDNSResponder, const char* p_pcDomain, MDNSResponder:hMDNSService p_hService, bool p_bProbeResult, void* p_pUserdata)': - Check the probe result and update the host or service domain name if the probe failed + In 'probeResultCallback(MDNSResponder* p_MDNSResponder, const char* p_pcDomain, + MDNSResponder:hMDNSService p_hService, bool p_bProbeResult, void* p_pUserdata)': Check the probe + result and update the host or service domain name if the probe failed - In 'dynamicServiceTxtCallback(MDNSResponder* p_MDNSResponder, const hMDNSService p_hService, void* p_pUserdata)': - Add dynamic TXT items by calling 'MDNS.addDynamicServiceTxt(p_hService, "c#", "1");' + In 'dynamicServiceTxtCallback(MDNSResponder* p_MDNSResponder, const hMDNSService p_hService, + void* p_pUserdata)': Add dynamic TXT items by calling 'MDNS.addDynamicServiceTxt(p_hService, + "c#", "1");' In loop(): Call 'MDNS.update();' @@ -51,15 +59,17 @@ For querying services: Static: Call 'uint32_t u32AnswerCount = MDNS.queryService("http", "tcp");' - Iterate answers by: 'for (uint32_t u=0; u // for UdpContext.h +#include // for UdpContext.h #include "WiFiUdp.h" #include "lwip/udp.h" #include "debug.h" @@ -111,10 +121,8 @@ #include #include - #include "ESP8266WiFi.h" - namespace esp8266 { @@ -124,7 +132,7 @@ namespace esp8266 namespace MDNSImplementation { -//this should be defined at build time +// this should be defined at build time #ifndef ARDUINO_BOARD #define ARDUINO_BOARD "generic" #endif @@ -135,1329 +143,1254 @@ 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 - -/** - 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) - { - return (m_pUDPContext != 0); - } +#define MDNS_UDPCONTEXT_TIMEOUT 50 /** - hMDNSService (opaque handle to access the service) + MDNSResponder */ - 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) + class MDNSResponder { - setInstanceName(s_pcHostname.c_str()); - } + 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); + } - /** - hMDNSTxt (opaque handle to access the TXT items) - */ - typedef void* hMDNSTxt; + /** + 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()); + } - // Add a (static) MDNS TXT item ('key' = 'value') to the service - hMDNSTxt addServiceTxt(const hMDNSService p_hService, - const char* p_pcKey, + /** + 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); - 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); + 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 - */ + /** + 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; + /** + hMDNSServiceQuery (opaque handle to access dynamic service queries) + */ + 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 + /** + 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 #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); + /** + 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); #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: - /** - 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 + /** + 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: + /** + MDNSServiceInfo, used in application callbacks + */ + 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 + { + 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; + + public: + const char* serviceDomain() + { + return p_pMDNSResponder.answerServiceDomain(p_hServiceQuery, p_u32AnswerIndex); + }; + bool hostDomainAvailable() { - return strcmp(a, b) < 0; + return (p_pMDNSResponder.hasAnswerHostDomain(p_hServiceQuery, p_u32AnswerIndex)); } - }; - using KeyValueMap = std::map; - 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()) + 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() { - for (auto kv = p_pMDNSResponder._answerKeyValue(p_hServiceQuery, p_u32AnswerIndex); kv != nullptr; kv = kv->m_pNext) + return (txtAvailable()) + ? p_pMDNSResponder.answerTxts(p_hServiceQuery, p_u32AnswerIndex) + : nullptr; + }; + const KeyValueMap& keyValues() + { + 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: + }; - /** - 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; - }; + protected: + /** + stcMDNSServiceTxt + */ + struct stcMDNSServiceTxt + { + stcMDNSServiceTxt* m_pNext; + char* m_pcKey; + char* m_pcValue; + bool m_bTemp; - /** - stcMDNSTxts - */ - struct stcMDNSServiceTxts - { - stcMDNSServiceTxt* m_pTxts; + stcMDNSServiceTxt(const char* p_pcKey = 0, const char* p_pcValue = 0, + bool p_bTemp = false); + stcMDNSServiceTxt(const stcMDNSServiceTxt& p_Other); + ~stcMDNSServiceTxt(void); - stcMDNSServiceTxts(void); - stcMDNSServiceTxts(const stcMDNSServiceTxts& p_Other); - ~stcMDNSServiceTxts(void); + stcMDNSServiceTxt& operator=(const stcMDNSServiceTxt& p_Other); + bool clear(void); - stcMDNSServiceTxts& operator=(const stcMDNSServiceTxts& p_Other); + 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); - bool clear(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 add(stcMDNSServiceTxt* p_pTxt); - bool remove(stcMDNSServiceTxt* p_pTxt); + bool set(const char* p_pcKey, const char* p_pcValue, bool p_bTemp = false); - bool removeTempTxts(void); + bool update(const char* p_pcValue); - stcMDNSServiceTxt* find(const char* p_pcKey); - const stcMDNSServiceTxt* find(const char* p_pcKey) const; - stcMDNSServiceTxt* find(const stcMDNSServiceTxt* p_pTxt); + size_t length(void) const; + }; - uint16_t length(void) const; + /** + stcMDNSTxts + */ + struct stcMDNSServiceTxts + { + stcMDNSServiceTxt* m_pTxts; - size_t c_strLength(void) const; - bool c_str(char* p_pcBuffer); + stcMDNSServiceTxts(void); + stcMDNSServiceTxts(const stcMDNSServiceTxts& p_Other); + ~stcMDNSServiceTxts(void); - size_t bufferLength(void) const; - bool buffer(char* p_pcBuffer); + stcMDNSServiceTxts& operator=(const stcMDNSServiceTxts& p_Other); - bool compare(const stcMDNSServiceTxts& p_Other) const; - bool operator==(const stcMDNSServiceTxts& p_Other) const; - bool operator!=(const stcMDNSServiceTxts& p_Other) const; - }; + bool clear(void); - /** - 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; + bool add(stcMDNSServiceTxt* p_pTxt); + bool remove(stcMDNSServiceTxt* p_pTxt); - /** - 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); - }; + bool removeTempTxts(void); - /** - stcMDNS_RRDomain - */ - struct stcMDNS_RRDomain - { - char m_acName[MDNS_DOMAIN_MAXLENGTH]; // Encoded domain name - uint16_t m_u16NameLength; // Length (incl. '\0') + stcMDNSServiceTxt* find(const char* p_pcKey); + const stcMDNSServiceTxt* find(const char* p_pcKey) const; + stcMDNSServiceTxt* find(const stcMDNSServiceTxt* p_pTxt); - stcMDNS_RRDomain(void); - stcMDNS_RRDomain(const stcMDNS_RRDomain& p_Other); + uint16_t length(void) const; - stcMDNS_RRDomain& operator=(const stcMDNS_RRDomain& p_Other); + size_t c_strLength(void) const; + bool c_str(char* p_pcBuffer); - bool clear(void); + size_t bufferLength(void) const; + bool buffer(char* p_pcBuffer); - bool addLabel(const char* p_pcLabel, - bool p_bPrependUnderline = false); + bool compare(const stcMDNSServiceTxts& p_Other) const; + bool operator==(const stcMDNSServiceTxts& p_Other) const; + bool operator!=(const stcMDNSServiceTxts& 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; + /** + 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; - size_t c_strLength(void) const; - bool c_str(char* p_pcBuffer); - }; + /** + 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); + }; - /** - stcMDNS_RRAttributes - */ - struct stcMDNS_RRAttributes - { - uint16_t m_u16Type; // Type - uint16_t m_u16Class; // Class, nearly always 'IN' + /** + stcMDNS_RRDomain + */ + struct stcMDNS_RRDomain + { + char m_acName[MDNS_DOMAIN_MAXLENGTH]; // Encoded domain name + uint16_t m_u16NameLength; // Length (incl. '\0') - stcMDNS_RRAttributes(uint16_t p_u16Type = 0, - uint16_t p_u16Class = 1 /*DNS_RRCLASS_IN Internet*/); - stcMDNS_RRAttributes(const stcMDNS_RRAttributes& p_Other); + stcMDNS_RRDomain(void); + stcMDNS_RRDomain(const stcMDNS_RRDomain& p_Other); - stcMDNS_RRAttributes& operator=(const stcMDNS_RRAttributes& p_Other); - }; + stcMDNS_RRDomain& operator=(const stcMDNS_RRDomain& p_Other); - /** - stcMDNS_RRHeader - */ - struct stcMDNS_RRHeader - { - stcMDNS_RRDomain m_Domain; - stcMDNS_RRAttributes m_Attributes; + bool clear(void); - stcMDNS_RRHeader(void); - stcMDNS_RRHeader(const stcMDNS_RRHeader& p_Other); + bool addLabel(const char* p_pcLabel, bool p_bPrependUnderline = false); - stcMDNS_RRHeader& operator=(const stcMDNS_RRHeader& p_Other); + 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 clear(void); - }; + size_t c_strLength(void) const; + bool c_str(char* p_pcBuffer); + }; - /** - stcMDNS_RRQuestion - */ - struct stcMDNS_RRQuestion - { - stcMDNS_RRQuestion* m_pNext; - stcMDNS_RRHeader m_Header; - bool m_bUnicast; // Unicast reply requested + /** + stcMDNS_RRAttributes + */ + struct stcMDNS_RRAttributes + { + uint16_t m_u16Type; // Type + uint16_t m_u16Class; // Class, nearly always 'IN' - stcMDNS_RRQuestion(void); - }; + stcMDNS_RRAttributes(uint16_t p_u16Type = 0, + uint16_t p_u16Class = 1 /*DNS_RRCLASS_IN Internet*/); + stcMDNS_RRAttributes(const stcMDNS_RRAttributes& p_Other); - /** - enuAnswerType - */ - typedef enum _enuAnswerType - { - AnswerType_A, - AnswerType_PTR, - AnswerType_TXT, - AnswerType_AAAA, - AnswerType_SRV, - AnswerType_Generic - } enuAnswerType; + stcMDNS_RRAttributes& operator=(const stcMDNS_RRAttributes& p_Other); + }; - /** - 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 + /** + stcMDNS_RRHeader + */ + struct stcMDNS_RRHeader + { + stcMDNS_RRDomain m_Domain; + stcMDNS_RRAttributes m_Attributes; - virtual ~stcMDNS_RRAnswer(void); + stcMDNS_RRHeader(void); + stcMDNS_RRHeader(const stcMDNS_RRHeader& p_Other); - enuAnswerType answerType(void) const; + stcMDNS_RRHeader& operator=(const stcMDNS_RRHeader& p_Other); - bool clear(void); + bool clear(void); + }; - protected: - stcMDNS_RRAnswer(enuAnswerType p_AnswerType, - const stcMDNS_RRHeader& p_Header, - uint32_t p_u32TTL); - }; + /** + stcMDNS_RRQuestion + */ + struct stcMDNS_RRQuestion + { + stcMDNS_RRQuestion* m_pNext; + stcMDNS_RRHeader m_Header; + bool m_bUnicast; // Unicast reply requested + + stcMDNS_RRQuestion(void); + }; + + /** + 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 + + virtual ~stcMDNS_RRAnswer(void); + + enuAnswerType answerType(void) const; + + bool clear(void); + + 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; + /** + stcMDNS_RRAnswerA + */ + 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; + /** + stcMDNS_RRAnswerPTR + */ + 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; + /** + stcMDNS_RRAnswerTXT + */ + 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; + /** + stcMDNS_RRAnswerAAAA + */ + 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; - - stcMDNS_RRAnswerSRV(const stcMDNS_RRHeader& p_Header, - uint32_t p_u32TTL); - ~stcMDNS_RRAnswerSRV(void); - - bool clear(void); - }; + /** + stcMDNS_RRAnswerSRV + */ + struct stcMDNS_RRAnswerSRV: public stcMDNS_RRAnswer + { + uint16_t m_u16Priority; + uint16_t m_u16Weight; + uint16_t m_u16Port; + stcMDNS_RRDomain m_SRVDomain; - /** - 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 + stcMDNS_RRAnswerSRV(const stcMDNS_RRHeader& p_Header, uint32_t p_u32TTL); + ~stcMDNS_RRAnswerSRV(void); - stcMDNS_RRAnswerGeneric(const stcMDNS_RRHeader& p_Header, - uint32_t p_u32TTL); - ~stcMDNS_RRAnswerGeneric(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 + stcMDNS_RRAnswerGeneric(const stcMDNS_RRHeader& p_Header, uint32_t p_u32TTL); + ~stcMDNS_RRAnswerGeneric(void); - /** - enuProbingStatus - */ - typedef enum _enuProbingStatus - { - ProbingStatus_WaitingForData, - ProbingStatus_ReadyToStart, - ProbingStatus_InProgress, - ProbingStatus_Done - } enuProbingStatus; + bool clear(void); + }; - /** - 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); - }; + /** + 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); + }; - /** - 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); - }; + /** + 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); + }; - /** - stcMDNSServiceQuery - */ - struct stcMDNSServiceQuery - { /** - stcAnswer + stcMDNSServiceQuery */ - struct stcAnswer + struct stcMDNSServiceQuery { /** - stcTTL + stcAnswer */ - struct stcTTL + struct stcAnswer { /** - timeoutLevel_t + stcTTL */ - typedef uint8_t timeoutLevel_t; + struct stcTTL + { + /** + 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; + + uint32_t m_u32TTL; + esp8266::polledTimeout::oneShotMs m_TTLTimeout; + timeoutLevel_t m_timeoutLevel; + + using timeoutBase = decltype(m_TTLTimeout); + + stcTTL(void); + bool set(uint32_t p_u32TTL); + + bool flagged(void); + bool restart(void); + + bool prepareDeletion(void); + bool finalTimeoutLevel(void) const; + + timeoutBase::timeType timeout(void) const; + }; +#ifdef MDNS_IP4_SUPPORT /** - TIMEOUTLEVELs + stcIP4Address */ - 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; - - using timeoutBase = decltype(m_TTLTimeout); - - stcTTL(void); - bool set(uint32_t p_u32TTL); - - bool flagged(void); - bool restart(void); - - bool prepareDeletion(void); - bool finalTimeoutLevel(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; + /** + stcIP6Address + */ + 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: /** - stcDomainCacheItem + stcMDNSSendParameter */ - struct stcDomainCacheItem + struct stcMDNSSendParameter { - 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); - }; + 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 - 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; - }; + 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); - // 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 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); + /* 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 _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, + 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); - 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); -#ifdef MDNS_IP6_SUPPORT - bool _writeMDNSAnswer_AAAA(IPAddress p_IPAddress, - stcMDNSSendParameter& p_rSendParameter); - bool _writeMDNSAnswer_PTR_IP6(IPAddress p_IPAddress, + 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); #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 +} // 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..3d79f05ebc 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS_Control.cpp +++ b/libraries/ESP8266mDNS/src/LEAmDNS_Control.cpp @@ -33,7 +33,8 @@ ESP8266mDNS Control.cpp */ -extern "C" { +extern "C" +{ #include "user_interface.h" } @@ -49,2084 +50,2302 @@ namespace esp8266 namespace MDNSImplementation { -/** - CONTROL -*/ - - -/** - MAINTENANCE -*/ - -/* - MDNSResponder::_process + /** + CONTROL + */ - Run the MDNS process. - Is called, every time the UDPContext receives data AND - should be called in every 'loop' by calling 'MDNS::update()'. + /** + MAINTENANCE + */ -*/ -bool MDNSResponder::_process(bool p_bUserContext) -{ + /* + MDNSResponder::_process - bool bResult = true; + Run the MDNS process. + Is called, every time the UDPContext receives data AND + should be called in every 'loop' by calling 'MDNS::update()'. - if (!p_bUserContext) + */ + bool MDNSResponder::_process(bool p_bUserContext) { + bool bResult = true; - if ((m_pUDPContext) && // UDPContext available AND - (m_pUDPContext->next())) // has content + 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 + + /* + MDNSResponder::_restart + */ + bool MDNSResponder::_restart(void) { - bResult = _updateProbeStatus() && // Probing - _checkServiceQueryCache(); // Service query cache check + return ((_resetProbeStatus(true /*restart*/)) && // Stop and restart probing + (_allocUDPContext())); // Restart UDP } - return bResult; -} - -/* - MDNSResponder::_restart -*/ -bool MDNSResponder::_restart(void) -{ - - return ((_resetProbeStatus(true/*restart*/)) && // Stop and restart probing - (_allocUDPContext())); // Restart UDP -} -/** - RECEIVING -*/ + /** + 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)) + /* + MDNSResponder::_parseMessage + */ + 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: - 1. allow for tiebreaking while probing in the case of a race condition between two instances probing for - the same name at the same time - 2. provide answers to questions for our host domain or any presented service + /* + MDNSResponder::_parseQuery - When reading the questions, a set of (planned) responses is created, eg. a reverse PTR question for the host domain - gets an A (IP address) response, a PTR question for the _services._dns-sd domain gets a PTR (type) response for any - registered service, ... + Queries are of interest in two cases: + 1. allow for tiebreaking while probing in the case of a race condition between two instances + probing for the same name at the same time + 2. provide answers to questions for our host domain or any presented service - As any mDNS responder should be able to handle 'legacy' queries (from DNS clients), this case is handled here also. - Legacy queries have got only one (unicast) question and are directed to the local DNS port (not the multicast port). - - 1. -*/ -bool MDNSResponder::_parseQuery(const MDNSResponder::stcMDNS_MsgHeader& p_MsgHeader) -{ + When reading the questions, a set of (planned) responses is created, eg. a reverse PTR + question for the host domain gets an A (IP address) response, a PTR question for the + _services._dns-sd domain gets a PTR (type) response for any registered service, ... - bool bResult = true; + As any mDNS responder should be able to handle 'legacy' queries (from DNS clients), this + case is handled here also. Legacy queries have got only one (unicast) question and are + directed to the local DNS port (not the multicast port). - stcMDNSSendParameter sendParameter; - uint8_t u8HostOrServiceReplies = 0; - for (uint16_t qd = 0; ((bResult) && (qd < p_MsgHeader.m_u16QDCount)); ++qd) + 1. + */ + bool MDNSResponder::_parseQuery(const MDNSResponder::stcMDNS_MsgHeader& p_MsgHeader) { + bool bResult = true; - 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); - DEBUG_EX_INFO(if (u8HostOrServiceReplies) + stcMDNSSendParameter sendParameter; + uint8_t u8HostOrServiceReplies = 0; + for (uint16_t qd = 0; ((bResult) && (qd < p_MsgHeader.m_u16QDCount)); ++qd) { - 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; - 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 service replies - for (stcMDNSService* pService = m_pServices; pService; pService = pService->m_pNext) + stcMDNS_RRQuestion questionRR; + if ((bResult = _readRRQuestion(questionRR))) { - // 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()); + // 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 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)) + bool bFullNameMatch = false; + 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 - // 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);); + // 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; + } + } - pService->m_ProbeInformation.m_bTiebreakNeeded = true; + // 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) + { + 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; + } } } - } - // 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 + // 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_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 { - - 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))) + // 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 - - //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); - }); - - for (uint32_t an = 0; ((bResult) && (an < u32Answers)); ++an) - { - stcMDNS_RRAnswer* pKnownRRAnswer = 0; - if (((bResult = _readRRAnswer(pKnownRRAnswer))) && - (pKnownRRAnswer)) + 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()); } ); + + // 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) { - - 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 - } - else - { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: FAILED to read known answer!\n"));); - } + } // 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 (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) + if (bResult) { - u8ReplyNeeded |= pService->m_u8ReplyMask; - } + // 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);); + 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; + sendParameter.m_bResponse = true; + sendParameter.m_bAuthorative = true; - bResult = _sendMDNSMessage(sendParameter); + bResult = _sendMDNSMessage(sendParameter); + } + DEBUG_EX_INFO(else { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: No reply needed\n")); + }); } - DEBUG_EX_INFO( - else + else { - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: No reply needed\n")); + DEBUG_EX_ERR( + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: Something FAILED!\n"));); + m_pUDPContext->flush(); } - ); - } - 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) + // + // 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) { - 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; + 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; } - 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: - 1. find domain name conflicts while probing - 2. get answers to service queries - - In both cases any included questions are ignored - - 1. If any answer has a domain name similar to one of the domain names we're planning to use (and are probing for), - then we've got a 'probing conflict'. The conflict has to be solved on our side of the conflict (eg. by - setting a new hostname and restart probing). The callback 'm_fnProbeResultCallback' is called with - 'p_bProbeResult=false' in this case. - - 2. Service queries like '_http._tcp.local' will (if available) produce PTR, SRV, TXT and A/AAAA answers. - All stored answers are pivoted by the service instance name (from the PTR record). Other answer parts, - like host domain or IP address are than attached to this element. - Any answer part carries a TTL, this is also stored (incl. the reception time); if the TTL is '0' the - answer (part) is withdrawn by the sender and should be removed from any cache. RFC 6762, 10.1 proposes to - set the caches TTL-value to 1 second in such a case and to delete the item only, if no update has - has taken place in this second. - Answer parts may arrive in 'unsorted' order, so they are grouped into three levels: - Level 1: PRT - names the service instance (and is used as pivot), voids all other parts if is withdrawn or outdates - Level 2: SRV - links the instance name to a host domain and port, voids A/AAAA parts if is withdrawn or outdates - 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 + /* + MDNSResponder::_parseResponse + + Responses are of interest in two cases: + 1. find domain name conflicts while probing + 2. get answers to service queries + + In both cases any included questions are ignored + + 1. If any answer has a domain name similar to one of the domain names we're planning to use + (and are probing for), then we've got a 'probing conflict'. The conflict has to be solved on + our side of the conflict (eg. by setting a new hostname and restart probing). The callback + 'm_fnProbeResultCallback' is called with 'p_bProbeResult=false' in this case. + + 2. Service queries like '_http._tcp.local' will (if available) produce PTR, SRV, TXT and + A/AAAA answers. All stored answers are pivoted by the service instance name (from the PTR + record). Other answer parts, like host domain or IP address are than attached to this + element. Any answer part carries a TTL, this is also stored (incl. the reception time); if + the TTL is '0' the answer (part) is withdrawn by the sender and should be removed from any + cache. RFC 6762, 10.1 proposes to set the caches TTL-value to 1 second in such a case and to + delete the item only, if no update has has taken place in this second. Answer parts may + arrive in 'unsorted' order, so they are grouped into three levels: Level 1: PRT - names the + service instance (and is used as pivot), voids all other parts if is withdrawn or outdates + Level 2: SRV - links the instance name to a host domain and port, voids A/AAAA parts if is + withdrawn or outdates 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();); - DEBUG_EX_INFO( - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse: Received a response\n")); - //_udpDump(); - ); + bool bResult = false; - bResult = true; - // - // Ignore questions here - stcMDNS_RRQuestion dummyRRQ; - for (uint16_t qd = 0; ((bResult) && (qd < p_MsgHeader.m_u16QDCount)); ++qd) + // A response should be the result of a query or a probe + if ((_hasServiceQueriesWaitingForAnswers()) || // Waiting for query answers OR + (_hasProbesWaitingForAnswers())) // Probe responses { - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse: Received a response containing a question... ignoring!\n"));); - bResult = _readRRQuestion(dummyRRQ); - } // for queries + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P( + PSTR("[MDNSResponder] _parseResponse: Received a response\n")); + //_udpDump(); + ); - // - // 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) - { - stcMDNS_RRAnswer* pRRAnswer = 0; - if (((bResult = _readRRAnswer(pRRAnswer))) && - (pRRAnswer)) + 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))); + // 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; + } } - else // Some failure while reading answers + else // Received an unexpected response -> ignore { - DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse: FAILED to read answers!\n"));); + /* 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; } - - // 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; - } - } - else // Received an unexpected response -> ignore - { - /* 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; + 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 - AAAA (01Cx): eg. esp8266.local AAAA OP TTL 1234:5678::90 - PTR (0x0C, IP4): eg. 012.789.456.123.in-addr.arpa PTR OP TTL esp8266.local - PTR (0x0C, IP6): eg. 90.0.0.0.0.0.0.0.0.0.0.0.78.56.34.12.ip6.arpa PTR OP TTL esp8266.local - Service: - PTR (0x0C, srv name): eg. _http._tcp.local PTR OP TTL MyESP._http._tcp.local - PTR (0x0C, srv type): eg. _services._dns-sd._udp.local PTR OP TTL _http._tcp.local - SRV (0x21): eg. MyESP._http._tcp.local SRV OP TTL PRIORITY WEIGHT PORT esp8266.local - TXT (0x10): eg. MyESP._http._tcp.local TXT OP TTL c#=1 + /* + MDNSResponder::_processAnswers + Host: + A (0x01): eg. esp8266.local A OP TTL 123.456.789.012 + AAAA (01Cx): eg. esp8266.local AAAA OP TTL 1234:5678::90 + PTR (0x0C, IP4): eg. 012.789.456.123.in-addr.arpa PTR OP TTL esp8266.local + PTR (0x0C, IP6): eg. 90.0.0.0.0.0.0.0.0.0.0.0.78.56.34.12.ip6.arpa PTR OP TTL + esp8266.local Service: PTR (0x0C, srv name): eg. _http._tcp.local PTR OP TTL + MyESP._http._tcp.local PTR (0x0C, srv type): eg. _services._dns-sd._udp.local PTR OP TTL + _http._tcp.local SRV (0x21): eg. MyESP._http._tcp.local SRV OP TTL PRIORITY + WEIGHT PORT esp8266.local TXT (0x10): eg. MyESP._http._tcp.local TXT OP TTL c#=1 + + */ + bool MDNSResponder::_processAnswers(const MDNSResponder::stcMDNS_RRAnswer* p_pAnswers) + { + bool bResult = false; -*/ -bool MDNSResponder::_processAnswers(const MDNSResponder::stcMDNS_RRAnswer* p_pAnswers) -{ - - bool bResult = false; - - if (p_pAnswers) - { - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAnswers: Processing answers...\n"));); - bResult = true; - - // 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; - - const stcMDNS_RRAnswer* pRRAnswer = p_pAnswers; - while ((pRRAnswer) && - (bResult)) + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P( + PSTR("[MDNSResponder] _processAnswers: Processing answers...\n"));); + bResult = true; + + // 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; -} - -/* - MDNSResponder::_processPTRAnswer -*/ -bool MDNSResponder::_processPTRAnswer(const MDNSResponder::stcMDNS_RRAnswerPTR* p_pPTRAnswer, - bool& p_rbFoundNewKeyAnswer) -{ - bool bResult = false; + 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; + } - if ((bResult = (0 != p_pPTRAnswer))) + /* + MDNSResponder::_processPTRAnswer + */ + 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 + // 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.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")); - ); + 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; -} - -/* - MDNSResponder::_processSRVAnswer -*/ -bool MDNSResponder::_processSRVAnswer(const MDNSResponder::stcMDNS_RRAnswerSRV* p_pSRVAnswer, - bool& p_rbFoundNewKeyAnswer) -{ - - bool bResult = false; + } // else: No p_pPTRAnswer + DEBUG_EX_ERR(if (!bResult) { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processPTRAnswer: FAILED!\n")); + }); + return bResult; + } - if ((bResult = (0 != p_pSRVAnswer))) + /* + MDNSResponder::_processSRVAnswer + */ + 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; -} - -/* - MDNSResponder::_processTXTAnswer -*/ -bool MDNSResponder::_processTXTAnswer(const MDNSResponder::stcMDNS_RRAnswerTXT* p_pTXTAnswer) -{ - - bool bResult = false; + 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; + } - if ((bResult = (0 != p_pTXTAnswer))) + /* + MDNSResponder::_processTXTAnswer + */ + 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))) + /* + MDNSResponder::_processAAnswer + */ + 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 - { - 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 + stcMDNSServiceQuery::stcAnswer::stcIP4Address* pIP4Address + = pSQAnswer->findIP4Address(p_pAAnswer->m_IPAddress); + if (pIP4Address) { - 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))) + /* + MDNSResponder::_processAAAAAnswer + */ + 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 + stcIP6Address* pIP6Address + = pSQAnswer->findIP6Address(p_pAAAAAnswer->m_IPAddress); + if (pIP6Address) { - 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()); - ); + // 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 { + pIP6Address = new stcIP6Address(p_pAAAAAnswer->m_IPAddress, + p_pAAAAAnswer->m_u32TTL); + if ((pIP6Address) && (pSQAnswer->addIP6Address(pIP6Address))) + { + pSQAnswer->m_u32ContentFlags |= ServiceQueryAnswerType_IP6Address; - 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 + */ -/* - PROBING -*/ + /* + MDNSResponder::_updateProbeStatus -/* - MDNSResponder::_updateProbeStatus - - Manages the (outgoing) probing process. - - If probing has not been started yet (ProbingStatus_NotStarted), the initial delay (see RFC 6762) is determined and - the process is started - - After timeout (of initial or subsequential delay) a probe message is send out for three times. If the message has - already been sent out three times, the probing has been successful and is finished. + Manages the (outgoing) probing process. + - If probing has not been started yet (ProbingStatus_NotStarted), the initial delay (see RFC + 6762) is determined and the process is started + - After timeout (of initial or subsequential delay) a probe message is send out for three + times. If the message has already been sent out three times, the probing has been successful + and is finished. - 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 + Conflict management is handled in '_parseResponse ff.' + Tiebraking is handled in 'parseQuery ff.' + */ + bool MDNSResponder::_updateProbeStatus(void) { + bool bResult = true; - 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 + // + // Probe host domain + if (ProbingStatus_ReadyToStart == m_HostProbeInformation.m_ProbingStatus) { - 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); - } + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P( + PSTR("[MDNSResponder] _updateProbeStatus: Starting host probing...\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"));); + // 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: 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 + else if ((ProbingStatus_InProgress == m_HostProbeInformation.m_ProbingStatus) + && // Probing AND + (m_HostProbeInformation.m_Timeout.expired())) // Time for next probe { - ++m_HostProbeInformation.m_u8SentCount; - - if (MDNS_ANNOUNCE_COUNT > m_HostProbeInformation.m_u8SentCount) + if (MDNS_PROBE_COUNT > m_HostProbeInformation.m_u8SentCount) // Send next probe { - 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);); + 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 + 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(); - 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 - { + if (m_HostProbeInformation.m_fnHostProbeResultCallback) + { + m_HostProbeInformation.m_fnHostProbeResultCallback(m_pcHostname, true); + } - 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 + // 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 (MDNS_PROBE_COUNT > pService->m_ProbeInformation.m_u8SentCount) // Send next probe + if ((bResult = _announce(true, false))) // Don't announce services here { - if ((bResult = _sendServiceProbe(*pService))) + ++m_HostProbeInformation.m_u8SentCount; + + if (MDNS_ANNOUNCE_COUNT > m_HostProbeInformation.m_u8SentCount) { - 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; + 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 // 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) + else { - pService->m_ProbeInformation.m_fnServiceProbeResultCallback(pService->m_pcName, pService, true); + m_HostProbeInformation.m_Timeout.resetToNeverExpires(); + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P( + PSTR("[MDNSResponder] _updateProbeStatus: Done host announcing.\n\n"));); } - // 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 + // + // 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_u8SentCount; - - if (MDNS_ANNOUNCE_COUNT > pService->m_ProbeInformation.m_u8SentCount) + 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 { - 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);); + 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 + 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 + /* + MDNSResponder::_resetProbeStatus - Resets the probe status. - If 'p_bRestart' is set, the status is set to ProbingStatus_NotStarted. Consequently, - 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) + Resets the probe status. + If 'p_bRestart' is set, the status is set to ProbingStatus_NotStarted. Consequently, + when running 'updateProbeStatus' (which is done in every '_update' loop), the probing + process is restarted. + */ + bool MDNSResponder::_resetProbeStatus(bool p_bRestart /*= true*/) { - pService->m_ProbeInformation.clear(false); - pService->m_ProbeInformation.m_ProbingStatus = (p_bRestart ? ProbingStatus_ReadyToStart : ProbingStatus_Done); - } - return true; -} - -/* - MDNSResponder::_hasProbesWaitingForAnswers -*/ -bool MDNSResponder::_hasProbesWaitingForAnswers(void) const -{ + m_HostProbeInformation.clear(false); + m_HostProbeInformation.m_ProbingStatus + = (p_bRestart ? ProbingStatus_ReadyToStart : ProbingStatus_Done); - bool bResult = ((ProbingStatus_InProgress == m_HostProbeInformation.m_ProbingStatus) && // Probing - (0 < m_HostProbeInformation.m_u8SentCount)); // And really probing + 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; + } - for (stcMDNSService* pService = m_pServices; ((!bResult) && (pService)); pService = pService->m_pNext) + /* + MDNSResponder::_hasProbesWaitingForAnswers + */ + 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 + /* + MDNSResponder::_sendHostProbe - Asks (probes) in the local network for the planned host domain - - (eg. esp8266.local) + Asks (probes) in the local network for the planned host domain + - (eg. esp8266.local) - To allow 'tiebreaking' (see '_parseQuery'), the answers for these questions are delivered in - the 'knwon answers' section of the query. - 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());); + To allow 'tiebreaking' (see '_parseQuery'), the answers for these questions are delivered in + the 'knwon answers' section of the query. + 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 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) - { - 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))); -} - -/* - MDNSResponder::_sendServiceProbe - - Asks (probes) in the local network for the planned service instance domain - - (eg. MyESP._http._tcp.local). - - To allow 'tiebreaking' (see '_parseQuery'), the answers for these questions are delivered in - the 'knwon answers' section of the query. - Service domain: - - 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());); + else + { + 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))); + } - bool bResult = true; + /* + MDNSResponder::_sendServiceProbe - // Requests for service instance domain - stcMDNSSendParameter sendParameter; - sendParameter.m_bCacheFlush = false; // RFC 6762 10.2 + Asks (probes) in the local network for the planned service instance domain + - (eg. MyESP._http._tcp.local). - sendParameter.m_pQuestions = new stcMDNS_RRQuestion; - if (((bResult = (0 != sendParameter.m_pQuestions))) && - ((bResult = _buildDomainForService(p_rService, true, sendParameter.m_pQuestions->m_Header.m_Domain)))) + To allow 'tiebreaking' (see '_parseQuery'), the answers for these questions are delivered in + the 'knwon answers' section of the query. + Service domain: + - 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());); - 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 + bool bResult = true; - // 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) + // Requests for service instance domain + 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)))) + { + 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) -{ + /* + MDNSResponder::_cancelProbingForHost + */ + bool MDNSResponder::_cancelProbingForHost(void) + { + bool bResult = false; - bool bResult = false; + m_HostProbeInformation.clear(false); + // Send host notification + if (m_HostProbeInformation.m_fnHostProbeResultCallback) + { + m_HostProbeInformation.m_fnHostProbeResultCallback(m_pcHostname, false); - m_HostProbeInformation.clear(false); - // Send host notification - if (m_HostProbeInformation.m_fnHostProbeResultCallback) - { - m_HostProbeInformation.m_fnHostProbeResultCallback(m_pcHostname, false); + bResult = true; + } - bResult = true; + for (stcMDNSService* pService = m_pServices; ((!bResult) && (pService)); + pService = pService->m_pNext) + { + bResult = _cancelProbingForService(*pService); + } + return bResult; } - for (stcMDNSService* pService = m_pServices; ((!bResult) && (pService)); pService = pService->m_pNext) + /* + MDNSResponder::_cancelProbingForService + */ + bool MDNSResponder::_cancelProbingForService(stcMDNSService& p_rService) { - bResult = _cancelProbingForService(*pService); - } - return bResult; -} - -/* - MDNSResponder::_cancelProbingForService -*/ -bool MDNSResponder::_cancelProbingForService(stcMDNSService& p_rService) -{ - - bool bResult = false; + 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; + 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: - - A/AAAA (eg. esp8266.local -> 192.168.2.120) - - PTR (eg. 192.168.2.120.in-addr.arpa -> esp8266.local) + /** + ANNOUNCING + */ - and all presented services: - - PTR_TYPE (_services._dns-sd._udp.local -> _http._tcp.local) - - PTR_NAME (eg. _http._tcp.local -> MyESP8266._http._tcp.local) - - SRV (eg. MyESP8266._http._tcp.local -> 5000 esp8266.local) - - TXT (eg. MyESP8266._http._tcp.local -> c#=1) + /* + MDNSResponder::_announce - Goodbye (Un-Announcing) for the host domain and all services is also handled here. - 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) -{ + Announces the host domain: + - A/AAAA (eg. esp8266.local -> 192.168.2.120) + - PTR (eg. 192.168.2.120.in-addr.arpa -> esp8266.local) - bool bResult = false; + and all presented services: + - PTR_TYPE (_services._dns-sd._udp.local -> _http._tcp.local) + - PTR_NAME (eg. _http._tcp.local -> MyESP8266._http._tcp.local) + - SRV (eg. MyESP8266._http._tcp.local -> 5000 esp8266.local) + - TXT (eg. MyESP8266._http._tcp.local -> c#=1) - stcMDNSSendParameter sendParameter; - if (ProbingStatus_Done == m_HostProbeInformation.m_ProbingStatus) + Goodbye (Un-Announcing) for the host domain and all services is also handled here. + 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; - bResult = true; + 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); - - 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);); + 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_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) + /* + MDNSResponder::_announceService + */ + bool MDNSResponder::_announceService(stcMDNSService& p_rService, bool p_bAnnounce /*= true*/) { + bool bResult = false; - 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; + 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 - // 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);); + // DON'T announce host + sendParameter.m_u8HostReplyMask = 0; - bResult = true; + // 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; + } + 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; + /** + SERVICE QUERY CACHE + */ - for (stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; pServiceQuery; pServiceQuery = pServiceQuery->m_pNext) + /* + MDNSResponder::_hasServiceQueriesWaitingForAnswers + */ + 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) - are checked for topicality based on the stored reception time and the answers TTL. - When the components TTL is outlasted by more than 80%, a new question is generated, to get updated information. - When no update arrived (in time), the component is removed from the answer (cache). -*/ -bool MDNSResponder::_checkServiceQueryCache(void) -{ + /* + MDNSResponder::_checkServiceQueryCache - bool bResult = true; + For any 'living' service query (m_bAwaitingAnswers == true) all available answers (their + components) are checked for topicality based on the stored reception time and the answers + TTL. When the components TTL is outlasted by more than 80%, a new question is generated, to + get updated information. When no update arrived (in time), the component is removed from the + answer (cache). - DEBUG_EX_INFO( - bool printedInfo = false; - ); - for (stcMDNSServiceQuery* pServiceQuery = m_pServiceQueries; ((bResult) && (pServiceQuery)); pServiceQuery = pServiceQuery->m_pNext) + */ + bool MDNSResponder::_checkServiceQueryCache(void) { + bool bResult = true; - // - // 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())) + 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)) { + stcMDNSServiceQuery::stcAnswer* pNextSQAnswer = pSQAnswer->m_pNext; - 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 + // 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; - ); - - 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()) - { + 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 = ((_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); + // 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())) - { + } // HostDomainAndPort flagged - if (!pSQAnswer->m_TTLTxts.finalTimeoutLevel()) + // Txts (from TXT) + if ((bResult) && (pSQAnswer->m_TTLTxts.flagged())) { - - 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) + if (!pSQAnswer->m_TTLTxts.finalTimeoutLevel()) { - MDNSServiceInfo serviceInfo(*this, (hMDNSServiceQuery)pServiceQuery, pServiceQuery->indexOfAnswer(pSQAnswer)); - pServiceQuery->m_fnCallback(serviceInfo, static_cast(ServiceQueryAnswerType_Txts), false); + 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;); } - } - } // 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... - - if (pIP4Address->m_TTL.flagged()) - { - - if (!pIP4Address->m_TTL.finalTimeoutLevel()) // Needs update + 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 ((bAUpdateQuerySent) || - ((bResult = _sendMDNSQuery(pSQAnswer->m_HostDomain, DNS_RRTYPE_A)))) + if (pServiceQuery->m_fnCallback) { - - 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; - ); + MDNSServiceInfo serviceInfo( + *this, (hMDNSServiceQuery)pServiceQuery, + pServiceQuery->indexOfAnswer(pSQAnswer)); + pServiceQuery->m_fnCallback( + serviceInfo, + static_cast(ServiceQueryAnswerType_Txts), false); } } - else + } // 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... + + if (pIP4Address->m_TTL.flagged()) { - // Timed out! -> Delete - DEBUG_EX_INFO( - 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; - ); - pSQAnswer->removeIP4Address(pIP4Address); - if (!pSQAnswer->m_pIP4Addresses) // NO IP4 address left -> remove content flag + if (!pIP4Address->m_TTL.finalTimeoutLevel()) // Needs update { - pSQAnswer->m_u32ContentFlags &= ~ServiceQueryAnswerType_IP4Address; + 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;); + } } - // Notify client - if (pServiceQuery->m_fnCallback) + else { - MDNSServiceInfo serviceInfo(*this, (hMDNSServiceQuery)pServiceQuery, pServiceQuery->indexOfAnswer(pSQAnswer)); - pServiceQuery->m_fnCallback(serviceInfo, static_cast(ServiceQueryAnswerType_IP4Address), false); + // Timed out! -> Delete + DEBUG_EX_INFO(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;); + 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); + } } - } - } // IP4 flagged + } // IP4 flagged - pIP4Address = pNextIP4Address; // Next - } // while + 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()) + // 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.finalTimeoutLevel()) // Needs update - { - - 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; - ); - } - } - else + 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. - - A question for the hostname (eg. esp8266.local) will result in an A/AAAA (eg. 192.168.2.129) reply. - - A question for the reverse IP address (eg. 192-168.2.120.inarpa.arpa) will result in an PTR_IP4 (eg. esp8266.local) reply. - 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"));); + /* + MDNSResponder::_replyMaskForHost - uint8_t u8ReplyMask = 0; - (p_pbFullNameMatch ? *p_pbFullNameMatch = false : 0); + Determines the relevant host answers for the given question. + - A question for the hostname (eg. esp8266.local) will result in an A/AAAA (eg. + 192.168.2.129) reply. + - A question for the reverse IP address (eg. 192-168.2.120.inarpa.arpa) will result in an + PTR_IP4 (eg. esp8266.local) reply. - if ((DNS_RRCLASS_IN == p_RRHeader.m_Attributes.m_u16Class) || - (DNS_RRCLASS_ANY == p_RRHeader.m_Attributes.m_u16Class)) + 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"));); - if ((DNS_RRTYPE_PTR == p_RRHeader.m_Attributes.m_u16Type) || - (DNS_RRTYPE_ANY == p_RRHeader.m_Attributes.m_u16Type)) + 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)) { - // 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 - - stcMDNS_RRDomain hostDomain; - if ((_buildDomainForHost(m_pcHostname, hostDomain)) && - (p_RRHeader.m_Domain == hostDomain)) // Host domain match - { + } // Address qeuest - (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; -} - -/* - MDNSResponder::_replyMaskForService - - Determines the relevant service answers for the given question - - A PTR dns-sd service enum question (_services.dns-sd._udp.local) will result into an PTR_TYPE (eg. _http._tcp.local) answer - - A PTR service type question (eg. _http._tcp.local) will result into an PTR_NAME (eg. MyESP._http._tcp.local) answer - - A PTR service name question (eg. MyESP._http._tcp.local) will result into an PTR_NAME (eg. MyESP._http._tcp.local) answer - - A SRV service name question (eg. MyESP._http._tcp.local) will result into an SRV (eg. 5000 MyESP.local) answer - - A TXT service name question (eg. MyESP._http._tcp.local) will result into an TXT (eg. c#=1) answer - - 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)) - { - - 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))) + else { - // Common service info requested - u8ReplyMask |= ContentFlag_PTR_TYPE; + // 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; + } - 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; - } + /* + MDNSResponder::_replyMaskForService + + Determines the relevant service answers for the given question + - A PTR dns-sd service enum question (_services.dns-sd._udp.local) will result into an + PTR_TYPE (eg. _http._tcp.local) answer + - A PTR service type question (eg. _http._tcp.local) will result into an PTR_NAME (eg. + MyESP._http._tcp.local) answer + - A PTR service name question (eg. MyESP._http._tcp.local) will result into an PTR_NAME (eg. + MyESP._http._tcp.local) answer + - A SRV service name question (eg. MyESP._http._tcp.local) will result into an SRV (eg. 5000 + MyESP.local) answer + - A TXT service name question (eg. MyESP._http._tcp.local) will result into an TXT (eg. + c#=1) answer + + 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 ((_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)) { + 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; + } - (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)) + 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 +} // namespace MDNSImplementation -} // namespace esp8266 +} // namespace esp8266 diff --git a/libraries/ESP8266mDNS/src/LEAmDNS_Helpers.cpp b/libraries/ESP8266mDNS/src/LEAmDNS_Helpers.cpp index d4014db993..2d12f9042e 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS_Helpers.cpp +++ b/libraries/ESP8266mDNS/src/LEAmDNS_Helpers.cpp @@ -23,7 +23,7 @@ */ #include -#include // strrstr() +#include // strrstr() #include "ESP8266mDNS.h" #include "LEAmDNS_lwIPdefs.h" @@ -38,53 +38,79 @@ namespace esp8266 namespace MDNSImplementation { -/** - HELPERS -*/ - -/* - MDNSResponder::indexDomain (static) + /** + HELPERS + */ - Updates the given domain 'p_rpcHostname' by appending a delimiter and an index number. + /* + MDNSResponder::indexDomain (static) - If the given domain already hasa numeric index (after the given delimiter), this index - incremented. If not, the delimiter and index '2' is added. + Updates the given domain 'p_rpcHostname' by appending a delimiter and an index number. - If 'p_rpcHostname' is empty (==0), the given default name 'p_pcDefaultHostname' is used, - if no default is given, 'esp8266' is used. + If the given domain already hasa numeric index (after the given delimiter), this index + incremented. If not, the delimiter and index '2' is added. -*/ -/*static*/ bool MDNSResponder::indexDomain(char*& p_rpcDomain, - const char* p_pcDivider /*= "-"*/, - const char* p_pcDefaultDomain /*= 0*/) -{ + If 'p_rpcHostname' is empty (==0), the given default name 'p_pcDefaultHostname' is used, + if no default is given, 'esp8266' is used. - 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* 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 + } + } - char acIndexBuffer[16]; - sprintf(acIndexBuffer, "%lu", (++ulIndex)); - size_t stLength = ((pFoundDivider - p_rpcDomain + strlen(pcDivider)) + strlen(acIndexBuffer) + 1); - char* pNewHostname = new char[stLength]; + 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; @@ -93,709 +119,659 @@ namespace MDNSImplementation } else { - DEBUG_EX_ERR(DEBUG_OUTPUT.println(F("[MDNSResponder] indexDomain: FAILED to alloc new hostname!"));); + 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 { - DEBUG_EX_ERR(DEBUG_OUTPUT.println(F("[MDNSResponder] indexDomain: FAILED to alloc new hostname!"));); + 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 + */ -/* - 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 -/* - MDNSResponder::_allocUDPContext + (Re-)Creates the one-and-only UDP context for the MDNS responder. + The context is added to the 'multicast'-group and listens to the MDNS port (5353). + The travel-distance for multicast messages is set to 1 (local, via MDNS_MULTICAST_TTL). + Messages are received via the MDNSResponder '_update' function. CAUTION: This function + is called from the WiFi stack side of the ESP stack system. - (Re-)Creates the one-and-only UDP context for the MDNS responder. - The context is added to the 'multicast'-group and listens to the MDNS port (5353). - The travel-distance for multicast messages is set to 1 (local, via MDNS_MULTICAST_TTL). - Messages are received via the MDNSResponder '_update' function. CAUTION: This function - 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)); + return true; } - else - { - return false; - } - - return true; -} -/* - MDNSResponder::_releaseUDPContext -*/ -bool MDNSResponder::_releaseUDPContext(void) -{ - - if (m_pUDPContext) + /* + MDNSResponder::_releaseUDPContext + */ + 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 + */ -/* - SERVICE QUERY -*/ - -/* - MDNSResponder::_allocServiceQuery -*/ -MDNSResponder::stcMDNSServiceQuery* MDNSResponder::_allocServiceQuery(void) -{ - - stcMDNSServiceQuery* pServiceQuery = new stcMDNSServiceQuery; - if (pServiceQuery) + /* + MDNSResponder::_allocServiceQuery + */ + 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) + /* + MDNSResponder::_removeServiceQuery + */ + 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); -} - -/* - MDNSResponder::_findServiceQuery + /* + MDNSResponder::_removeLegacyServiceQuery + */ + bool MDNSResponder::_removeLegacyServiceQuery(void) + { + stcMDNSServiceQuery* pLegacyServiceQuery = _findLegacyServiceQuery(); + return (pLegacyServiceQuery ? _removeServiceQuery(pLegacyServiceQuery) : true); + } - 'Convert' hMDNSServiceQuery to stcMDNSServiceQuery* (ensure existence) + /* + MDNSResponder::_findServiceQuery -*/ -MDNSResponder::stcMDNSServiceQuery* MDNSResponder::_findServiceQuery(MDNSResponder::hMDNSServiceQuery p_hServiceQuery) -{ + 'Convert' hMDNSServiceQuery to stcMDNSServiceQuery* (ensure existence) - 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::_findLegacyServiceQuery + */ + 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) + /* + MDNSResponder::_releaseServiceQueries + */ + 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::_findNextServiceQueryByServiceType + */ + 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 + */ -/* - HOSTNAME -*/ - -/* - MDNSResponder::_setHostname -*/ -bool MDNSResponder::_setHostname(const char* p_pcHostname) -{ - //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _allocHostname (%s)\n"), p_pcHostname);); + /* + MDNSResponder::_setHostname + */ + 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) + /* + MDNSResponder::_releaseHostname + */ + 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))) + /* + 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))) + { + pService->m_bAutoName = (0 == p_pcName); + pService->m_u16Port = p_u16Port; - 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) + /* + MDNSResponder::_releaseService + */ + 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)) { - m_pServices = p_pService->m_pNext; + pPred = pPred->m_pNext; + } + if (pPred) + { + 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) + /* + MDNSResponder::_releaseServices + */ + 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::_findService + */ + 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::_findService + */ + 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; + /* + SERVICE TXT + */ - 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::_allocServiceTxt + */ + MDNSResponder::stcMDNSServiceTxt* + MDNSResponder::_allocServiceTxt(MDNSResponder::stcMDNSService* p_pService, const char* p_pcKey, + const char* p_pcValue, bool p_bTemp) { + stcMDNSServiceTxt* pTxt = 0; - pTxt = new stcMDNSServiceTxt; - if (pTxt) + 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))); -} - -/* - 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::_releaseServiceTxt + */ + bool MDNSResponder::_releaseServiceTxt(MDNSResponder::stcMDNSService* p_pService, + MDNSResponder::stcMDNSServiceTxt* p_pTxt) { - p_pTxt->update(p_pcValue); - p_pTxt->m_bTemp = p_bTemp; + return ((p_pService) && (p_pTxt) && (p_pService->m_Txts.remove(p_pTxt))); } - return p_pTxt; -} -/* - MDNSResponder::_findServiceTxt -*/ -MDNSResponder::stcMDNSServiceTxt* MDNSResponder::_findServiceTxt(MDNSResponder::stcMDNSService* p_pService, - const char* p_pcKey) -{ + /* + 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)))) + { + p_pTxt->update(p_pcValue); + p_pTxt->m_bTemp = p_bTemp; + } + return p_pTxt; + } - return (p_pService ? p_pService->m_Txts.find(p_pcKey) : 0); -} + /* + 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::_findServiceTxt -*/ -MDNSResponder::stcMDNSServiceTxt* MDNSResponder::_findServiceTxt(MDNSResponder::stcMDNSService* p_pService, - const hMDNSTxt p_hTxt) -{ + /* + 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); + } - 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; -/* - 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))) + { + 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; + } - if ((p_pService) && - (p_pcKey) && - (strlen(p_pcKey))) + 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; + } - stcMDNSServiceTxt* pTxt = p_pService->m_Txts.find(p_pcKey); - if (pTxt) + /* + MDNSResponder::_collectServiceTxts + */ + bool MDNSResponder::_collectServiceTxts(MDNSResponder::stcMDNSService& p_rService) + { + // Call Dynamic service callbacks + if (m_fnServiceTxtCallback) { - pResult = _updateServiceTxt(p_pService, pTxt, p_pcValue, p_bTemp); + m_fnServiceTxtCallback((hMDNSService)&p_rService); } - else + if (p_rService.m_fnTxtCallback) { - pResult = _allocServiceTxt(p_pService, p_pcKey, p_pcValue, p_bTemp); + p_rService.m_fnTxtCallback((hMDNSService)&p_rService); } + return true; } - 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::_collectServiceTxts -*/ -bool MDNSResponder::_collectServiceTxts(MDNSResponder::stcMDNSService& p_rService) -{ - - // Call Dynamic service callbacks - if (m_fnServiceTxtCallback) + /* + MDNSResponder::_releaseTempServiceTxts + */ + bool MDNSResponder::_releaseTempServiceTxts(MDNSResponder::stcMDNSService& p_rService) { - m_fnServiceTxtCallback((hMDNSService)&p_rService); + return (p_rService.m_Txts.removeTempTxts()); } - if (p_rService.m_fnTxtCallback) - { - p_rService.m_fnTxtCallback((hMDNSService)&p_rService); - } - return true; -} - -/* - MDNSResponder::_releaseTempServiceTxts -*/ -bool MDNSResponder::_releaseTempServiceTxts(MDNSResponder::stcMDNSService& p_rService) -{ - - return (p_rService.m_Txts.removeTempTxts()); -} - -/* - MISC -*/ + /* + 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) + /* + MDNSResponder::_printRRDomain + */ + 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) - { - DEBUG_OUTPUT.printf_P(PSTR("%c"), *(pCursor++)); - } - u8Length = *pCursor++; - if (u8Length) + while (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")); - - return true; -} + else // empty domain + { + DEBUG_OUTPUT.printf_P(PSTR("-empty-")); + } + // DEBUG_OUTPUT.printf_P(PSTR("\n")); -/* - MDNSResponder::_printRRAnswer -*/ -bool MDNSResponder::_printRRAnswer(const MDNSResponder::stcMDNS_RRAnswer& p_RRAnswer) const -{ + return true; + } - 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 + /* + 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 + { #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; - } - DEBUG_OUTPUT.printf_P(PSTR("\n")); + 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")); - return true; -} + return true; + } #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..9b89141285 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS_Priv.h +++ b/libraries/ESP8266mDNS/src/LEAmDNS_Priv.h @@ -37,7 +37,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 @@ -48,8 +48,9 @@ namespace MDNSImplementation #endif // -// If ENABLE_ESP_MDNS_RESPONDER_PASSIV_MODE is defined, the mDNS responder ignores a successful probing -// This allows to drive the responder in a environment, where 'update()' isn't called in the loop +// If ENABLE_ESP_MDNS_RESPONDER_PASSIV_MODE is defined, the mDNS responder ignores a successful +// probing This allows to drive the responder in a environment, where 'update()' isn't called in the +// loop //#define ENABLE_ESP_MDNS_RESPONDER_PASSIV_MODE // Enable/disable debug trace macros @@ -62,7 +63,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 +73,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,19 +89,34 @@ 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') #ifdef MDNS_IP4_SUPPORT - #define DNS_MQUERY_IPV4_GROUP_INIT (IPAddress(224, 0, 0, 251)) // ip_addr_t v4group = DNS_MQUERY_IPV4_GROUP_INIT - #endif - #ifdef MDNS_IP6_SUPPORT - #define DNS_MQUERY_IPV6_GROUP_INIT IPADDR6_INIT_HOST(0xFF020000,0,0,0xFB) // ip_addr_t v6group = DNS_MQUERY_IPV6_GROUP_INIT - #endif*/ + #define DNS_MQUERY_IPV4_GROUP_INIT (IPAddress(224, 0, 0, 251)) // ip_addr_t + v4group = DNS_MQUERY_IPV4_GROUP_INIT #endif #ifdef MDNS_IP6_SUPPORT #define + DNS_MQUERY_IPV6_GROUP_INIT IPADDR6_INIT_HOST(0xFF020000,0,0,0xFB) // ip_addr_t v6group = + DNS_MQUERY_IPV6_GROUP_INIT #endif*/ //#define MDNS_MULTICAST_PORT 5353 /* @@ -111,44 +127,44 @@ 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' + 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 +183,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..977a924394 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS_Structs.cpp +++ b/libraries/ESP8266mDNS/src/LEAmDNS_Structs.cpp @@ -35,2453 +35,2264 @@ namespace esp8266 namespace MDNSImplementation { -/** - STRUCTS -*/ - -/** - MDNSResponder::stcMDNSServiceTxt - - One MDNS TXT item. - m_pcValue may be '\0'. - Objects can be chained together (list, m_pNext). - A 'm_bTemp' flag differentiates between static and dynamic items. - 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) -{ + /** + STRUCTS + */ - setKey(p_pcKey); - setValue(p_pcValue); -} + /** + MDNSResponder::stcMDNSServiceTxt -/* - 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 destructor -*/ -MDNSResponder::stcMDNSServiceTxt::~stcMDNSServiceTxt(void) -{ + One MDNS TXT item. + m_pcValue may be '\0'. + Objects can be chained together (list, m_pNext). + A 'm_bTemp' flag differentiates between static and dynamic items. + Output as byte array 'c#=1' is supported. + */ - clear(); -} + /* + 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::operator= -*/ -MDNSResponder::stcMDNSServiceTxt& MDNSResponder::stcMDNSServiceTxt::operator=(const MDNSResponder::stcMDNSServiceTxt& p_Other) -{ + /* + 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); + } - if (&p_Other != this) + /* + MDNSResponder::stcMDNSServiceTxt::~stcMDNSServiceTxt destructor + */ + MDNSResponder::stcMDNSServiceTxt::~stcMDNSServiceTxt(void) { clear(); - set(p_Other.m_pcKey, p_Other.m_pcValue, p_Other.m_bTemp); } - return *this; -} - -/* - MDNSResponder::stcMDNSServiceTxt::clear -*/ -bool MDNSResponder::stcMDNSServiceTxt::clear(void) -{ - - releaseKey(); - releaseValue(); - return true; -} - -/* - MDNSResponder::stcMDNSServiceTxt::allocKey -*/ -char* MDNSResponder::stcMDNSServiceTxt::allocKey(size_t p_stLength) -{ - releaseKey(); - if (p_stLength) + /* + MDNSResponder::stcMDNSServiceTxt::operator= + */ + MDNSResponder::stcMDNSServiceTxt& + MDNSResponder::stcMDNSServiceTxt::operator=(const MDNSResponder::stcMDNSServiceTxt& p_Other) { - m_pcKey = new char[p_stLength + 1]; + if (&p_Other != this) + { + clear(); + set(p_Other.m_pcKey, p_Other.m_pcValue, p_Other.m_bTemp); + } + return *this; } - return m_pcKey; -} - -/* - MDNSResponder::stcMDNSServiceTxt::setKey -*/ -bool MDNSResponder::stcMDNSServiceTxt::setKey(const char* p_pcKey, - size_t p_stLength) -{ - bool bResult = false; + /* + MDNSResponder::stcMDNSServiceTxt::clear + */ + bool MDNSResponder::stcMDNSServiceTxt::clear(void) + { + releaseKey(); + releaseValue(); + return true; + } - releaseKey(); - if (p_stLength) + /* + MDNSResponder::stcMDNSServiceTxt::allocKey + */ + char* MDNSResponder::stcMDNSServiceTxt::allocKey(size_t p_stLength) { - if (allocKey(p_stLength)) + releaseKey(); + if (p_stLength) { - strncpy(m_pcKey, p_pcKey, p_stLength); - m_pcKey[p_stLength] = 0; - bResult = true; + m_pcKey = new char[p_stLength + 1]; } + return m_pcKey; } - return bResult; -} - -/* - MDNSResponder::stcMDNSServiceTxt::setKey -*/ -bool MDNSResponder::stcMDNSServiceTxt::setKey(const char* p_pcKey) -{ - return setKey(p_pcKey, (p_pcKey ? strlen(p_pcKey) : 0)); -} + /* + MDNSResponder::stcMDNSServiceTxt::setKey + */ + bool MDNSResponder::stcMDNSServiceTxt::setKey(const char* p_pcKey, size_t p_stLength) + { + bool bResult = false; -/* - MDNSResponder::stcMDNSServiceTxt::releaseKey -*/ -bool MDNSResponder::stcMDNSServiceTxt::releaseKey(void) -{ + releaseKey(); + if (p_stLength) + { + if (allocKey(p_stLength)) + { + strncpy(m_pcKey, p_pcKey, p_stLength); + m_pcKey[p_stLength] = 0; + bResult = true; + } + } + return bResult; + } - if (m_pcKey) + /* + MDNSResponder::stcMDNSServiceTxt::setKey + */ + bool MDNSResponder::stcMDNSServiceTxt::setKey(const char* p_pcKey) { - delete[] m_pcKey; - m_pcKey = 0; + return setKey(p_pcKey, (p_pcKey ? strlen(p_pcKey) : 0)); } - return true; -} - -/* - MDNSResponder::stcMDNSServiceTxt::allocValue -*/ -char* MDNSResponder::stcMDNSServiceTxt::allocValue(size_t p_stLength) -{ - releaseValue(); - if (p_stLength) + /* + MDNSResponder::stcMDNSServiceTxt::releaseKey + */ + bool MDNSResponder::stcMDNSServiceTxt::releaseKey(void) { - m_pcValue = new char[p_stLength + 1]; + if (m_pcKey) + { + delete[] m_pcKey; + m_pcKey = 0; + } + return true; } - return m_pcValue; -} - -/* - MDNSResponder::stcMDNSServiceTxt::setValue -*/ -bool MDNSResponder::stcMDNSServiceTxt::setValue(const char* p_pcValue, - size_t p_stLength) -{ - bool bResult = false; + /* + MDNSResponder::stcMDNSServiceTxt::allocValue + */ + char* MDNSResponder::stcMDNSServiceTxt::allocValue(size_t p_stLength) + { + releaseValue(); + if (p_stLength) + { + m_pcValue = new char[p_stLength + 1]; + } + return m_pcValue; + } - releaseValue(); - if (p_stLength) + /* + MDNSResponder::stcMDNSServiceTxt::setValue + */ + 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 + + /* + MDNSResponder::stcMDNSServiceTxt::setValue + */ + bool MDNSResponder::stcMDNSServiceTxt::setValue(const char* p_pcValue) { - bResult = true; + return setValue(p_pcValue, (p_pcValue ? strlen(p_pcValue) : 0)); } - return bResult; -} - -/* - MDNSResponder::stcMDNSServiceTxt::setValue -*/ -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) + /* + MDNSResponder::stcMDNSServiceTxt::releaseValue + */ + 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))); -} - -/* - MDNSResponder::stcMDNSServiceTxt::update -*/ -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) + /* + MDNSResponder::stcMDNSServiceTxt::set + */ + bool MDNSResponder::stcMDNSServiceTxt::set(const char* p_pcKey, const char* p_pcValue, + bool p_bTemp /*= false*/) { - stLength += strlen(m_pcKey); // Key - stLength += 1; // '=' - stLength += (m_pcValue ? strlen(m_pcValue) : 0); // Value + m_bTemp = p_bTemp; + return ((setKey(p_pcKey)) && (setValue(p_pcValue))); } - return stLength; -} - - -/** - MDNSResponder::stcMDNSServiceTxts - - A list of zero or more MDNS TXT items. - Dynamic TXT items can be removed by 'removeTempTxts'. - A TXT item can be looke up by its 'key' member. - Export as ';'-separated byte array is supported. - Export as 'length byte coded' byte array is supported. - Comparison ((all A TXT items in B and equal) AND (all B TXT items in A and equal)) is supported. - -*/ - -/* - MDNSResponder::stcMDNSServiceTxts::stcMDNSServiceTxts constructor -*/ -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 destructor -*/ -MDNSResponder::stcMDNSServiceTxts::~stcMDNSServiceTxts(void) -{ - clear(); -} + /* + MDNSResponder::stcMDNSServiceTxt::update + */ + bool MDNSResponder::stcMDNSServiceTxt::update(const char* p_pcValue) + { + return setValue(p_pcValue); + } -/* - MDNSResponder::stcMDNSServiceTxts::operator= -*/ -MDNSResponder::stcMDNSServiceTxts& MDNSResponder::stcMDNSServiceTxts::operator=(const stcMDNSServiceTxts& p_Other) -{ + /* + MDNSResponder::stcMDNSServiceTxt::length - if (this != &p_Other) + length of eg. 'c#=1' without any closing '\0' + */ + size_t MDNSResponder::stcMDNSServiceTxt::length(void) const { - clear(); - - for (stcMDNSServiceTxt* pOtherTxt = p_Other.m_pTxts; pOtherTxt; pOtherTxt = pOtherTxt->m_pNext) + size_t stLength = 0; + if (m_pcKey) { - add(new stcMDNSServiceTxt(*pOtherTxt)); + stLength += strlen(m_pcKey); // Key + stLength += 1; // '=' + stLength += (m_pcValue ? strlen(m_pcValue) : 0); // Value } + return stLength; } - return *this; -} -/* - MDNSResponder::stcMDNSServiceTxts::clear -*/ -bool MDNSResponder::stcMDNSServiceTxts::clear(void) -{ + /** + MDNSResponder::stcMDNSServiceTxts - while (m_pTxts) - { - stcMDNSServiceTxt* pNext = m_pTxts->m_pNext; - delete m_pTxts; - m_pTxts = pNext; - } - return true; -} + A list of zero or more MDNS TXT items. + Dynamic TXT items can be removed by 'removeTempTxts'. + A TXT item can be looke up by its 'key' member. + Export as ';'-separated byte array is supported. + Export as 'length byte coded' byte array is supported. + Comparison ((all A TXT items in B and equal) AND (all B TXT items in A and equal)) is + supported. -/* - MDNSResponder::stcMDNSServiceTxts::add -*/ -bool MDNSResponder::stcMDNSServiceTxts::add(MDNSResponder::stcMDNSServiceTxt* p_pTxt) -{ + */ - bool bResult = false; + /* + MDNSResponder::stcMDNSServiceTxts::stcMDNSServiceTxts constructor + */ + MDNSResponder::stcMDNSServiceTxts::stcMDNSServiceTxts(void) : m_pTxts(0) { } - if (p_pTxt) + /* + MDNSResponder::stcMDNSServiceTxts::stcMDNSServiceTxts copy-constructor + */ + MDNSResponder::stcMDNSServiceTxts::stcMDNSServiceTxts(const stcMDNSServiceTxts& p_Other) : + m_pTxts(0) { - p_pTxt->m_pNext = m_pTxts; - m_pTxts = p_pTxt; - bResult = true; + operator=(p_Other); } - return bResult; -} - -/* - MDNSResponder::stcMDNSServiceTxts::remove -*/ -bool MDNSResponder::stcMDNSServiceTxts::remove(stcMDNSServiceTxt* p_pTxt) -{ - bool bResult = false; + /* + MDNSResponder::stcMDNSServiceTxts::~stcMDNSServiceTxts destructor + */ + MDNSResponder::stcMDNSServiceTxts::~stcMDNSServiceTxts(void) + { + clear(); + } - if (p_pTxt) + /* + MDNSResponder::stcMDNSServiceTxts::operator= + */ + MDNSResponder::stcMDNSServiceTxts& + MDNSResponder::stcMDNSServiceTxts::operator=(const stcMDNSServiceTxts& p_Other) { - stcMDNSServiceTxt* pPred = m_pTxts; - while ((pPred) && - (pPred->m_pNext != p_pTxt)) - { - pPred = pPred->m_pNext; - } - if (pPred) + if (this != &p_Other) { - pPred->m_pNext = p_pTxt->m_pNext; - delete p_pTxt; - bResult = true; + clear(); + + for (stcMDNSServiceTxt* pOtherTxt = p_Other.m_pTxts; pOtherTxt; + pOtherTxt = pOtherTxt->m_pNext) + { + add(new stcMDNSServiceTxt(*pOtherTxt)); + } } - else if (m_pTxts == p_pTxt) // No predecessor, but first item + return *this; + } + + /* + MDNSResponder::stcMDNSServiceTxts::clear + */ + bool MDNSResponder::stcMDNSServiceTxts::clear(void) + { + while (m_pTxts) { - m_pTxts = p_pTxt->m_pNext; - delete p_pTxt; - bResult = true; + stcMDNSServiceTxt* pNext = m_pTxts->m_pNext; + delete m_pTxts; + m_pTxts = pNext; } + return true; } - return bResult; -} - -/* - MDNSResponder::stcMDNSServiceTxts::removeTempTxts -*/ -bool MDNSResponder::stcMDNSServiceTxts::removeTempTxts(void) -{ - - bool bResult = true; - stcMDNSServiceTxt* pTxt = m_pTxts; - while ((bResult) && - (pTxt)) + /* + MDNSResponder::stcMDNSServiceTxts::add + */ + bool MDNSResponder::stcMDNSServiceTxts::add(MDNSResponder::stcMDNSServiceTxt* p_pTxt) { - stcMDNSServiceTxt* pNext = pTxt->m_pNext; - if (pTxt->m_bTemp) + bool bResult = false; + + if (p_pTxt) { - bResult = remove(pTxt); + p_pTxt->m_pNext = m_pTxts; + m_pTxts = p_pTxt; + bResult = true; } - pTxt = pNext; + return bResult; } - return bResult; -} -/* - MDNSResponder::stcMDNSServiceTxts::find -*/ -MDNSResponder::stcMDNSServiceTxt* MDNSResponder::stcMDNSServiceTxts::find(const char* p_pcKey) -{ + /* + MDNSResponder::stcMDNSServiceTxts::remove + */ + bool MDNSResponder::stcMDNSServiceTxts::remove(stcMDNSServiceTxt* p_pTxt) + { + bool bResult = false; - stcMDNSServiceTxt* pResult = 0; + if (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 + { + m_pTxts = p_pTxt->m_pNext; + delete p_pTxt; + bResult = true; + } + } + return bResult; + } - for (stcMDNSServiceTxt* pTxt = m_pTxts; pTxt; pTxt = pTxt->m_pNext) + /* + MDNSResponder::stcMDNSServiceTxts::removeTempTxts + */ + bool MDNSResponder::stcMDNSServiceTxts::removeTempTxts(void) { - if ((p_pcKey) && - (0 == strcmp(pTxt->m_pcKey, p_pcKey))) + bool bResult = true; + + stcMDNSServiceTxt* pTxt = m_pTxts; + while ((bResult) && (pTxt)) { - pResult = pTxt; - break; + stcMDNSServiceTxt* pNext = pTxt->m_pNext; + if (pTxt->m_bTemp) + { + bResult = remove(pTxt); + } + pTxt = pNext; } + return bResult; } - return pResult; -} -/* - MDNSResponder::stcMDNSServiceTxts::find -*/ -const MDNSResponder::stcMDNSServiceTxt* MDNSResponder::stcMDNSServiceTxts::find(const char* p_pcKey) const -{ + /* + MDNSResponder::stcMDNSServiceTxts::find + */ + MDNSResponder::stcMDNSServiceTxt* MDNSResponder::stcMDNSServiceTxts::find(const char* p_pcKey) + { + stcMDNSServiceTxt* pResult = 0; - const stcMDNSServiceTxt* pResult = 0; + for (stcMDNSServiceTxt* pTxt = m_pTxts; pTxt; pTxt = pTxt->m_pNext) + { + if ((p_pcKey) && (0 == strcmp(pTxt->m_pcKey, p_pcKey))) + { + pResult = pTxt; + break; + } + } + return pResult; + } - for (const stcMDNSServiceTxt* pTxt = m_pTxts; pTxt; pTxt = pTxt->m_pNext) + /* + MDNSResponder::stcMDNSServiceTxts::find + */ + 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; - pResult = pTxt; - break; + for (const stcMDNSServiceTxt* pTxt = m_pTxts; pTxt; pTxt = pTxt->m_pNext) + { + 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) -{ + /* + MDNSResponder::stcMDNSServiceTxts::find + */ + MDNSResponder::stcMDNSServiceTxt* + MDNSResponder::stcMDNSServiceTxts::find(const stcMDNSServiceTxt* p_pTxt) + { + stcMDNSServiceTxt* pResult = 0; - stcMDNSServiceTxt* pResult = 0; + for (stcMDNSServiceTxt* pTxt = m_pTxts; pTxt; pTxt = pTxt->m_pNext) + { + if (p_pTxt == pTxt) + { + pResult = pTxt; + break; + } + } + return pResult; + } - for (stcMDNSServiceTxt* pTxt = m_pTxts; pTxt; pTxt = pTxt->m_pNext) + /* + MDNSResponder::stcMDNSServiceTxts::length + */ + uint16_t MDNSResponder::stcMDNSServiceTxts::length(void) const { - if (p_pTxt == pTxt) + uint16_t u16Length = 0; + + stcMDNSServiceTxt* pTxt = m_pTxts; + while (pTxt) { - pResult = pTxt; - break; + u16Length += 1; // Length byte + u16Length += pTxt->length(); // Text + pTxt = pTxt->m_pNext; } + return u16Length; } - return pResult; -} - -/* - MDNSResponder::stcMDNSServiceTxts::length -*/ -uint16_t MDNSResponder::stcMDNSServiceTxts::length(void) const -{ - uint16_t u16Length = 0; + /* + MDNSResponder::stcMDNSServiceTxts::c_strLength - stcMDNSServiceTxt* pTxt = m_pTxts; - while (pTxt) + (incl. closing '\0'). Length bytes place is used for delimiting ';' and closing '\0' + */ + size_t MDNSResponder::stcMDNSServiceTxts::c_strLength(void) const { - u16Length += 1; // Length byte - u16Length += pTxt->length(); // Text - pTxt = pTxt->m_pNext; + return length(); } - 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(); -} - -/* - MDNSResponder::stcMDNSServiceTxts::c_str -*/ -bool MDNSResponder::stcMDNSServiceTxts::c_str(char* p_pcBuffer) -{ - - bool bResult = false; - if (p_pcBuffer) + /* + MDNSResponder::stcMDNSServiceTxts::c_str + */ + 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) - { - *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))) + size_t stLength; + if ((bResult = (0 != (stLength = (pTxt->m_pcKey ? strlen(pTxt->m_pcKey) : 0))))) { - strncpy(p_pcBuffer, pTxt->m_pcValue, stLength); p_pcBuffer[stLength] = 0; + 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); -} -/* - MDNSResponder::stcMDNSServiceTxts::toBuffer -*/ -bool MDNSResponder::stcMDNSServiceTxts::buffer(char* p_pcBuffer) -{ + /* + MDNSResponder::stcMDNSServiceTxts::bufferLength - bool bResult = false; + (incl. closing '\0'). + */ + size_t MDNSResponder::stcMDNSServiceTxts::bufferLength(void) const + { + return (length() + 1); + } - if (p_pcBuffer) + /* + MDNSResponder::stcMDNSServiceTxts::toBuffer + */ + 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()))) + /* + MDNSResponder::stcMDNSServiceTxts::compare + */ + 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); -} + /* + MDNSResponder::stcMDNSServiceTxts::operator== + */ + 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 -{ + /* + MDNSResponder::stcMDNSServiceTxts::operator!= + */ + bool MDNSResponder::stcMDNSServiceTxts::operator!=(const stcMDNSServiceTxts& p_Other) const + { + return !compare(p_Other); + } - return !compare(p_Other); -} + /** + MDNSResponder::stcMDNS_MsgHeader + A MDNS message header. -/** - 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), + /* + 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_RRDomain - - A MDNS domain object. - The labels of the domain are stored (DNS-like encoded) in 'm_acName': - [length byte]varlength label[length byte]varlength label[0] - 'm_u16NameLength' stores the used length of 'm_acName'. - Dynamic label addition is supported. - Comparison is supported. - Export as byte array 'esp8266.local' is supported. - -*/ - -/* - MDNSResponder::stcMDNS_RRDomain::stcMDNS_RRDomain constructor -*/ -MDNSResponder::stcMDNS_RRDomain::stcMDNS_RRDomain(void) - : m_u16NameLength(0) -{ - - clear(); -} + 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::stcMDNS_RRDomain copy-constructor -*/ -MDNSResponder::stcMDNS_RRDomain::stcMDNS_RRDomain(const stcMDNS_RRDomain& p_Other) - : m_u16NameLength(0) -{ + /** + MDNSResponder::stcMDNS_RRDomain - operator=(p_Other); -} + A MDNS domain object. + The labels of the domain are stored (DNS-like encoded) in 'm_acName': + [length byte]varlength label[length byte]varlength label[0] + 'm_u16NameLength' stores the used length of 'm_acName'. + Dynamic label addition is supported. + Comparison is supported. + Export as byte array 'esp8266.local' is supported. -/* - MDNSResponder::stcMDNS_RRDomain::operator = -*/ -MDNSResponder::stcMDNS_RRDomain& MDNSResponder::stcMDNS_RRDomain::operator=(const stcMDNS_RRDomain& p_Other) -{ + */ - if (&p_Other != this) + /* + MDNSResponder::stcMDNS_RRDomain::stcMDNS_RRDomain constructor + */ + MDNSResponder::stcMDNS_RRDomain::stcMDNS_RRDomain(void) : m_u16NameLength(0) { - memcpy(m_acName, p_Other.m_acName, sizeof(m_acName)); - m_u16NameLength = p_Other.m_u16NameLength; + clear(); } - return *this; -} -/* - MDNSResponder::stcMDNS_RRDomain::clear -*/ -bool MDNSResponder::stcMDNS_RRDomain::clear(void) -{ - - memset(m_acName, 0, sizeof(m_acName)); - m_u16NameLength = 0; - return true; -} + /* + 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::addLabel -*/ -bool MDNSResponder::stcMDNS_RRDomain::addLabel(const char* p_pcLabel, - bool p_bPrependUnderline /*= false*/) -{ + /* + MDNSResponder::stcMDNS_RRDomain::operator = + */ + 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)); + m_u16NameLength = p_Other.m_u16NameLength; + } + return *this; + } - bool bResult = false; + /* + MDNSResponder::stcMDNS_RRDomain::clear + */ + bool MDNSResponder::stcMDNS_RRDomain::clear(void) + { + memset(m_acName, 0, sizeof(m_acName)); + m_u16NameLength = 0; + return true; + } - 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)))) + /* + MDNSResponder::stcMDNS_RRDomain::addLabel + */ + bool MDNSResponder::stcMDNS_RRDomain::addLabel(const char* p_pcLabel, + bool p_bPrependUnderline /*= false*/) { - // Length byte - m_acName[m_u16NameLength] = (unsigned char)stLength; // Might be 0! - ++m_u16NameLength; - // Label - if (stLength) + 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) + /* + MDNSResponder::stcMDNS_RRDomain::compare + */ + 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 + 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 { - 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; + 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); -} - -/* - MDNSResponder::stcMDNS_RRDomain::operator != -*/ -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); -} - -/* - 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) + /* + MDNSResponder::stcMDNS_RRDomain::operator == + */ + bool MDNSResponder::stcMDNS_RRDomain::operator==(const stcMDNS_RRDomain& p_Other) const { - stLength += (*pucLabelLength + 1 /* +1 for '.' or '\0'*/); - pucLabelLength += (*pucLabelLength + 1); + return compare(p_Other); } - return stLength; -} -/* - MDNSResponder::stcMDNS_RRDomain::c_str -*/ -bool MDNSResponder::stcMDNS_RRDomain::c_str(char* p_pcBuffer) -{ + /* + MDNSResponder::stcMDNS_RRDomain::operator != + */ + bool MDNSResponder::stcMDNS_RRDomain::operator!=(const stcMDNS_RRDomain& p_Other) const + { + return !compare(p_Other); + } - bool bResult = false; + /* + 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); + } - if (p_pcBuffer) + /* + MDNSResponder::stcMDNS_RRDomain::c_strLength + */ + size_t MDNSResponder::stcMDNS_RRDomain::c_strLength(void) const { - *p_pcBuffer = 0; + size_t stLength = 0; + unsigned char* pucLabelLength = (unsigned char*)m_acName; while (*pucLabelLength) { - memcpy(p_pcBuffer, (const char*)(pucLabelLength + 1), *pucLabelLength); - p_pcBuffer += *pucLabelLength; + stLength += (*pucLabelLength + 1 /* +1 for '.' or '\0'*/); pucLabelLength += (*pucLabelLength + 1); - *p_pcBuffer++ = (*pucLabelLength ? '.' : '\0'); } - bResult = true; + return stLength; } - 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_RRDomain::c_str + */ + bool MDNSResponder::stcMDNS_RRDomain::c_str(char* p_pcBuffer) + { + bool bResult = false; -} + if (p_pcBuffer) + { + *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; + } + return bResult; + } -/* - MDNSResponder::stcMDNS_RRAttributes::stcMDNS_RRAttributes copy-constructor -*/ -MDNSResponder::stcMDNS_RRAttributes::stcMDNS_RRAttributes(const MDNSResponder::stcMDNS_RRAttributes& p_Other) -{ + /** + MDNSResponder::stcMDNS_RRAttributes - operator=(p_Other); -} + A MDNS attributes object. -/* - MDNSResponder::stcMDNS_RRAttributes::operator = -*/ -MDNSResponder::stcMDNS_RRAttributes& MDNSResponder::stcMDNS_RRAttributes::operator=(const MDNSResponder::stcMDNS_RRAttributes& p_Other) -{ + */ - if (&p_Other != this) + /* + 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) { - m_u16Type = p_Other.m_u16Type; - m_u16Class = p_Other.m_u16Class; } - 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 copy-constructor -*/ -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_RRAttributes::stcMDNS_RRAttributes copy-constructor + */ + MDNSResponder::stcMDNS_RRAttributes::stcMDNS_RRAttributes( + const MDNSResponder::stcMDNS_RRAttributes& p_Other) { - m_Domain = p_Other.m_Domain; - m_Attributes = p_Other.m_Attributes; + operator=(p_Other); } - return *this; -} - -/* - MDNSResponder::stcMDNS_RRHeader::clear -*/ -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_RRAnswer - - A MDNS answer record object (header + answer content). - This is a 'virtual' base class for all other MDNS answer classes. - -*/ - -/* - 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 destructor -*/ -MDNSResponder::stcMDNS_RRAnswer::~stcMDNS_RRAnswer(void) -{ - -} - -/* - MDNSResponder::stcMDNS_RRAnswer::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; -} - - -/** - MDNSResponder::stcMDNS_RRAnswerA - - A MDNS A answer object. - Extends the base class by an IP4 address member. - -*/ - -#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 destructor -*/ -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; -} -#endif - - -/** - MDNSResponder::stcMDNS_RRAnswerPTR - - A MDNS PTR answer object. - Extends the base class by a MDNS domain member. - -*/ - -/* - 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 destructor -*/ -MDNSResponder::stcMDNS_RRAnswerPTR::~stcMDNS_RRAnswerPTR(void) -{ - - clear(); -} - -/* - MDNSResponder::stcMDNS_RRAnswerPTR::clear -*/ -bool MDNSResponder::stcMDNS_RRAnswerPTR::clear(void) -{ - - m_PTRDomain.clear(); - return true; -} - - -/** - MDNSResponder::stcMDNS_RRAnswerTXT - - A MDNS TXT answer object. - Extends the base class by a MDNS TXT items list member. - -*/ - -/* - 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 destructor -*/ -MDNSResponder::stcMDNS_RRAnswerTXT::~stcMDNS_RRAnswerTXT(void) -{ - - clear(); -} - -/* - MDNSResponder::stcMDNS_RRAnswerTXT::clear -*/ -bool MDNSResponder::stcMDNS_RRAnswerTXT::clear(void) -{ - - m_Txts.clear(); - return true; -} - - -/** - MDNSResponder::stcMDNS_RRAnswerAAAA - - A MDNS AAAA answer object. - (Should) extend the base class by an IP6 address member. - -*/ - -#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 destructor -*/ -MDNSResponder::stcMDNS_RRAnswerAAAA::~stcMDNS_RRAnswerAAAA(void) -{ - - clear(); -} -/* - MDNSResponder::stcMDNS_RRAnswerAAAA::clear -*/ -bool MDNSResponder::stcMDNS_RRAnswerAAAA::clear(void) -{ - - return true; -} -#endif - - -/** - MDNSResponder::stcMDNS_RRAnswerSRV - - A MDNS SRV answer object. - Extends the base class by a port member. - -*/ - -/* - 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 destructor -*/ -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; -} + /* + MDNSResponder::stcMDNS_RRAttributes::operator = + */ + MDNSResponder::stcMDNS_RRAttributes& MDNSResponder::stcMDNS_RRAttributes::operator=( + const MDNSResponder::stcMDNS_RRAttributes& p_Other) + { + if (&p_Other != this) + { + m_u16Type = p_Other.m_u16Type; + m_u16Class = p_Other.m_u16Class; + } + return *this; + } + /** + MDNSResponder::stcMDNS_RRHeader -/** - MDNSResponder::stcMDNS_RRAnswerGeneric + A MDNS record header (domain and attributes) object. - An unknown (generic) MDNS answer object. - Extends the base class by a RDATA buffer member. + */ -*/ + /* + MDNSResponder::stcMDNS_RRHeader::stcMDNS_RRHeader constructor + */ + MDNSResponder::stcMDNS_RRHeader::stcMDNS_RRHeader(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 destructor -*/ -MDNSResponder::stcMDNS_RRAnswerGeneric::~stcMDNS_RRAnswerGeneric(void) -{ - - clear(); -} + /* + MDNSResponder::stcMDNS_RRHeader::stcMDNS_RRHeader copy-constructor + */ + MDNSResponder::stcMDNS_RRHeader::stcMDNS_RRHeader(const stcMDNS_RRHeader& p_Other) + { + operator=(p_Other); + } -/* - MDNSResponder::stcMDNS_RRAnswerGeneric::clear -*/ -bool MDNSResponder::stcMDNS_RRAnswerGeneric::clear(void) -{ + /* + MDNSResponder::stcMDNS_RRHeader::operator = + */ + MDNSResponder::stcMDNS_RRHeader& + MDNSResponder::stcMDNS_RRHeader::operator=(const MDNSResponder::stcMDNS_RRHeader& p_Other) + { + if (&p_Other != this) + { + m_Domain = p_Other.m_Domain; + m_Attributes = p_Other.m_Attributes; + } + return *this; + } - if (m_pu8RDData) + /* + MDNSResponder::stcMDNS_RRHeader::clear + */ + bool MDNSResponder::stcMDNS_RRHeader::clear(void) { - delete[] m_pu8RDData; - m_pu8RDData = 0; + m_Domain.clear(); + return true; } - m_u16RDLength = 0; - return true; -} + /** + MDNSResponder::stcMDNS_RRQuestion + A MDNS question record object (header + question flags) -/** - MDNSResponder::stcProbeInformation + */ - Probing status information for a host or service domain + /* + MDNSResponder::stcMDNS_RRQuestion::stcMDNS_RRQuestion constructor + */ + MDNSResponder::stcMDNS_RRQuestion::stcMDNS_RRQuestion(void) : m_pNext(0), m_bUnicast(false) { } -*/ + /** + MDNSResponder::stcMDNS_RRAnswer -/* - 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) -{ -} + A MDNS answer record object (header + answer content). + This is a 'virtual' base class for all other MDNS answer classes. -/* - 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) + /* + 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) { - m_fnHostProbeResultCallback = 0; - m_fnServiceProbeResultCallback = 0; + // Extract 'cache flush'-bit + m_bCacheFlush = (m_Header.m_Attributes.m_u16Class & 0x8000); + m_Header.m_Attributes.m_u16Class &= (~0x8000); } - return true; -} - -/** - MDNSResponder::stcMDNSService - - A MDNS service object (to be announced by the MDNS responder) - The service instance may be '\0'; in this case the hostname is used - and the flag m_bAutoName is set. If the hostname changes, all 'auto- - named' services are renamed also. - m_u8Replymask is used while preparing a response to a MDNS query. It is - 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) -{ + /* + MDNSResponder::stcMDNS_RRAnswer::~stcMDNS_RRAnswer destructor + */ + MDNSResponder::stcMDNS_RRAnswer::~stcMDNS_RRAnswer(void) { } - setName(p_pcName); - setService(p_pcService); - setProtocol(p_pcProtocol); -} + /* + MDNSResponder::stcMDNS_RRAnswer::answerType + */ + MDNSResponder::enuAnswerType MDNSResponder::stcMDNS_RRAnswer::answerType(void) const + { + return m_AnswerType; + } -/* - MDNSResponder::stcMDNSService::~stcMDNSService destructor -*/ -MDNSResponder::stcMDNSService::~stcMDNSService(void) -{ + /* + MDNSResponder::stcMDNS_RRAnswer::clear + */ + bool MDNSResponder::stcMDNS_RRAnswer::clear(void) + { + m_pNext = 0; + m_Header.clear(); + return true; + } - releaseName(); - releaseService(); - releaseProtocol(); -} + /** + MDNSResponder::stcMDNS_RRAnswerA -/* - MDNSResponder::stcMDNSService::setName -*/ -bool MDNSResponder::stcMDNSService::setName(const char* p_pcName) -{ + A MDNS A answer object. + Extends the base class by an IP4 address member. - bool bResult = false; + */ - releaseName(); - size_t stLength = (p_pcName ? strlen(p_pcName) : 0); - if (stLength) +#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) { - if ((bResult = (0 != (m_pcName = new char[stLength + 1])))) - { - strncpy(m_pcName, p_pcName, stLength); - m_pcName[stLength] = 0; - } } - else + + /* + MDNSResponder::stcMDNS_RRAnswerA::stcMDNS_RRAnswerA destructor + */ + MDNSResponder::stcMDNS_RRAnswerA::~stcMDNS_RRAnswerA(void) { - bResult = true; + clear(); } - return bResult; -} - -/* - MDNSResponder::stcMDNSService::releaseName -*/ -bool MDNSResponder::stcMDNSService::releaseName(void) -{ - if (m_pcName) + /* + MDNSResponder::stcMDNS_RRAnswerA::clear + */ + bool MDNSResponder::stcMDNS_RRAnswerA::clear(void) { - delete[] m_pcName; - m_pcName = 0; + m_IPAddress = IPAddress(0, 0, 0, 0); + return true; } - return true; -} +#endif + + /** + MDNSResponder::stcMDNS_RRAnswerPTR -/* - MDNSResponder::stcMDNSService::setService -*/ -bool MDNSResponder::stcMDNSService::setService(const char* p_pcService) -{ + A MDNS PTR answer object. + Extends the base class by a MDNS domain member. - bool bResult = false; + */ - releaseService(); - size_t stLength = (p_pcService ? strlen(p_pcService) : 0); - if (stLength) + /* + 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) { - if ((bResult = (0 != (m_pcService = new char[stLength + 1])))) - { - strncpy(m_pcService, p_pcService, stLength); - m_pcService[stLength] = 0; - } } - else + + /* + MDNSResponder::stcMDNS_RRAnswerPTR::~stcMDNS_RRAnswerPTR destructor + */ + MDNSResponder::stcMDNS_RRAnswerPTR::~stcMDNS_RRAnswerPTR(void) { - bResult = true; + clear(); } - return bResult; -} - -/* - MDNSResponder::stcMDNSService::releaseService -*/ -bool MDNSResponder::stcMDNSService::releaseService(void) -{ - if (m_pcService) + /* + MDNSResponder::stcMDNS_RRAnswerPTR::clear + */ + bool MDNSResponder::stcMDNS_RRAnswerPTR::clear(void) { - delete[] m_pcService; - m_pcService = 0; + m_PTRDomain.clear(); + return true; } - return true; -} -/* - MDNSResponder::stcMDNSService::setProtocol -*/ -bool MDNSResponder::stcMDNSService::setProtocol(const char* p_pcProtocol) -{ + /** + MDNSResponder::stcMDNS_RRAnswerTXT - bool bResult = false; + A MDNS TXT answer object. + Extends the base class by a MDNS TXT items list member. - releaseProtocol(); - size_t stLength = (p_pcProtocol ? strlen(p_pcProtocol) : 0); - if (stLength) + */ + + /* + 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) { - if ((bResult = (0 != (m_pcProtocol = new char[stLength + 1])))) - { - strncpy(m_pcProtocol, p_pcProtocol, stLength); - m_pcProtocol[stLength] = 0; - } } - else + + /* + MDNSResponder::stcMDNS_RRAnswerTXT::~stcMDNS_RRAnswerTXT destructor + */ + MDNSResponder::stcMDNS_RRAnswerTXT::~stcMDNS_RRAnswerTXT(void) { - bResult = true; + clear(); } - return bResult; -} - -/* - MDNSResponder::stcMDNSService::releaseProtocol -*/ -bool MDNSResponder::stcMDNSService::releaseProtocol(void) -{ - if (m_pcProtocol) + /* + MDNSResponder::stcMDNS_RRAnswerTXT::clear + */ + bool MDNSResponder::stcMDNS_RRAnswerTXT::clear(void) { - delete[] m_pcProtocol; - m_pcProtocol = 0; + m_Txts.clear(); + return true; } - return true; -} - -/** - MDNSResponder::stcMDNSServiceQuery + /** + MDNSResponder::stcMDNS_RRAnswerAAAA - A MDNS service query object. - Service queries may be static or dynamic. - As the static service query is processed in the blocking function 'queryService', - only one static service service may exist. The processing of the answers is done - on the WiFi-stack side of the ESP stack structure (via 'UDPContext.onRx(_update)'). + A MDNS AAAA answer object. + (Should) extend the base class by an IP6 address member. -*/ + */ -/** - MDNSResponder::stcMDNSServiceQuery::stcAnswer - - One answer for a service query. - Every answer must contain - - a service instance entry (pivot), - and may contain - - a host domain, - - a port - - an IP4 address - (- an IP6 address) - - a MDNS TXTs - The existence of a component is flagged in 'm_u32ContentFlags'. - For every answer component a TTL value is maintained. - Answer objects can be connected to a linked list. - - For the host domain, service domain and TXTs components, a char array - representation can be retrieved (which is created on demand). +#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 destructor + */ + MDNSResponder::stcMDNS_RRAnswerAAAA::~stcMDNS_RRAnswerAAAA(void) + { + clear(); + } -/** - MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL + /* + MDNSResponder::stcMDNS_RRAnswerAAAA::clear + */ + bool MDNSResponder::stcMDNS_RRAnswerAAAA::clear(void) + { + return true; + } +#endif - The TTL (Time-To-Live) for an specific answer content. - The 80% and outdated states are calculated based on the current time (millis) - and the 'set' time (also millis). - If the answer is scheduled for an update, the corresponding flag should be set. + /** + MDNSResponder::stcMDNS_RRAnswerSRV - / + A MDNS SRV answer object. + Extends the base class by a port member. - / * - MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::stcTTL constructor - / - MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::stcTTL(uint32_t p_u32TTL / *= 0* /) - : m_bUpdateScheduled(false) { + */ - set(p_u32TTL * 1000); + /* + 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::stcMDNSServiceQuery::stcAnswer::stcTTL::set - / - bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::set(uint32_t p_u32TTL) { - - m_TTLTimeFlag.restart(p_u32TTL * 1000); - m_bUpdateScheduled = false; - - return true; + /* + MDNSResponder::stcMDNS_RRAnswerSRV::~stcMDNS_RRAnswerSRV destructor + */ + MDNSResponder::stcMDNS_RRAnswerSRV::~stcMDNS_RRAnswerSRV(void) + { + clear(); } - / * - MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::has80Percent - / - bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::has80Percent(void) const { - - return ((m_TTLTimeFlag.getTimeout()) && - (!m_bUpdateScheduled) && - (m_TTLTimeFlag.hypotheticalTimeout((m_TTLTimeFlag.getTimeout() * 800) / 1000))); + /* + MDNSResponder::stcMDNS_RRAnswerSRV::clear + */ + bool MDNSResponder::stcMDNS_RRAnswerSRV::clear(void) + { + m_u16Priority = 0; + m_u16Weight = 0; + m_u16Port = 0; + m_SRVDomain.clear(); + return true; } - / * - MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::isOutdated - / - bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::isOutdated(void) const { + /** + MDNSResponder::stcMDNS_RRAnswerGeneric - return ((m_TTLTimeFlag.getTimeout()) && - (m_TTLTimeFlag.flagged())); - }*/ + An unknown (generic) MDNS answer object. + Extends the base class by a RDATA buffer member. + */ -/** - MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL + /* + 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) + { + } - The TTL (Time-To-Live) for an specific answer content. - The 80% and outdated states are calculated based on the current time (millis) - and the 'set' time (also millis). - If the answer is scheduled for an update, the corresponding flag should be set. + /* + MDNSResponder::stcMDNS_RRAnswerGeneric::~stcMDNS_RRAnswerGeneric destructor + */ + MDNSResponder::stcMDNS_RRAnswerGeneric::~stcMDNS_RRAnswerGeneric(void) + { + clear(); + } -*/ + /* + MDNSResponder::stcMDNS_RRAnswerGeneric::clear + */ + bool MDNSResponder::stcMDNS_RRAnswerGeneric::clear(void) + { + if (m_pu8RDData) + { + delete[] m_pu8RDData; + m_pu8RDData = 0; + } + m_u16RDLength = 0; -/* - 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) -{ + return true; + } -} + /** + MDNSResponder::stcProbeInformation -/* - MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::set -*/ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::set(uint32_t p_u32TTL) -{ + Probing status information for a host or service domain + + */ - m_u32TTL = p_u32TTL; - if (m_u32TTL) + /* + 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_timeoutLevel = TIMEOUTLEVEL_BASE; // Set to 80% - m_TTLTimeout.reset(timeout()); } - else + + /* + MDNSResponder::stcProbeInformation::clear + */ + bool MDNSResponder::stcProbeInformation::clear(bool p_bClearUserdata /*= false*/) { - m_timeoutLevel = TIMEOUTLEVEL_UNSET; // undef - m_TTLTimeout.resetToNeverExpires(); + 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::stcMDNSServiceQuery::stcAnswer::stcTTL::flagged -*/ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::flagged(void) -{ + /** + MDNSResponder::stcMDNSService - return ((m_u32TTL) && - (TIMEOUTLEVEL_UNSET != m_timeoutLevel) && - (m_TTLTimeout.expired())); -} + A MDNS service object (to be announced by the MDNS responder) + The service instance may be '\0'; in this case the hostname is used + and the flag m_bAutoName is set. If the hostname changes, all 'auto- + named' services are renamed also. + m_u8Replymask is used while preparing a response to a MDNS query. It is + reset in '_sendMDNSMessage' afterwards. + */ -/* - MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::restart -*/ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::restart(void) -{ + /* + 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); + } - bool bResult = true; + /* + MDNSResponder::stcMDNSService::~stcMDNSService destructor + */ + MDNSResponder::stcMDNSService::~stcMDNSService(void) + { + releaseName(); + releaseService(); + releaseProtocol(); + } - if ((TIMEOUTLEVEL_BASE <= m_timeoutLevel) && // >= 80% AND - (TIMEOUTLEVEL_FINAL > m_timeoutLevel)) // < 100% + /* + MDNSResponder::stcMDNSService::setName + */ + bool MDNSResponder::stcMDNSService::setName(const char* p_pcName) { + bool bResult = false; - m_timeoutLevel += TIMEOUTLEVEL_INTERVAL; // increment by 5% - m_TTLTimeout.reset(timeout()); + 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 + { + bResult = true; + } + return bResult; } - else + + /* + MDNSResponder::stcMDNSService::releaseName + */ + bool MDNSResponder::stcMDNSService::releaseName(void) { - bResult = false; - m_TTLTimeout.resetToNeverExpires(); - m_timeoutLevel = TIMEOUTLEVEL_UNSET; + if (m_pcName) + { + delete[] m_pcName; + m_pcName = 0; + } + return true; } - return bResult; -} -/* - MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::prepareDeletion -*/ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::prepareDeletion(void) -{ + /* + MDNSResponder::stcMDNSService::setService + */ + bool MDNSResponder::stcMDNSService::setService(const char* p_pcService) + { + bool bResult = false; - m_timeoutLevel = TIMEOUTLEVEL_FINAL; - m_TTLTimeout.reset(1 * 1000); // See RFC 6762, 10.1 + releaseService(); + size_t stLength = (p_pcService ? strlen(p_pcService) : 0); + if (stLength) + { + if ((bResult = (0 != (m_pcService = new char[stLength + 1])))) + { + strncpy(m_pcService, p_pcService, stLength); + m_pcService[stLength] = 0; + } + } + else + { + bResult = true; + } + return bResult; + } - return true; -} + /* + MDNSResponder::stcMDNSService::releaseService + */ + bool MDNSResponder::stcMDNSService::releaseService(void) + { + if (m_pcService) + { + delete[] m_pcService; + m_pcService = 0; + } + return true; + } -/* - MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::finalTimeoutLevel -*/ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::finalTimeoutLevel(void) const -{ + /* + MDNSResponder::stcMDNSService::setProtocol + */ + bool MDNSResponder::stcMDNSService::setProtocol(const char* p_pcProtocol) + { + bool bResult = false; - return (TIMEOUTLEVEL_FINAL == m_timeoutLevel); -} + releaseProtocol(); + size_t stLength = (p_pcProtocol ? strlen(p_pcProtocol) : 0); + if (stLength) + { + if ((bResult = (0 != (m_pcProtocol = new char[stLength + 1])))) + { + strncpy(m_pcProtocol, p_pcProtocol, stLength); + m_pcProtocol[stLength] = 0; + } + } + else + { + bResult = true; + } + return bResult; + } -/* - 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::stcMDNSService::releaseProtocol + */ + bool MDNSResponder::stcMDNSService::releaseProtocol(void) { - return (m_u32TTL * 800L); // to milliseconds + if (m_pcProtocol) + { + delete[] m_pcProtocol; + m_pcProtocol = 0; + } + return true; } - 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; -} + /** + MDNSResponder::stcMDNSServiceQuery + A MDNS service query object. + Service queries may be static or dynamic. + As the static service query is processed in the blocking function 'queryService', + only one static service service may exist. The processing of the answers is done + on the WiFi-stack side of the ESP stack structure (via 'UDPContext.onRx(_update)'). -#ifdef MDNS_IP4_SUPPORT -/** - MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address + */ -*/ + /** + MDNSResponder::stcMDNSServiceQuery::stcAnswer -/* - 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) -{ + One answer for a service query. + Every answer must contain + - a service instance entry (pivot), + and may contain + - a host domain, + - a port + - an IP4 address + (- an IP6 address) + - a MDNS TXTs + The existence of a component is flagged in 'm_u32ContentFlags'. + For every answer component a TTL value is maintained. + Answer objects can be connected to a linked list. - m_TTL.set(p_u32TTL); -} -#endif + For the host domain, service domain and TXTs components, a char array + representation can be retrieved (which is created on demand). + */ -/** - MDNSResponder::stcMDNSServiceQuery::stcAnswer -*/ + /** + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL -/* - 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), -#ifdef MDNS_IP4_SUPPORT - m_pIP4Addresses(0), -#endif -#ifdef MDNS_IP6_SUPPORT - m_pIP6Addresses(0), -#endif - m_u32ContentFlags(0) -{ -} + The TTL (Time-To-Live) for an specific answer content. + The 80% and outdated states are calculated based on the current time (millis) + and the 'set' time (also millis). + If the answer is scheduled for an update, the corresponding flag should be set. -/* - MDNSResponder::stcMDNSServiceQuery::stcAnswer::~stcAnswer destructor -*/ -MDNSResponder::stcMDNSServiceQuery::stcAnswer::~stcAnswer(void) -{ + / - clear(); -} + / * + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::stcTTL constructor + / + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::stcTTL(uint32_t p_u32TTL / *= 0* /) + : m_bUpdateScheduled(false) { -/* - MDNSResponder::stcMDNSServiceQuery::stcAnswer::clear -*/ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::clear(void) -{ + set(p_u32TTL * 1000); + } - return ((releaseTxts()) && -#ifdef MDNS_IP4_SUPPORT - (releaseIP4Addresses()) && -#endif -#ifdef MDNS_IP6_SUPPORT - (releaseIP6Addresses()) -#endif - (releaseHostDomain()) && - (releaseServiceDomain())); -} + / * + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::set + / + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::set(uint32_t p_u32TTL) { -/* - MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocServiceDomain + m_TTLTimeFlag.restart(p_u32TTL * 1000); + m_bUpdateScheduled = false; - Alloc memory for the char array representation of the service domain. + return true; + } -*/ -char* MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocServiceDomain(size_t p_stLength) -{ + / * + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::has80Percent + / + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::has80Percent(void) const { - releaseServiceDomain(); - if (p_stLength) - { - m_pcServiceDomain = new char[p_stLength]; - } - return m_pcServiceDomain; -} + return ((m_TTLTimeFlag.getTimeout()) && + (!m_bUpdateScheduled) && + (m_TTLTimeFlag.hypotheticalTimeout((m_TTLTimeFlag.getTimeout() * 800) / 1000))); + } -/* - MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseServiceDomain -*/ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseServiceDomain(void) -{ + / * + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::isOutdated + / + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::isOutdated(void) const { - if (m_pcServiceDomain) - { - delete[] m_pcServiceDomain; - m_pcServiceDomain = 0; - } - return true; -} + return ((m_TTLTimeFlag.getTimeout()) && + (m_TTLTimeFlag.flagged())); + }*/ -/* - MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocHostDomain + /** + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL - Alloc memory for the char array representation of the host domain. + The TTL (Time-To-Live) for an specific answer content. + The 80% and outdated states are calculated based on the current time (millis) + and the 'set' time (also millis). + If the answer is scheduled for an update, the corresponding flag should be set. -*/ -char* MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocHostDomain(size_t p_stLength) -{ + */ - releaseHostDomain(); - if (p_stLength) + /* + 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_pcHostDomain = new char[p_stLength]; } - return m_pcHostDomain; -} - -/* - MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseHostDomain -*/ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseHostDomain(void) -{ - if (m_pcHostDomain) + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::set + */ + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::set(uint32_t p_u32TTL) { - delete[] m_pcHostDomain; - m_pcHostDomain = 0; + 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::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) + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::flagged + */ + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::flagged(void) { - m_pcTxts = new char[p_stLength]; + return ((m_u32TTL) && (TIMEOUTLEVEL_UNSET != m_timeoutLevel) && (m_TTLTimeout.expired())); } - return m_pcTxts; -} - -/* - MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseTxts -*/ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseTxts(void) -{ - if (m_pcTxts) + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::restart + */ + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::restart(void) { - delete[] m_pcTxts; - m_pcTxts = 0; - } - return true; -} + bool bResult = true; -#ifdef MDNS_IP4_SUPPORT -/* - MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseIP4Addresses -*/ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseIP4Addresses(void) -{ - - while (m_pIP4Addresses) - { - stcIP4Address* pNext = m_pIP4Addresses->m_pNext; - delete m_pIP4Addresses; - m_pIP4Addresses = pNext; + 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 true; -} -/* - MDNSResponder::stcMDNSServiceQuery::stcAnswer::addIP4Address -*/ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::addIP4Address(MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* p_pIP4Address) -{ + /* + 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 bResult = false; + return true; + } - if (p_pIP4Address) + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::finalTimeoutLevel + */ + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::finalTimeoutLevel(void) const { - p_pIP4Address->m_pNext = m_pIP4Addresses; - m_pIP4Addresses = p_pIP4Address; - bResult = true; + return (TIMEOUTLEVEL_FINAL == m_timeoutLevel); } - return bResult; -} - -/* - MDNSResponder::stcMDNSServiceQuery::stcAnswer::removeIP4Address -*/ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::removeIP4Address(MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* p_pIP4Address) -{ - - bool bResult = false; - if (p_pIP4Address) + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::timeout + */ + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::timeoutBase::timeType + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::timeout(void) const { - stcIP4Address* pPred = m_pIP4Addresses; - while ((pPred) && - (pPred->m_pNext != p_pIP4Address)) + if (TIMEOUTLEVEL_BASE == m_timeoutLevel) // 80% { - pPred = pPred->m_pNext; + return (m_u32TTL * 800L); // to milliseconds } - if (pPred) + else if ((TIMEOUTLEVEL_BASE < m_timeoutLevel) && // >80% AND + (TIMEOUTLEVEL_FINAL >= m_timeoutLevel)) // <= 100% { - 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 (m_u32TTL * 50L); + } // else: invalid + return MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::timeoutBase::neverExpires; } - 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)); -} +#ifdef MDNS_IP4_SUPPORT + /** + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address -/* - 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::stcIP4Address constructor + */ + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address::stcIP4Address( + IPAddress p_IPAddress, uint32_t p_u32TTL /*= 0*/) : + m_pNext(0), + m_IPAddress(p_IPAddress) { - if (pIP4Address->m_IPAddress == p_IPAddress) - { - break; - } - pIP4Address = pIP4Address->m_pNext; + m_TTL.set(p_u32TTL); } - return pIP4Address; -} - -/* - MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP4AddressCount -*/ -uint32_t MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP4AddressCount(void) const -{ +#endif - uint32_t u32Count = 0; + /** + MDNSResponder::stcMDNSServiceQuery::stcAnswer + */ - stcIP4Address* pIP4Address = m_pIP4Addresses; - while (pIP4Address) + /* + 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), +#ifdef MDNS_IP4_SUPPORT + m_pIP4Addresses(0), +#endif +#ifdef MDNS_IP6_SUPPORT + m_pIP6Addresses(0), +#endif + m_u32ContentFlags(0) { - ++u32Count; - pIP4Address = pIP4Address->m_pNext; } - return u32Count; -} -/* - MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP4AddressAtIndex -*/ -MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP4AddressAtIndex(uint32_t p_u32Index) -{ + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::~stcAnswer destructor + */ + MDNSResponder::stcMDNSServiceQuery::stcAnswer::~stcAnswer(void) + { + clear(); + } - return (stcIP4Address*)(((const stcAnswer*)this)->IP4AddressAtIndex(p_u32Index)); -} + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::clear + */ + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::clear(void) + { + return ((releaseTxts()) && +#ifdef MDNS_IP4_SUPPORT + (releaseIP4Addresses()) && +#endif +#ifdef MDNS_IP6_SUPPORT + (releaseIP6Addresses()) +#endif + (releaseHostDomain()) + && (releaseServiceDomain())); + } -/* - MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP4AddressAtIndex (const) -*/ -const MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP4AddressAtIndex(uint32_t p_u32Index) const -{ + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocServiceDomain - const stcIP4Address* pIP4Address = 0; + Alloc memory for the char array representation of the service domain. - if (((uint32_t)(-1) != p_u32Index) && - (m_pIP4Addresses)) + */ + char* MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocServiceDomain(size_t p_stLength) { - - uint32_t u32Index; - for (pIP4Address = m_pIP4Addresses, u32Index = 0; ((pIP4Address) && (u32Index < p_u32Index)); pIP4Address = pIP4Address->m_pNext, ++u32Index); + releaseServiceDomain(); + if (p_stLength) + { + m_pcServiceDomain = new char[p_stLength]; + } + return m_pcServiceDomain; } - return pIP4Address; -} -#endif - -#ifdef MDNS_IP6_SUPPORT -/* - MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseIP6Addresses -*/ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseIP6Addresses(void) -{ - while (m_pIP6Addresses) + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseServiceDomain + */ + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseServiceDomain(void) { - stcIP6Address* pNext = m_pIP6Addresses->m_pNext; - delete m_pIP6Addresses; - m_pIP6Addresses = pNext; + if (m_pcServiceDomain) + { + delete[] m_pcServiceDomain; + m_pcServiceDomain = 0; + } + return true; } - return true; -} -/* - MDNSResponder::stcMDNSServiceQuery::stcAnswer::addIP6Address -*/ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::addIP6Address(MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* p_pIP6Address) -{ + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocHostDomain - bool bResult = false; + Alloc memory for the char array representation of the host domain. - if (p_pIP6Address) + */ + char* MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocHostDomain(size_t p_stLength) { - p_pIP6Address->m_pNext = m_pIP6Addresses; - m_pIP6Addresses = p_pIP6Address; - bResult = true; + releaseHostDomain(); + if (p_stLength) + { + m_pcHostDomain = new char[p_stLength]; + } + return m_pcHostDomain; } - return bResult; -} -/* - MDNSResponder::stcMDNSServiceQuery::stcAnswer::removeIP6Address -*/ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::removeIP6Address(MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* p_pIP6Address) -{ + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseHostDomain + */ + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseHostDomain(void) + { + if (m_pcHostDomain) + { + delete[] m_pcHostDomain; + m_pcHostDomain = 0; + } + return true; + } - bool bResult = false; + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocTxts - if (p_pIP6Address) + Alloc memory for the char array representation of the TXT items. + + */ + char* MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocTxts(size_t p_stLength) { - stcIP6Address* pPred = m_pIP6Addresses; - while ((pPred) && - (pPred->m_pNext != p_pIP6Address)) + releaseTxts(); + if (p_stLength) { - pPred = pPred->m_pNext; + m_pcTxts = new char[p_stLength]; } - if (pPred) + return m_pcTxts; + } + + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseTxts + */ + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseTxts(void) + { + if (m_pcTxts) { - pPred->m_pNext = p_pIP6Address->m_pNext; - delete p_pIP6Address; - bResult = true; + delete[] m_pcTxts; + m_pcTxts = 0; } - else if (m_pIP6Addresses == p_pIP6Address) // No predecessor, but first item + return true; + } + +#ifdef MDNS_IP4_SUPPORT + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseIP4Addresses + */ + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseIP4Addresses(void) + { + while (m_pIP4Addresses) { - m_pIP6Addresses = p_pIP6Address->m_pNext; - delete p_pIP6Address; - bResult = true; + stcIP4Address* pNext = m_pIP4Addresses->m_pNext; + delete m_pIP4Addresses; + m_pIP4Addresses = pNext; } + return true; } - 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::findIP6Address (const) -*/ -const MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::findIP6Address(const IPAddress& p_IPAddress) const -{ - const stcIP6Address* pIP6Address = m_pIP6Addresses; - while (pIP6Address) + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::addIP4Address + */ + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::addIP4Address( + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* p_pIP4Address) { - if (p_IP6Address->m_IPAddress == p_IPAddress) + bool bResult = false; + + if (p_pIP4Address) { - break; + p_pIP4Address->m_pNext = m_pIP4Addresses; + m_pIP4Addresses = p_pIP4Address; + bResult = true; } - pIP6Address = pIP6Address->m_pNext; + return bResult; } - return pIP6Address; -} -/* - MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP6AddressCount -*/ -uint32_t MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP6AddressCount(void) const -{ + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::removeIP4Address + */ + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::removeIP4Address( + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* p_pIP4Address) + { + bool bResult = false; - uint32_t u32Count = 0; + if (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 + { + m_pIP4Addresses = p_pIP4Address->m_pNext; + delete p_pIP4Address; + bResult = true; + } + } + return bResult; + } - stcIP6Address* pIP6Address = m_pIP6Addresses; - while (pIP6Address) + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::findIP4Address (const) + */ + const MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::findIP4Address( + const IPAddress& p_IPAddress) const { - ++u32Count; - pIP6Address = pIP6Address->m_pNext; + return (stcIP4Address*)(((const stcAnswer*)this)->findIP4Address(p_IPAddress)); } - return u32Count; -} -/* - MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP6AddressAtIndex (const) -*/ -const MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP6AddressAtIndex(uint32_t p_u32Index) const -{ + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::findIP4Address + */ + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::findIP4Address(const IPAddress& p_IPAddress) + { + stcIP4Address* pIP4Address = m_pIP4Addresses; + while (pIP4Address) + { + if (pIP4Address->m_IPAddress == p_IPAddress) + { + break; + } + pIP4Address = pIP4Address->m_pNext; + } + return pIP4Address; + } - return (stcIP6Address*)(((const stcAnswer*)this)->IP6AddressAtIndex(p_u32Index)); -} + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP4AddressCount + */ + uint32_t MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP4AddressCount(void) const + { + uint32_t u32Count = 0; -/* - MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP6AddressAtIndex -*/ -MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP6AddressAtIndex(uint32_t p_u32Index) -{ + stcIP4Address* pIP4Address = m_pIP4Addresses; + while (pIP4Address) + { + ++u32Count; + pIP4Address = pIP4Address->m_pNext; + } + return u32Count; + } - stcIP6Address* pIP6Address = 0; + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP4AddressAtIndex + */ + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP4AddressAtIndex(uint32_t p_u32Index) + { + return (stcIP4Address*)(((const stcAnswer*)this)->IP4AddressAtIndex(p_u32Index)); + } - if (((uint32_t)(-1) != p_u32Index) && - (m_pIP6Addresses)) + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP4AddressAtIndex (const) + */ + const MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP4AddressAtIndex(uint32_t p_u32Index) const { + const stcIP4Address* pIP4Address = 0; - uint32_t u32Index; - for (pIP6Address = m_pIP6Addresses, u32Index = 0; ((pIP6Address) && (u32Index < p_u32Index)); pIP6Address = pIP6Address->m_pNext, ++u32Index); + 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 pIP6Address; -} #endif +#ifdef MDNS_IP6_SUPPORT + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseIP6Addresses + */ + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseIP6Addresses(void) + { + while (m_pIP6Addresses) + { + stcIP6Address* pNext = m_pIP6Addresses->m_pNext; + delete m_pIP6Addresses; + m_pIP6Addresses = pNext; + } + return true; + } -/** - MDNSResponder::stcMDNSServiceQuery - - A service query object. - A static query is flagged via 'm_bLegacyQuery'; while the function 'queryService' - is waiting for answers, the internal flag 'm_bAwaitingAnswers' is set. When the - timeout is reached, the flag is removed. These two flags are only used for static - service queries. - All answers to the service query are stored in 'm_pAnswers' list. - Individual answers may be addressed by index (in the list of answers). - Every time a answer component is added (or changes) in a dynamic service query, - the callback 'm_fnCallback' is called. - The answer list may be searched by service and host domain. - - 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::stcAnswer::addIP6Address + */ + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::addIP6Address( + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* p_pIP6Address) + { + bool bResult = false; -/* - MDNSResponder::stcMDNSServiceQuery::~stcMDNSServiceQuery destructor -*/ -MDNSResponder::stcMDNSServiceQuery::~stcMDNSServiceQuery(void) -{ + if (p_pIP6Address) + { + p_pIP6Address->m_pNext = m_pIP6Addresses; + m_pIP6Addresses = p_pIP6Address; + bResult = true; + } + return bResult; + } - clear(); -} + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::removeIP6Address + */ + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::removeIP6Address( + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* p_pIP6Address) + { + bool bResult = false; -/* - MDNSResponder::stcMDNSServiceQuery::clear -*/ -bool MDNSResponder::stcMDNSServiceQuery::clear(void) -{ + if (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 + { + m_pIP6Addresses = p_pIP6Address->m_pNext; + delete p_pIP6Address; + bResult = true; + } + } + return bResult; + } - m_fnCallback = 0; - m_bLegacyQuery = false; - m_u8SentCount = 0; - m_ResendTimeout.resetToNeverExpires(); - m_bAwaitingAnswers = true; - while (m_pAnswers) + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::findIP6Address + */ + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::findIP6Address(const IP6Address& p_IPAddress) { - stcAnswer* pNext = m_pAnswers->m_pNext; - delete m_pAnswers; - m_pAnswers = pNext; + return (stcIP6Address*)(((const stcAnswer*)this)->findIP6Address(p_IPAddress)); } - return true; -} - -/* - MDNSResponder::stcMDNSServiceQuery::answerCount -*/ -uint32_t MDNSResponder::stcMDNSServiceQuery::answerCount(void) const -{ - uint32_t u32Count = 0; - - stcAnswer* pAnswer = m_pAnswers; - while (pAnswer) + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::findIP6Address (const) + */ + const MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::findIP6Address( + const IPAddress& p_IPAddress) const { - ++u32Count; - pAnswer = pAnswer->m_pNext; + const stcIP6Address* pIP6Address = m_pIP6Addresses; + while (pIP6Address) + { + if (p_IP6Address->m_IPAddress == p_IPAddress) + { + break; + } + pIP6Address = pIP6Address->m_pNext; + } + return pIP6Address; } - return u32Count; -} -/* - MDNSResponder::stcMDNSServiceQuery::answerAtIndex -*/ -const MDNSResponder::stcMDNSServiceQuery::stcAnswer* MDNSResponder::stcMDNSServiceQuery::answerAtIndex(uint32_t p_u32Index) const -{ + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP6AddressCount + */ + uint32_t MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP6AddressCount(void) const + { + uint32_t u32Count = 0; - const stcAnswer* pAnswer = 0; + stcIP6Address* pIP6Address = m_pIP6Addresses; + while (pIP6Address) + { + ++u32Count; + pIP6Address = pIP6Address->m_pNext; + } + return u32Count; + } - if (((uint32_t)(-1) != p_u32Index) && - (m_pAnswers)) + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP6AddressAtIndex (const) + */ + const MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP6AddressAtIndex(uint32_t p_u32Index) const { - - uint32_t u32Index; - for (pAnswer = m_pAnswers, u32Index = 0; ((pAnswer) && (u32Index < p_u32Index)); pAnswer = pAnswer->m_pNext, ++u32Index); + return (stcIP6Address*)(((const stcAnswer*)this)->IP6AddressAtIndex(p_u32Index)); } - return pAnswer; -} -/* - MDNSResponder::stcMDNSServiceQuery::answerAtIndex -*/ -MDNSResponder::stcMDNSServiceQuery::stcAnswer* MDNSResponder::stcMDNSServiceQuery::answerAtIndex(uint32_t p_u32Index) -{ + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP6AddressAtIndex + */ + MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP6AddressAtIndex(uint32_t p_u32Index) + { + stcIP6Address* pIP6Address = 0; - return (stcAnswer*)(((const stcMDNSServiceQuery*)this)->answerAtIndex(p_u32Index)); -} + 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; + } +#endif -/* - MDNSResponder::stcMDNSServiceQuery::indexOfAnswer -*/ -uint32_t MDNSResponder::stcMDNSServiceQuery::indexOfAnswer(const MDNSResponder::stcMDNSServiceQuery::stcAnswer* p_pAnswer) const -{ + /** + MDNSResponder::stcMDNSServiceQuery + + A service query object. + A static query is flagged via 'm_bLegacyQuery'; while the function 'queryService' + is waiting for answers, the internal flag 'm_bAwaitingAnswers' is set. When the + timeout is reached, the flag is removed. These two flags are only used for static + service queries. + All answers to the service query are stored in 'm_pAnswers' list. + Individual answers may be addressed by index (in the list of answers). + Every time a answer component is added (or changes) in a dynamic service query, + the callback 'm_fnCallback' is called. + The answer list may be searched by service and host domain. + + 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(); + } - uint32_t u32Index = 0; + /* + MDNSResponder::stcMDNSServiceQuery::~stcMDNSServiceQuery destructor + */ + MDNSResponder::stcMDNSServiceQuery::~stcMDNSServiceQuery(void) + { + clear(); + } - for (const stcAnswer* pAnswer = m_pAnswers; pAnswer; pAnswer = pAnswer->m_pNext, ++u32Index) + /* + MDNSResponder::stcMDNSServiceQuery::clear + */ + bool MDNSResponder::stcMDNSServiceQuery::clear(void) { - if (pAnswer == p_pAnswer) + m_fnCallback = 0; + m_bLegacyQuery = false; + m_u8SentCount = 0; + m_ResendTimeout.resetToNeverExpires(); + m_bAwaitingAnswers = true; + while (m_pAnswers) { - return u32Index; + stcAnswer* pNext = m_pAnswers->m_pNext; + delete m_pAnswers; + m_pAnswers = pNext; } + return true; } - return ((uint32_t)(-1)); -} -/* - MDNSResponder::stcMDNSServiceQuery::addAnswer -*/ -bool MDNSResponder::stcMDNSServiceQuery::addAnswer(MDNSResponder::stcMDNSServiceQuery::stcAnswer* p_pAnswer) -{ + /* + MDNSResponder::stcMDNSServiceQuery::answerCount + */ + uint32_t MDNSResponder::stcMDNSServiceQuery::answerCount(void) const + { + uint32_t u32Count = 0; - bool bResult = false; + stcAnswer* pAnswer = m_pAnswers; + while (pAnswer) + { + ++u32Count; + pAnswer = pAnswer->m_pNext; + } + return u32Count; + } - if (p_pAnswer) + /* + MDNSResponder::stcMDNSServiceQuery::answerAtIndex + */ + const MDNSResponder::stcMDNSServiceQuery::stcAnswer* + MDNSResponder::stcMDNSServiceQuery::answerAtIndex(uint32_t p_u32Index) const { - p_pAnswer->m_pNext = m_pAnswers; - m_pAnswers = p_pAnswer; - bResult = true; - } - return bResult; -} + const stcAnswer* pAnswer = 0; -/* - MDNSResponder::stcMDNSServiceQuery::removeAnswer -*/ -bool MDNSResponder::stcMDNSServiceQuery::removeAnswer(MDNSResponder::stcMDNSServiceQuery::stcAnswer* p_pAnswer) -{ + 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; + } - bool bResult = false; + /* + MDNSResponder::stcMDNSServiceQuery::answerAtIndex + */ + MDNSResponder::stcMDNSServiceQuery::stcAnswer* + MDNSResponder::stcMDNSServiceQuery::answerAtIndex(uint32_t p_u32Index) + { + return (stcAnswer*)(((const stcMDNSServiceQuery*)this)->answerAtIndex(p_u32Index)); + } - if (p_pAnswer) + /* + MDNSResponder::stcMDNSServiceQuery::indexOfAnswer + */ + uint32_t MDNSResponder::stcMDNSServiceQuery::indexOfAnswer( + const MDNSResponder::stcMDNSServiceQuery::stcAnswer* p_pAnswer) const { - stcAnswer* pPred = m_pAnswers; - while ((pPred) && - (pPred->m_pNext != p_pAnswer)) + uint32_t u32Index = 0; + + for (const stcAnswer* pAnswer = m_pAnswers; pAnswer; pAnswer = pAnswer->m_pNext, ++u32Index) { - pPred = pPred->m_pNext; + if (pAnswer == p_pAnswer) + { + return u32Index; + } } - if (pPred) + return ((uint32_t)(-1)); + } + + /* + MDNSResponder::stcMDNSServiceQuery::addAnswer + */ + bool MDNSResponder::stcMDNSServiceQuery::addAnswer( + MDNSResponder::stcMDNSServiceQuery::stcAnswer* p_pAnswer) + { + bool bResult = false; + + if (p_pAnswer) { - pPred->m_pNext = p_pAnswer->m_pNext; - delete p_pAnswer; - bResult = true; + p_pAnswer->m_pNext = m_pAnswers; + m_pAnswers = p_pAnswer; + bResult = true; } - else if (m_pAnswers == p_pAnswer) // No predecessor, but first item + return bResult; + } + + /* + MDNSResponder::stcMDNSServiceQuery::removeAnswer + */ + bool MDNSResponder::stcMDNSServiceQuery::removeAnswer( + MDNSResponder::stcMDNSServiceQuery::stcAnswer* p_pAnswer) + { + 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::findAnswerForServiceDomain + */ + 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::findAnswerForHostDomain + */ + 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 + /** + MDNSResponder::stcMDNSSendParameter - A 'collection' of properties and flags for one MDNS query or response. - Mainly managed by the 'Control' functions. - The current offset in the UPD output buffer is tracked to be able to do - a simple host or service domain compression. + A 'collection' of properties and flags for one MDNS query or response. + Mainly managed by the 'Control' functions. + The current offset in the UPD output buffer is tracked to be able to do + a simple host or service domain compression. -*/ + */ -/** - MDNSResponder::stcMDNSSendParameter::stcDomainCacheItem + /** + MDNSResponder::stcMDNSSendParameter::stcDomainCacheItem - A cached host or service domain, incl. the offset in the UDP output buffer. + 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), + /* + 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 -*/ - -/* - MDNSResponder::stcMDNSSendParameter::stcMDNSSendParameter constructor -*/ -MDNSResponder::stcMDNSSendParameter::stcMDNSSendParameter(void) - : m_pQuestions(0), - m_pDomainCacheItems(0) -{ - - clear(); -} - -/* - MDNSResponder::stcMDNSSendParameter::~stcMDNSSendParameter destructor -*/ -MDNSResponder::stcMDNSSendParameter::~stcMDNSSendParameter(void) -{ - - clear(); -} - -/* - MDNSResponder::stcMDNSSendParameter::clear -*/ -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_bCacheFlush = true; - - while (m_pQuestions) { - stcMDNS_RRQuestion* pNext = m_pQuestions->m_pNext; - delete m_pQuestions; - m_pQuestions = pNext; } - return clearCachedNames();; -} -/* - MDNSResponder::stcMDNSSendParameter::clear cached names -*/ -bool MDNSResponder::stcMDNSSendParameter::clearCachedNames(void) -{ - - m_u16Offset = 0; + /** + MDNSResponder::stcMDNSSendParameter + */ - while (m_pDomainCacheItems) + /* + MDNSResponder::stcMDNSSendParameter::stcMDNSSendParameter constructor + */ + MDNSResponder::stcMDNSSendParameter::stcMDNSSendParameter(void) : + m_pQuestions(0), m_pDomainCacheItems(0) { - stcDomainCacheItem* pNext = m_pDomainCacheItems->m_pNext; - delete m_pDomainCacheItems; - m_pDomainCacheItems = pNext; + clear(); } - m_pDomainCacheItems = nullptr; - return true; -} + /* + MDNSResponder::stcMDNSSendParameter::~stcMDNSSendParameter destructor + */ + MDNSResponder::stcMDNSSendParameter::~stcMDNSSendParameter(void) + { + clear(); + } -/* - MDNSResponder::stcMDNSSendParameter::shiftOffset -*/ -bool MDNSResponder::stcMDNSSendParameter::shiftOffset(uint16_t p_u16Shift) -{ + /* + MDNSResponder::stcMDNSSendParameter::clear + */ + bool MDNSResponder::stcMDNSSendParameter::clear(void) + { + m_u16ID = 0; + m_u8HostReplyMask = 0; + m_u16Offset = 0; - m_u16Offset += p_u16Shift; - return true; -} + m_bLegacyQuery = false; + m_bResponse = false; + m_bAuthorative = false; + m_bUnicast = false; + m_bUnannounce = false; -/* - MDNSResponder::stcMDNSSendParameter::addDomainCacheItem -*/ -bool MDNSResponder::stcMDNSSendParameter::addDomainCacheItem(const void* p_pHostnameOrService, - bool p_bAdditionalData, - uint16_t p_u16Offset) -{ + m_bCacheFlush = true; - bool bResult = false; + while (m_pQuestions) + { + stcMDNS_RRQuestion* pNext = m_pQuestions->m_pNext; + delete m_pQuestions; + m_pQuestions = pNext; + } - stcDomainCacheItem* pNewItem = 0; - if ((p_pHostnameOrService) && - (p_u16Offset) && - ((pNewItem = new stcDomainCacheItem(p_pHostnameOrService, p_bAdditionalData, p_u16Offset)))) + return clearCachedNames(); + ; + } + /* + MDNSResponder::stcMDNSSendParameter::clear cached names + */ + bool MDNSResponder::stcMDNSSendParameter::clearCachedNames(void) { + m_u16Offset = 0; - pNewItem->m_pNext = m_pDomainCacheItems; - bResult = ((m_pDomainCacheItems = pNewItem)); - } - return bResult; -} + while (m_pDomainCacheItems) + { + stcDomainCacheItem* pNext = m_pDomainCacheItems->m_pNext; + delete m_pDomainCacheItems; + m_pDomainCacheItems = pNext; + } + m_pDomainCacheItems = nullptr; -/* - MDNSResponder::stcMDNSSendParameter::findCachedDomainOffset -*/ -uint16_t MDNSResponder::stcMDNSSendParameter::findCachedDomainOffset(const void* p_pHostnameOrService, - bool p_bAdditionalData) const -{ + return true; + } - const stcDomainCacheItem* pCacheItem = m_pDomainCacheItems; + /* + MDNSResponder::stcMDNSSendParameter::shiftOffset + */ + bool MDNSResponder::stcMDNSSendParameter::shiftOffset(uint16_t p_u16Shift) + { + m_u16Offset += p_u16Shift; + return true; + } - for (; pCacheItem; pCacheItem = pCacheItem->m_pNext) + /* + MDNSResponder::stcMDNSSendParameter::addDomainCacheItem + */ + bool MDNSResponder::stcMDNSSendParameter::addDomainCacheItem(const void* p_pHostnameOrService, + bool p_bAdditionalData, + uint16_t p_u16Offset) { - if ((pCacheItem->m_pHostnameOrService == p_pHostnameOrService) && - (pCacheItem->m_bAdditionalData == p_bAdditionalData)) // Found cache item + bool bResult = false; + + stcDomainCacheItem* pNewItem = 0; + if ((p_pHostnameOrService) && (p_u16Offset) + && ((pNewItem + = new stcDomainCacheItem(p_pHostnameOrService, p_bAdditionalData, p_u16Offset)))) { - break; + pNewItem->m_pNext = m_pDomainCacheItems; + bResult = ((m_pDomainCacheItems = pNewItem)); } + return bResult; } - return (pCacheItem ? pCacheItem->m_u16Offset : 0); -} -} // namespace MDNSImplementation - -} // namespace esp8266 + /* + 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) + { + if ((pCacheItem->m_pHostnameOrService == p_pHostnameOrService) + && (pCacheItem->m_bAdditionalData == p_bAdditionalData)) // Found cache item + { + break; + } + } + return (pCacheItem ? pCacheItem->m_u16Offset : 0); + } +} // namespace MDNSImplementation +} // namespace esp8266 diff --git a/libraries/ESP8266mDNS/src/LEAmDNS_Transfer.cpp b/libraries/ESP8266mDNS/src/LEAmDNS_Transfer.cpp index ebe66dff1c..5074b74cfb 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS_Transfer.cpp +++ b/libraries/ESP8266mDNS/src/LEAmDNS_Transfer.cpp @@ -22,7 +22,8 @@ */ -extern "C" { +extern "C" +{ #include "user_interface.h" } @@ -30,7 +31,6 @@ extern "C" { #include "LEAmDNS_lwIPdefs.h" #include "LEAmDNS_Priv.h" - namespace esp8266 { @@ -40,1749 +40,1843 @@ 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"; + /** + 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"; #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 -*/ + /** + TRANSFER + */ + /** + SENDING + */ -/** - SENDING -*/ + /* + MDNSResponder::_sendMDNSMessage -/* - MDNSResponder::_sendMDNSMessage + Unicast responses are prepared and sent directly to the querier. + Multicast responses or queries are transferred to _sendMDNSMessage_Multicast - Unicast responses are prepared and sent directly to the querier. - Multicast responses or queries are transferred to _sendMDNSMessage_Multicast + Any reply flags in installed services are removed at the end! - Any reply flags in installed services are removed at the end! + */ + bool MDNSResponder::_sendMDNSMessage(MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + { + bool bResult = true; -*/ -bool MDNSResponder::_sendMDNSMessage(MDNSResponder::stcMDNSSendParameter& p_rSendParameter) -{ + 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); + } - 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")); + DEBUG_EX_ERR(if (!bResult) { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _sendMDNSMessage: FAILED!\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); - } - - // Finally clear service reply masks - for (stcMDNSService* pService = m_pServices; pService; pService = pService->m_pNext) - { - pService->m_u8ReplyMask = 0; + return bResult; } - 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; + /* + MDNSResponder::_sendMDNSMessage_Multicast - for (netif* pNetIf = netif_list; pNetIf; pNetIf = pNetIf->next) + 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) { - 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. - In the first loop 'only' the header information (mainly number of answers) are collected, - while in the seconds loop, the header and all queries and answers are written to the UDP - output buffer. + /* + MDNSResponder::_prepareMDNSMessage -*/ -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); + The MDNS message is composed in a two-step process. + In the first loop 'only' the header information (mainly number of answers) are collected, + while in the seconds loop, the header and all queries and answers are written to the UDP + output buffer. - /** - 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) + bool MDNSResponder::_prepareMDNSMessage(MDNSResponder::stcMDNSSendParameter& p_rSendParameter, + IPAddress p_IPAddress) { - 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)) - { - ((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)) + 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 == 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 { - bNeedsAdditionalAnswerAAAA = true; + ((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 + { + ((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; -} - -/* - 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); -} - -/* - MDNSResponder::_sendMDNSQuery - - Creates and sends a query for the given domain and query type. + 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; + } -*/ -bool MDNSResponder::_sendMDNSQuery(const MDNSResponder::stcMDNS_RRDomain& p_QueryDomain, - uint16_t p_u16QueryType, - stcMDNSServiceQuery::stcAnswer* p_pKnownAnswers /*= 0*/) -{ + /* + MDNSResponder::_sendMDNSServiceQuery - bool bResult = false; + Creates and sends a PTR query for the given service domain. - stcMDNSSendParameter sendParameter; - if (0 != ((sendParameter.m_pQuestions = new stcMDNS_RRQuestion))) + */ + bool + MDNSResponder::_sendMDNSServiceQuery(const MDNSResponder::stcMDNSServiceQuery& p_ServiceQuery) { - 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 + return _sendMDNSQuery(p_ServiceQuery.m_ServiceTypeDomain, DNS_RRTYPE_PTR); + } - // TODO: Add known answer to the query - (void)p_pKnownAnswers; + /* + MDNSResponder::_sendMDNSQuery - 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; -} + Creates and sends a query for the given domain and query type. -/** - HELPERS -*/ + */ + bool MDNSResponder::_sendMDNSQuery(const MDNSResponder::stcMDNS_RRDomain& p_QueryDomain, + uint16_t p_u16QueryType, + stcMDNSServiceQuery::stcAnswer* p_pKnownAnswers /*= 0*/) + { + bool bResult = false; -/** - RESOURCE RECORDS -*/ + 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 + + // 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; + } -/* - MDNSResponder::_readRRQuestion + /** + HELPERS + */ - Reads a question (eg. MyESP._http._tcp.local ANY IN) from the UPD input buffer. + /** + RESOURCE RECORDS + */ -*/ -bool MDNSResponder::_readRRQuestion(MDNSResponder::stcMDNS_RRQuestion& p_rRRQuestion) -{ - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRQuestion\n"));); + /* + MDNSResponder::_readRRQuestion - bool bResult = false; + Reads a question (eg. MyESP._http._tcp.local ANY IN) from the UPD input buffer. - if ((bResult = _readRRHeader(p_rRRQuestion.m_Header))) + */ + bool MDNSResponder::_readRRQuestion(MDNSResponder::stcMDNS_RRQuestion& p_rRRQuestion) { - // 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_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRQuestion\n"));); -/* - MDNSResponder::_readRRAnswer + bool bResult = false; - Reads an answer (eg. _http._tcp.local PTR OP TTL MyESP._http._tcp.local) - from the UDP input buffer. - After reading the domain and type info, the further processing of the answer - is transferred the answer specific reading functions. - Unknown answer types are processed by the generic answer reader (to remove them - from the input buffer). + 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; + } -*/ -bool MDNSResponder::_readRRAnswer(MDNSResponder::stcMDNS_RRAnswer*& p_rpRRAnswer) -{ - //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswer\n"));); + /* + MDNSResponder::_readRRAnswer - bool bResult = false; + Reads an answer (eg. _http._tcp.local PTR OP TTL MyESP._http._tcp.local) + from the UDP input buffer. + After reading the domain and type info, the further processing of the answer + is transferred the answer specific reading functions. + Unknown answer types are processed by the generic answer reader (to remove them + from the input buffer). - stcMDNS_RRHeader header; - uint32_t u32TTL; - uint16_t u16RDLength; - if ((_readRRHeader(header)) && - (_udpRead32(u32TTL)) && - (_udpRead16(u16RDLength))) + */ + bool MDNSResponder::_readRRAnswer(MDNSResponder::stcMDNS_RRAnswer*& p_rpRRAnswer) { + // DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAnswer\n"));); - /* 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")); - );*/ + bool bResult = false; - switch (header.m_Attributes.m_u16Type & (~0x8000)) // Topmost bit might carry 'cache flush' flag + stcMDNS_RRHeader header; + uint32_t u32TTL; + uint16_t u16RDLength; + if ((_readRRHeader(header)) && (_udpRead32(u32TTL)) && (_udpRead16(u16RDLength))) { -#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 + /* 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 { #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( + 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_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; -} + /* + 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; + } #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; -} - -/* - MDNSResponder::_readRRAnswerTXT + /* + 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; + } - 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; + /* + MDNSResponder::_readRRAnswerTXT - p_rRRAnswerTXT.clear(); - if (p_u16RDLength) + Read TXT items from a buffer like 4c#=15ff=20 + */ + 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 - - 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")); + } // 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")); + }); + } + 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) -{ + /* + 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 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); -/* - 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]))) + { + 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; + } - p_rRRAnswerGeneric.clear(); - if (((p_rRRAnswerGeneric.m_u16RDLength = p_u16RDLength)) && - ((p_rRRAnswerGeneric.m_pu8RDData = new unsigned char[p_rRRAnswerGeneric.m_u16RDLength]))) + /* + MDNSResponder::_readRRHeader + */ + bool MDNSResponder::_readRRHeader(MDNSResponder::stcMDNS_RRHeader& p_rRRHeader) { + // DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRHeader\n"));); - bResult = _udpReadBuffer(p_rRRAnswerGeneric.m_pu8RDData, p_rRRAnswerGeneric.m_u16RDLength); + 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; } - 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"));); + /* + MDNSResponder::_readRRDomain - 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; -} + Reads a (maybe multilevel compressed) domain from the UDP input buffer. -/* - MDNSResponder::_readRRDomain + */ + bool MDNSResponder::_readRRDomain(MDNSResponder::stcMDNS_RRDomain& p_rRRDomain) + { + // DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain\n"));); - Reads a (maybe multilevel compressed) domain from the UDP input buffer. + 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 MDNSResponder::_readRRDomain(MDNSResponder::stcMDNS_RRDomain& p_rRRDomain) -{ - //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain\n"));); + /* + MDNSResponder::_readRRDomain_Loop - 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; -} + Reads a domain from the UDP input buffer. For every compression level, the functions + calls itself recursively. To avoid endless recursion because of malformed MDNS records, + the maximum recursion depth is set by MDNS_DOMAIN_MAX_REDIRCTION. -/* - MDNSResponder::_readRRDomain_Loop - - Reads a domain from the UDP input buffer. For every compression level, the functions - calls itself recursively. To avoid endless recursion because of malformed MDNS records, - 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);); + + bool bResult = false; - uint8_t u8Len = 0; - do + 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( - 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; + 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; + } } + // 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 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; -} + /* + MDNSResponder::_readRRAttributes + */ + bool MDNSResponder::_readRRAttributes(MDNSResponder::stcMDNS_RRAttributes& p_rRRAttributes) + { + // DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAttributes\n"));); -/* - 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 -{ + 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; + } - 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; -} + /* + DOMAIN NAMES + */ -/* - MDNSResponder::_buildDomainForDNSSD + /* + MDNSResponder::_buildDomainForHost - Builds the '_services._dns-sd._udp.local' domain. - Used while detecting generic service enum question (DNS-SD) and answering these questions. + Builds a MDNS host domain (eg. esp8266.local) for the given hostname. -*/ -bool MDNSResponder::_buildDomainForDNSSD(MDNSResponder::stcMDNS_RRDomain& p_rDNSSDDomain) const -{ + */ + 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; + } - 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::_buildDomainForDNSSD -/* - MDNSResponder::_buildDomainForService + Builds the '_services._dns-sd._udp.local' domain. + Used while detecting generic service enum question (DNS-SD) and answering these questions. - Builds the domain for the given service (eg. _http._tcp.local or - MyESP._http._tcp.local (if p_bIncludeName is set)). + */ + 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::_buildDomainForService(const MDNSResponder::stcMDNSService& p_Service, - bool p_bIncludeName, - MDNSResponder::stcMDNS_RRDomain& p_rServiceDomain) const -{ + /* + MDNSResponder::_buildDomainForService - 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; -} + Builds the domain for the given service (eg. _http._tcp.local or + MyESP._http._tcp.local (if p_bIncludeName is set)). -/* - MDNSResponder::_buildDomainForService + */ + 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; + } - Builds the domain for the given service properties (eg. _http._tcp.local). - The usual prepended '_' are added, if missing in the input strings. + /* + MDNSResponder::_buildDomainForService -*/ -bool MDNSResponder::_buildDomainForService(const char* p_pcService, - const char* p_pcProtocol, - MDNSResponder::stcMDNS_RRDomain& p_rServiceDomain) const -{ + Builds the domain for the given service properties (eg. _http._tcp.local). + The usual prepended '_' are added, if missing in the input strings. - 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 -{ + /* + MDNSResponder::_buildDomainForReverseIP4 - bool bResult = true; + 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; - 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; -} -#endif - + /* + MDNSResponder::_buildDomainForReverseIP6 -/* - 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; -} - -/* - MDNSResponder::_udpRead8 -*/ -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))) + Used while detecting reverse IP6 questions and answering these + */ + bool MDNSResponder::_buildDomainForReverseIP6( + IPAddress p_IP4Address, MDNSResponder::stcMDNS_RRDomain& p_rReverseIP6Domain) const { - p_ru16Value = lwip_ntohs(p_ru16Value); - bResult = true; + // TODO: Implement + return false; } - return bResult; -} - -/* - MDNSResponder::_udpRead32 -*/ -bool MDNSResponder::_udpRead32(uint32_t& p_ru32Value) -{ +#endif - bool bResult = false; + /* + UDP + */ - if (_udpReadBuffer((unsigned char*)&p_ru32Value, sizeof(p_ru32Value))) + /* + MDNSResponder::_udpReadBuffer + */ + bool MDNSResponder::_udpReadBuffer(unsigned char* p_pBuffer, size_t p_stLength) { - p_ru32Value = lwip_ntohl(p_ru32Value); - bResult = true; + 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; } - 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; -} - -/* - MDNSResponder::_udpAppend8 -*/ -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))); -} - -/* - MDNSResponder::_udpAppend32 -*/ -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; - - uint32_t u32StartPosition = m_pUDPContext->tell(); - DEBUG_OUTPUT.println("UDP Context Dump:"); - uint32_t u32Counter = 0; - uint8_t u8Byte = 0; - - while (_udpRead8(u8Byte)) + /* + MDNSResponder::_udpRead8 + */ + bool MDNSResponder::_udpRead8(uint8_t& p_ru8Value) { - DEBUG_OUTPUT.printf_P(PSTR("%02x %s"), u8Byte, ((++u32Counter % cu8BytesPerLine) ? "" : "\n")); + return _udpReadBuffer((unsigned char*)&p_ru8Value, sizeof(p_ru8Value)); } - DEBUG_OUTPUT.printf_P(PSTR("%sDone: %u bytes\n"), (((u32Counter) && (u32Counter % cu8BytesPerLine)) ? "\n" : ""), u32Counter); - if (!p_bMovePointer) // Restore + /* + MDNSResponder::_udpRead16 + */ + bool MDNSResponder::_udpRead16(uint16_t& p_ru16Value) { - m_pUDPContext->seek(u32StartPosition); - } - return true; -} + bool bResult = false; -/* - MDNSResponder::_udpDump -*/ -bool MDNSResponder::_udpDump(unsigned p_uOffset, - unsigned p_uLength) -{ + if (_udpReadBuffer((unsigned char*)&p_ru16Value, sizeof(p_ru16Value))) + { + p_ru16Value = lwip_ntohs(p_ru16Value); + bResult = true; + } + return bResult; + } - if ((m_pUDPContext) && - (m_pUDPContext->isValidOffset(p_uOffset))) + /* + MDNSResponder::_udpRead32 + */ + bool MDNSResponder::_udpRead32(uint32_t& p_ru32Value) { - unsigned uCurrentPosition = m_pUDPContext->tell(); // Remember start position + bool bResult = false; - m_pUDPContext->seek(p_uOffset); - uint8_t u8Byte; - for (unsigned u = 0; ((u < p_uLength) && (_udpRead8(u8Byte))); ++u) + if (_udpReadBuffer((unsigned char*)&p_ru32Value, sizeof(p_ru32Value))) { - DEBUG_OUTPUT.printf_P(PSTR("%02x "), u8Byte); + p_ru32Value = lwip_ntohl(p_ru32Value); + bResult = true; } - // Return to start position - m_pUDPContext->seek(uCurrentPosition); + return bResult; } - return true; -} -#endif - - -/** - READ/WRITE MDNS STRUCTS -*/ - -/* - MDNSResponder::_readMDNSMsgHeader - Read a MDNS header from the UDP input buffer. - | 8 | 8 | 8 | 8 | - 00| Identifier | Flags & Codes | - 01| Question count | Answer count | - 02| NS answer count | Ad answer count | + /* + 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; + } - All 16-bit and 32-bit elements need to be translated form network coding to host coding (done in _udpRead16 and _udpRead32) - 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) -{ + /* + MDNSResponder::_udpAppend8 + */ + bool MDNSResponder::_udpAppend8(uint8_t p_u8Value) + { + return (_udpAppendBuffer((unsigned char*)&p_u8Value, sizeof(p_u8Value))); + } - 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))) + /* + MDNSResponder::_udpAppend16 + */ + bool MDNSResponder::_udpAppend16(uint16_t p_u16Value) { + p_u16Value = lwip_htons(p_u16Value); + return (_udpAppendBuffer((unsigned char*)&p_u16Value, sizeof(p_u16Value))); + } - 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"), - (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, - (unsigned)p_rMsgHeader.m_u16QDCount, - (unsigned)p_rMsgHeader.m_u16ANCount, - (unsigned)p_rMsgHeader.m_u16NSCount, - (unsigned)p_rMsgHeader.m_u16ARCount););*/ - bResult = true; + /* + MDNSResponder::_udpAppend32 + */ + bool MDNSResponder::_udpAppend32(uint32_t p_u32Value) + { + p_u32Value = lwip_htonl(p_u32Value); + return (_udpAppendBuffer((unsigned char*)&p_u32Value, sizeof(p_u32Value))); } - 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) -{ +#ifdef DEBUG_ESP_MDNS_RESPONDER + /* + MDNSResponder::_udpDump + */ + bool MDNSResponder::_udpDump(bool p_bMovePointer /*= false*/) + { + const uint8_t cu8BytesPerLine = 16; - return ((_udpAppend8(p_u8Value)) && - (p_rSendParameter.shiftOffset(sizeof(p_u8Value)))); -} + uint32_t u32StartPosition = m_pUDPContext->tell(); + DEBUG_OUTPUT.println("UDP Context Dump:"); + uint32_t u32Counter = 0; + uint8_t u8Byte = 0; -/* - MDNSResponder::_write16 -*/ -bool MDNSResponder::_write16(uint16_t p_u16Value, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) -{ + 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); - return ((_udpAppend16(p_u16Value)) && - (p_rSendParameter.shiftOffset(sizeof(p_u16Value)))); -} + if (!p_bMovePointer) // Restore + { + m_pUDPContext->seek(u32StartPosition); + } + return true; + } -/* - MDNSResponder::_write32 -*/ -bool MDNSResponder::_write32(uint32_t p_u32Value, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) -{ + /* + MDNSResponder::_udpDump + */ + bool MDNSResponder::_udpDump(unsigned p_uOffset, unsigned p_uLength) + { + if ((m_pUDPContext) && (m_pUDPContext->isValidOffset(p_uOffset))) + { + unsigned uCurrentPosition = m_pUDPContext->tell(); // Remember start position - return ((_udpAppend32(p_u32Value)) && - (p_rSendParameter.shiftOffset(sizeof(p_u32Value)))); -} + 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 true; + } +#endif -/* - MDNSResponder::_writeMDNSMsgHeader + /** + READ/WRITE MDNS STRUCTS + */ - Write MDNS header to the UDP output buffer. + /* + MDNSResponder::_readMDNSMsgHeader - All 16-bit and 32-bit elements need to be translated form host coding to network coding (done in _udpAppend16 and _udpAppend32) - 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"), - (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, - (unsigned)p_MsgHeader.m_u16QDCount, - (unsigned)p_MsgHeader.m_u16ANCount, - (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; -} + Read a MDNS header from the UDP input buffer. + | 8 | 8 | 8 | 8 | + 00| Identifier | Flags & Codes | + 01| Question count | Answer count | + 02| NS answer count | Ad answer count | -/* - MDNSResponder::_writeRRAttributes -*/ -bool MDNSResponder::_writeMDNSRRAttributes(const MDNSResponder::stcMDNS_RRAttributes& p_Attributes, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) -{ + All 16-bit and 32-bit elements need to be translated form network coding to host coding + (done in _udpRead16 and _udpRead32) 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; - bool bResult = ((_write16(p_Attributes.m_u16Type, p_rSendParameter)) && - (_write16(p_Attributes.m_u16Class, p_rSendParameter))); + 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"), + (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, (unsigned)p_rMsgHeader.m_u16QDCount, + (unsigned)p_rMsgHeader.m_u16ANCount, + (unsigned)p_rMsgHeader.m_u16NSCount, + (unsigned)p_rMsgHeader.m_u16ARCount););*/ + 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] _writeMDNSRRAttributes: 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)))); + } -/* - MDNSResponder::_writeMDNSRRDomain -*/ -bool MDNSResponder::_writeMDNSRRDomain(const MDNSResponder::stcMDNS_RRDomain& p_Domain, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) -{ + /* + MDNSResponder::_write16 + */ + bool MDNSResponder::_write16(uint16_t p_u16Value, + MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + { + return ((_udpAppend16(p_u16Value)) && (p_rSendParameter.shiftOffset(sizeof(p_u16Value)))); + } - bool bResult = ((_udpAppendBuffer((const unsigned char*)p_Domain.m_acName, p_Domain.m_u16NameLength)) && - (p_rSendParameter.shiftOffset(p_Domain.m_u16NameLength))); + /* + MDNSResponder::_write32 + */ + bool MDNSResponder::_write32(uint32_t p_u32Value, + MDNSResponder::stcMDNSSendParameter& p_rSendParameter) + { + return ((_udpAppend32(p_u32Value)) && (p_rSendParameter.shiftOffset(sizeof(p_u32Value)))); + } - DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSRRDomain: FAILED!\n")); - }); - return bResult; -} + /* + MDNSResponder::_writeMDNSMsgHeader -/* - MDNSResponder::_writeMDNSHostDomain + Write MDNS header to the UDP output buffer. - Write a host domain to the UDP output buffer. - If the domain record is part of the answer, the records length is - prepended (p_bPrependRDLength is set). + All 16-bit and 32-bit elements need to be translated form host coding to network coding + (done in _udpAppend16 and _udpAppend32) 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"), + (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, + (unsigned)p_MsgHeader.m_u16QDCount, + (unsigned)p_MsgHeader.m_u16ANCount, + (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; + } - A very simple form of name compression is applied here: - If the domain is written to the UDP output buffer, the write offset is stored - together with a domain id (the pointer) in a p_rSendParameter substructure (cache). - If the same domain (pointer) should be written to the UDP output later again, - the old offset is retrieved from the cache, marked as a compressed domain offset - and written to the output buffer. + /* + 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))); -*/ -bool MDNSResponder::_writeMDNSHostDomain(const char* p_pcHostname, - bool p_bPrependRDLength, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) -{ + DEBUG_EX_ERR(if (!bResult) { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSRRAttributes: FAILED!\n")); + }); + return bResult; + } - // 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::_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; + } -/* - MDNSResponder::_writeMDNSServiceDomain + /* + MDNSResponder::_writeMDNSHostDomain - Write a service domain to the UDP output buffer. - If the domain record is part of the answer, the records length is - prepended (p_bPrependRDLength is set). + Write a host domain to the UDP output buffer. + If the domain record is part of the answer, the records length is + prepended (p_bPrependRDLength is set). - A very simple form of name compression is applied here: see '_writeMDNSHostDomain' - The cache differentiates of course between service domains which includes - the instance name (p_bIncludeName is set) and thoose who don't. + A very simple form of name compression is applied here: + If the domain is written to the UDP output buffer, the write offset is stored + together with a domain id (the pointer) in a p_rSendParameter substructure (cache). + If the same domain (pointer) should be written to the UDP output later again, + the old offset is retrieved from the cache, marked as a compressed domain offset + and written to the output buffer. -*/ -bool MDNSResponder::_writeMDNSServiceDomain(const MDNSResponder::stcMDNSService& p_Service, - bool p_bIncludeName, - bool p_bPrependRDLength, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) -{ + */ + 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; + } - // 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::_writeMDNSServiceDomain -} + Write a service domain to the UDP output buffer. + If the domain record is part of the answer, the records length is + prepended (p_bPrependRDLength is set). -/* - MDNSResponder::_writeMDNSQuestion + A very simple form of name compression is applied here: see '_writeMDNSHostDomain' + The cache differentiates of course between service domains which includes + the instance name (p_bIncludeName is set) and thoose who don't. - Write a MDNS question to the UDP output buffer + */ + 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; + } - QNAME (host/service domain, eg. esp8266.local) - QTYPE (16bit, eg. ANY) - QCLASS (16bit, eg. IN) + /* + MDNSResponder::_writeMDNSQuestion -*/ -bool MDNSResponder::_writeMDNSQuestion(MDNSResponder::stcMDNS_RRQuestion& p_Question, - MDNSResponder::stcMDNSSendParameter& p_rSendParameter) -{ - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSQuestion\n"));); + Write a MDNS question to the UDP output buffer - bool bResult = ((_writeMDNSRRDomain(p_Question.m_Header.m_Domain, p_rSendParameter)) && - (_writeMDNSRRAttributes(p_Question.m_Header.m_Attributes, p_rSendParameter))); + QNAME (host/service domain, eg. esp8266.local) + QTYPE (16bit, eg. ANY) + QCLASS (16bit, eg. IN) - DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSQuestion: FAILED!\n")); - }); - return bResult; + */ + 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))); + 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. + /* + MDNSResponder::_writeMDNSAnswer_A - NAME (var, host/service domain, eg. esp8266.local - TYPE (16bit, eg. A) - CLASS (16bit, eg. IN) - TTL (32bit, eg. 120) - RDLENGTH (16bit, eg 4) - RDATA (var, eg. 123.456.789.012) + Write a MDNS A answer to the UDP output buffer. - 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());); + NAME (var, host/service domain, eg. esp8266.local + TYPE (16bit, eg. A) + CLASS (16bit, eg. IN) + TTL (32bit, eg. 120) + RDLENGTH (16bit, eg 4) + RDATA (var, eg. 123.456.789.012) - 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 + 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; + } - Write a MDNS reverse IP4 PTR answer to the UDP output buffer. - See: '_writeMDNSAnswer_A' + /* + MDNSResponder::_writeMDNSAnswer_PTR_IP4 - 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) + Write a MDNS reverse IP4 PTR answer to the UDP output buffer. + See: '_writeMDNSAnswer_A' - DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_IP4: FAILED!\n")); - }); - return bResult; -} + 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; + } #endif -/* - MDNSResponder::_writeMDNSAnswer_PTR_TYPE + /* + MDNSResponder::_writeMDNSAnswer_PTR_TYPE - Write a MDNS PTR answer to the UDP output buffer. - See: '_writeMDNSAnswer_A' + Write a MDNS PTR answer to the UDP output buffer. + See: '_writeMDNSAnswer_A' - PTR all-services -> service type - 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; -} - -/* - MDNSResponder::_writeMDNSAnswer_PTR_NAME - - Write a MDNS PTR answer to the UDP output buffer. - See: '_writeMDNSAnswer_A' - - PTR service type -> service name - 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) + PTR all-services -> service type + 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; + } - DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_PTR_NAME: FAILED!\n")); - }); - return bResult; -} + /* + MDNSResponder::_writeMDNSAnswer_PTR_NAME + Write a MDNS PTR answer to the UDP output buffer. + See: '_writeMDNSAnswer_A' -/* - MDNSResponder::_writeMDNSAnswer_TXT + PTR service type -> service name + 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; + } - Write a MDNS TXT answer to the UDP output buffer. - See: '_writeMDNSAnswer_A' + /* + MDNSResponder::_writeMDNSAnswer_TXT - The TXT items in the RDATA block are 'length byte encoded': [len]vardata + Write a MDNS TXT answer to the UDP output buffer. + See: '_writeMDNSAnswer_A' - 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"));); + The TXT items in the RDATA block are 'length byte encoded': [len]vardata - bool bResult = false; + 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"));); - stcMDNS_RRAttributes attributes(DNS_RRTYPE_TXT, - ((p_rSendParameter.m_bCacheFlush ? 0x8000 : 0) | DNS_RRCLASS_IN)); // Cache flush? & INternet + bool bResult = false; - 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 - { + stcMDNS_RRAttributes attributes(DNS_RRTYPE_TXT, + ((p_rSendParameter.m_bCacheFlush ? 0x8000 : 0) + | DNS_RRCLASS_IN)); // Cache flush? & INternet - 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) + 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 { - 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 + /* + MDNSResponder::_writeMDNSAnswer_AAAA - Write a MDNS AAAA answer to the UDP output buffer. - See: '_writeMDNSAnswer_A' + Write a MDNS AAAA answer to the UDP output buffer. + See: '_writeMDNSAnswer_A' - 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"));); + 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 + 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 + DEBUG_EX_ERR(if (!bResult) { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _writeMDNSAnswer_AAAA: FAILED!\n")); + }); + return bResult; + } - Write a MDNS reverse IP6 PTR answer to the UDP output buffer. - See: '_writeMDNSAnswer_A' + /* + MDNSResponder::_writeMDNSAnswer_PTR_IP6 - 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"));); + Write a MDNS reverse IP6 PTR answer to the UDP output buffer. + See: '_writeMDNSAnswer_A' - 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; -} + 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; + } #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; -} - -} // namespace MDNSImplementation - -} // namespace esp8266 - - - + /* + 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; + } +} // 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/Hash/examples/sha1/sha1.ino b/libraries/Hash/examples/sha1/sha1.ino index e9260ed9c5..4fe9f8a9c3 100644 --- a/libraries/Hash/examples/sha1/sha1.ino +++ b/libraries/Hash/examples/sha1/sha1.ino @@ -22,9 +22,7 @@ void loop() { sha1("test", &hash[0]); Serial.print("SHA1:"); - for (uint16_t i = 0; i < 20; i++) { - Serial.printf("%02x", hash[i]); - } + for (uint16_t i = 0; i < 20; i++) { Serial.printf("%02x", hash[i]); } Serial.println(); delay(1000); diff --git a/libraries/I2S/examples/InputSerialPlotter/InputSerialPlotter.ino b/libraries/I2S/examples/InputSerialPlotter/InputSerialPlotter.ino index 713440d73f..50b3206cc7 100644 --- a/libraries/I2S/examples/InputSerialPlotter/InputSerialPlotter.ino +++ b/libraries/I2S/examples/InputSerialPlotter/InputSerialPlotter.ino @@ -15,13 +15,14 @@ void setup() { // on non-native USB ports Serial.begin(115200); while (!Serial) { - ; // wait for serial port to connect. Needed for native USB port only + ; // wait for serial port to connect. Needed for native USB port only } // 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..689a50d579 100644 --- a/libraries/I2S/examples/SimpleTone/SimpleTone.ino +++ b/libraries/I2S/examples/SimpleTone/SimpleTone.ino @@ -10,13 +10,13 @@ #include -const int frequency = 440; // frequency of square wave in Hz -const int amplitude = 500; // amplitude of square wave -const int sampleRate = 8000; // sample rate in Hz +const int frequency = 440; // frequency of square wave in Hz +const int amplitude = 500; // amplitude of square wave +const int sampleRate = 8000; // sample rate in Hz -const int halfWavelength = (sampleRate / frequency); // half wavelength of square wave +const int halfWavelength = (sampleRate / frequency); // half wavelength of square wave -short sample = amplitude; // current sample value +short sample = amplitude; // current sample value int count = 0; void setup() { @@ -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..ab6cf58eb8 100644 --- a/libraries/LittleFS/examples/LittleFS_Timestamp/LittleFS_Timestamp.ino +++ b/libraries/LittleFS/examples/LittleFS_Timestamp/LittleFS_Timestamp.ino @@ -9,7 +9,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char *ssid = STASSID; @@ -19,7 +19,7 @@ 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,7 +33,7 @@ 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); @@ -41,7 +41,7 @@ void listDir(const char * dirname) { } -void readFile(const char * path) { +void readFile(const char *path) { Serial.printf("Reading file: %s\n", path); File file = LittleFS.open(path, "r"); @@ -51,13 +51,11 @@ void readFile(const char * path) { } Serial.print("Read from file: "); - while (file.available()) { - Serial.write(file.read()); - } + while (file.available()) { Serial.write(file.read()); } 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"); @@ -70,11 +68,11 @@ void writeFile(const char * path, const char * message) { } else { Serial.println("Write failed"); } - delay(2000); // Make sure the CREATE and LASTWRITE times are different + delay(2000); // Make sure the CREATE and LASTWRITE times are different 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() { } - +void loop() {} diff --git a/libraries/LittleFS/examples/SpeedTest/SpeedTest.ino b/libraries/LittleFS/examples/SpeedTest/SpeedTest.ino index 35e0ac66e6..5b0870b37b 100644 --- a/libraries/LittleFS/examples/SpeedTest/SpeedTest.ino +++ b/libraries/LittleFS/examples/SpeedTest/SpeedTest.ino @@ -44,9 +44,7 @@ void DoTest(FS *fs) { } uint8_t data[256]; - for (int i = 0; i < 256; i++) { - data[i] = (uint8_t) i; - } + for (int i = 0; i < 256; i++) { data[i] = (uint8_t)i; } Serial.printf("Creating %dKB file, may take a while...\n", TESTSIZEKB); unsigned long start = millis(); @@ -56,9 +54,7 @@ void DoTest(FS *fs) { return; } for (int i = 0; i < TESTSIZEKB; i++) { - for (int j = 0; j < 4; j++) { - f.write(data, 256); - } + for (int j = 0; j < 4; j++) { f.write(data, 256); } } f.close(); unsigned long stop = millis(); @@ -72,9 +68,7 @@ void DoTest(FS *fs) { start = millis(); f = fs->open("/testwrite.bin", "r"); for (int i = 0; i < TESTSIZEKB; i++) { - for (int j = 0; j < 4; j++) { - f.read(data, 256); - } + for (int j = 0; j < 4; j++) { f.read(data, 256); } } f.close(); stop = millis(); @@ -85,9 +79,7 @@ void DoTest(FS *fs) { f = fs->open("/testwrite.bin", "r"); f.read(); for (int i = 0; i < TESTSIZEKB; i++) { - for (int j = 0; j < 4; j++) { - f.read(data + 1, 256); - } + for (int j = 0; j < 4; j++) { f.read(data + 1, 256); } } f.close(); stop = millis(); @@ -115,9 +107,7 @@ void DoTest(FS *fs) { Serial.printf("Writing 64K file in 1-byte chunks\n"); start = millis(); f = fs->open("/test1b.bin", "w"); - for (int i = 0; i < 65536; i++) { - f.write((uint8_t*)&i, 1); - } + for (int i = 0; i < 65536; i++) { f.write((uint8_t *)&i, 1); } f.close(); stop = millis(); Serial.printf("==> Time to write 64KB in 1b chunks = %lu milliseconds = %s\n", stop - start, rate(start, stop, 65536)); @@ -127,7 +117,7 @@ void DoTest(FS *fs) { f = fs->open("/test1b.bin", "r"); for (int i = 0; i < 65536; i++) { char c; - f.read((uint8_t*)&c, 1); + f.read((uint8_t *)&c, 1); } f.close(); stop = millis(); diff --git a/libraries/Netdump/examples/Netdump/Netdump.ino b/libraries/Netdump/examples/Netdump/Netdump.ino index dbba63869b..37210a8a0a 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; @@ -20,43 +20,36 @@ const char* password = STAPSK; Netdump nd; -//FS* filesystem = &SPIFFS; +// 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; -enum class SerialOption : uint8_t { - AllFull, - LocalNone, - HTTPChar -}; +enum class SerialOption : uint8_t { AllFull, + LocalNone, + HTTPChar }; 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 - nd.printDump(Serial, Packet::PacketDetail::NONE, - [](Packet n) { + 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 - nd.printDump(Serial, Packet::PacketDetail::CHAR, - [](Packet n) { + case SerialOption::HTTPChar: // Only HTTP traffic, show packet content as chars + nd.printDump(Serial, Packet::PacketDetail::CHAR, [](Packet n) { return (n.isHTTP()); - } - ); + }); break; - default : - Serial.printf("No valid SerialOption provided\r\n"); + default: Serial.printf("No valid SerialOption provided\r\n"); }; } @@ -80,49 +73,39 @@ void setup(void) { if (WiFi.waitForConnectResult() != WL_CONNECTED) { Serial.println("WiFi Failed, stopping sketch"); - while (1) { - delay(1000); - } + while (1) { delay(1000); } } - if (!MDNS.begin("netdumphost")) { - Serial.println("Error setting up MDNS responder!"); - } + if (!MDNS.begin("netdumphost")) { Serial.println("Error setting up MDNS responder!"); } filesystem->begin(); - webServer.on("/list", - []() { + webServer.on("/list", []() { Dir dir = filesystem->openDir("/"); String d = "

    File list

    "; while (dir.next()) { d.concat("
  3. " + dir.fileName() + "
  4. "); } webServer.send(200, "text.html", d); - } - ); + }); - webServer.on("/req", - []() { + 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", - []() { + webServer.on("/reset", []() { nd.reset(); 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 @@ -132,18 +115,18 @@ void setup(void) { 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"); + 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 +136,3 @@ void loop(void) { webServer.handleClient(); MDNS.update(); } - diff --git a/libraries/Netdump/src/Netdump.cpp b/libraries/Netdump/src/Netdump.cpp index 4d4deb05b2..6cee79a646 100644 --- a/libraries/Netdump/src/Netdump.cpp +++ b/libraries/Netdump/src/Netdump.cpp @@ -23,7 +23,6 @@ #include #include "Schedule.h" - namespace NetCapture { @@ -69,24 +68,26 @@ 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]; @@ -98,10 +99,11 @@ bool Netdump::tcpDump(WiFiServer &tcpDumpServer, const Filter nf) } bufferIndex = 0; - schedule_function([&tcpDumpServer, this, nf]() - { - tcpDumpLoop(tcpDumpServer, nf); - }); + schedule_function( + [&tcpDumpServer, this, nf]() + { + tcpDumpLoop(tcpDumpServer, nf); + }); return true; } @@ -109,7 +111,8 @@ 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 +121,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 +134,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); @@ -145,7 +148,7 @@ void Netdump::printDumpProcess(Print& out, Packet::PacketDetail ndd, const Packe void Netdump::fileDumpProcess(File& outfile, const Packet& np) const { - size_t incl_len = np.getPacketSize() > maxPcapLength ? maxPcapLength : np.getPacketSize(); + size_t incl_len = np.getPacketSize() > maxPcapLength ? maxPcapLength : np.getPacketSize(); uint32_t pcapHeader[4]; struct timeval tv; @@ -154,7 +157,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 +171,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[1] = tv.tv_usec; - pcapHeader[2] = incl_len; - pcapHeader[3] = np.getPacketSize(); - bufferIndex += 16; // pcap header size + 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 memcpy(&packetBuffer[bufferIndex], np.rawData(), incl_len); bufferIndex += incl_len; } @@ -189,7 +192,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 +202,12 @@ 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()) { @@ -216,11 +221,12 @@ void Netdump::tcpDumpLoop(WiFiServer &tcpDumpServer, const Filter nf) if (tcpDumpServer.status() != CLOSED) { - schedule_function([&tcpDumpServer, this, nf]() - { - tcpDumpLoop(tcpDumpServer, nf); - }); + schedule_function( + [&tcpDumpServer, this, nf]() + { + tcpDumpLoop(tcpDumpServer, nf); + }); } } -} // namespace NetCapture +} // namespace NetCapture diff --git a/libraries/Netdump/src/Netdump.h b/libraries/Netdump/src/Netdump.h index 0e8b6cbb00..928000622b 100644 --- a/libraries/Netdump/src/Netdump.h +++ b/libraries/Netdump/src/Netdump.h @@ -38,9 +38,8 @@ using namespace experimental::CBListImplentation; class Netdump { public: - - using Filter = std::function; - using Callback = std::function; + using Filter = std::function; + using Callback = std::function; using LwipCallback = std::function; Netdump(); @@ -53,15 +52,14 @@ 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: Callback netDumpCallback = nullptr; Filter netDumpFilter = nullptr; static void capture(int netif_idx, const char* data, size_t len, int out, int success); - static CallBackList lwipCallback; + static CallBackList lwipCallback; CallBackList::CallBackHandler lwipHandler; void netdumpCapture(int netif_idx, const char* data, size_t len, int out, int success); @@ -69,19 +67,19 @@ 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; WiFiClient tcpDumpClient; - char* packetBuffer = nullptr; - int bufferIndex = 0; + char* packetBuffer = nullptr; + int bufferIndex = 0; - static constexpr int tcpBufferSize = 2048; - static constexpr int maxPcapLength = 1024; - static constexpr uint32_t pcapMagic = 0xa1b2c3d4; + static constexpr int tcpBufferSize = 2048; + static constexpr int maxPcapLength = 1024; + 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..f71b618f1d 100644 --- a/libraries/Netdump/src/NetdumpIP.cpp +++ b/libraries/Netdump/src/NetdumpIP.cpp @@ -24,11 +24,10 @@ namespace NetCapture { -NetdumpIP::NetdumpIP() -{ -} +NetdumpIP::NetdumpIP() { } -NetdumpIP::NetdumpIP(uint8_t first_octet, uint8_t second_octet, uint8_t third_octet, uint8_t fourth_octet) +NetdumpIP::NetdumpIP(uint8_t first_octet, uint8_t second_octet, uint8_t third_octet, + uint8_t fourth_octet) { setV4(); (*this)[0] = first_octet; @@ -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,12 +96,12 @@ 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 - uint8_t dots = 0; + uint16_t acc = 0; // Accumulator + uint8_t dots = 0; while (*address) { @@ -124,7 +123,7 @@ bool NetdumpIP::fromString4(const char *address) return false; } (*this)[dots++] = acc; - acc = 0; + acc = 0; } else { @@ -144,12 +143,12 @@ 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 - int dots = 0, doubledots = -1; + 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,22 +180,22 @@ bool NetdumpIP::fromString6(const char *address) address++; } if (dots == 7) - // too many separators + // too many separators { return false; } reinterpret_cast(rawip)[dots++] = PP_HTONS(acc); - acc = 0; + acc = 0; } else - // Invalid char + // Invalid char { return false; } } if (doubledots == -1 && dots != 7) - // Too few separators + // Too few separators { return false; } @@ -206,7 +205,8 @@ bool NetdumpIP::fromString6(const char *address) { for (int i = dots - doubledots - 1; i >= 0; i--) { - reinterpret_cast(rawip)[8 - dots + doubledots + i] = reinterpret_cast(rawip)[doubledots + i]; + reinterpret_cast(rawip)[8 - dots + doubledots + i] + = reinterpret_cast(rawip)[doubledots + i]; } for (int i = doubledots; i < 8 - dots + doubledots; i++) { @@ -223,12 +223,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 +252,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 +279,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,7 +295,7 @@ bool NetdumpIP::compareIP(const IPAddress& ip) const { switch (ipv) { - case IPversion::UNSET : + case IPversion::UNSET: if (ip.isSet()) { return false; @@ -306,7 +305,7 @@ bool NetdumpIP::compareIP(const IPAddress& ip) const return true; } break; - case IPversion::IPV4 : + case IPversion::IPV4: if (ip.isV6() || !ip.isSet()) { return false; @@ -316,7 +315,7 @@ bool NetdumpIP::compareIP(const IPAddress& ip) const return compareRaw(IPversion::IPV4, rawip, reinterpret_cast(&ip.v4())); } break; - case IPversion::IPV6 : + case IPversion::IPV6: if (ip.isV4() || !ip.isSet()) { return false; @@ -326,7 +325,7 @@ bool NetdumpIP::compareIP(const IPAddress& ip) const return compareRaw(IPversion::IPV6, rawip, reinterpret_cast(ip.raw6())); } break; - default : + default: return false; break; } @@ -336,7 +335,7 @@ bool NetdumpIP::compareIP(const NetdumpIP& nip) const { switch (ipv) { - case IPversion::UNSET : + case IPversion::UNSET: if (nip.isSet()) { return false; @@ -346,7 +345,7 @@ bool NetdumpIP::compareIP(const NetdumpIP& nip) const return true; } break; - case IPversion::IPV4 : + case IPversion::IPV4: if (nip.isV6() || !nip.isSet()) { return false; @@ -356,7 +355,7 @@ bool NetdumpIP::compareIP(const NetdumpIP& nip) const return compareRaw(IPversion::IPV4, rawip, nip.rawip); } break; - case IPversion::IPV6 : + case IPversion::IPV6: if (nip.isV4() || !nip.isSet()) { return false; @@ -366,10 +365,10 @@ bool NetdumpIP::compareIP(const NetdumpIP& nip) const return compareRaw(IPversion::IPV6, rawip, nip.rawip); } break; - default : + default: return false; break; } } -} // namespace NetCapture +} // namespace NetCapture diff --git a/libraries/Netdump/src/NetdumpIP.h b/libraries/Netdump/src/NetdumpIP.h index 8a450c374a..18747a9103 100644 --- a/libraries/Netdump/src/NetdumpIP.h +++ b/libraries/Netdump/src/NetdumpIP.h @@ -22,7 +22,7 @@ class NetdumpIP 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,15 +31,20 @@ class NetdumpIP return rawip[index]; } - bool fromString(const char *address); + bool fromString(const char* address); String toString(); private: - enum class IPversion {UNSET, IPV4, IPV6}; + enum class IPversion + { + UNSET, + IPV4, + IPV6 + }; IPversion ipv = IPversion::UNSET; - uint8_t rawip[16] = {0}; + uint8_t rawip[16] = { 0 }; void setV4() { @@ -70,14 +75,15 @@ 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: bool operator==(const IPAddress& addr) const { @@ -95,9 +101,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..49efaecc1a 100644 --- a/libraries/Netdump/src/NetdumpPacket.cpp +++ b/libraries/Netdump/src/NetdumpPacket.cpp @@ -25,7 +25,8 @@ namespace NetCapture { -void Packet::printDetail(Print& out, const String& indent, const char* data, size_t size, PacketDetail pd) const +void Packet::printDetail(Print& out, const String& indent, const char* data, size_t size, + PacketDetail pd) const { if (pd == PacketDetail::NONE) { @@ -159,21 +160,24 @@ 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()); + 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()); + 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); + printDetail(sstr, PSTR(" D "), &data[ETH_HDR_LEN], packetLength - ETH_HDR_LEN, + netdumpDetail); } void Packet::DNStoString(PacketDetail netdumpDetail, StreamString& sstr) const @@ -198,8 +202,10 @@ void Packet::DNStoString(PacketDetail netdumpDetail, StreamString& sstr) const sstr.printf_P(PSTR("DR=%d "), t); } sstr.printf_P(PSTR("\r\n")); - printDetail(sstr, PSTR(" H "), &data[ETH_HDR_LEN + getIpHdrLen()], getUdpHdrLen(), netdumpDetail); - printDetail(sstr, PSTR(" D "), &data[ETH_HDR_LEN + getIpHdrLen() + getUdpHdrLen()], getUdpLen(), netdumpDetail); + printDetail(sstr, PSTR(" H "), &data[ETH_HDR_LEN + getIpHdrLen()], getUdpHdrLen(), + netdumpDetail); + printDetail(sstr, PSTR(" D "), &data[ETH_HDR_LEN + getIpHdrLen() + getUdpHdrLen()], + getUdpLen(), netdumpDetail); } void Packet::UDPtoString(PacketDetail netdumpDetail, StreamString& sstr) const @@ -207,8 +213,10 @@ void Packet::UDPtoString(PacketDetail netdumpDetail, StreamString& sstr) const sstr.printf_P(PSTR("%s>%s "), sourceIP().toString().c_str(), destIP().toString().c_str()); sstr.printf_P(PSTR("%d:%d"), getSrcPort(), getDstPort()); sstr.printf_P(PSTR("\r\n")); - printDetail(sstr, PSTR(" H "), &data[ETH_HDR_LEN + getIpHdrLen()], getUdpHdrLen(), netdumpDetail); - printDetail(sstr, PSTR(" D "), &data[ETH_HDR_LEN + getIpHdrLen() + getUdpHdrLen()], getUdpLen(), netdumpDetail); + printDetail(sstr, PSTR(" H "), &data[ETH_HDR_LEN + getIpHdrLen()], getUdpHdrLen(), + netdumpDetail); + printDetail(sstr, PSTR(" D "), &data[ETH_HDR_LEN + getIpHdrLen() + getUdpHdrLen()], + getUdpLen(), netdumpDetail); } void Packet::TCPtoString(PacketDetail netdumpDetail, StreamString& sstr) const @@ -217,17 +225,20 @@ 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)) { sstr.print(chars[i]); } sstr.print(']'); - sstr.printf_P(PSTR(" len: %u seq: %u, ack: %u, wnd: %u "), getTcpLen(), getTcpSeq(), getTcpAck(), getTcpWindow()); + sstr.printf_P(PSTR(" len: %u seq: %u, ack: %u, wnd: %u "), getTcpLen(), getTcpSeq(), + getTcpAck(), getTcpWindow()); sstr.printf_P(PSTR("\r\n")); - printDetail(sstr, PSTR(" H "), &data[ETH_HDR_LEN + getIpHdrLen()], getTcpHdrLen(), netdumpDetail); - printDetail(sstr, PSTR(" D "), &data[ETH_HDR_LEN + getIpHdrLen() + getTcpHdrLen()], getTcpLen(), netdumpDetail); + printDetail(sstr, PSTR(" H "), &data[ETH_HDR_LEN + getIpHdrLen()], getTcpHdrLen(), + netdumpDetail); + printDetail(sstr, PSTR(" D "), &data[ETH_HDR_LEN + getIpHdrLen() + getTcpHdrLen()], + getTcpLen(), netdumpDetail); } void Packet::ICMPtoString(PacketDetail, StreamString& sstr) const @@ -237,20 +248,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 +287,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")); } @@ -281,7 +332,8 @@ void Packet::IPtoString(PacketDetail netdumpDetail, StreamString& sstr) const sstr.printf_P(PSTR("%s>%s "), sourceIP().toString().c_str(), destIP().toString().c_str()); sstr.printf_P(PSTR("Unknown IP type : %d\r\n"), ipType()); printDetail(sstr, PSTR(" H "), &data[ETH_HDR_LEN], getIpHdrLen(), netdumpDetail); - printDetail(sstr, PSTR(" D "), &data[ETH_HDR_LEN + getIpHdrLen()], getIpTotalLen() - getIpHdrLen(), netdumpDetail); + printDetail(sstr, PSTR(" D "), &data[ETH_HDR_LEN + getIpHdrLen()], + getIpTotalLen() - getIpHdrLen(), netdumpDetail); } void Packet::UKNWtoString(PacketDetail, StreamString& sstr) const @@ -298,13 +350,13 @@ const String Packet::toString() const return toString(PacketDetail::NONE); } - const String Packet::toString(PacketDetail netdumpDetail) const { StreamString sstr; sstr.reserve(128); - sstr.printf_P(PSTR("%d %3s %-4s "), netif_idx, out ? "out" : "in ", packetType().toString().c_str()); + sstr.printf_P(PSTR("%d %3s %-4s "), netif_idx, out ? "out" : "in ", + packetType().toString().c_str()); if (netdumpDetail == PacketDetail::RAW) { @@ -320,56 +372,56 @@ const String Packet::toString(PacketDetail netdumpDetail) const switch (thisPacketType) { - case PacketType::ARP : + case PacketType::ARP: { ARPtoString(netdumpDetail, sstr); break; } - case PacketType::MDNS : - case PacketType::DNS : + 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 : + 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 : + case PacketType::TCP: + case PacketType::HTTP: { TCPtoString(netdumpDetail, sstr); break; } - case PacketType::ICMP : + case PacketType::ICMP: { ICMPtoString(netdumpDetail, sstr); break; } - case PacketType::IGMP : + case PacketType::IGMP: { IGMPtoString(netdumpDetail, sstr); break; } - case PacketType::IPv4 : - case PacketType::IPv6 : + case PacketType::IPv4: + case PacketType::IPv6: { IPtoString(netdumpDetail, sstr); break; } - case PacketType::UKNW : + case PacketType::UKNW: { UKNWtoString(netdumpDetail, sstr); break; } - default : + default: { sstr.printf_P(PSTR("Non identified packet\r\n")); break; @@ -378,4 +430,4 @@ const String Packet::toString(PacketDetail netdumpDetail) const return sstr; } -} // namespace NetCapture +} // namespace NetCapture diff --git a/libraries/Netdump/src/NetdumpPacket.h b/libraries/Netdump/src/NetdumpPacket.h index a898ef230f..37e20abb2e 100644 --- a/libraries/Netdump/src/NetdumpPacket.h +++ b/libraries/Netdump/src/NetdumpPacket.h @@ -37,8 +37,8 @@ int constexpr ETH_HDR_LEN = 14; class Packet { 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) + 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) { setPacketTypes(); }; @@ -75,7 +75,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 +87,18 @@ 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 +116,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 +137,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 +245,7 @@ class Packet return ip; }; - bool hasIP(NetdumpIP ip) const + bool hasIP(NetdumpIP ip) const { return (isIP() && ((ip == sourceIP()) || (ip == destIP()))); } @@ -270,21 +271,20 @@ 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))); } const String toString() const; const String toString(PacketDetail netdumpDetail) const; - void printDetail(Print& out, const String& indent, const char* data, size_t size, PacketDetail pd) const; + void printDetail(Print& out, const String& indent, const char* data, size_t size, + PacketDetail pd) const; - const PacketType packetType() const; + const PacketType packetType() const; const std::vector& allPacketTypes() const; - private: - void setPacketType(PacketType); void setPacketTypes(); @@ -298,17 +298,16 @@ 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; - size_t packetLength; - int out; - int success; - PacketType thisPacketType; + time_t packetTime; + int netif_idx; + const char* data; + size_t packetLength; + int out; + int success; + PacketType thisPacketType; 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..9e08e31c23 100644 --- a/libraries/Netdump/src/PacketType.cpp +++ b/libraries/Netdump/src/PacketType.cpp @@ -10,33 +10,50 @@ namespace NetCapture { -PacketType::PacketType() -{ -} +PacketType::PacketType() { } 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..bbf5b61d64 100644 --- a/libraries/Netdump/src/PacketType.h +++ b/libraries/Netdump/src/PacketType.h @@ -15,7 +15,6 @@ namespace NetCapture class PacketType { public: - enum PType : int { ARP, diff --git a/libraries/SD/examples/Datalogger/Datalogger.ino b/libraries/SD/examples/Datalogger/Datalogger.ino index a023b63821..c71149f41a 100644 --- a/libraries/SD/examples/Datalogger/Datalogger.ino +++ b/libraries/SD/examples/Datalogger/Datalogger.ino @@ -48,9 +48,7 @@ void loop() { for (int analogPin = 0; analogPin < 3; analogPin++) { int sensor = analogRead(analogPin); dataString += String(sensor); - if (analogPin < 2) { - dataString += ","; - } + if (analogPin < 2) { dataString += ","; } } // open the file. note that only one file can be open at a time, @@ -65,16 +63,5 @@ void loop() { Serial.println(dataString); } // if the file isn't open, pop up an error: - else { - Serial.println("error opening datalog.txt"); - } + else { Serial.println("error opening datalog.txt"); } } - - - - - - - - - diff --git a/libraries/SD/examples/DumpFile/DumpFile.ino b/libraries/SD/examples/DumpFile/DumpFile.ino index 3574652890..f96861db1d 100644 --- a/libraries/SD/examples/DumpFile/DumpFile.ino +++ b/libraries/SD/examples/DumpFile/DumpFile.ino @@ -45,17 +45,11 @@ void setup() { // if the file is available, write to it: if (dataFile) { - while (dataFile.available()) { - Serial.write(dataFile.read()); - } + while (dataFile.available()) { Serial.write(dataFile.read()); } dataFile.close(); } // if the file isn't open, pop up an error: - else { - Serial.println("error opening datalog.txt"); - } -} - -void loop() { + else { Serial.println("error opening datalog.txt"); } } +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..90742198b9 100644 --- a/libraries/SD/examples/ReadWrite/ReadWrite.ino +++ b/libraries/SD/examples/ReadWrite/ReadWrite.ino @@ -57,9 +57,7 @@ void setup() { Serial.println("test.txt:"); // read from the file until there's nothing else in it: - while (myFile.available()) { - Serial.write(myFile.read()); - } + while (myFile.available()) { Serial.write(myFile.read()); } // close the file: myFile.close(); } else { @@ -71,5 +69,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..1eaec2300d 100644 --- a/libraries/SD/examples/listfiles/listfiles.ino +++ b/libraries/SD/examples/listfiles/listfiles.ino @@ -52,14 +52,12 @@ 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; } - for (uint8_t i = 0; i < numTabs; i++) { - Serial.print('\t'); - } + for (uint8_t i = 0; i < numTabs; i++) { Serial.print('\t'); } Serial.print(entry.name()); if (entry.isDirectory()) { Serial.println("/"); @@ -70,7 +68,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..5e97614366 100644 --- a/libraries/SPISlave/examples/SPISlave_Master/SPISlave_Master.ino +++ b/libraries/SPISlave/examples/SPISlave_Master/SPISlave_Master.ino @@ -17,73 +17,68 @@ #include class ESPMaster { - private: - uint8_t _ss_pin; +private: + uint8_t _ss_pin; - public: - ESPMaster(uint8_t pin): _ss_pin(pin) {} - void begin() { - pinMode(_ss_pin, OUTPUT); - digitalWrite(_ss_pin, HIGH); - } +public: + 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++]); } + while (i++ < 32) { SPI.transfer(0); } + digitalWrite(_ss_pin, HIGH); + } - String readData() { - char data[33]; - data[32] = 0; - readData((uint8_t *)data); - return String(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)); - } + 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..95d407f271 100644 --- a/libraries/SPISlave/examples/SPISlave_SafeMaster/SPISlave_SafeMaster.ino +++ b/libraries/SPISlave/examples/SPISlave_SafeMaster/SPISlave_SafeMaster.ino @@ -18,77 +18,73 @@ #include class ESPSafeMaster { - private: - 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(); - } +private: + uint8_t _ss_pin; + void _pulseSS() { + digitalWrite(_ss_pin, HIGH); + delayMicroseconds(5); + digitalWrite(_ss_pin, LOW); + } - 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; - } +public: + ESPSafeMaster(uint8_t pin) + : _ss_pin(pin) {} + void begin() { + pinMode(_ss_pin, OUTPUT); + _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(); - } + 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 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 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 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 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(); + } - String readData() { - char data[33]; - data[32] = 0; - readData((uint8_t *)data); - return String(data); - } + 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(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..3b8bf0e01c 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) { + SPISlave.onData([](uint8_t *data, size_t len) { String message = String((char *)data); - (void) len; + (void)len; if (message.equals("Hello Slave!")) { SPISlave.setData("Hello Master!"); } else if (message.equals("Are you alive?")) { @@ -50,7 +50,7 @@ void setup() { // Can be used to exchange small data or status information SPISlave.onStatus([](uint32_t data) { Serial.printf("Status: %u\n", data); - SPISlave.setStatus(millis()); //set next status + SPISlave.setStatus(millis()); // set next status }); // The master has read the status register diff --git a/libraries/Servo/examples/Sweep/Sweep.ino b/libraries/Servo/examples/Sweep/Sweep.ino index 5a6bd6ef40..9149366df2 100644 --- a/libraries/Servo/examples/Sweep/Sweep.ino +++ b/libraries/Servo/examples/Sweep/Sweep.ino @@ -23,14 +23,13 @@ void setup() { void loop() { int pos; - for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees + 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 + 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 } } - diff --git a/libraries/TFT_Touch_Shield_V2/examples/drawCircle/drawCircle.ino b/libraries/TFT_Touch_Shield_V2/examples/drawCircle/drawCircle.ino index fbc22a861c..6c2d2171de 100644 --- a/libraries/TFT_Touch_Shield_V2/examples/drawCircle/drawCircle.ino +++ b/libraries/TFT_Touch_Shield_V2/examples/drawCircle/drawCircle.ino @@ -8,22 +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() { - -} +void loop() {} /********************************************************************************************************* END FILE diff --git a/libraries/TFT_Touch_Shield_V2/examples/drawLines/drawLines.ino b/libraries/TFT_Touch_Shield_V2/examples/drawLines/drawLines.ino index a777044d3e..9a2b02d3e0 100644 --- a/libraries/TFT_Touch_Shield_V2/examples/drawLines/drawLines.ino +++ b/libraries/TFT_Touch_Shield_V2/examples/drawLines/drawLines.ino @@ -8,21 +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 // start: (60, 100) length: 100 color: green - Tft.drawHorizontalLine(30, 60, 150, BLUE); //Draw a horizontal line - //start: (30, 60), high: 150, color: blue + Tft.drawHorizontalLine(30, 60, 150, BLUE); // Draw a horizontal line + // start: (30, 60), high: 150, color: blue } -void loop() { - -} +void loop() {} /********************************************************************************************************* END FILE diff --git a/libraries/TFT_Touch_Shield_V2/examples/drawNumber/drawNumber.ino b/libraries/TFT_Touch_Shield_V2/examples/drawNumber/drawNumber.ino index ed62233796..35dfc3d6e0 100644 --- a/libraries/TFT_Touch_Shield_V2/examples/drawNumber/drawNumber.ino +++ b/libraries/TFT_Touch_Shield_V2/examples/drawNumber/drawNumber.ino @@ -9,29 +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() { - -} +void loop() {} /********************************************************************************************************* END FILE diff --git a/libraries/TFT_Touch_Shield_V2/examples/drawRectangle/drawRectangle.ino b/libraries/TFT_Touch_Shield_V2/examples/drawRectangle/drawRectangle.ino index a2d7af8709..0819c77c9b 100644 --- a/libraries/TFT_Touch_Shield_V2/examples/drawRectangle/drawRectangle.ino +++ b/libraries/TFT_Touch_Shield_V2/examples/drawRectangle/drawRectangle.ino @@ -16,9 +16,7 @@ void setup() { Tft.drawRectangle(100, 170, 120, 60, BLUE); } -void loop() { - -} +void loop() {} /********************************************************************************************************* END FILE *********************************************************************************************************/ \ No newline at end of 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..39826866b9 100644 --- a/libraries/TFT_Touch_Shield_V2/examples/paint/paint.ino +++ b/libraries/TFT_Touch_Shield_V2/examples/paint/paint.ino @@ -5,29 +5,27 @@ #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 // The 2.8" TFT Touch shield has 300 ohms across the X plate -TouchScreen ts = TouchScreen(XP, YP, XM, YM); //init TouchScreen port pins +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++) { - Tft.fillRectangle(i * 30, 0, 30, ColorPaletteHigh, colors[i]); - } + // Draw the pallet + for (int i = 0; i < 8; i++) { Tft.fillRectangle(i * 30, 0, 30, ColorPaletteHigh, colors[i]); } } void loop() { // a point object holds x y and z coordinates. Point p = ts.getPoint(); - //map the ADC value read to into pixel coordinates + // map the ADC value read to into pixel coordinates p.x = map(p.x, TS_MINX, TS_MAXX, 0, 240); p.y = map(p.y, TS_MINY, TS_MAXY, 0, 320); diff --git a/libraries/TFT_Touch_Shield_V2/examples/shapes/shapes.ino b/libraries/TFT_Touch_Shield_V2/examples/shapes/shapes.ino index 6607a01cff..5a1e960c9c 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..b02dedbe98 100644 --- a/libraries/TFT_Touch_Shield_V2/examples/text/text.ino +++ b/libraries/TFT_Touch_Shield_V2/examples/text/text.ino @@ -11,23 +11,19 @@ void setup() { 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.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 + 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("World!!", 60, 220, 4, WHITE); // draw string: "world!!", (80, 230), size: 4, color: WHITE } -void loop() { - -} +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..691f5be7ca 100644 --- a/libraries/TFT_Touch_Shield_V2/examples/tftbmp/tftbmp.ino +++ b/libraries/TFT_Touch_Shield_V2/examples/tftbmp/tftbmp.ino @@ -16,21 +16,22 @@ #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", @@ -54,7 +55,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 +67,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 +83,6 @@ void loop() { delay(1000); } - } /*********************************************/ @@ -90,15 +92,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,9 +112,9 @@ 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] = __color[k] << 6 | (sdbuffer[buffidx + 1] >> 2); // green - __color[k] = __color[k] << 5 | (sdbuffer[buffidx + 0] >> 3); // blue + __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 buffidx += 3; } @@ -131,7 +133,6 @@ void bmpdraw(File f, int x, int y) { TFT_CS_HIGH; } - } Serial.print(millis() - time, DEC); @@ -169,13 +170,11 @@ 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; } - if (read16(f) != 1) { - return false; - } + if (read16(f) != 1) { return false; } bmpDepth = read16(f); Serial.print("bitdepth "); diff --git a/libraries/TFT_Touch_Shield_V2/examples/tftbmp2/tftbmp2.ino b/libraries/TFT_Touch_Shield_V2/examples/tftbmp2/tftbmp2.ino index 03423a4ef5..0a698fb150 100644 --- a/libraries/TFT_Touch_Shield_V2/examples/tftbmp2/tftbmp2.ino +++ b/libraries/TFT_Touch_Shield_V2/examples/tftbmp2/tftbmp2.ino @@ -18,18 +18,19 @@ #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; @@ -37,44 +38,30 @@ File bmpFile; bool checkBMP(char *_name, char r_name[]) { int len = 0; - if (NULL == _name) { - return false; - } + if (NULL == _name) { return false; } while (*_name) { r_name[len++] = *(_name++); - if (len > FILENAME_LEN) { - return false; - } + if (len > FILENAME_LEN) { return false; } } r_name[len] = '\0'; - if (len < 5) { - return false; - } + if (len < 5) { return false; } // 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')) \ - && (r_name[len - 1] == 'p' || (r_name[len - 1] == 'P'))) { - return true; - } + 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) { - break; - } + if (!entry) { break; } if (!entry.isDirectory()) { char *ptmp = entry.name(); @@ -94,9 +81,7 @@ void searchDirectory() { Serial.print(__Gnfile_num); Serial.println(" file: "); - for (int i = 0; i < __Gnfile_num; i++) { - Serial.println(__Gsbmp_files[i]); - } + for (int i = 0; i < __Gnfile_num; i++) { Serial.println(__Gsbmp_files[i]); } } @@ -114,7 +99,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!"); @@ -153,12 +139,13 @@ 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 +153,8 @@ void loop() { bmpdraw(bmpFile, 0, 0, 1); bmpFile.close(); - while (1); + while (1) + ; } /*********************************************/ @@ -176,12 +164,12 @@ 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,12 +182,10 @@ 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) { - bmpFile.seek(__Gnbmp_image_offset + (__Gnbmp_height - 1 - i) * 240 * 3); - } + if (dir) { bmpFile.seek(__Gnbmp_image_offset + (__Gnbmp_height - 1 - i) * 240 * 3); } for (int j = 0; j < (240 / BUFFPIXEL); j++) { @@ -210,9 +196,9 @@ 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] = __color[k] << 6 | (sdbuffer[buffidx + 1] >> 2); // green - __color[k] = __color[k] << 5 | (sdbuffer[buffidx + 0] >> 3); // blue + __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 buffidx += 3; } @@ -239,7 +225,6 @@ void bmpdraw(File f, int x, int y, int dir) { TFT_CS_HIGH; } - } Serial.print(millis() - time, DEC); @@ -276,13 +261,11 @@ 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; } - if (read16(f) != 1) { - return false; - } + if (read16(f) != 1) { return false; } bmpDepth = read16(f); Serial.print("bitdepth "); diff --git a/libraries/Ticker/examples/TickerBasic/TickerBasic.ino b/libraries/Ticker/examples/TickerBasic/TickerBasic.ino index 2fabd98315..4ccbe3a2e6 100644 --- a/libraries/Ticker/examples/TickerBasic/TickerBasic.ino +++ b/libraries/Ticker/examples/TickerBasic/TickerBasic.ino @@ -24,9 +24,7 @@ void flip() { ++count; // when the counter reaches a certain value, start blinking like crazy - if (count == 20) { - flipper.attach(0.1, flip); - } + if (count == 20) { flipper.attach(0.1, flip); } // when the counter reaches yet another value, stop blinking else if (count == 120) { flipper.detach(); @@ -41,5 +39,4 @@ void setup() { flipper.attach(0.3, flip); } -void loop() { -} +void loop() {} diff --git a/libraries/Ticker/examples/TickerFunctional/TickerFunctional.ino b/libraries/Ticker/examples/TickerFunctional/TickerFunctional.ino index 33c9435982..a023adfdd8 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)); - } +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)); + } }; void staticBlink() { @@ -60,5 +61,4 @@ void setup() { }); } -void loop() { -} +void loop() {} diff --git a/libraries/Ticker/examples/TickerParameter/TickerParameter.ino b/libraries/Ticker/examples/TickerParameter/TickerParameter.ino index 8263c0bb56..0c49eaf4ff 100644 --- a/libraries/Ticker/examples/TickerParameter/TickerParameter.ino +++ b/libraries/Ticker/examples/TickerParameter/TickerParameter.ino @@ -46,5 +46,4 @@ void setup() { tickerSetChar.attach_ms(26, setPinChar, (char)1); } -void loop() { -} +void loop() {} diff --git a/libraries/Wire/Wire.cpp b/libraries/Wire/Wire.cpp index e9fc796bbf..b2d9a6affc 100644 --- a/libraries/Wire/Wire.cpp +++ b/libraries/Wire/Wire.cpp @@ -22,7 +22,8 @@ Modified January 2017 by Bjorn Hammarberg (bjoham@esp8266.com) - i2c slave support */ -extern "C" { +extern "C" +{ #include #include #include @@ -31,9 +32,8 @@ extern "C" { #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. +// Some boards don't have these pins available, and hence don't support Wire. +// Check here for compile-time error. #if !defined(PIN_WIRE_SDA) || !defined(PIN_WIRE_SCL) #error Wire library is not supported on this board #endif @@ -41,13 +41,13 @@ extern "C" { // Initialize Class Variables ////////////////////////////////////////////////// uint8_t TwoWire::rxBuffer[I2C_BUFFER_LENGTH]; -size_t TwoWire::rxBufferIndex = 0; -size_t TwoWire::rxBufferLength = 0; +size_t TwoWire::rxBufferIndex = 0; +size_t TwoWire::rxBufferLength = 0; uint8_t TwoWire::txAddress = 0; uint8_t TwoWire::txBuffer[I2C_BUFFER_LENGTH]; -size_t TwoWire::txBufferIndex = 0; -size_t TwoWire::txBufferLength = 0; +size_t TwoWire::txBufferIndex = 0; +size_t TwoWire::txBufferLength = 0; uint8_t TwoWire::transmitting = 0; void (*TwoWire::user_onRequest)(void); @@ -58,7 +58,7 @@ static int default_scl_pin = SCL; // Constructors //////////////////////////////////////////////////////////////// -TwoWire::TwoWire() {} +TwoWire::TwoWire() { } // Public Methods ////////////////////////////////////////////////////////////// @@ -126,8 +126,8 @@ size_t TwoWire::requestFrom(uint8_t address, size_t size, bool sendStop) { size = I2C_BUFFER_LENGTH; } - size_t read = (twi_readFrom(address, rxBuffer, size, sendStop) == 0) ? size : 0; - rxBufferIndex = 0; + size_t read = (twi_readFrom(address, rxBuffer, size, sendStop) == 0) ? size : 0; + rxBufferIndex = 0; rxBufferLength = read; return read; } @@ -149,14 +149,15 @@ uint8_t TwoWire::requestFrom(int address, int quantity) uint8_t TwoWire::requestFrom(int address, int quantity, int sendStop) { - return requestFrom(static_cast(address), static_cast(quantity), static_cast(sendStop)); + return requestFrom(static_cast(address), static_cast(quantity), + static_cast(sendStop)); } void TwoWire::beginTransmission(uint8_t address) { - transmitting = 1; - txAddress = address; - txBufferIndex = 0; + transmitting = 1; + txAddress = address; + txBufferIndex = 0; txBufferLength = 0; } @@ -167,10 +168,10 @@ void TwoWire::beginTransmission(int address) uint8_t TwoWire::endTransmission(uint8_t sendStop) { - int8_t ret = twi_writeTo(txAddress, txBuffer, txBufferLength, sendStop); - txBufferIndex = 0; + int8_t ret = twi_writeTo(txAddress, txBuffer, txBufferLength, sendStop); + txBufferIndex = 0; txBufferLength = 0; - transmitting = 0; + transmitting = 0; return ret; } @@ -199,7 +200,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) { @@ -255,9 +256,9 @@ int TwoWire::peek(void) void TwoWire::flush(void) { - rxBufferIndex = 0; + rxBufferIndex = 0; rxBufferLength = 0; - txBufferIndex = 0; + txBufferIndex = 0; txBufferLength = 0; } @@ -283,7 +284,7 @@ void TwoWire::onReceiveService(uint8_t* inBytes, size_t numBytes) } // set rx iterator vars - rxBufferIndex = 0; + rxBufferIndex = 0; rxBufferLength = numBytes; // alert user program @@ -300,7 +301,7 @@ void TwoWire::onRequestService(void) // reset tx buffer iterator vars // !!! this will kill any pending pre-master sendTo() activity - txBufferIndex = 0; + txBufferIndex = 0; txBufferLength = 0; // alert user program @@ -312,7 +313,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..0ff796c7ef 100644 --- a/libraries/Wire/Wire.h +++ b/libraries/Wire/Wire.h @@ -27,45 +27,45 @@ #include #include "Stream.h" - #ifndef I2C_BUFFER_LENGTH // DEPRECATED: Do not use BUFFER_LENGTH, prefer I2C_BUFFER_LENGTH #define BUFFER_LENGTH 128 #define I2C_BUFFER_LENGTH BUFFER_LENGTH #endif -class TwoWire : public Stream +class TwoWire: public Stream { private: static uint8_t rxBuffer[]; - static size_t rxBufferIndex; - static size_t rxBufferLength; + static size_t rxBufferIndex; + static size_t rxBufferLength; static uint8_t txAddress; static uint8_t txBuffer[]; - static size_t txBufferIndex; - static size_t txBufferLength; + static size_t txBufferIndex; + static size_t txBufferLength; static uint8_t transmitting; static void (*user_onRequest)(void); static void (*user_onReceive)(size_t); static void onRequestService(void); static void onReceiveService(uint8_t*, size_t); + 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 begin(); - void begin(uint8_t); - void begin(int); - void setClock(uint32_t); - void setClockStretchLimit(uint32_t); - void beginTransmission(uint8_t); - void beginTransmission(int); + 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 begin(); + void begin(uint8_t); + void begin(int); + void setClock(uint32_t); + void setClockStretchLimit(uint32_t); + void beginTransmission(uint8_t); + void beginTransmission(int); uint8_t endTransmission(void); uint8_t endTransmission(uint8_t); - size_t requestFrom(uint8_t address, size_t size, bool sendStop); + size_t requestFrom(uint8_t address, size_t size, bool sendStop); uint8_t status(); uint8_t requestFrom(uint8_t, uint8_t); @@ -74,14 +74,14 @@ 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 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 onRequest(void (*)(void)); + 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 onRequest(void (*)(void)); using Print::write; }; @@ -91,4 +91,3 @@ extern TwoWire Wire; #endif #endif - diff --git a/libraries/Wire/examples/master_reader/master_reader.ino b/libraries/Wire/examples/master_reader/master_reader.ino index 323830f847..a6de2b2d8e 100644 --- a/libraries/Wire/examples/master_reader/master_reader.ino +++ b/libraries/Wire/examples/master_reader/master_reader.ino @@ -18,8 +18,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 +27,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 + while (Wire.available()) { // slave may send less than requested + char c = Wire.read(); // receive a byte as 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..4ca0d64db2 100644 --- a/libraries/Wire/examples/master_writer/master_writer.ino +++ b/libraries/Wire/examples/master_writer/master_writer.ino @@ -18,7 +18,7 @@ const int16_t I2C_MASTER = 0x42; const int16_t I2C_SLAVE = 0x08; void setup() { - Wire.begin(SDA_PIN, SCL_PIN, I2C_MASTER); // join i2c bus (address optional for master) + Wire.begin(SDA_PIN, SCL_PIN, I2C_MASTER); // join i2c bus (address optional for master) } byte x = 0; @@ -28,10 +28,10 @@ void loop() { static periodic nextPing(1000); 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.beginTransmission(I2C_SLAVE); // transmit to device #8 + 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..60115e21b4 100644 --- a/libraries/Wire/examples/slave_receiver/slave_receiver.ino +++ b/libraries/Wire/examples/slave_receiver/slave_receiver.ino @@ -18,24 +18,23 @@ 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 + Wire.begin(SDA_PIN, SCL_PIN, I2C_SLAVE); // new syntax: join i2c bus (address required for slave) + Wire.onReceive(receiveEvent); // register event } -void loop() { -} +void loop() {} // function that executes whenever data is received from master // this function is registered as an event, see setup() void receiveEvent(size_t 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 + (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 } - 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..00137e38ac 100644 --- a/libraries/Wire/examples/slave_sender/slave_sender.ino +++ b/libraries/Wire/examples/slave_sender/slave_sender.ino @@ -17,16 +17,15 @@ 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.onRequest(requestEvent); // register event + Wire.begin(SDA_PIN, SCL_PIN, I2C_SLAVE); // join i2c bus with address #8 + Wire.onRequest(requestEvent); // register event } -void loop() { -} +void loop() {} // function that executes whenever data is requested by master // this function is registered as an event, see setup() void requestEvent() { - Wire.write("hello\n"); // respond with message of 6 bytes + Wire.write("hello\n"); // respond with message of 6 bytes // as expected by master } diff --git a/libraries/esp8266/examples/Blink/Blink.ino b/libraries/esp8266/examples/Blink/Blink.ino index de23fb519f..d2083049dd 100644 --- a/libraries/esp8266/examples/Blink/Blink.ino +++ b/libraries/esp8266/examples/Blink/Blink.ino @@ -10,12 +10,12 @@ */ 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 diff --git a/libraries/esp8266/examples/BlinkPolledTimeout/BlinkPolledTimeout.ino b/libraries/esp8266/examples/BlinkPolledTimeout/BlinkPolledTimeout.ino index 11e2aff482..765fd88932 100644 --- a/libraries/esp8266/examples/BlinkPolledTimeout/BlinkPolledTimeout.ino +++ b/libraries/esp8266/examples/BlinkPolledTimeout/BlinkPolledTimeout.ino @@ -26,7 +26,7 @@ #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() { @@ -38,7 +38,7 @@ void ledToggle() { } -esp8266::polledTimeout::periodicFastUs halfPeriod(500000); //use fully qualified type and avoid importing all ::esp8266 namespace to the global namespace +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 void setup() { @@ -50,43 +50,37 @@ void setup() { Serial.printf("periodic/oneShotFastUs::timeMax() = %u us\n", (uint32_t)esp8266::polledTimeout::periodicFastUs::timeMax()); Serial.printf("periodic/oneShotFastNs::timeMax() = %u ns\n", (uint32_t)esp8266::polledTimeout::periodicFastNs::timeMax()); -#if 0 // 1 for debugging polledTimeout +#if 0 // 1 for debugging polledTimeout Serial.printf("periodic/oneShotMs::rangeCompensate = %u\n", (uint32_t)esp8266::polledTimeout::periodicMs::rangeCompensate); Serial.printf("periodic/oneShotFastMs::rangeCompensate = %u\n", (uint32_t)esp8266::polledTimeout::periodicFastMs::rangeCompensate); Serial.printf("periodic/oneShotFastUs::rangeCompensate = %u\n", (uint32_t)esp8266::polledTimeout::periodicFastUs::rangeCompensate); 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 + using esp8266::polledTimeout::oneShotMs; // import the type to the local namespace - //STEP1; turn the led ON + // STEP1; turn the led ON ledOn(); - //STEP2: wait for ON timeout + // STEP2: wait for ON timeout oneShotMs timeoutOn(2000); - while (!timeoutOn) { - yield(); - } + while (!timeoutOn) { yield(); } - //STEP3: turn the led OFF + // STEP3: turn the led OFF ledOff(); - //STEP4: wait for OFF timeout to assure the led is kept off for this time before exiting setup + // STEP4: wait for OFF timeout to assure the led is kept off for this time before exiting setup oneShotMs timeoutOff(2000); - while (!timeoutOff) { - yield(); - } + while (!timeoutOff) { yield(); } - //Done with STEPs, do other stuff - 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. + // Done with STEPs, do other stuff + 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) { - ledToggle(); - } + if (halfPeriod) { ledToggle(); } } diff --git a/libraries/esp8266/examples/CallBackList/CallBackGeneric.ino b/libraries/esp8266/examples/CallBackList/CallBackGeneric.ino index ce4dac2470..e77b35ef66 100644 --- a/libraries/esp8266/examples/CallBackList/CallBackGeneric.ino +++ b/libraries/esp8266/examples/CallBackList/CallBackGeneric.ino @@ -5,25 +5,25 @@ using namespace experimental::CBListImplentation; class exampleClass { - public: - exampleClass() {}; +public: + 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; @@ -60,5 +60,4 @@ void setup() { }); } -void loop() { -} +void loop() {} diff --git a/libraries/esp8266/examples/CheckFlashCRC/CheckFlashCRC.ino b/libraries/esp8266/examples/CheckFlashCRC/CheckFlashCRC.ino index fa520722f6..f4bdfb022d 100644 --- a/libraries/esp8266/examples/CheckFlashCRC/CheckFlashCRC.ino +++ b/libraries/esp8266/examples/CheckFlashCRC/CheckFlashCRC.ino @@ -21,25 +21,24 @@ void setup() { uint32_t ptr = (uint32_t)corruptme; // Find a page aligned spot inside the array ptr += 2 * SPI_FLASH_SEC_SIZE; - ptr &= ~(SPI_FLASH_SEC_SIZE - 1); // Sectoralign + ptr &= ~(SPI_FLASH_SEC_SIZE - 1); // Sectoralign 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 spi_flash_erase_sector(sector); - spi_flash_write(sector * SPI_FLASH_SEC_SIZE, (uint32_t*)space, SPI_FLASH_SEC_SIZE); + spi_flash_write(sector * SPI_FLASH_SEC_SIZE, (uint32_t *)space, SPI_FLASH_SEC_SIZE); Serial.printf("CRC check: %s\n", ESP.checkFlashCRC() ? "OK" : "ERROR"); Serial.printf("...Correcting the flash...\n"); memset(space, 0, SPI_FLASH_SEC_SIZE); spi_flash_erase_sector(sector); - spi_flash_write(sector * SPI_FLASH_SEC_SIZE, (uint32_t*)space, SPI_FLASH_SEC_SIZE); + spi_flash_write(sector * SPI_FLASH_SEC_SIZE, (uint32_t *)space, SPI_FLASH_SEC_SIZE); Serial.printf("CRC check: %s\n", ESP.checkFlashCRC() ? "OK" : "ERROR"); } -void loop() { -} +void loop() {} diff --git a/libraries/esp8266/examples/CheckFlashConfig/CheckFlashConfig.ino b/libraries/esp8266/examples/CheckFlashConfig/CheckFlashConfig.ino index 9c3a54d7da..5d958b8f5b 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..d0406a3882 100644 --- a/libraries/esp8266/examples/ConfigFile/ConfigFile.ino +++ b/libraries/esp8266/examples/ConfigFile/ConfigFile.ino @@ -81,5 +81,4 @@ void setup() { } } -void loop() { -} +void loop() {} diff --git a/libraries/esp8266/examples/FadePolledTimeout/FadePolledTimeout.ino b/libraries/esp8266/examples/FadePolledTimeout/FadePolledTimeout.ino index 1f192dd01c..5ad731db3c 100644 --- a/libraries/esp8266/examples/FadePolledTimeout/FadePolledTimeout.ino +++ b/libraries/esp8266/examples/FadePolledTimeout/FadePolledTimeout.ino @@ -39,17 +39,15 @@ 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 + 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) { - yield(); - } + while (!timeoutOn) { yield(); } stepPeriod.reset(); } diff --git a/libraries/esp8266/examples/HeapMetric/HeapMetric.ino b/libraries/esp8266/examples/HeapMetric/HeapMetric.ino index 5c7a27dbbe..4df382134a 100644 --- a/libraries/esp8266/examples/HeapMetric/HeapMetric.ino +++ b/libraries/esp8266/examples/HeapMetric/HeapMetric.ino @@ -52,53 +52,40 @@ 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); - if (rawMemoryMaxFreeBlockSize < rawMemoryEstimate) { - --blocks; - } + int rawMemoryEstimate = blocks * ((blocksize + UMM_OVERHEAD_ADJUST + 7) & ~7) + ((blocks * sizeof(void*) + UMM_OVERHEAD_ADJUST + 7) & ~7); + if (rawMemoryMaxFreeBlockSize < rawMemoryEstimate) { --blocks; } Serial.printf("\nFilling memory with blocks of %d bytes each\n", blocksize); stats("before"); p = (void**)malloc(sizeof(void*) * blocks); - for (int i = 0; i < blocks; i++) { - p[i] = malloc(blocksize); - } + for (int i = 0; i < blocks; i++) { p[i] = malloc(blocksize); } stats("array and blocks allocation"); for (int i = 0; i < blocks; i += 2) { - if (p[i]) { - free(p[i]); - } + if (p[i]) { free(p[i]); } p[i] = nullptr; } stats("freeing every other blocks"); for (int i = 0; i < (blocks - 1); i += 4) { - if (p[i + 1]) { - free(p[i + 1]); - } + if (p[i + 1]) { free(p[i + 1]); } p[i + 1] = nullptr; } stats("freeing every other remaining blocks"); for (int i = 0; i < blocks; i++) { - if (p[i]) { - free(p[i]); - } + if (p[i]) { free(p[i]); } } stats("freeing array"); @@ -158,5 +145,4 @@ void setup() { #endif } -void loop() { -} +void loop() {} diff --git a/libraries/esp8266/examples/HelloCrypto/HelloCrypto.ino b/libraries/esp8266/examples/HelloCrypto/HelloCrypto.ino index 1fb90134c2..b6af648738 100644 --- a/libraries/esp8266/examples/HelloCrypto/HelloCrypto.ino +++ b/libraries/esp8266/examples/HelloCrypto/HelloCrypto.ino @@ -21,7 +21,7 @@ namespace TypeCast = experimental::TypeConversion; https://github.com/esp8266/Arduino/issues/1143 https://arduino-esp8266.readthedocs.io/en/latest/PROGMEM.html */ -constexpr char masterKey[] PROGMEM = "w86vn@rpfA O+S"; // Use 8 random characters or more +constexpr char masterKey[] PROGMEM = "w86vn@rpfA O+S"; // Use 8 random characters or more void setup() { // Prevents the flash memory from being worn out, see: https://github.com/esp8266/Arduino/issues/1054 . @@ -42,18 +42,18 @@ void loop() { String exampleData = F("Hello Crypto World!"); Serial.println(String(F("This is our example data: ")) + exampleData); - uint8_t resultArray[SHA256::NATURAL_LENGTH] { 0 }; - uint8_t derivedKey[ENCRYPTION_KEY_LENGTH] { 0 }; + uint8_t resultArray[SHA256::NATURAL_LENGTH]{ 0 }; + uint8_t derivedKey[ENCRYPTION_KEY_LENGTH]{ 0 }; static uint32_t encryptionCounter = 0; // Generate the salt to use for HKDF - uint8_t hkdfSalt[16] { 0 }; + uint8_t hkdfSalt[16]{ 0 }; getNonceGenerator()(hkdfSalt, sizeof hkdfSalt); // Generate the key to use for HMAC and encryption - HKDF hkdfInstance(FPSTR(masterKey), (sizeof masterKey) - 1, hkdfSalt, sizeof hkdfSalt); // (sizeof masterKey) - 1 removes the terminating null value of the c-string + HKDF hkdfInstance(FPSTR(masterKey), (sizeof masterKey) - 1, hkdfSalt, sizeof hkdfSalt); // (sizeof masterKey) - 1 removes the terminating null value of the c-string hkdfInstance.produce(derivedKey, sizeof derivedKey); // Hash @@ -71,8 +71,8 @@ void loop() { // 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 - uint8_t resultingTag[16] { 0 }; // The tag is always 16 bytes + uint8_t resultingNonce[12]{ 0 }; // The nonce is always 12 bytes + uint8_t resultingTag[16]{ 0 }; // The tag is always 16 bytes Serial.println(String(F("\nThis is the data to encrypt: ")) + dataToEncrypt); diff --git a/libraries/esp8266/examples/HwdtStackDump/HwdtStackDump.ino b/libraries/esp8266/examples/HwdtStackDump/HwdtStackDump.ino index ff1c41e93b..babd15a9c3 100644 --- a/libraries/esp8266/examples/HwdtStackDump/HwdtStackDump.ino +++ b/libraries/esp8266/examples/HwdtStackDump/HwdtStackDump.ino @@ -19,12 +19,12 @@ #include #include #include -#include // g_pcont - only needed for this debug demo +#include // g_pcont - only needed for this debug demo #include #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* ssid = STASSID; @@ -39,7 +39,7 @@ extern "C" { #define thunk_ets_uart_printf ets_uart_printf #else - int thunk_ets_uart_printf(const char *format, ...) __attribute__((format(printf, 1, 2))); + 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 @@ -47,10 +47,10 @@ extern "C" { //////////////////////////////////////////////////////////////////// void setup(void) { - WiFi.persistent(false); // w/o this a flash write occurs at every boot + 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 ...")); @@ -77,9 +77,7 @@ void setup(void) { disable_extra4k_at_link_time(); #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); + 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); #if defined(DEBUG_ESP_HWDT) || defined(DEBUG_ESP_HWDT_NOEXTRA4K) Serial.print(F("and with the HWDT")); #if defined(DEBUG_ESP_HWDT_NOEXTRA4K) diff --git a/libraries/esp8266/examples/HwdtStackDump/ProcessKey.ino b/libraries/esp8266/examples/HwdtStackDump/ProcessKey.ino index 7d182bf377..4c98899cf4 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; @@ -14,7 +14,8 @@ void processKey(Print& out, int hotKey) { out.printf_P(PSTR("Restart, ESP.restart(); ...\r\n")); ESP.restart(); break; - case 's': { + 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); @@ -32,7 +33,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(); @@ -74,10 +77,8 @@ void processKey(Print& out, int hotKey) { out.println(F("by the compiler after detecting a divide by zero.")); out.printf_P(PSTR("This should not print %d\n"), divideA_B_bp(1, 0)); break; - case '\r': - out.println(); - case '\n': - break; + case '\r': out.println(); + case '\n': break; case '?': out.println(); out.println(F("Press a key + ")); diff --git a/libraries/esp8266/examples/I2SInput/I2SInput.ino b/libraries/esp8266/examples/I2SInput/I2SInput.ino index 836da2685b..6e2e11b07b 100644 --- a/libraries/esp8266/examples/I2SInput/I2SInput.ino +++ b/libraries/esp8266/examples/I2SInput/I2SInput.ino @@ -35,7 +35,7 @@ void setup() { WiFi.forceSleepBegin(); delay(500); - i2s_rxtx_begin(true, false); // Enable I2S RX + i2s_rxtx_begin(true, false); // Enable I2S RX i2s_set_rate(11025); delay(1000); diff --git a/libraries/esp8266/examples/I2STransmit/I2STransmit.ino b/libraries/esp8266/examples/I2STransmit/I2STransmit.ino index 2eaab265d2..229e34fcd0 100644 --- a/libraries/esp8266/examples/I2STransmit/I2STransmit.ino +++ b/libraries/esp8266/examples/I2STransmit/I2STransmit.ino @@ -14,7 +14,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif // Set your network here @@ -26,7 +26,7 @@ WiFiUDP udp; const IPAddress listener = { 192, 168, 1, 2 }; const int port = 8266; -int16_t buffer[100][2]; // Temp staging for samples +int16_t buffer[100][2]; // Temp staging for samples void setup() { Serial.begin(115200); @@ -48,7 +48,7 @@ void setup() { Serial.print("My IP: "); Serial.println(WiFi.localIP()); - i2s_rxtx_begin(true, false); // Enable I2S RX + i2s_rxtx_begin(true, false); // Enable I2S RX i2s_set_rate(11025); Serial.print("\nStart the listener on "); @@ -60,21 +60,16 @@ void setup() { udp.beginPacket(listener, port); udp.write("I2S Receiver\r\n"); udp.endPacket(); - } void loop() { static uint32_t cnt = 0; // Each loop will send 100 raw samples (400 bytes) // UDP needs to be < TCP_MSS which can be 500 bytes in LWIP2 - for (int i = 0; i < 100; i++) { - i2s_read_sample(&buffer[i][0], &buffer[i][1], true); - } + for (int i = 0; i < 100; i++) { i2s_read_sample(&buffer[i][0], &buffer[i][1], true); } udp.beginPacket(listener, port); - udp.write((uint8_t*)buffer, sizeof(buffer)); + udp.write((uint8_t *)buffer, sizeof(buffer)); udp.endPacket(); cnt++; - if ((cnt % 100) == 0) { - Serial.printf("%" PRIu32 "\n", cnt); - } + if ((cnt % 100) == 0) { Serial.printf("%" PRIu32 "\n", cnt); } } diff --git a/libraries/esp8266/examples/IramReserve/IramReserve.ino b/libraries/esp8266/examples/IramReserve/IramReserve.ino index 96d7479da4..24bea8e012 100644 --- a/libraries/esp8266/examples/IramReserve/IramReserve.ino +++ b/libraries/esp8266/examples/IramReserve/IramReserve.ino @@ -18,9 +18,9 @@ #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 +#include // For config/core-isa.h #endif // durable - as in long life, persisting across reboots. @@ -58,8 +58,7 @@ 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); } @@ -70,16 +69,13 @@ void setup() { delay(10); Serial.printf_P(PSTR("\r\nSetup ...\r\n")); - if (!is_iram_valid()) { - DURABLE->bootCounter = 0; - } + if (!is_iram_valid()) { DURABLE->bootCounter = 0; } DURABLE->bootCounter++; 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) { @@ -109,11 +105,8 @@ extern "C" void umm_init_iram(void) { uintptr_t sec_heap = (uintptr_t)_text_end + 32; sec_heap &= ~7; size_t sec_heap_sz = 0xC000UL - (sec_heap - (uintptr_t)XCHAL_INSTRAM1_VADDR); - 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); - } + 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); } } #else @@ -125,6 +118,5 @@ void setup() { Serial.println("\r\n\r\nThis sketch requires Tools Option: 'MMU: 16KB cache + 48KB IRAM and 2nd Heap (shared)'"); } -void loop(void) { -} +void loop(void) {} #endif diff --git a/libraries/esp8266/examples/IramReserve/ProcessKey.ino b/libraries/esp8266/examples/IramReserve/ProcessKey.ino index 7d182bf377..4c98899cf4 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; @@ -14,7 +14,8 @@ void processKey(Print& out, int hotKey) { out.printf_P(PSTR("Restart, ESP.restart(); ...\r\n")); ESP.restart(); break; - case 's': { + 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); @@ -32,7 +33,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(); @@ -74,10 +77,8 @@ void processKey(Print& out, int hotKey) { out.println(F("by the compiler after detecting a divide by zero.")); out.printf_P(PSTR("This should not print %d\n"), divideA_B_bp(1, 0)); break; - case '\r': - out.println(); - case '\n': - break; + case '\r': out.println(); + case '\n': break; case '?': out.println(); out.println(F("Press a key + ")); diff --git a/libraries/esp8266/examples/LowPowerDemo/LowPowerDemo.ino b/libraries/esp8266/examples/LowPowerDemo/LowPowerDemo.ino index 2c22416e0d..9a6fbc5bfd 100644 --- a/libraries/esp8266/examples/LowPowerDemo/LowPowerDemo.ino +++ b/libraries/esp8266/examples/LowPowerDemo/LowPowerDemo.ino @@ -38,14 +38,14 @@ 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include -#include // crc32() +#include // crc32() #include -#include // WiFiState structure details +#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) @@ -63,9 +63,9 @@ ADC_MODE(ADC_VCC); // allows you to monitor the internal VCC level; it varies w // 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_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 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); @@ -85,7 +85,7 @@ uint32_t timeout = 30E3; // 30 second timeout on the WiFi connection // This structure is stored in RTC memory to save the WiFi state and reset count (number of Deep Sleeps), // and it reconnects twice as fast as the first connection; it's used several places in this demo struct nv_s { - WiFiState wss; // core's WiFi save state + WiFiState wss; // core's WiFi save state struct { uint32_t crc32; @@ -94,29 +94,29 @@ struct nv_s { } rtcData; }; -static nv_s* nv = (nv_s*)RTC_USER_MEM; // user RTC RAM area +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 -const uint32_t blinkDelay = 100; // fast blink rate for the LED when waiting for the user +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::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 + 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 + 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(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(); @@ -124,17 +124,15 @@ void setup() { String resetCause = ESP.getResetReason(); Serial.println(resetCause); resetCount = 0; - if ((resetCause == "External System") || (resetCause == "Power on")) { - Serial.println(F("I'm awake and starting the Low Power tests")); - } + if ((resetCause == "External System") || (resetCause == "Power on")) { Serial.println(F("I'm awake and starting the Low Power tests")); } // 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 = resetCount; // update the reset count & CRC + nv->rtcData.rstCount = resetCount; // update the reset count & CRC updateRTCcrc(); if (resetCount == 1) { // show that millis() is cleared across the Deep Sleep reset @@ -164,7 +162,7 @@ void loop() { } else if (resetCount == 4) { resetTests(); } -} //end of loop() +} // end of loop() void runTest1() { Serial.println(F("\n1st test - running with WiFi unconfigured")); @@ -181,13 +179,13 @@ void runTest2() { Serial.println(F("The amperage will drop in 7 seconds.")); 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, - 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. - At 100 mS and above it's essentially all delay() time. On an oscilloscope you'll see the - time between beacons at > 67 mA more often with less delay() percentage. You can change - the '90' mS to other values to see the effect it has on Automatic Modem Sleep. */ + 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. + At 100 mS and above it's essentially all delay() time. On an oscilloscope you'll see the + time between beacons at > 67 mA more often with less delay() percentage. You can change + the '90' mS to other values to see the effect it has on Automatic Modem Sleep. */ } else { Serial.println(F("no WiFi connection, test skipped")); } @@ -201,10 +199,10 @@ void runTest3() { // delay(10); // it doesn't always go to sleep unless you delay(10); yield() wasn't reliable 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 - 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.*/ + 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.*/ } void runTest4() { @@ -215,13 +213,11 @@ void runTest4() { // and WiFi reconnects after the forceSleepWake more quickly 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.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)) { - yield(); - } + while (((!WiFi.localIP()) || (WiFi.status() != WL_CONNECTED)) && (!wifiTimeout)) { yield(); } if ((WiFi.status() == WL_CONNECTED) && WiFi.localIP()) { // won't go into Automatic Sleep without an active WiFi connection float reConn = (millis() - wifiBegin); @@ -229,9 +225,9 @@ void runTest4() { Serial.printf("%1.2f seconds\n", reConn / 1000); 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', - and below ~ 350 mS delay() the 'Automatic Light Sleep' is less frequent. Above 500 mS - delay() doesn't make significant improvement in power savings. */ + 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 { Serial.println(F("no WiFi connection, test skipped")); } @@ -241,61 +237,61 @@ 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() + 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; + 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) // only LOLEVEL or HILEVEL interrupts work, no edge, that's an SDK or CPU limitation - wifi_fpm_set_wakeup_cb(wakeupCallback); // set wakeup callback + 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) - delay(10e3 + 1); // delay needs to be 1 mS longer than sleep or it only goes into Modem Sleep + 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 } 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 + 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 + 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() + 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_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 + 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 + 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 delay(10); } - delay(50); // debounce time for the switch, pushbutton released + 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 + 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() - ESP.deepSleep(10E6, WAKE_RF_DEFAULT); // good night! D0 fires a reset in 10 seconds... + 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 @@ -308,12 +304,12 @@ void runTest8() { 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, - // and no extended RFCAL as it goes into Deep 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() - ESP.deepSleep(10E6, WAKE_RFCAL); // good night! D0 fires a reset in 10 seconds... + 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 } @@ -322,11 +318,11 @@ void runTest9() { 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 + 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() - ESP.deepSleepInstant(10E6, WAKE_NO_RFCAL); // good night! D0 fires a reset in 10 seconds... + 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 } @@ -335,11 +331,11 @@ void runTest10() { 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.forceSleepBegin(); // Forced Modem Sleep for a more Instant Deep 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() - ESP.deepSleepInstant(10E6, WAKE_RF_DISABLED); // good night! D0 fires a reset in 10 seconds... + 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 } @@ -361,25 +357,25 @@ void waitPushbutton(bool usesDelay, unsigned int delayTime) { // loop until the } 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 + } 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(); + 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 + while (!altDelay) { // this simulates 'your program running', not delay() time } } } } - delay(50); // debounce time for the switch, pushbutton pressed + 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 } -void readVoltage() { // read internal VCC +void readVoltage() { // read internal VCC float volts = ESP.getVcc(); Serial.printf("The internal VCC reads %1.2f volts\n", volts / 1000); } @@ -391,18 +387,18 @@ void printMillis() { } void updateRTCcrc() { // updates the reset count CRC - nv->rtcData.crc32 = crc32((uint8_t*) &nv->rtcData.rstCount, sizeof(nv->rtcData.rstCount)); + 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 + 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 ((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 @@ -411,7 +407,7 @@ void initWiFi() { with other WiFi devices on your network. */ 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.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 ")); @@ -420,9 +416,7 @@ void initWiFi() { DEBUG_PRINTLN(WiFi.macAddress()); } wifiTimeout.reset(timeout); - while (((!WiFi.localIP()) || (WiFi.status() != WL_CONNECTED)) && (!wifiTimeout)) { - yield(); - } + while (((!WiFi.localIP()) || (WiFi.status() != WL_CONNECTED)) && (!wifiTimeout)) { yield(); } if ((WiFi.status() == WL_CONNECTED) && WiFi.localIP()) { DEBUG_PRINTLN(F("WiFi connected")); Serial.print(F("WiFi connect time = ")); diff --git a/libraries/esp8266/examples/MMU48K/MMU48K.ino b/libraries/esp8266/examples/MMU48K/MMU48K.ino index d75d91232b..93f2bde32b 100644 --- a/libraries/esp8266/examples/MMU48K/MMU48K.ino +++ b/libraries/esp8266/examples/MMU48K/MMU48K.ino @@ -4,20 +4,20 @@ #include #if defined(CORE_MOCK) -#define XCHAL_INSTRAM1_VADDR 0x40100000 +#define XCHAL_INSTRAM1_VADDR 0x40100000 #else -#include // For config/core-isa.h +#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; +int *nullPointer = NULL; -char *probe_b = NULL; +char *probe_b = NULL; short *probe_s = NULL; -char *probe_c = (char *)0x40110000; +char *probe_c = (char *)0x40110000; short *unaligned_probe_s = NULL; uint32_t read_var = 0x11223344; @@ -33,7 +33,7 @@ uint32_t read_var = 0x11223344; 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)); @@ -68,7 +69,7 @@ bool isValid(uint32_t *probe) { } -void dump_mem32(const void * addr, const size_t len) { +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) { @@ -77,9 +78,7 @@ void dump_mem32(const void * addr, const size_t len) { } for (size_t i = 0; i < len;) { ets_uart_printf("%p: ", &addr32[i]); - do { - ets_uart_printf(" 0x%08x", addr32[i]); - } while (i++, (i & 3) && (i < len)); + do { ets_uart_printf(" 0x%08x", addr32[i]); } while (i++, (i & 3) && (i < len)); ets_uart_printf("\n"); } ets_uart_printf("\n"); @@ -87,7 +86,7 @@ void dump_mem32(const void * addr, const size_t len) { extern "C" void _text_end(void); // extern void *_text_end; -void print_mmu_status(Print& oStream) { +void print_mmu_status(Print &oStream) { oStream.println(); oStream.printf_P(PSTR("MMU Configuration")); oStream.println(); @@ -137,7 +136,7 @@ void setup() { { HeapSelectIram ephemeral; // Serial.printf_P(PSTR("ESP.getFreeHeap(): %u\n"), ESP.getFreeHeap()); - gobble_sz = ESP.getFreeHeap() - UMM_OVERHEAD_ADJUST; // - 4096; + gobble_sz = ESP.getFreeHeap() - UMM_OVERHEAD_ADJUST; // - 4096; gobble = (uint32_t *)malloc(gobble_sz); } Serial.printf_P(PSTR("\r\nmalloc() from IRAM Heap:\r\n")); @@ -152,9 +151,7 @@ void setup() { #if (MMU_IRAM_SIZE > 0x8000) || defined(MMU_IRAM_HEAP) || defined(MMU_SEC_HEAP) if (isValid(gobble)) { // Put something in our new memory - for (size_t i = 0; i < (gobble_sz / 4); i++) { - gobble[i] = (uint32_t)&gobble[i]; - } + for (size_t i = 0; i < (gobble_sz / 4); i++) { gobble[i] = (uint32_t)&gobble[i]; } // Now is it there? dump_mem32(gobble, 32); @@ -170,12 +167,12 @@ void setup() { probe_b = (char *)gobble; probe_s = (short *)((uintptr_t)gobble); unaligned_probe_s = (short *)((uintptr_t)gobble + 1); - } -void processKey(Print& out, int hotKey) { +void processKey(Print &out, int hotKey) { switch (hotKey) { - case 't': { + case 't': + { uint32_t tmp; out.printf_P(PSTR("Test how much time is added by exception handling")); out.println(); @@ -227,7 +224,8 @@ void processKey(Print& out, int hotKey) { out.printf_P(PSTR("Read Byte from iRAM, 0x%02X at %p"), probe_b[0], probe_b); out.println(); break; - case 'B': { + case 'B': + { out.printf_P(PSTR("Load/Store exception by writing byte to iRAM")); out.println(); char val = 0x55; @@ -246,7 +244,8 @@ void processKey(Print& out, int hotKey) { out.printf_P(PSTR("Read short from iRAM, 0x%04X at %p"), probe_s[0], probe_s); out.println(); break; - case 'S': { + case 'S': + { out.printf_P(PSTR("Load/Store exception by writing short to iRAM")); out.println(); short int val = 0x0AA0; @@ -272,10 +271,8 @@ void processKey(Print& out, int hotKey) { out.printf_P(PSTR("This should not print %d"), divideA_B(1, 0)); out.println(); break; - case '\r': - out.println(); - case '\n': - break; + case '\r': out.println(); + case '\n': break; case '?': out.println(); out.println(F("Press a key + ")); 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..6388c1a9cf 100644 --- a/libraries/esp8266/examples/NTP-TZ-DST/NTP-TZ-DST.ino +++ b/libraries/esp8266/examples/NTP-TZ-DST/NTP-TZ-DST.ino @@ -15,11 +15,11 @@ #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 +#define RTC_UTC_TEST 1510592825 // 1510592825 = Monday 13 November 2017 17:07:05 UTC // This database is autogenerated from IANA timezone database @@ -44,17 +44,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); //////////////////////////////////////////////////////// @@ -64,14 +64,14 @@ static time_t now; static uint32_t now_ms, now_us; static esp8266::polledTimeout::periodicMs showTimeNow(60000); -static int time_machine_days = 0; // 0 = present +static int time_machine_days = 0; // 0 = present static bool time_machine_running = false; static bool time_machine_run_once = false; // OPTIONAL: change SNTP startup delay // a weak function is already defined and returns 0 (RFC violation) // it can be redefined: -//uint32_t sntp_startup_delay_MS_rfc_not_less_than_60000 () +// uint32_t sntp_startup_delay_MS_rfc_not_less_than_60000 () //{ // //info_sntp_startup_delay_MS_rfc_not_less_than_60000_has_been_called = true; // return 60000; // 60s (or lwIP's original default: (random() % 5000)) @@ -80,7 +80,7 @@ static bool time_machine_run_once = false; // OPTIONAL: change SNTP update delay // a weak function is already defined and returns 1 hour // it can be redefined: -//uint32_t sntp_update_delay_MS_rfc_not_less_than_15000 () +// uint32_t sntp_update_delay_MS_rfc_not_less_than_15000 () //{ // //info_sntp_update_delay_MS_rfc_not_less_than_15000_has_been_called = true; // return 15000; // 15s @@ -92,9 +92,15 @@ static bool time_machine_run_once = false; 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 +141,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: "); @@ -152,9 +158,7 @@ void showTime() { } else { Serial.printf("%s ", sntp.toString().c_str()); } - Serial.printf("- IPv6: %s - Reachability: %o\n", - sntp.isV6() ? "Yes" : "No", - sntp_getreachability(i)); + Serial.printf("- IPv6: %s - Reachability: %o\n", sntp.isV6() ? "Yes" : "No", sntp_getreachability(i)); } } @@ -168,12 +172,8 @@ void showTime() { while (true) { 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); - 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); + Serial.printf("time(): %u gettimeofday(): %u.%06u seconds are unchanged\n", (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); break; } prevtv = tv; @@ -194,10 +194,8 @@ void time_is_set(bool from_sntp /* <= this parameter is optional */) { } else { time_machine_running = from_sntp && !time_machine_run_once; } - if (time_machine_running) { - Serial.printf("\n-- \n-- Starting time machine demo to show libc's " - "automatic DST handling\n-- \n"); - } + if (time_machine_running) { Serial.printf("\n-- \n-- Starting time machine demo to show libc's " + "automatic DST handling\n-- \n"); } } Serial.print("settimeofday("); @@ -212,9 +210,7 @@ void time_is_set(bool from_sntp /* <= this parameter is optional */) { if (time_machine_running) { now = time(nullptr); const tm* tm = localtime(&now); - Serial.printf(": future=%3ddays: DST=%s - ", - time_machine_days, - tm->tm_isdst ? "true " : "false"); + Serial.printf(": future=%3ddays: DST=%s - ", time_machine_days, tm->tm_isdst ? "true " : "false"); Serial.print(ctime(&now)); gettimeofday(&tv, nullptr); constexpr int days = 30; @@ -261,10 +257,10 @@ void setup() { // Former configTime is still valid, here is the call for 7 hours to the west // with an enabled 30mn DST - //configTime(7 * 3600, 3600 / 2, "pool.ntp.org"); + // configTime(7 * 3600, 3600 / 2, "pool.ntp.org"); // OPTIONAL: disable obtaining SNTP servers from DHCP - //sntp_servermode_dhcp(0); // 0: disable obtaining SNTP servers from DHCP (enabled by default) + // sntp_servermode_dhcp(0); // 0: disable obtaining SNTP servers from DHCP (enabled by default) // Give now a chance to the settimeofday callback, // because it is *always* deferred to the next yield()/loop()-call. @@ -280,7 +276,5 @@ void setup() { } void loop() { - if (showTimeNow) { - showTime(); - } + if (showTimeNow) { showTime(); } } diff --git a/libraries/esp8266/examples/RTCUserMemory/RTCUserMemory.ino b/libraries/esp8266/examples/RTCUserMemory/RTCUserMemory.ino index 9736995c74..b1699d0cda 100644 --- a/libraries/esp8266/examples/RTCUserMemory/RTCUserMemory.ino +++ b/libraries/esp8266/examples/RTCUserMemory/RTCUserMemory.ino @@ -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: "); @@ -51,13 +51,11 @@ void setup() { } // Generate new data set for the struct - for (size_t i = 0; i < sizeof(rtcData.data); i++) { - rtcData.data[i] = random(0, 128); - } + for (size_t i = 0; i < sizeof(rtcData.data); i++) { 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(); @@ -67,8 +65,7 @@ void setup() { ESP.deepSleep(5e6); } -void loop() { -} +void loop() {} uint32_t calculateCRC32(const uint8_t *data, size_t length) { uint32_t crc = 0xffffffff; @@ -76,19 +73,15 @@ uint32_t calculateCRC32(const uint8_t *data, size_t length) { uint8_t c = *data++; for (uint32_t i = 0x80; i > 0; i >>= 1) { bool bit = crc & 0x80000000; - if (c & i) { - bit = !bit; - } + if (c & i) { bit = !bit; } crc <<= 1; - if (bit) { - crc ^= 0x04c11db7; - } + if (bit) { crc ^= 0x04c11db7; } } } return crc; } -//prints all rtcData, including the leading crc32 +// prints all rtcData, including the leading crc32 void printMemory() { char buf[3]; uint8_t *ptr = (uint8_t *)&rtcData; diff --git a/libraries/esp8266/examples/SerialDetectBaudrate/SerialDetectBaudrate.ino b/libraries/esp8266/examples/SerialDetectBaudrate/SerialDetectBaudrate.ino index 61967c691f..ec41562357 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: @@ -13,9 +13,7 @@ void setup() { Serial.printf("\nDetected baudrate is %lu, switching to that baudrate now...\n", detectedBaudrate); // Wait for printf to finish - while (Serial.availableForWrite() != UART_TX_FIFO_SIZE) { - yield(); - } + while (Serial.availableForWrite() != UART_TX_FIFO_SIZE) { yield(); } // Clear Tx buffer to avoid extra characters being printed Serial.flush(); @@ -29,6 +27,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..4a8b6e4f45 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 FAKE_INCREASED_AVAILABLE 100 // test readBytes's timeout #define TIMEOUT 5000 -#define DEBUG(x...) //x +#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; @@ -37,31 +37,22 @@ static uint64_t timeout; 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); - if (Serial.hasOverrun()) { - logger->printf("overrun!\n"); - } + 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); + if (Serial.hasOverrun()) { logger->printf("overrun!\n"); } logger->printf("should be (size=%d idx=%d..%d):\n ", BUFFER_SIZE, in_idx, in_idx + local_receive_size - 1); - for (size_t i = in_idx; i < in_idx + local_receive_size; i++) { - logger->printf("%02x(%c) ", buf[i], (unsigned char)((buf[i] > 31 && buf[i] < 128) ? buf[i] : '.')); - } + for (size_t i = in_idx; i < in_idx + local_receive_size; i++) { logger->printf("%02x(%c) ", buf[i], (unsigned char)((buf[i] > 31 && buf[i] < 128) ? buf[i] : '.')); } logger->print("\n\nis: "); - for (size_t i = 0; i < local_receive_size; i++) { - logger->printf("%02x(%c) ", temp[i], (unsigned char)((temp[i] > 31 && temp[i] < 128) ? temp[i] : '.')); - } + for (size_t i = 0; i < local_receive_size; i++) { logger->printf("%02x(%c) ", temp[i], (unsigned char)((temp[i] > 31 && temp[i] < 128) ? temp[i] : '.')); } logger->println("\n\n"); - while (true) { - delay(1000); - } + while (true) { delay(1000); } } void setup() { pinMode(LED_BUILTIN, OUTPUT); Serial.begin(BAUD); - Serial.swap(); // RX=GPIO13 TX=GPIO15 + Serial.swap(); // RX=GPIO13 TX=GPIO15 Serial.setRxBufferSize(SERIAL_SIZE_RX); // using HardwareSerial0 pins, @@ -75,26 +66,22 @@ 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); + logger->printf("\n\nBAUD: %d - CoreRxBuffer: %d bytes - TestBuffer: %d bytes\n", baud, SERIAL_SIZE_RX, BUFFER_SIZE); - size_for_1sec = baud / 10; // 8n1=10baudFor8bits + size_for_1sec = baud / 10; // 8n1=10baudFor8bits logger->printf("led changes state every %zd bytes (= 1 second)\n", size_for_1sec); logger->printf("press 's' to stop reading, not writing (induces overrun)\n"); logger->printf("press 't' to toggle timeout testing on readBytes\n"); // prepare send/compare buffer - for (size_t i = 0; i < sizeof buf; i++) { - buf[i] = (uint8_t)i; - } + for (size_t i = 0; i < sizeof buf; i++) { buf[i] = (uint8_t)i; } // bind RX and TX USC0(0) |= (1 << UCLBE); - while (Serial.read() == -1); - if (Serial.hasOverrun()) { - logger->print("overrun?\n"); - } + while (Serial.read() == -1) + ; + if (Serial.hasOverrun()) { logger->print("overrun?\n"); } timeout = (start_ms = last_ms = millis()) + TIMEOUT; logger->println("setup done"); @@ -103,59 +90,35 @@ void setup() { void loop() { size_t maxlen = Serial.availableForWrite(); // check remaining space in buffer - if (maxlen > BUFFER_SIZE - out_idx) { - maxlen = BUFFER_SIZE - out_idx; - } + if (maxlen > BUFFER_SIZE - out_idx) { 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; - if (maxlen > in_out) { - maxlen = in_out; - } + 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; } DEBUG(logger->printf("(aw%i/w%i", Serial.availableForWrite(), maxlen)); size_t local_written_size = Serial.write(buf + out_idx, maxlen); DEBUG(logger->printf(":w%i/aw%i/ar%i)\n", local_written_size, Serial.availableForWrite(), Serial.available())); - if (local_written_size > maxlen) { - error("bad write"); - } - if ((out_idx += local_written_size) == BUFFER_SIZE) { - out_idx = 0; - } + if (local_written_size > maxlen) { error("bad write"); } + if ((out_idx += local_written_size) == BUFFER_SIZE) { out_idx = 0; } yield(); DEBUG(logger->printf("----------\n")); - if (Serial.hasOverrun()) { - logger->printf("rx overrun!\n"); - } - if (Serial.hasRxError()) { - logger->printf("rx error!\n"); - } + if (Serial.hasOverrun()) { logger->printf("rx overrun!\n"); } + if (Serial.hasRxError()) { logger->printf("rx error!\n"); } if (reading) { // receive data maxlen = Serial.available() + testReadBytesTimeout; - if (maxlen > maxavail) { - maxavail = maxlen; - } + if (maxlen > maxavail) { maxavail = maxlen; } // check space in temp receive buffer - if (maxlen > BUFFER_SIZE - in_idx) { - maxlen = BUFFER_SIZE - in_idx; - } + if (maxlen > BUFFER_SIZE - in_idx) { maxlen = BUFFER_SIZE - in_idx; } DEBUG(logger->printf("(ar%i/r%i", Serial.available(), maxlen)); local_receive_size = Serial.readBytes(temp, maxlen); DEBUG(logger->printf(":r%i/ar%i)\n", local_receive_size, Serial.available())); - if (local_receive_size > maxlen) { - error("bad read"); - } + if (local_receive_size > maxlen) { error("bad read"); } if (local_receive_size) { - if (memcmp(buf + in_idx, temp, local_receive_size) != 0) { - error("fail"); - } - if ((in_idx += local_receive_size) == BUFFER_SIZE) { - in_idx = 0; - } + if (memcmp(buf + in_idx, temp, local_receive_size) != 0) { error("fail"); } + if ((in_idx += local_receive_size) == BUFFER_SIZE) { in_idx = 0; } in_total += local_receive_size; } DEBUG(logger->printf("r(%d) ok\n", local_receive_size)); @@ -166,21 +129,18 @@ void loop() { digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); size_for_led = 0; - if (in_prev == in_total) { - error("receiving nothing?\n"); - } + if (in_prev == in_total) { error("receiving nothing?\n"); } 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; timeout = (last_ms = now_ms) + TIMEOUT; } - if (logger->available()) - switch (logger->read()) { + if (logger->available()) switch (logger->read()) { case 's': logger->println("now stopping reading, keeping writing"); reading = false; diff --git a/libraries/esp8266/examples/SigmaDeltaDemo/SigmaDeltaDemo.ino b/libraries/esp8266/examples/SigmaDeltaDemo/SigmaDeltaDemo.ino index bdc1799eb7..d1592e7588 100644 --- a/libraries/esp8266/examples/SigmaDeltaDemo/SigmaDeltaDemo.ino +++ b/libraries/esp8266/examples/SigmaDeltaDemo/SigmaDeltaDemo.ino @@ -5,16 +5,15 @@ void setup() { Serial.begin(115200); - pinMode(LED_BUILTIN, OUTPUT); // blinkie & sigma-delta mix + pinMode(LED_BUILTIN, OUTPUT); // blinkie & sigma-delta mix uint32_t reqFreq = 1000; uint32_t realFreq; - realFreq = sigmaDeltaSetup(0, reqFreq); // chose a low frequency + realFreq = sigmaDeltaSetup(0, reqFreq); // chose a low frequency 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..f177b53edc 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(); @@ -110,7 +110,7 @@ void testStreamString() { result.clear(); S2Stream input(inputString); // reading stream will consume the string - input.setConsume(); // can be omitted, this is the default + input.setConsume(); // can be omitted, this is the default input.sendSize(result, 1); input.sendSize(result, 2); @@ -181,8 +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)); + Serial.printf("sizeof: String:%d Stream:%d StreamString:%d SStream:%d\n", (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..903306a1dd 100644 --- a/libraries/esp8266/examples/TestEspApi/TestEspApi.ino +++ b/libraries/esp8266/examples/TestEspApi/TestEspApi.ino @@ -28,60 +28,19 @@ Stream& ehConsolePort(Serial); // UNLESS: You swap the TX pin using the alternate pinout. const uint8_t LED_PIN = 1; -const char * const RST_REASONS[] = { - "REASON_DEFAULT_RST", - "REASON_WDT_RST", - "REASON_EXCEPTION_RST", - "REASON_SOFT_WDT_RST", - "REASON_SOFT_RESTART", - "REASON_DEEP_SLEEP_AWAKE", - "REASON_EXT_SYS_RST" -}; +const char* const RST_REASONS[] = { "REASON_DEFAULT_RST", "REASON_WDT_RST", "REASON_EXCEPTION_RST", "REASON_SOFT_WDT_RST", "REASON_SOFT_RESTART", "REASON_DEEP_SLEEP_AWAKE", "REASON_EXT_SYS_RST" }; -const char * const FLASH_SIZE_MAP_NAMES[] = { - "FLASH_SIZE_4M_MAP_256_256", - "FLASH_SIZE_2M", - "FLASH_SIZE_8M_MAP_512_512", - "FLASH_SIZE_16M_MAP_512_512", - "FLASH_SIZE_32M_MAP_512_512", - "FLASH_SIZE_16M_MAP_1024_1024", - "FLASH_SIZE_32M_MAP_1024_1024" -}; +const char* const FLASH_SIZE_MAP_NAMES[] = { "FLASH_SIZE_4M_MAP_256_256", "FLASH_SIZE_2M", "FLASH_SIZE_8M_MAP_512_512", "FLASH_SIZE_16M_MAP_512_512", "FLASH_SIZE_32M_MAP_512_512", "FLASH_SIZE_16M_MAP_1024_1024", "FLASH_SIZE_32M_MAP_1024_1024" }; -const char * const OP_MODE_NAMES[] { - "NULL_MODE", - "STATION_MODE", - "SOFTAP_MODE", - "STATIONAP_MODE" -}; +const char* const OP_MODE_NAMES[]{ "NULL_MODE", "STATION_MODE", "SOFTAP_MODE", "STATIONAP_MODE" }; -const char * const AUTH_MODE_NAMES[] { - "AUTH_OPEN", - "AUTH_WEP", - "AUTH_WPA_PSK", - "AUTH_WPA2_PSK", - "AUTH_WPA_WPA2_PSK", - "AUTH_MAX" -}; +const char* const AUTH_MODE_NAMES[]{ "AUTH_OPEN", "AUTH_WEP", "AUTH_WPA_PSK", "AUTH_WPA2_PSK", "AUTH_WPA_WPA2_PSK", "AUTH_MAX" }; -const char * const PHY_MODE_NAMES[] { - "", - "PHY_MODE_11B", - "PHY_MODE_11G", - "PHY_MODE_11N" -}; +const char* const PHY_MODE_NAMES[]{ "", "PHY_MODE_11B", "PHY_MODE_11G", "PHY_MODE_11N" }; -const char * const EVENT_NAMES[] { - "EVENT_STAMODE_CONNECTED", - "EVENT_STAMODE_DISCONNECTED", - "EVENT_STAMODE_AUTHMODE_CHANGE", - "EVENT_STAMODE_GOT_IP", - "EVENT_SOFTAPMODE_STACONNECTED", - "EVENT_SOFTAPMODE_STADISCONNECTED", - "EVENT_MAX" -}; +const char* const EVENT_NAMES[]{ "EVENT_STAMODE_CONNECTED", "EVENT_STAMODE_DISCONNECTED", "EVENT_STAMODE_AUTHMODE_CHANGE", "EVENT_STAMODE_GOT_IP", "EVENT_SOFTAPMODE_STACONNECTED", "EVENT_SOFTAPMODE_STADISCONNECTED", "EVENT_MAX" }; -const char * const EVENT_REASONS[] { +const char* const EVENT_REASONS[]{ "", "REASON_UNSPECIFIED", "REASON_AUTH_EXPIRE", @@ -108,27 +67,21 @@ const char * const EVENT_REASONS[] { "REASON_CIPHER_SUITE_REJECTED", }; -const char * const EVENT_REASONS_200[] { - "REASON_BEACON_TIMEOUT", - "REASON_NO_AP_FOUND" -}; +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(" ("); switch (event->event) { - case EVENT_STAMODE_CONNECTED: - break; - case EVENT_STAMODE_DISCONNECTED: - break; - case EVENT_STAMODE_AUTHMODE_CHANGE: - break; - case EVENT_STAMODE_GOT_IP: - break; + case EVENT_STAMODE_CONNECTED: break; + case EVENT_STAMODE_DISCONNECTED: break; + case EVENT_STAMODE_AUTHMODE_CHANGE: break; + case EVENT_STAMODE_GOT_IP: break; case EVENT_SOFTAPMODE_STACONNECTED: - case EVENT_SOFTAPMODE_STADISCONNECTED: { - char mac[32] = {0}; + 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); ehConsolePort.print(mac); @@ -139,16 +92,16 @@ void wifi_event_handler_cb(System_Event_t * event) { 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 +126,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 +164,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 +172,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 +183,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 +246,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..30cacb1127 100644 --- a/libraries/esp8266/examples/UartDownload/UartDownload.ino +++ b/libraries/esp8266/examples/UartDownload/UartDownload.ino @@ -59,11 +59,10 @@ 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 +constexpr size_t syncPktSz = sizeof(syncPkt) - 1; // Don't compare zero terminator char // // Use the discovery of an ESP_SYNC packet, to trigger calling UART Download @@ -71,9 +70,7 @@ constexpr size_t syncPktSz = sizeof(syncPkt) - 1; // Don't compare zero terminat // the slipFrameMarker. // void proxyEspSync() { - if (!uartDownloadEnable) { - return; - } + if (!uartDownloadEnable) { return; } byte buf[pktBufSz]; @@ -90,7 +87,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. @@ -111,8 +108,7 @@ void setup() { // stub, then both devices shift their UART speeds to the command line value. Serial.begin(115200); - Serial.println(F( - "\r\n\r\n" + 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" @@ -143,20 +139,17 @@ void cmdLoop(Print& oStream, int key) { ESP.restart(); break; - // ... + // ... case '?': oStream.println(F("\r\nHot key help:")); - if (!uartDownloadEnable) { - oStream.println(F(" e - Enable monitor for detecting ESP_SYNC from esptool.py")); - } + if (!uartDownloadEnable) { oStream.println(F(" e - Enable monitor for detecting ESP_SYNC from esptool.py")); } oStream.println(F(" D - Boot into UART download mode")); oStream.println(F(" R - Restart")); oStream.println(F(" ? - This help message\r\n")); break; - default: - break; + default: break; } oStream.println(); diff --git a/libraries/esp8266/examples/interactive/interactive.ino b/libraries/esp8266/examples/interactive/interactive.ino index b3bd1ff931..0f0c56e31c 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); @@ -35,16 +35,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" - ); + 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"); } void WiFiOn() { @@ -65,9 +63,16 @@ void WiFiOff() { void loop() { #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()); @@ -91,7 +96,7 @@ void loop() { 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 '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..e8005d7687 100644 --- a/libraries/esp8266/examples/irammem/irammem.ino +++ b/libraries/esp8266/examples/irammem/irammem.ino @@ -21,51 +21,39 @@ #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; for (size_t u = 0; u < len; u++) { uint16_t x1 = mmu_get_uint16(&x[0]); - for (size_t v = 0; v < len; v++) { - x[v] = mmu_get_uint16(&x[v]) + x1; - } + for (size_t v = 0; v < len; v++) { x[v] = mmu_get_uint16(&x[v]) + x1; } } } // 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]); - for (size_t v = 0; v < len; v++) { - x[v] = mmu_get_uint16(&x[v]) + x1; - } + for (size_t v = 0; v < len; v++) { x[v] = mmu_get_uint16(&x[v]) + x1; } } } #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]); - for (size_t v = 0; v < len; v++) { - x[v] = mmu_get_uint16(&x[v]) + x1; - } + for (size_t v = 0; v < len; v++) { x[v] = mmu_get_uint16(&x[v]) + x1; } } } #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]); - for (size_t v = 0; v < len; v++) { - x[v] = mmu_get_uint16(&x[v]) + x1; - } + for (size_t v = 0; v < len; v++) { x[v] = mmu_get_uint16(&x[v]) + x1; } } } @@ -73,8 +61,7 @@ void aliasTestO3(uint16_t *x) { // 8-bit access will take longer as it will be processed thought // 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) { +__attribute__((noinline)) IRAM_ATTR 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 @@ -88,24 +75,21 @@ uint32_t timedRead_Reference(uint8_t *res) { return ESP.getCycleCount() - b; } #pragma GCC optimize("Os") -__attribute__((noinline)) IRAM_ATTR -uint32_t timedRead_Os(uint8_t *res) { +__attribute__((noinline)) IRAM_ATTR 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) { +__attribute__((noinline)) IRAM_ATTR 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) { +__attribute__((noinline)) IRAM_ATTR 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); @@ -155,25 +139,21 @@ bool test4_32bit_loads() { 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]); - } + for (size_t i = 0; i < sz; i++) { Serial.printf(" %3u", ref[i]); } Serial.printf("\r\n Got: "); - for (size_t i = 0; i < sz; i++) { - Serial.printf(" %3u", x[i]); - } + for (size_t i = 0; i < sz; i++) { Serial.printf(" %3u", x[i]); } Serial.printf("\r\n"); } bool testPunning() { bool result = true; // Get reference result for verifing test - alignas(uint32_t) uint16_t x_ref[] = {1, 2, 3, 0}; + 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 +165,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 +177,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))) { @@ -215,9 +195,7 @@ bool testPunning() { 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++) { - sum += *(x++); - } + for (int i = 0; i < n * 1024; i++) { sum += *(x++); } *res = sum; return ESP.getCycleCount() - b; } @@ -235,9 +213,7 @@ uint32_t cyclesToWrite_nKx32(int n, unsigned int *x) { 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++) { - sum += *(x++); - } + for (int i = 0; i < n * 1024; i++) { sum += *(x++); } *res = sum; return ESP.getCycleCount() - b; } @@ -255,9 +231,7 @@ uint32_t cyclesToWrite_nKx16(int n, unsigned short *x) { 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++) { - sum += *(x++); - } + for (int i = 0; i < n * 1024; i++) { sum += *(x++); } *res = sum; return ESP.getCycleCount() - b; } @@ -272,17 +246,15 @@ 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++) { - sum += *(x++); - } + for (int i = 0; i < n * 1024; i++) { sum += *(x++); } *res = sum; 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++) { @@ -297,7 +269,7 @@ 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++) { - sum += mmu_get_uint16(x++); //*(x++); + sum += mmu_get_uint16(x++); //*(x++); } *res = sum; return ESP.getCycleCount() - b; @@ -318,7 +290,7 @@ 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++) { - sum += mmu_get_int16(x++); //*(x++); + sum += mmu_get_int16(x++); //*(x++); } *res = sum; return ESP.getCycleCount() - b; @@ -335,17 +307,17 @@ 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++) { - sum += mmu_get_uint8(x++); //*(x++); + sum += mmu_get_uint8(x++); //*(x++); } *res = sum; 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++) { @@ -363,19 +335,20 @@ bool perfTest_nK(int nK, uint32_t *mem, uint32_t *imem) { 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");; - t = cyclesToWrite_nKx16(nK, (uint16_t*)mem); + 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); + t = cyclesToRead_nKx16(nK, (uint16_t *)mem, &verify_res); Serial.printf("DRAM Memory Read: %7d cycles for %dK by uint16, %3d AVG cycles/transfer (sum %08x)\r\n", t, nK, t / (nK * 1024), verify_res); - t = cyclesToWrite_nKxs16(nK, (int16_t*)mem); + t = cyclesToWrite_nKxs16(nK, (int16_t *)mem); Serial.printf("DRAM Memory Write: %7d cycles for %dK by int16, %3d AVG cycles/transfer\r\n", t, nK, t / (nK * 1024)); - t = cyclesToRead_nKxs16(nK, (int16_t*)mem, &verify_sres); + t = cyclesToRead_nKxs16(nK, (int16_t *)mem, &verify_sres); Serial.printf("DRAM Memory Read: %7d cycles for %dK by int16, %3d AVG cycles/transfer (sum %08x)\r\n", t, nK, t / (nK * 1024), verify_sres); - t = cyclesToWrite_nKx16_viaInline(nK, (uint16_t*)imem); + t = cyclesToWrite_nKx16_viaInline(nK, (uint16_t *)imem); Serial.printf("IRAM Memory Write Inline: %7d cycles for %dK by uint16, %3d AVG cycles/transfer\r\n", t, nK, t / (nK * 1024)); - t = cyclesToRead_nKx16_viaInline(nK, (uint16_t*)imem, &res); + t = cyclesToRead_nKx16_viaInline(nK, (uint16_t *)imem, &res); Serial.printf("IRAM Memory Read Inline: %7d cycles for %dK by uint16, %3d AVG cycles/transfer (sum %08x) ", t, nK, t / (nK * 1024), res); if (res == verify_res) { Serial.printf("- passed\r\n"); @@ -384,9 +357,9 @@ bool perfTest_nK(int nK, uint32_t *mem, uint32_t *imem) { success = false; } - t = cyclesToWrite_nKxs16_viaInline(nK, (int16_t*)imem); + t = cyclesToWrite_nKxs16_viaInline(nK, (int16_t *)imem); Serial.printf("IRAM Memory Write Inline: %7d cycles for %dK by int16, %3d AVG cycles/transfer\r\n", t, nK, t / (nK * 1024)); - t = cyclesToRead_nKxs16_viaInline(nK, (int16_t*)imem, &sres); + t = cyclesToRead_nKxs16_viaInline(nK, (int16_t *)imem, &sres); Serial.printf("IRAM Memory Read Inline: %7d cycles for %dK by int16, %3d AVG cycles/transfer (sum %08x) ", t, nK, t / (nK * 1024), sres); if (sres == verify_sres) { Serial.printf("- passed\r\n"); @@ -395,9 +368,9 @@ bool perfTest_nK(int nK, uint32_t *mem, uint32_t *imem) { success = false; } - t = cyclesToWrite_nKx16(nK, (uint16_t*)imem); + t = cyclesToWrite_nKx16(nK, (uint16_t *)imem); Serial.printf("IRAM 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*)imem, &res); + t = cyclesToRead_nKx16(nK, (uint16_t *)imem, &res); Serial.printf("IRAM Memory Read: %7d cycles for %dK by uint16, %3d AVG cycles/transfer (sum %08x) ", t, nK, t / (nK * 1024), res); if (res == verify_res) { Serial.printf("- passed\r\n"); @@ -405,9 +378,9 @@ bool perfTest_nK(int nK, uint32_t *mem, uint32_t *imem) { Serial.printf("!= (sum %08x ) - failed\r\n", verify_res); success = false; } - t = cyclesToWrite_nKxs16(nK, (int16_t*)imem); + t = cyclesToWrite_nKxs16(nK, (int16_t *)imem); Serial.printf("IRAM Memory Write: %7d cycles for %dK by int16, %3d AVG cycles/transfer\r\n", t, nK, t / (nK * 1024)); - t = cyclesToRead_nKxs16(nK, (int16_t*)imem, &sres); + t = cyclesToRead_nKxs16(nK, (int16_t *)imem, &sres); Serial.printf("IRAM Memory Read: %7d cycles for %dK by int16, %3d AVG cycles/transfer (sum %08x) ", t, nK, t / (nK * 1024), sres); if (sres == verify_sres) { Serial.printf("- passed\r\n"); @@ -416,15 +389,16 @@ 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");; - t = cyclesToWrite_nKx8(nK, (uint8_t*)mem); + 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); + t = cyclesToRead_nKx8(nK, (uint8_t *)mem, &verify_res); Serial.printf("DRAM Memory Read: %7d cycles for %dK by uint8, %3d AVG cycles/transfer (sum %08x)\r\n", t, nK, t / (nK * 1024), verify_res); - t = cyclesToWrite_nKx8_viaInline(nK, (uint8_t*)imem); + t = cyclesToWrite_nKx8_viaInline(nK, (uint8_t *)imem); Serial.printf("IRAM Memory Write Inline: %7d cycles for %dK by uint8, %3d AVG cycles/transfer\r\n", t, nK, t / (nK * 1024)); - t = cyclesToRead_nKx8_viaInline(nK, (uint8_t*)imem, &res); + t = cyclesToRead_nKx8_viaInline(nK, (uint8_t *)imem, &res); Serial.printf("IRAM Memory Read Inline: %7d cycles for %dK by uint8, %3d AVG cycles/transfer (sum %08x) ", t, nK, t / (nK * 1024), res); if (res == verify_res) { Serial.printf("- passed\r\n"); @@ -433,9 +407,9 @@ bool perfTest_nK(int nK, uint32_t *mem, uint32_t *imem) { success = false; } - t = cyclesToWrite_nKx8(nK, (uint8_t*)imem); + t = cyclesToWrite_nKx8(nK, (uint8_t *)imem); Serial.printf("IRAM 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*)imem, &res); + t = cyclesToRead_nKx8(nK, (uint8_t *)imem, &res); Serial.printf("IRAM Memory Read: %7d cycles for %dK by uint8, %3d AVG cycles/transfer (sum %08x) ", t, nK, t / (nK * 1024), res); if (res == verify_res) { Serial.printf("- passed\r\n"); @@ -469,9 +443,7 @@ void setup() { Serial.printf("DRAM free: %6d\r\n", ESP.getFreeHeap()); 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; - } + if (!mem) { return; } // Now request from the IRAM heap #ifdef USE_SET_IRAM_HEAP @@ -495,14 +467,13 @@ void setup() { Serial.printf("IRAM buffer: Address %p, free %d\r\n", imem, ESP.getFreeHeap()); } #endif - if (!imem) { - return; - } + if (!imem) { return; } 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); @@ -595,8 +566,7 @@ void setup() { uint32_t hmax; uint8_t hfrag; ESP.getHeapStats(&hfree, &hmax, &hfrag); - ETS_PRINTF("ESP.getHeapStats(free: %u, max: %u, frag: %u)\n", - hfree, hmax, hfrag); + ETS_PRINTF("ESP.getHeapStats(free: %u, max: %u, frag: %u)\n", hfree, hmax, hfrag); if (free_iram > UMM_OVERHEAD_ADJUST) { void *all = malloc(free_iram - UMM_OVERHEAD_ADJUST); ETS_PRINTF("%p = malloc(%u)\n", all, free_iram); @@ -611,19 +581,22 @@ void setup() { } } -void processKey(Print& out, int hotKey) { +void processKey(Print &out, int hotKey) { switch (hotKey) { - case 'd': { + 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()); @@ -638,10 +611,8 @@ void processKey(Print& out, int hotKey) { out.printf_P(PSTR("Restart, ESP.restart(); ...\r\n")); ESP.restart(); break; - case '\r': - out.println(); - case '\n': - break; + case '\r': out.println(); + case '\n': break; case '?': out.println(); out.println(F("Press a key + ")); diff --git a/libraries/esp8266/examples/virtualmem/virtualmem.ino b/libraries/esp8266/examples/virtualmem/virtualmem.ino index 47b9396cc7..1c4e3340fa 100644 --- a/libraries/esp8266/examples/virtualmem/virtualmem.ino +++ b/libraries/esp8266/examples/virtualmem/virtualmem.ino @@ -2,9 +2,7 @@ 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++) { - sum += *(x++); - } + for (int i = 0; i < 1024; i++) { sum += *(x++); } *res = sum; return ESP.getCycleCount() - b; } @@ -23,9 +21,7 @@ uint32_t cyclesToWrite1Kx32(unsigned int *x) { 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++) { - sum += *(x++); - } + for (int i = 0; i < 1024; i++) { sum += *(x++); } *res = sum; return ESP.getCycleCount() - b; } @@ -40,17 +36,15 @@ 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++) { - sum += *(x++); - } + for (int i = 0; i < 1024; i++) { sum += *(x++); } *res = sum; 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++) { @@ -88,24 +82,24 @@ void setup() { t = cyclesToRead1Kx32(mem, &res); Serial.printf("Physical Memory Read: %d cycles for 4K (sum %08x)\n", t, res); - t = cyclesToWrite1Kx16((uint16_t*)vm); + t = cyclesToWrite1Kx16((uint16_t *)vm); Serial.printf("Virtual Memory Write: %d cycles for 2K by 16\n", t); - t = cyclesToWrite1Kx16((uint16_t*)mem); + t = cyclesToWrite1Kx16((uint16_t *)mem); Serial.printf("Physical Memory Write: %d cycles for 2K by 16\n", t); - t = cyclesToRead1Kx16((uint16_t*)vm, &res); + t = cyclesToRead1Kx16((uint16_t *)vm, &res); Serial.printf("Virtual Memory Read: %d cycles for 2K by 16 (sum %08x)\n", t, res); - t = cyclesToRead1Kx16((uint16_t*)mem, &res); + t = cyclesToRead1Kx16((uint16_t *)mem, &res); Serial.printf("Physical Memory Read: %d cycles for 2K by 16 (sum %08x)\n", t, res); - t = cyclesToWrite1Kx8((uint8_t*)vm); + t = cyclesToWrite1Kx8((uint8_t *)vm); Serial.printf("Virtual Memory Write: %d cycles for 1K by 8\n", t); - t = cyclesToWrite1Kx8((uint8_t*)mem); + t = cyclesToWrite1Kx8((uint8_t *)mem); Serial.printf("Physical Memory Write: %d cycles for 1K by 8\n", t); - t = cyclesToRead1Kx8((uint8_t*)vm, &res); + t = cyclesToRead1Kx8((uint8_t *)vm, &res); Serial.printf("Virtual Memory Read: %d cycles for 1K by 8 (sum %08x)\n", t, res); - t = cyclesToRead1Kx8((uint8_t*)mem, &res); + t = cyclesToRead1Kx8((uint8_t *)mem, &res); Serial.printf("Physical Memory Read: %d cycles for 1K by 8 (sum %08x)\n", t, res); // Let's use external heap to make a big ole' String @@ -133,6 +127,4 @@ void setup() { ESP.resetHeap(); } -void loop() { - -} +void loop() {} diff --git a/libraries/lwIP_PPP/examples/PPPServer/PPPServer.ino b/libraries/lwIP_PPP/examples/PPPServer/PPPServer.ino index ed2943c278..f5e93eeb4b 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 @@ -34,18 +34,15 @@ #define NAPT 200 #define NAPT_PORT 3 -#define RX 13 // d1mini D7 -#define TX 15 // d1mini D8 +#define RX 13 // d1mini D7 +#define TX 15 // d1mini D8 SoftwareSerial ppplink(RX, TX); HardwareSerial& logger = Serial; 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()); + 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()); logger.printf("Heap before: %d\n", ESP.getFreeHeap()); err_t ret = ip_napt_init(NAPT, NAPT_PORT); @@ -53,9 +50,7 @@ void PPPConnectedCallback(netif* nif) { if (ret == ERR_OK) { ret = ip_napt_enable_no(nif->num, 1); logger.printf("ip_napt_enable(nif): ret=%d (OK=%d)\n", (int)ret, (int)ERR_OK); - if (ret == ERR_OK) { - logger.printf("PPP client is NATed\n"); - } + if (ret == ERR_OK) { logger.printf("PPP client is NATed\n"); } // could not make this work yet, // but packets are arriving on ppp client (= linux host) @@ -64,9 +59,7 @@ void PPPConnectedCallback(netif* nif) { logger.printf("redirect443=%d\n", ip_portmap_add(IP_PROTO_TCP, ip_2_ip4(&nif->ip_addr)->addr, 443, ip_2_ip4(&nif->gw)->addr, 443)); } logger.printf("Heap after napt init: %d\n", ESP.getFreeHeap()); - if (ret != ERR_OK) { - logger.printf("NAPT initialization failed\n"); - } + if (ret != ERR_OK) { logger.printf("NAPT initialization failed\n"); } } void setup() { @@ -79,10 +72,7 @@ void setup() { logger.print('.'); 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()); + 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()); ppplink.begin(PPPLINKBAUD); ppplink.enableIntTx(true); @@ -107,5 +97,4 @@ void setup() { #endif -void loop() { -} +void loop() {} diff --git a/libraries/lwIP_PPP/src/PPPServer.cpp b/libraries/lwIP_PPP/src/PPPServer.cpp index 98fddd7777..2e44d2433a 100644 --- a/libraries/lwIP_PPP/src/PPPServer.cpp +++ b/libraries/lwIP_PPP/src/PPPServer.cpp @@ -2,8 +2,8 @@ // This is still beta / a work in progress // testing on linux: -// sudo /usr/sbin/pppd /dev/ttyUSB1 38400 noipdefault nocrtscts local defaultroute noauth nodetach debug dump -// sudo /usr/sbin/pppd /dev/ttyUSB1 38400 noipdefault nocrtscts local defaultroute noauth +// sudo /usr/sbin/pppd /dev/ttyUSB1 38400 noipdefault nocrtscts local defaultroute noauth nodetach +// debug dump sudo /usr/sbin/pppd /dev/ttyUSB1 38400 noipdefault nocrtscts local defaultroute noauth // proxy arp is needed but we don't have it // http://lwip.100.n7.nabble.com/PPP-proxy-arp-support-tp33286p33345.html @@ -16,9 +16,7 @@ #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) { } bool PPPServer::handlePackets() { @@ -38,15 +36,15 @@ bool PPPServer::handlePackets() void PPPServer::link_status_cb_s(ppp_pcb* pcb, int err_code, void* ctx) { - bool stop = true; - netif* nif = ppp_netif(pcb); + bool stop = true; + netif* nif = ppp_netif(pcb); 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"); #if LWIP_IPV4 @@ -68,54 +66,54 @@ void PPPServer::link_status_cb_s(ppp_pcb* pcb, int err_code, void* ctx) 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. */ + case PPPERR_PARAM: /* Invalid parameter. */ ets_printf("ppp_link_status_cb: PPPERR_PARAM\n"); break; - case PPPERR_OPEN: /* Unable to open PPP session. */ + 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. */ + 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. */ + case PPPERR_ALLOC: /* Unable to allocate resources. */ ets_printf("ppp_link_status_cb: PPPERR_ALLOC\n"); break; - case PPPERR_USER: /* User interrupt. */ + case PPPERR_USER: /* User interrupt. */ ets_printf("ppp_link_status_cb: PPPERR_USER\n"); break; - case PPPERR_CONNECT: /* Connection lost. */ + case PPPERR_CONNECT: /* Connection lost. */ ets_printf("ppp_link_status_cb: PPPERR_CONNECT\n"); break; - case PPPERR_AUTHFAIL: /* Failed authentication challenge. */ + case PPPERR_AUTHFAIL: /* Failed authentication challenge. */ ets_printf("ppp_link_status_cb: PPPERR_AUTHFAIL\n"); break; - case PPPERR_PROTOCOL: /* Failed to meet protocol. */ + case PPPERR_PROTOCOL: /* Failed to meet protocol. */ ets_printf("ppp_link_status_cb: PPPERR_PROTOCOL\n"); break; - case PPPERR_PEERDEAD: /* Connection timeout. */ + case PPPERR_PEERDEAD: /* Connection timeout. */ ets_printf("ppp_link_status_cb: PPPERR_PEERDEAD\n"); break; - case PPPERR_IDLETIMEOUT: /* Idle Timeout. */ + case PPPERR_IDLETIMEOUT: /* Idle Timeout. */ ets_printf("ppp_link_status_cb: PPPERR_IDLETIMEOUT\n"); break; - case PPPERR_CONNECTTIME: /* PPPERR_CONNECTTIME. */ + case PPPERR_CONNECTTIME: /* PPPERR_CONNECTTIME. */ ets_printf("ppp_link_status_cb: PPPERR_CONNECTTIME\n"); break; - case PPPERR_LOOPBACK: /* Connection timeout. */ + case PPPERR_LOOPBACK: /* Connection timeout. */ ets_printf("ppp_link_status_cb: PPPERR_LOOPBACK\n"); break; @@ -165,22 +163,24 @@ bool PPPServer::begin(const IPAddress& ourAddress, const IPAddress& peer) ppp_set_ipcp_ouraddr(_ppp, ip_2_ip4((const ip_addr_t*)ourAddress)); ppp_set_ipcp_hisaddr(_ppp, ip_2_ip4((const ip_addr_t*)peer)); - //ip4_addr_t addr; - //IP4_ADDR(&addr, 10,0,1,254); - //ppp_set_ipcp_dnsaddr(_ppp, 0, &addr); + // ip4_addr_t addr; + // IP4_ADDR(&addr, 10,0,1,254); + // ppp_set_ipcp_dnsaddr(_ppp, 0, &addr); - //ppp_set_auth(_ppp, PPPAUTHTYPE_ANY, "login", "password"); - //ppp_set_auth_required(_ppp, 1); + // ppp_set_auth(_ppp, PPPAUTHTYPE_ANY, "login", "password"); + // ppp_set_auth_required(_ppp, 1); ppp_set_silent(_ppp, 1); ppp_listen(_ppp); netif_set_status_callback(&_netif, _cb); _enabled = true; - if (!schedule_recurrent_function_us([&]() -{ - return this->handlePackets(); - }, 1000)) + if (!schedule_recurrent_function_us( + [&]() + { + 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..260ebfe2d8 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 @@ -40,7 +39,6 @@ class PPPServer { public: - PPPServer(Stream* sio); bool begin(const IPAddress& ourAddress, const IPAddress& peer = IPAddress(172, 31, 255, 254)); @@ -56,22 +54,20 @@ class PPPServer } protected: - static constexpr size_t _bufsize = 128; - Stream* _sio; - ppp_pcb* _ppp; - netif _netif; + Stream* _sio; + ppp_pcb* _ppp; + netif _netif; void (*_cb)(netif*); uint8_t _buf[_bufsize]; - bool _enabled; + bool _enabled; // feed ppp from stream - to call on a regular basis or on interrupt bool handlePackets(); 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); - + 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..979d88e9ea 100644 --- a/libraries/lwIP_enc28j60/src/utility/enc28j60.cpp +++ b/libraries/lwIP_enc28j60/src/utility/enc28j60.cpp @@ -42,10 +42,9 @@ #include "enc28j60.h" - -void serial_printf(const char *fmt, ...) +void serial_printf(const char* fmt, ...) { - char buf[128]; + char buf[128]; va_list args; va_start(args, fmt); vsnprintf(buf, 128, fmt, 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,39 +139,34 @@ 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) +uint8_t ENC28J60::is_mac_mii_reg(uint8_t reg) { /* MAC or MII register (otherwise, ETH register)? */ switch (_bank) @@ -184,8 +182,7 @@ ENC28J60::is_mac_mii_reg(uint8_t reg) } } /*---------------------------------------------------------------------------*/ -uint8_t -ENC28J60::readreg(uint8_t reg) +uint8_t ENC28J60::readreg(uint8_t reg) { uint8_t r; enc28j60_arch_spi_select(); @@ -200,8 +197,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 +205,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 +220,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 +235,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 +254,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(); @@ -283,8 +273,7 @@ ENC28J60::readdata(uint8_t *buf, int len) return i; } /*---------------------------------------------------------------------------*/ -uint8_t -ENC28J60::readdatabyte(void) +uint8_t ENC28J60::readdatabyte(void) { uint8_t r; readdata(&r, 1); @@ -292,8 +281,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 */ @@ -304,8 +292,7 @@ ENC28J60::softreset(void) /*---------------------------------------------------------------------------*/ //#if DEBUG -uint8_t -ENC28J60::readrev(void) +uint8_t ENC28J60::readrev(void) { uint8_t rev; setregbank(MAADRX_BANK); @@ -324,8 +311,7 @@ ENC28J60::readrev(void) /*---------------------------------------------------------------------------*/ -bool -ENC28J60::reset(void) +bool ENC28J60::reset(void) { PRINTF("enc28j60: resetting chip\n"); @@ -398,7 +384,7 @@ 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); @@ -470,8 +456,7 @@ 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 */ @@ -531,12 +516,11 @@ ENC28J60::reset(void) return true; } /*---------------------------------------------------------------------------*/ -boolean -ENC28J60::begin(const uint8_t *address) +boolean ENC28J60::begin(const uint8_t* address) { _localMac = address; - bool ret = reset(); + bool ret = reset(); uint8_t rev = readrev(); PRINTF("ENC28J60 rev. B%d\n", rev); @@ -546,8 +530,7 @@ ENC28J60::begin(const uint8_t *address) /*---------------------------------------------------------------------------*/ -uint16_t -ENC28J60::sendFrame(const uint8_t *data, uint16_t datalen) +uint16_t ENC28J60::sendFrame(const uint8_t* data, uint16_t datalen) { uint16_t dataend; @@ -598,13 +581,14 @@ 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) { uint16_t erdpt; - uint8_t tsv[7]; + uint8_t tsv[7]; erdpt = (readreg(ERDPTH) << 8) | readreg(ERDPTL); writereg(ERDPTL, (dataend + 1) & 0xff); writereg(ERDPTH, (dataend + 1) >> 8); @@ -612,35 +596,32 @@ ENC28J60::sendFrame(const uint8_t *data, uint16_t datalen) 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]); + " 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 { - 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]); + 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]); } #endif - //sent_packets++; - //PRINTF("enc28j60: sent_packets %d\n", sent_packets); + // sent_packets++; + // PRINTF("enc28j60: sent_packets %d\n", sent_packets); return datalen; } /*---------------------------------------------------------------------------*/ -uint16_t -ENC28J60::readFrame(uint8_t *buffer, uint16_t bufsize) +uint16_t ENC28J60::readFrame(uint8_t* buffer, uint16_t bufsize) { readFrameSize(); return readFrameData(buffer, bufsize); } -uint16_t -ENC28J60::readFrameSize() +uint16_t ENC28J60::readFrameSize() { uint8_t n; @@ -662,13 +643,13 @@ ENC28J60::readFrameSize() /* Read the next packet pointer */ nxtpkt[0] = readdatabyte(); nxtpkt[1] = readdatabyte(); - _next = (nxtpkt[1] << 8) + nxtpkt[0]; + _next = (nxtpkt[1] << 8) + nxtpkt[0]; PRINTF("enc28j60: nxtpkt 0x%02x%02x\n", _nxtpkt[1], _nxtpkt[0]); length[0] = readdatabyte(); length[1] = readdatabyte(); - _len = (length[1] << 8) + length[0]; + _len = (length[1] << 8) + length[0]; PRINTF("enc28j60: length 0x%02x%02x\n", length[1], length[0]); @@ -682,19 +663,16 @@ 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) +uint16_t ENC28J60::readFrameData(uint8_t* buffer, uint16_t framesize) { if (framesize < _len) { - buffer = nullptr; /* flush rx fifo */ @@ -733,12 +711,12 @@ ENC28J60::readFrameData(uint8_t *buffer, uint16_t framesize) PRINTF("enc28j60: rx err: flushed %d\n", _len); 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]); + 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]); - //received_packets++; - //PRINTF("enc28j60: received_packets %d\n", received_packets); + // received_packets++; + // PRINTF("enc28j60: received_packets %d\n", received_packets); return _len; } diff --git a/libraries/lwIP_enc28j60/src/utility/enc28j60.h b/libraries/lwIP_enc28j60/src/utility/enc28j60.h index 07ec39e929..07f71f96ff 100644 --- a/libraries/lwIP_enc28j60/src/utility/enc28j60.h +++ b/libraries/lwIP_enc28j60/src/utility/enc28j60.h @@ -46,7 +46,6 @@ */ class ENC28J60 { - public: /** Constructor that uses the default hardware SPI pins @@ -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); + virtual uint16_t readFrame(uint8_t* buffer, uint16_t bufsize); protected: - static constexpr bool interruptIsPossible() { return false; @@ -109,38 +107,37 @@ class ENC28J60 @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: - 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 writedatabyte(uint8_t byte); - int readdata(uint8_t *buf, int len); + 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 writedatabyte(uint8_t byte); + int readdata(uint8_t* buf, int len); uint8_t readdatabyte(void); - void softreset(void); + void softreset(void); uint8_t readrev(void); - bool reset(void); + bool reset(void); - void enc28j60_arch_spi_init(void); + void enc28j60_arch_spi_init(void); uint8_t enc28j60_arch_spi_write(uint8_t data); uint8_t enc28j60_arch_spi_read(void); - void enc28j60_arch_spi_select(void); - void enc28j60_arch_spi_deselect(void); + void enc28j60_arch_spi_select(void); + void enc28j60_arch_spi_deselect(void); // Previously defined in contiki/core/sys/clock.h void clock_delay_usec(uint16_t dt); - uint8_t _bank; - int8_t _cs; + uint8_t _bank; + 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..84ec861e31 100644 --- a/libraries/lwIP_w5100/src/utility/w5100.cpp +++ b/libraries/lwIP_w5100/src/utility/w5100.cpp @@ -35,15 +35,14 @@ #include #include "w5100.h" - uint8_t Wiznet5100::wizchip_read(uint16_t address) { uint8_t ret; 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; @@ -136,14 +134,14 @@ void Wiznet5100::wizchip_send_data(const uint8_t *wizdata, uint16_t len) ptr = getSn_TX_WR(); dst_mask = ptr & TxBufferMask; - dst_ptr = TxBufferAddress + dst_mask; + dst_ptr = TxBufferAddress + dst_mask; if (dst_mask + len > TxBufferLength) { size = TxBufferLength - dst_mask; wizchip_write_buf(dst_ptr, wizdata, size); wizdata += size; - size = len - size; + size = len - size; dst_ptr = TxBufferAddress; wizchip_write_buf(dst_ptr, wizdata, 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; @@ -167,15 +165,14 @@ void Wiznet5100::wizchip_recv_data(uint8_t *wizdata, uint16_t len) ptr = getSn_RX_RD(); src_mask = ptr & RxBufferMask; - src_ptr = RxBufferAddress + src_mask; - + src_ptr = RxBufferAddress + src_mask; if ((src_mask + len) > RxBufferLength) { size = RxBufferLength - src_mask; wizchip_read_buf(src_ptr, wizdata, size); wizdata += size; - size = len - size; + size = len - size; src_ptr = RxBufferAddress; wizchip_read_buf(src_ptr, wizdata, size); } @@ -201,19 +198,17 @@ 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 +252,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(); @@ -288,7 +284,7 @@ uint16_t Wiznet5100::readFrameSize() return 0; } - uint8_t head[2]; + uint8_t head[2]; uint16_t data_len = 0; wizchip_recv_data(head, 2); @@ -307,7 +303,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 +325,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..6e1f2c35cd 100644 --- a/libraries/lwIP_w5100/src/utility/w5100.h +++ b/libraries/lwIP_w5100/src/utility/w5100.h @@ -32,17 +32,15 @@ // original sources: https://github.com/njh/W5100MacRaw -#ifndef W5100_H -#define W5100_H +#ifndef W5100_H +#define W5100_H #include #include #include - class Wiznet5100 { - public: /** Constructor that uses the default hardware SPI pins @@ -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); + uint16_t readFrame(uint8_t* buffer, uint16_t bufsize); protected: - static constexpr bool interruptIsPossible() { return false; @@ -110,28 +107,30 @@ 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 */ - 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 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]; + int8_t _cs; + uint8_t _mac_address[6]; /** Default function to select chip. - @note This function help not to access wrong address. If you do not describe this function or register any functions, - null function is called. + @note This function help not to access wrong address. If you do not describe this function + or register any functions, null function is called. */ inline void wizchip_cs_select() { @@ -140,8 +139,8 @@ class Wiznet5100 /** Default function to deselect chip. - @note This function help not to access wrong address. If you do not describe this function or register any functions, - null function is called. + @note This function help not to access wrong address. If you do not describe this function + or register any functions, null function is called. */ inline void wizchip_cs_deselect() { @@ -194,7 +193,6 @@ class Wiznet5100 */ void wizchip_write_buf(uint16_t address, const uint8_t* pBuf, uint16_t len); - /** Reset WIZCHIP by softly. */ @@ -204,15 +202,15 @@ class Wiznet5100 It copies data to internal TX memory @details This function reads the Tx write pointer register and after that, - it copies the wizdata(pointer buffer) of the length of len(variable) bytes to internal TX memory - and updates the Tx write pointer register. - This function is being called by send() and sendto() function also. + it copies the wizdata(pointer buffer) of the length of len(variable) bytes to + internal TX memory and updates the Tx write pointer register. This function is being called + by send() and sendto() function also. @param wizdata Pointer buffer to write data @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,11 +224,12 @@ 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. - @details It discards the data of the length of len(variable) bytes in internal RX memory. + @details It discards the data of the length of len(variable) bytes in internal RX + memory. @param len Data length */ void wizchip_recv_ignore(uint16_t len); @@ -247,106 +246,105 @@ 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 */ enum { - Sn_IR_CON = 0x01, ///< CON Interrupt - Sn_IR_DISCON = 0x02, ///< DISCON Interrupt - Sn_IR_RECV = 0x04, ///< RECV Interrupt + Sn_IR_CON = 0x01, ///< CON Interrupt + Sn_IR_DISCON = 0x02, ///< DISCON Interrupt + Sn_IR_RECV = 0x04, ///< RECV Interrupt Sn_IR_TIMEOUT = 0x08, ///< TIMEOUT Interrupt - Sn_IR_SENDOK = 0x10, ///< SEND_OK Interrupt + Sn_IR_SENDOK = 0x10, ///< SEND_OK Interrupt }; /** 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 }; /** @@ -371,7 +369,8 @@ class Wiznet5100 /** Set local MAC address - @param (uint8_t*)shar Pointer variable to set local MAC address. It should be allocated 6 bytes. + @param (uint8_t*)shar Pointer variable to set local MAC address. It should be allocated 6 + bytes. @sa getSHAR() */ inline void setSHAR(const uint8_t* macaddr) @@ -381,7 +380,8 @@ class Wiznet5100 /** Get local MAC address - @param (uint8_t*)shar Pointer variable to get local MAC address. It should be allocated 6 bytes. + @param (uint8_t*)shar Pointer variable to get local MAC address. It should be allocated 6 + bytes. @sa setSHAR() */ inline void getSHAR(uint8_t* macaddr) @@ -496,4 +496,4 @@ class Wiznet5100 } }; -#endif // W5100_H +#endif // W5100_H diff --git a/libraries/lwIP_w5500/examples/TCPClient/TCPClient.ino b/libraries/lwIP_w5500/examples/TCPClient/TCPClient.ino index bdece2d88b..f2ba967592 100644 --- a/libraries/lwIP_w5500/examples/TCPClient/TCPClient.ino +++ b/libraries/lwIP_w5500/examples/TCPClient/TCPClient.ino @@ -5,32 +5,30 @@ #include #include -//or #include -//or #include +// or #include +// or #include -#include // WiFiClient (-> TCPClient) +#include // WiFiClient (-> TCPClient) const char* host = "djxmmx.net"; const uint16_t port = 17; using TCPClient = WiFiClient; -#define CSPIN 16 // wemos/lolin/nodemcu D0 +#define CSPIN 16 // wemos/lolin/nodemcu D0 Wiznet5500lwIP eth(CSPIN); void setup() { Serial.begin(115200); SPI.begin(); - SPI.setClockDivider(SPI_CLOCK_DIV4); // 4 MHz? + SPI.setClockDivider(SPI_CLOCK_DIV4); // 4 MHz? SPI.setBitOrder(MSBFIRST); SPI.setDataMode(SPI_MODE0); - eth.setDefault(); // use ethernet for default route + eth.setDefault(); // use ethernet for default route if (!eth.begin()) { Serial.println("ethernet hardware not found ... sleeping"); - while (1) { - delay(1000); - } + while (1) { delay(1000); } } else { Serial.print("connecting ethernet"); while (!eth.connected()) { @@ -60,9 +58,7 @@ void loop() { // This will send a string to the server Serial.println("sending data to server"); - if (client.connected()) { - client.println("hello from ESP8266"); - } + if (client.connected()) { client.println("hello from ESP8266"); } // wait for data to be available unsigned long timeout = millis(); @@ -89,7 +85,7 @@ void loop() { client.stop(); if (wait) { - delay(300000); // execute once every 5 minutes, don't flood remote service + delay(300000); // execute once every 5 minutes, don't flood remote service } wait = true; } 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..978cf9e74c 100644 --- a/libraries/lwIP_w5500/src/utility/w5500.cpp +++ b/libraries/lwIP_w5500/src/utility/w5500.cpp @@ -35,7 +35,6 @@ #include #include "w5500.h" - uint8_t Wiznet5500::wizchip_read(uint8_t block, uint16_t address) { uint8_t ret; @@ -95,10 +94,11 @@ 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) +void Wiznet5500::wizchip_write_buf(uint8_t block, uint16_t address, const uint8_t* pBuf, + uint16_t len) { uint16_t i; @@ -123,7 +123,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 +141,6 @@ uint16_t Wiznet5500::getSn_TX_FSR() return val; } - uint16_t Wiznet5500::getSn_RX_RSR() { uint16_t val = 0, val1 = 0; @@ -155,7 +155,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 +171,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 +198,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); } @@ -244,7 +244,7 @@ void Wiznet5500::wizphy_reset() int8_t Wiznet5500::wizphy_setphypmode(uint8_t pmode) { uint8_t tmp = 0; - tmp = getPHYCFGR(); + tmp = getPHYCFGR(); if ((tmp & PHYCFGR_OPMD) == 0) { return -1; @@ -278,14 +278,12 @@ 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(); @@ -360,7 +359,7 @@ uint16_t Wiznet5500::readFrameSize() return 0; } - uint8_t head[2]; + uint8_t head[2]; uint16_t data_len = 0; wizchip_recv_data(head, 2); @@ -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..f7babb51e9 100644 --- a/libraries/lwIP_w5500/src/utility/w5500.h +++ b/libraries/lwIP_w5500/src/utility/w5500.h @@ -39,11 +39,8 @@ #include #include - - class Wiznet5500 { - public: /** Constructor that uses the default hardware SPI pins @@ -51,7 +48,6 @@ class Wiznet5500 */ 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); + 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); - + 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,16 +128,14 @@ 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]; + int8_t _cs; + uint8_t _mac_address[6]; /** Default function to select chip. - @note This function help not to access wrong address. If you do not describe this function or register any functions, - null function is called. + @note This function help not to access wrong address. If you do not describe this function + or register any functions, null function is called. */ inline void wizchip_cs_select() { @@ -153,8 +144,8 @@ class Wiznet5500 /** Default function to deselect chip. - @note This function help not to access wrong address. If you do not describe this function or register any functions, - null function is called. + @note This function help not to access wrong address. If you do not describe this function + or register any functions, null function is called. */ inline void wizchip_cs_deselect() { @@ -163,8 +154,8 @@ class Wiznet5500 /** Default function to read in SPI interface. - @note This function help not to access wrong address. If you do not describe this function or register any functions, - null function is called. + @note This function help not to access wrong address. If you do not describe this function + or register any functions, null function is called. */ inline uint8_t wizchip_spi_read_byte() { @@ -173,15 +164,14 @@ class Wiznet5500 /** Default function to write in SPI interface. - @note This function help not to access wrong address. If you do not describe this function or register any functions, - null function is called. + @note This function help not to access wrong address. If you do not describe this function + or register any functions, null function is called. */ inline void wizchip_spi_write_byte(uint8_t wb) { _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. */ @@ -262,7 +251,8 @@ class Wiznet5500 void wizphy_reset(); /** - set the power mode of phy inside WIZCHIP. Refer to @ref PHYCFGR in W5500, @ref PHYSTATUS in W5200 + set the power mode of phy inside WIZCHIP. Refer to @ref PHYCFGR in W5500, @ref PHYSTATUS in + W5200 @param pmode Settig value of power down mode. */ int8_t wizphy_setphypmode(uint8_t pmode); @@ -271,15 +261,15 @@ class Wiznet5500 It copies data to internal TX memory @details This function reads the Tx write pointer register and after that, - it copies the wizdata(pointer buffer) of the length of len(variable) bytes to internal TX memory - and updates the Tx write pointer register. - This function is being called by send() and sendto() function also. + it copies the wizdata(pointer buffer) of the length of len(variable) bytes to + internal TX memory and updates the Tx write pointer register. This function is being called + by send() and sendto() function also. @param wizdata Pointer buffer to write data @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,183 +283,180 @@ 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. - @details It discards the data of the length of len(variable) bytes in internal RX memory. + @details It discards the data of the length of len(variable) bytes in internal RX + memory. @param len Data length */ void wizchip_recv_ignore(uint16_t len); - - /** Common registers */ enum { - MR = 0x0000, ///< Mode Register address (R/W) - SHAR = 0x0009, ///< Source MAC Register address (R/W) + MR = 0x0000, ///< Mode Register address (R/W) + SHAR = 0x0009, ///< Source MAC Register address (R/W) INTLEVEL = 0x0013, ///< Set Interrupt low level timer register address (R/W) - IR = 0x0015, ///< Interrupt Register (R/W) - _IMR_ = 0x0016, ///< Interrupt mask register (R/W) - SIR = 0x0017, ///< Socket Interrupt Register (R/W) - SIMR = 0x0018, ///< Socket Interrupt Mask Register (R/W) - _RTR_ = 0x0019, ///< Timeout register address (1 is 100us) (R/W) - _RCR_ = 0x001B, ///< Retry count register (R/W) - UIPR = 0x0028, ///< Unreachable IP register address in UDP mode (R) - UPORTR = 0x002C, ///< Unreachable Port register address in UDP mode (R) - PHYCFGR = 0x002E, ///< PHY Status Register (R/W) + IR = 0x0015, ///< Interrupt Register (R/W) + _IMR_ = 0x0016, ///< Interrupt mask register (R/W) + SIR = 0x0017, ///< Socket Interrupt Register (R/W) + SIMR = 0x0018, ///< Socket Interrupt Mask Register (R/W) + _RTR_ = 0x0019, ///< Timeout register address (1 is 100us) (R/W) + _RCR_ = 0x001B, ///< Retry count register (R/W) + UIPR = 0x0028, ///< Unreachable IP register address in UDP mode (R) + UPORTR = 0x002C, ///< Unreachable Port register address in UDP mode (R) + PHYCFGR = 0x002E, ///< PHY Status Register (R/W) VERSIONR = 0x0039, ///< Chip version register address (R) }; /** Socket registers */ enum { - Sn_MR = 0x0000, ///< Socket Mode register (R/W) - Sn_CR = 0x0001, ///< Socket command register (R/W) - Sn_IR = 0x0002, ///< Socket interrupt register (R) - Sn_SR = 0x0003, ///< Socket status register (R) - Sn_PORT = 0x0004, ///< Source port register (R/W) - Sn_DHAR = 0x0006, ///< Peer MAC register address (R/W) - Sn_DIPR = 0x000C, ///< Peer IP register address (R/W) - Sn_DPORT = 0x0010, ///< Peer port register address (R/W) - Sn_MSSR = 0x0012, ///< Maximum Segment Size(Sn_MSSR0) register address (R/W) - Sn_TOS = 0x0015, ///< IP Type of Service(TOS) Register (R/W) - Sn_TTL = 0x0016, ///< IP Time to live(TTL) Register (R/W) + Sn_MR = 0x0000, ///< Socket Mode register (R/W) + Sn_CR = 0x0001, ///< Socket command register (R/W) + Sn_IR = 0x0002, ///< Socket interrupt register (R) + Sn_SR = 0x0003, ///< Socket status register (R) + Sn_PORT = 0x0004, ///< Source port register (R/W) + Sn_DHAR = 0x0006, ///< Peer MAC register address (R/W) + Sn_DIPR = 0x000C, ///< Peer IP register address (R/W) + Sn_DPORT = 0x0010, ///< Peer port register address (R/W) + Sn_MSSR = 0x0012, ///< Maximum Segment Size(Sn_MSSR0) register address (R/W) + Sn_TOS = 0x0015, ///< IP Type of Service(TOS) Register (R/W) + Sn_TTL = 0x0016, ///< IP Time to live(TTL) Register (R/W) Sn_RXBUF_SIZE = 0x001E, ///< Receive memory size register (R/W) Sn_TXBUF_SIZE = 0x001F, ///< Transmit memory size register (R/W) - Sn_TX_FSR = 0x0020, ///< Transmit free memory size register (R) - Sn_TX_RD = 0x0022, ///< Transmit memory read pointer register address (R) - Sn_TX_WR = 0x0024, ///< Transmit memory write pointer register address (R/W) - Sn_RX_RSR = 0x0026, ///< Received data size register (R) - Sn_RX_RD = 0x0028, ///< Read point of Receive memory (R/W) - Sn_RX_WR = 0x002A, ///< Write point of Receive memory (R) - Sn_IMR = 0x002C, ///< Socket interrupt mask register (R) - Sn_FRAG = 0x002D, ///< Fragment field value in IP header register (R/W) - Sn_KPALVTR = 0x002F, ///< Keep Alive Timer register (R/W) + Sn_TX_FSR = 0x0020, ///< Transmit free memory size register (R) + Sn_TX_RD = 0x0022, ///< Transmit memory read pointer register address (R) + Sn_TX_WR = 0x0024, ///< Transmit memory write pointer register address (R/W) + Sn_RX_RSR = 0x0026, ///< Received data size register (R) + Sn_RX_RD = 0x0028, ///< Read point of Receive memory (R/W) + Sn_RX_WR = 0x002A, ///< Write point of Receive memory (R) + Sn_IMR = 0x002C, ///< Socket interrupt mask register (R) + Sn_FRAG = 0x002D, ///< Fragment field value in IP header register (R/W) + Sn_KPALVTR = 0x002F, ///< Keep Alive Timer register (R/W) }; /** Mode register values */ enum { - MR_RST = 0x80, ///< Reset - MR_WOL = 0x20, ///< Wake on LAN - MR_PB = 0x10, ///< Ping block + MR_RST = 0x80, ///< Reset + MR_WOL = 0x20, ///< Wake on LAN + MR_PB = 0x10, ///< Ping block MR_PPPOE = 0x08, ///< Enable PPPoE - MR_FARP = 0x02, ///< Enable UDP_FORCE_ARP CHECK + MR_FARP = 0x02, ///< Enable UDP_FORCE_ARP CHECK }; /* Interrupt Register values */ enum { IR_CONFLICT = 0x80, ///< Check IP conflict - IR_UNREACH = 0x40, ///< Get the destination unreachable message in UDP sending - IR_PPPoE = 0x20, ///< Get the PPPoE close message - IR_MP = 0x10, ///< Get the magic packet interrupt + IR_UNREACH = 0x40, ///< Get the destination unreachable message in UDP sending + IR_PPPoE = 0x20, ///< Get the PPPoE close message + IR_MP = 0x10, ///< Get the magic packet interrupt }; /* 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 */ enum { - Sn_IR_CON = 0x01, ///< CON Interrupt - Sn_IR_DISCON = 0x02, ///< DISCON Interrupt - Sn_IR_RECV = 0x04, ///< RECV Interrupt + Sn_IR_CON = 0x01, ///< CON Interrupt + Sn_IR_DISCON = 0x02, ///< DISCON Interrupt + Sn_IR_RECV = 0x04, ///< RECV Interrupt Sn_IR_TIMEOUT = 0x08, ///< TIMEOUT Interrupt - Sn_IR_SENDOK = 0x10, ///< SEND_OK Interrupt + Sn_IR_SENDOK = 0x10, ///< SEND_OK Interrupt }; /** 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_OPMDC_ALLA = (7 << 3), + 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), + PHYCFGR_OPMDC_NA = (5 << 3), PHYCFGR_OPMDC_100FA = (4 << 3), - PHYCFGR_OPMDC_100F = (3 << 3), - PHYCFGR_OPMDC_100H = (2 << 3), - PHYCFGR_OPMDC_10F = (1 << 3), - PHYCFGR_OPMDC_10H = (0 << 3), - PHYCFGR_DPX_FULL = (1 << 2), - PHYCFGR_DPX_HALF = (0 << 2), - PHYCFGR_SPD_100 = (1 << 1), - PHYCFGR_SPD_10 = (0 << 1), - PHYCFGR_LNK_ON = (1 << 0), - PHYCFGR_LNK_OFF = (0 << 0), + PHYCFGR_OPMDC_100F = (3 << 3), + PHYCFGR_OPMDC_100H = (2 << 3), + PHYCFGR_OPMDC_10F = (1 << 3), + PHYCFGR_OPMDC_10H = (0 << 3), + PHYCFGR_DPX_FULL = (1 << 2), + PHYCFGR_DPX_HALF = (0 << 2), + PHYCFGR_SPD_100 = (1 << 1), + PHYCFGR_SPD_10 = (0 << 1), + PHYCFGR_LNK_ON = (1 << 0), + PHYCFGR_LNK_OFF = (0 << 0), }; enum { - PHY_SPEED_10 = 0, ///< Link Speed 10 - PHY_SPEED_100 = 1, ///< Link Speed 100 + PHY_SPEED_10 = 0, ///< Link Speed 10 + PHY_SPEED_100 = 1, ///< Link Speed 100 PHY_DUPLEX_HALF = 0, ///< Link Half-Duplex PHY_DUPLEX_FULL = 1, ///< Link Full-Duplex - PHY_LINK_OFF = 0, ///< Link Off - PHY_LINK_ON = 1, ///< Link On - PHY_POWER_NORM = 0, ///< PHY power normal mode - PHY_POWER_DOWN = 1, ///< PHY power down mode + PHY_LINK_OFF = 0, ///< Link Off + PHY_LINK_ON = 1, ///< Link On + PHY_POWER_NORM = 0, ///< PHY power normal mode + PHY_POWER_DOWN = 1, ///< PHY power down mode }; - /** Set Mode Register @param (uint8_t)mr The value to be set. @@ -492,7 +479,8 @@ class Wiznet5500 /** Set local MAC address - @param (uint8_t*)shar Pointer variable to set local MAC address. It should be allocated 6 bytes. + @param (uint8_t*)shar Pointer variable to set local MAC address. It should be allocated 6 + bytes. @sa getSHAR() */ inline void setSHAR(const uint8_t* macaddr) @@ -502,7 +490,8 @@ class Wiznet5500 /** Get local MAC address - @param (uint8_t*)shar Pointer variable to get local MAC address. It should be allocated 6 bytes. + @param (uint8_t*)shar Pointer variable to get local MAC address. It should be allocated 6 + bytes. @sa setSHAR() */ inline void getSHAR(uint8_t* macaddr) @@ -764,4 +753,4 @@ class Wiznet5500 } }; -#endif // W5500_H +#endif // W5500_H 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/ci/style_check.sh b/tests/ci/style_check.sh index 609b7e4577..ddcd48b906 100755 --- a/tests/ci/style_check.sh +++ b/tests/ci/style_check.sh @@ -2,12 +2,12 @@ # # CI job for checking examples style -set -ev +set -e -x -org=$(cd ${0%/*}; pwd) -${org}/../restyle.sh +root=$(git rev-parse --show-toplevel) +${root}/tests/restyle.sh -# Revert changes which astyle might have done to the submodules, +# Revert changes which formatter might have done to the submodules, # as we don't want to fail the build because of the 3rd party libraries git --version || true git submodule foreach --recursive 'git reset --hard' diff --git a/tests/clang-format-arduino.yaml b/tests/clang-format-arduino.yaml new file mode 100644 index 0000000000..1a307caab9 --- /dev/null +++ b/tests/clang-format-arduino.yaml @@ -0,0 +1,149 @@ +# Taken from https://github.com/arduino/arduino-language-server/blob/e453c5fbd059bae673bb21d028f5ca8e690744be/handler/handler.go#L1769-L1952 +# Which will be used in the IDE 2.0+ when 'format sketch' option is selected + +Language: Cpp +# LLVM is the default style setting, used when a configuration option is not set here +BasedOnStyle: LLVM +AccessModifierOffset: -2 +AlignAfterOpenBracket: Align +AlignConsecutiveAssignments: false +AlignConsecutiveBitFields: false +AlignConsecutiveDeclarations: false +AlignConsecutiveMacros: false +AlignEscapedNewlines: DontAlign +AlignOperands: Align +AlignTrailingComments: true +AllowAllArgumentsOnNextLine: true +AllowAllConstructorInitializersOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: Always +AllowShortCaseLabelsOnASingleLine: true +AllowShortEnumsOnASingleLine: true +AllowShortFunctionsOnASingleLine: Empty +AllowShortIfStatementsOnASingleLine: Always +AllowShortLambdasOnASingleLine: Empty +AllowShortLoopsOnASingleLine: true +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: No +BinPackArguments: true +BinPackParameters: true +# Only used when "BreakBeforeBraces" set to "Custom" +BraceWrapping: + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: Never + AfterEnum: false + AfterFunction: false + AfterNamespace: false + #AfterObjCDeclaration: + AfterStruct: false + AfterUnion: false + AfterExternBlock: false + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: false + SplitEmptyRecord: false + SplitEmptyNamespace: false +# Java-specific +#BreakAfterJavaFieldAnnotations: +BreakBeforeBinaryOperators: NonAssignment +BreakBeforeBraces: Attach +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: BeforeColon +BreakInheritanceList: BeforeColon +BreakStringLiterals: false +# v12 has various problems with this set to 0 (no limit) +# possible workaround is to set this to 4294967295 aka some large number +# see https://reviews.llvm.org/D96896 +ColumnLimit: 0 +# "" matches none +CommentPragmas: "" +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: true +ConstructorInitializerIndentWidth: 2 +ContinuationIndentWidth: 2 +Cpp11BracedListStyle: false +DeriveLineEnding: true +DerivePointerAlignment: true +DisableFormat: false +# Docs say "Do not use this in config files". The default (LLVM 11.0.1) is "false". +#ExperimentalAutoDetectBinPacking: +FixNamespaceComments: false +ForEachMacros: [] +IncludeBlocks: Preserve +IncludeCategories: [] +# "" matches none +IncludeIsMainRegex: "" +IncludeIsMainSourceRegex: "" +IndentCaseBlocks: true +IndentCaseLabels: true +IndentExternBlock: Indent +IndentGotoLabels: false +IndentPPDirectives: None +IndentWidth: 2 +IndentWrappedFunctionNames: false +InsertTrailingCommas: None +# Java-specific +#JavaImportGroups: +# JavaScript-specific +#JavaScriptQuotes: +#JavaScriptWrapImports +KeepEmptyLinesAtTheStartOfBlocks: true +MacroBlockBegin: "" +MacroBlockEnd: "" +# Set to a large number to effectively disable +MaxEmptyLinesToKeep: 100000 +NamespaceIndentation: None +NamespaceMacros: [] +# Objective C-specific +#ObjCBinPackProtocolList: +#ObjCBlockIndentWidth: +#ObjCBreakBeforeNestedBlockParam: +#ObjCSpaceAfterProperty: +#ObjCSpaceBeforeProtocolList +PenaltyBreakAssignment: 1 +PenaltyBreakBeforeFirstCallParameter: 1 +PenaltyBreakComment: 1 +PenaltyBreakFirstLessLess: 1 +PenaltyBreakString: 1 +PenaltyBreakTemplateDeclaration: 1 +PenaltyExcessCharacter: 1 +PenaltyReturnTypeOnItsOwnLine: 1 +# Used as a fallback if alignment style can't be detected from code (DerivePointerAlignment: true) +PointerAlignment: Right +RawStringFormats: [] +ReflowComments: true +SortIncludes: false +SortUsingDeclarations: false +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: false +SpaceBeforeAssignmentOperators: true +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatements +SpaceBeforeRangeBasedForLoopColon: true +SpaceBeforeSquareBrackets: false +SpaceInEmptyBlock: false +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 2 +SpacesInAngles: false +SpacesInCStyleCastParentheses: false +SpacesInConditionalStatement: false +SpacesInContainerLiterals: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Auto +StatementMacros: [] +TabWidth: 2 +TypenameMacros: [] +# Default to LF if line endings can't be detected from the content (DeriveLineEnding). +UseCRLF: false +UseTab: Never +WhitespaceSensitiveMacros: [] diff --git a/tests/clang-format-core.yaml b/tests/clang-format-core.yaml new file mode 100644 index 0000000000..f8e8bd13b9 --- /dev/null +++ b/tests/clang-format-core.yaml @@ -0,0 +1,29 @@ +BasedOnStyle: WebKit +AlignTrailingComments: true +SortIncludes: false +ColumnLimit: 100 +KeepEmptyLinesAtTheStartOfBlocks: false +SpaceAfterTemplateKeyword: false +SpaceBeforeInheritanceColon: false +SpacesBeforeTrailingComments: 2 +AlignTrailingComments: true +AllowShortBlocksOnASingleLine: Empty +AllowShortFunctionsOnASingleLine: Empty +AllowShortIfStatementsOnASingleLine: false +AllowShortLambdasOnASingleLine: Empty +AllowShortLoopsOnASingleLine: false +AlignConsecutiveAssignments: Consecutive +AlignConsecutiveBitFields: Consecutive +AlignConsecutiveDeclarations: Consecutive +AlignAfterOpenBracket: Align +AlignOperands: Align +AlwaysBreakTemplateDeclarations: Yes +BreakConstructorInitializers: AfterColon +BreakBeforeBinaryOperators: All +BreakBeforeTernaryOperators: true +BreakBeforeConceptDeclarations: true +FixNamespaceComments: true +NamespaceIndentation: Inner +BreakBeforeBraces: Allman +IndentWidth: 4 +IndentCaseLabels: false diff --git a/tests/device/libraries/BSTest/src/BSArduino.h b/tests/device/libraries/BSTest/src/BSArduino.h index 2fd4dc66e0..10cd2c37d9 100644 --- a/tests/device/libraries/BSTest/src/BSArduino.h +++ b/tests/device/libraries/BSTest/src/BSArduino.h @@ -7,29 +7,30 @@ namespace bs class ArduinoIOHelper { public: - ArduinoIOHelper(Stream& stream) : m_stream(stream) - { - } + 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); - char temp[128]; - char* buffer = temp; - size_t len = vsnprintf(temp, sizeof(temp), format, arg); + char temp[128]; + 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); ets_vsnprintf(buffer, len + 1, format, arg); va_end(arg); } - len = m_stream.write((const uint8_t*) buffer, len); - if (buffer != temp) { + len = m_stream.write((const uint8_t*)buffer, len); + if (buffer != temp) + { delete[] buffer; } return len; @@ -40,16 +41,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,10 +69,11 @@ class ArduinoIOHelper typedef ArduinoIOHelper IOHelper; -inline void fatal() { +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 060bcdf18c..0d8c18365f 100644 --- a/tests/device/libraries/BSTest/src/BSArgs.h +++ b/tests/device/libraries/BSTest/src/BSArgs.h @@ -18,134 +18,162 @@ 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() do { \ - char_out = 0; \ - argv[argc++] = next_arg_start; \ - state = SS_SPACE; \ - } 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) - */ -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) { - int char_in = (unsigned char) *in_ptr; - if (char_in == 0) { - break; - } - int char_out = -1; - - 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; +#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 + * + * - 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 = '"'; + 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) + { + int char_in = (unsigned char)*in_ptr; + if (char_in == 0) + { + break; } - 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; + int char_out = -1; + + 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; } - 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; + /* need to output anything? */ + if (char_out >= 0) + { + *out_ptr = char_out; + ++out_ptr; } - break; } - /* need to output anything? */ - if (char_out >= 0) { - *out_ptr = char_out; - ++out_ptr; + /* 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; } - } - /* 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 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 05a874f956..91eb68e580 100644 --- a/tests/device/libraries/BSTest/src/BSProtocol.h +++ b/tests/device/libraries/BSTest/src/BSProtocol.h @@ -11,108 +11,120 @@ 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') { - return false; + 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); } - char* argv[4]; - size_t argc = split_args(line_buf, argv, sizeof(argv)/sizeof(argv[0])); - if (argc == 0) { - return false; + + template + void output_pretest_result(IO& io, bool res) + { + io.printf(BS_LINE_PREFIX "pretest result=%d\n", res ? 1 : 0); } - if (strcmp(argv[0], "setenv") == 0) { - if (argc != 3) { + + 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') + { 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; -} -} // ::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 4d1bfb56f0..93a29ba7a1 100644 --- a/tests/device/libraries/BSTest/src/BSStdio.h +++ b/tests/device/libraries/BSTest/src/BSStdio.h @@ -9,11 +9,9 @@ namespace bs class StdIOHelper { public: - StdIOHelper() - { - } + StdIOHelper() { } - size_t printf(const char *format, ...) + size_t printf(const char* format, ...) { va_list arg; va_start(arg, format); @@ -25,11 +23,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,10 +39,11 @@ class StdIOHelper typedef StdIOHelper IOHelper; -inline void fatal() { +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 11b4ee9f6e..f73de3e471 100644 --- a/tests/device/libraries/BSTest/src/BSTest.h +++ b/tests/device/libraries/BSTest/src/BSTest.h @@ -20,15 +20,18 @@ namespace bs { -typedef void(*test_case_func_t)(); +typedef void (*test_case_func_t)(); class TestCase { 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) + 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,36 +63,40 @@ class TestCase const char* desc() const { - return (m_desc)?m_desc:""; + return (m_desc) ? m_desc : ""; } protected: - TestCase* m_next = nullptr; + TestCase* m_next = nullptr; test_case_func_t m_func; - const char* m_file; - size_t m_line; - const char* m_name; - const char* m_desc; + const char* m_file; + size_t m_line; + const char* m_name; + const char* m_desc; }; -struct Registry { - void add(test_case_func_t func, const char* file, size_t line, const char* name, const char* desc) +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; } TestCase* m_first = nullptr; - TestCase* m_last = nullptr; + TestCase* m_last = nullptr; }; -struct Env { - std::function m_check_pass; +struct Env +{ + std::function m_check_pass; std::function m_check_fail; std::function m_fail; - Registry m_registry; + Registry m_registry; }; extern Env g_env; @@ -98,25 +105,27 @@ template class Runner { typedef Runner Tself; + 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); - g_env.m_fail = std::bind(&Tself::fail, this, std::placeholders::_1); + g_env.m_fail = std::bind(&Tself::fail, this, std::placeholders::_1); } ~Runner() { g_env.m_check_pass = 0; g_env.m_check_fail = 0; - g_env.m_fail = 0; + g_env.m_fail = 0; } void run() { - do { - } while(do_menu()); + do + { + } while (do_menu()); } void check_pass() @@ -132,7 +141,8 @@ class Runner void fail(size_t line) { - protocol::output_test_end(m_io, false, m_check_pass_count + m_check_fail_count, m_check_fail_count, line); + protocol::output_test_end(m_io, false, m_check_pass_count + m_check_fail_count, + m_check_fail_count, line); bs::fatal(); } @@ -141,22 +151,28 @@ 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) { - int id; + 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) { + for (int i = 0; i != id - 1 && tc; ++i, tc = tc->next()) + ; + if (!tc) + { bs::fatal(); } m_check_pass_count = 0; @@ -164,12 +180,13 @@ class Runner protocol::output_test_start(m_io, tc->file(), tc->line(), tc->name(), tc->desc()); tc->run(); bool success = m_check_fail_count == 0; - protocol::output_test_end(m_io, success, m_check_pass_count + m_check_fail_count, m_check_fail_count); + protocol::output_test_end(m_io, success, m_check_pass_count + m_check_fail_count, + m_check_fail_count); } } protected: - IO& m_io; + IO& m_io; size_t m_check_pass_count; size_t m_check_fail_count; }; @@ -177,7 +194,8 @@ class Runner class AutoReg { public: - AutoReg(test_case_func_t func, const char* file, size_t line, const char* name, const char* desc = nullptr) + 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); } @@ -185,39 +203,59 @@ 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(); } } -} // ::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); - -#endif //BSTEST_H +#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 diff --git a/tests/device/libraries/BSTest/test/test.cpp b/tests/device/libraries/BSTest/test/test.cpp index 863373e0de..6f0c253417 100644 --- a/tests/device/libraries/BSTest/test/test.cpp +++ b/tests/device/libraries/BSTest/test/test.cpp @@ -3,21 +3,23 @@ BS_ENV_DECLARE(); - int main() { - while(true) { - try{ + while (true) + { + try + { BS_RUN(); return 0; - }catch(...) { + } + catch (...) + { printf("Exception\n\n"); } } return 1; } - TEST_CASE("this test runs successfully", "[bluesmoke]") { CHECK(1 + 1 == 2); @@ -38,17 +40,12 @@ 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("this test also runs successfully", "[bluesmoke]") { } TEST_CASE("environment variables can be set and read from python", "[bluesmoke]") { @@ -57,4 +54,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 17f29098cd..9a19da58a4 100644 --- a/tests/device/test_libc/libm_string.c +++ b/tests/device/test_libc/libm_string.c @@ -3,8 +3,6 @@ #include #include - - #define memcmp memcmp_P #define memcpy memcpy_P #define memmem memmem_P @@ -18,416 +16,404 @@ #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 ) +static void _DEFUN(checkit, (ok, l), int ok _AND 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; + } +} /* 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) +static void _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); } } - - 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("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"; @@ -499,68 +485,69 @@ void libm_test_string() 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"); - -#if 0 /* strerror - VERY system-dependent. */ + /* 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[]; @@ -572,4 +559,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 2485af0923..02c536ed98 100644 --- a/tests/device/test_libc/memcpy-1.c +++ b/tests/device/test_libc/memcpy-1.c @@ -31,7 +31,6 @@ #include #include - #define memcmp memcmp_P #define memcpy memcpy_P #define memmem memmem_P @@ -69,106 +68,105 @@ #define TOO_MANY_ERRORS 11 static int errors = 0; -static void -print_error (char const* msg, ...) -{ - errors++; - if (errors == TOO_MANY_ERRORS) +static void 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) +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]; + 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) - abort (); - - printf("ok\n"); + /* 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"); } diff --git a/tests/device/test_libc/memmove1.c b/tests/device/test_libc/memmove1.c index f64feae759..8a6403ee94 100644 --- a/tests/device/test_libc/memmove1.c +++ b/tests/device/test_libc/memmove1.c @@ -55,140 +55,132 @@ #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) - 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. */ -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; - 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. */ -void -fill (unsigned char dest[MAX*3]) +void 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..e8663b9ba9 100644 --- a/tests/device/test_libc/strcmp-1.c +++ b/tests/device/test_libc/strcmp-1.c @@ -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,186 +105,183 @@ #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, ...) +static void 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. */ } } - extern int rand_seed; -void strcmp_main(void) +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) + 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) { - printf ("ERROR. FAILED.\n"); - abort (); + printf("ERROR. FAILED.\n"); + abort(); } - //exit (0); - printf("ok\n"); + // exit (0); + printf("ok\n"); } diff --git a/tests/device/test_libc/tstring.c b/tests/device/test_libc/tstring.c index 7e806b1027..7d508d4c6e 100644 --- a/tests/device/test_libc/tstring.c +++ b/tests/device/test_libc/tstring.c @@ -26,336 +26,297 @@ #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 ffeeae05cd..4b1d7070de 100644 --- a/tests/host/common/Arduino.cpp +++ b/tests/host/common/Arduino.cpp @@ -1,14 +1,14 @@ /* 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. */ @@ -41,7 +41,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(); @@ -58,38 +57,35 @@ 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; } -extern "C" void esp_suspend() -{ -} +extern "C" void esp_suspend() { } -extern "C" void esp_schedule() -{ -} +extern "C" void esp_schedule() { } -extern "C" void esp_yield() -{ -} +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; @@ -107,15 +103,14 @@ extern "C" void delayMicroseconds(unsigned int us) } #include "cont.h" -cont_t* g_pcont = NULL; -extern "C" void cont_suspend(cont_t*) -{ -} +cont_t* g_pcont = NULL; +extern "C" void cont_suspend(cont_t*) { } -extern "C" int __mockverbose (const char* fmt, ...) +extern "C" int __mockverbose(const char* fmt, ...) { (void)fmt; return 0; } -int mockverbose (const char* fmt, ...) __attribute__ ((weak, alias("__mockverbose"), format (printf, 1, 2))); +int mockverbose(const char* fmt, ...) + __attribute__((weak, alias("__mockverbose"), format(printf, 1, 2))); diff --git a/tests/host/common/ArduinoCatch.cpp b/tests/host/common/ArduinoCatch.cpp index 6a1e3cca23..2a3404a931 100644 --- a/tests/host/common/ArduinoCatch.cpp +++ b/tests/host/common/ArduinoCatch.cpp @@ -1,14 +1,14 @@ /* 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. */ @@ -17,4 +17,3 @@ #include #include #include "Arduino.h" - diff --git a/tests/host/common/ArduinoMain.cpp b/tests/host/common/ArduinoMain.cpp index ddda929d46..80e0a0c85b 100644 --- a/tests/host/common/ArduinoMain.cpp +++ b/tests/host/common/ArduinoMain.cpp @@ -30,7 +30,7 @@ */ #include -#include // wifi_get_ip_info() +#include // wifi_get_ip_info() #include #include @@ -41,280 +41,280 @@ #define MOCK_PORT_SHIFTER 9000 -bool user_exit = false; -bool run_once = false; -const char* host_interface = nullptr; -size_t spiffs_kb = 1024; -size_t littlefs_kb = 1024; -bool ignore_sigint = false; -bool restore_tty = false; -bool mockdebug = false; -int mock_port_shifter = MOCK_PORT_SHIFTER; -const char* fspath = nullptr; +bool user_exit = false; +bool run_once = false; +const char* host_interface = nullptr; +size_t spiffs_kb = 1024; +size_t littlefs_kb = 1024; +bool ignore_sigint = false; +bool restore_tty = false; +bool mockdebug = false; +int mock_port_shifter = MOCK_PORT_SHIFTER; +const char* fspath = nullptr; #define STDIN STDIN_FILENO 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" - "\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" - "\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); + 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" + "\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); } -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 () +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..c85e0b9dbc 100644 --- a/tests/host/common/ArduinoMainLittlefs.cpp +++ b/tests/host/common/ArduinoMainLittlefs.cpp @@ -3,15 +3,14 @@ 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..035cc9e752 100644 --- a/tests/host/common/ArduinoMainSpiffs.cpp +++ b/tests/host/common/ArduinoMainSpiffs.cpp @@ -3,15 +3,14 @@ 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..cfcaacef2a 100644 --- a/tests/host/common/ArduinoMainUdp.cpp +++ b/tests/host/common/ArduinoMainUdp.cpp @@ -33,28 +33,28 @@ #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..a0bc7610d8 100644 --- a/tests/host/common/ClientContextSocket.cpp +++ b/tests/host/common/ClientContextSocket.cpp @@ -39,168 +39,173 @@ #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..cf9987fea0 100644 --- a/tests/host/common/ClientContextTools.cpp +++ b/tests/host/common/ClientContextTools.cpp @@ -35,23 +35,24 @@ #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; - 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..c6bf0faa53 100644 --- a/tests/host/common/EEPROM.h +++ b/tests/host/common/EEPROM.h @@ -32,46 +32,53 @@ #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 1b93d72ece..3c40de0684 100644 --- a/tests/host/common/HostWiring.cpp +++ b/tests/host/common/HostWiring.cpp @@ -42,60 +42,82 @@ static uint8_t _mode[GPIONUM]; static uint8_t _gpio[GPIONUM]; -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); if (pin < GPIONUM) { - _mode[pin] = mode; + _mode[pin] = mode; } } void digitalWrite(uint8_t pin, uint8_t val) { - VERBOSE("digitalWrite(pin=%d val=%d)\n", pin, val); - if (pin < GPIONUM) { + VERBOSE("digitalWrite(pin=%d val=%d)\n", pin, val); + if (pin < GPIONUM) + { _gpio[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); - if (pin < GPIONUM) { - return _gpio[pin] != 0; - } else { - return 0; + if (pin < GPIONUM) + { + return _gpio[pin] != 0; + } + else + { + return 0; } } diff --git a/tests/host/common/MockEEPROM.cpp b/tests/host/common/MockEEPROM.cpp index 6357c73dd2..ff44b6b222 100644 --- a/tests/host/common/MockEEPROM.cpp +++ b/tests/host/common/MockEEPROM.cpp @@ -42,52 +42,52 @@ #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 293f6c5047..75c609ef65 100644 --- a/tests/host/common/MockEsp.cpp +++ b/tests/host/common/MockEsp.cpp @@ -36,204 +36,223 @@ #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() +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; } -void EspClass::getHeapStats(uint32_t* hfree, uint32_t* hmax, uint8_t* hfrag) { - uint32_t hf = 10 * 1024; - float hm = 1 * 1024; +void EspClass::getHeapStats(uint32_t* hfree, uint32_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) +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) +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) +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) +bool EspClass::flashRead(uint32_t offset, uint8_t* data, size_t size) { - (void)offset; - (void)data; - (void)size; - return true; + (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::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() @@ -241,9 +260,7 @@ uint32_t EspClass::getFreeContStack() return 4000; } -void EspClass::resetFreeContStack() -{ -} +void EspClass::resetFreeContStack() { } uint32_t EspClass::getCycleCount() { @@ -257,23 +274,15 @@ uint32_t esp_get_cycle_count() return (((uint64_t)t.tv_sec) * 1000000 + t.tv_usec) * (F_CPU / 1000000); } -void EspClass::setDramHeap() -{ -} +void EspClass::setDramHeap() { } -void EspClass::setIramHeap() -{ -} +void EspClass::setIramHeap() { } -void EspClass::setExternalHeap() -{ -} +void EspClass::setExternalHeap() { } -void EspClass::resetHeap() -{ -} +void EspClass::resetHeap() { } -void EspClass::reset () +void EspClass::reset() { abort(); } diff --git a/tests/host/common/MockSPI.cpp b/tests/host/common/MockSPI.cpp index 251cad914a..94422ddd2e 100644 --- a/tests/host/common/MockSPI.cpp +++ b/tests/host/common/MockSPI.cpp @@ -35,29 +35,23 @@ SPIClass SPI; #endif -SPIClass::SPIClass () -{ -} +SPIClass::SPIClass() { } uint8_t SPIClass::transfer(uint8_t data) { - return data; + return data; } -void SPIClass::begin() -{ -} +void SPIClass::begin() { } -void SPIClass::end() -{ -} +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 eb2c41ed12..2d9f79e999 100644 --- a/tests/host/common/MockTools.cpp +++ b/tests/host/common/MockTools.cpp @@ -34,56 +34,91 @@ 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() { } + 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) +void configTime(int timezone, int daylightOffset_sec, 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); } void configTime(const char* tz, 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='%s') (time will be host's)\n", tz); + mockverbose("configTime: TODO (tz='%s') (time will be host's)\n", tz); } diff --git a/tests/host/common/MockUART.cpp b/tests/host/common/MockUART.cpp index dc6514ae40..cce3648c58 100644 --- a/tests/host/common/MockUART.cpp +++ b/tests/host/common/MockUART.cpp @@ -28,475 +28,455 @@ is responsible for feeding the RX FIFO new data by calling uart_new_data(). */ -#include // write -#include // gettimeofday -#include // localtime +#include // write +#include // gettimeofday +#include // localtime #include "Arduino.h" #include "uart.h" //#define UART_DISCARD_NEWEST -extern "C" { - -bool blocking_uart = true; // system default - -static int s_uart_debug_nr = UART1; - -static uart_t *UART[2] = { NULL, NULL }; - -struct uart_rx_buffer_ +extern "C" { - size_t size; - size_t rpos; - size_t wpos; - uint8_t * buffer; -}; + bool blocking_uart = true; // system default -struct uart_ -{ - int uart_nr; - int baud_rate; - bool rx_enabled; - bool tx_enabled; - bool rx_overrun; - struct uart_rx_buffer_ * rx_buffer; -}; + static int s_uart_debug_nr = UART1; -bool serial_timestamp = false; + static uart_t* UART[2] = { NULL, NULL }; -// 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_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; + + // 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++); + size_t ret = size; + const int uart_nr = uart->uart_nr; + while (size--) + uart_do_write_char(uart_nr, *buf++); - return ret; -} + return ret; + } -size_t -uart_tx_free(uart_t* uart) -{ - if(uart == NULL || !uart->tx_enabled) - return 0; + size_t uart_tx_free(uart_t* uart) + { + if (uart == NULL || !uart->tx_enabled) + return 0; - return UART_TX_FIFO_SIZE; -} + return UART_TX_FIFO_SIZE; + } -void -uart_wait_tx_empty(uart_t* uart) -{ - (void) uart; -} + void uart_wait_tx_empty(uart_t* uart) + { + (void)uart; + } -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_flush(uart_t* uart) + { + if (uart == NULL) + return; + + if (uart->rx_enabled) + { + uart->rx_buffer->rpos = 0; + uart->rx_buffer->wpos = 0; + } + } -void -uart_set_baudrate(uart_t* uart, int baud_rate) -{ - if(uart == NULL) - return; + void uart_set_baudrate(uart_t* uart, int baud_rate) + { + if (uart == NULL) + return; - uart->baud_rate = baud_rate; -} + uart->baud_rate = baud_rate; + } -int -uart_get_baudrate(uart_t* uart) -{ - if(uart == NULL) - return 0; + int uart_get_baudrate(uart_t* uart) + { + if (uart == NULL) + return 0; - return uart->baud_rate; -} + return uart->baud_rate; + } -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); -} + 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); + } -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; -} + 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; + } -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); -} + 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_swap(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_tx(uart_t* uart, int tx_pin) -{ - (void) uart; - (void) tx_pin; - return true; -} + bool uart_set_tx(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_pins(uart_t* uart, int tx, int rx) + { + (void)uart; + (void)tx; + (void)rx; + return true; + } -bool -uart_tx_enabled(uart_t* uart) -{ - if(uart == NULL) - return false; + bool uart_tx_enabled(uart_t* uart) + { + if (uart == NULL) + return false; - return uart->tx_enabled; -} + return uart->tx_enabled; + } -bool -uart_rx_enabled(uart_t* uart) -{ - if(uart == NULL) - return false; + bool uart_rx_enabled(uart_t* uart) + { + if (uart == NULL) + return false; - return uart->rx_enabled; -} + return uart->rx_enabled; + } -bool -uart_has_overrun(uart_t* uart) -{ - if(uart == NULL || !uart->rx_overrun) - 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; -} + // clear flag + uart->rx_overrun = false; + return true; + } -bool -uart_has_rx_error(uart_t* uart) -{ - (void) uart; - return false; -} + bool uart_has_rx_error(uart_t* uart) + { + (void)uart; + return false; + } -void -uart_set_debug(int uart_nr) -{ - (void)uart_nr; -} + void uart_set_debug(int uart_nr) + { + (void)uart_nr; + } -int -uart_get_debug() + int uart_get_debug() + { + return s_uart_debug_nr; + } + + void uart_start_detect_baudrate(int uart_nr) + { + (void)uart_nr; + } + + int uart_detect_baudrate(int uart_nr) + { + (void)uart_nr; + return 115200; + } +}; + +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..f199a2b588 100644 --- a/tests/host/common/MockWiFiServer.cpp +++ b/tests/host/common/MockWiFiServer.cpp @@ -44,32 +44,31 @@ 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 #include uint32_t UdpContext::staticMCastAddr = 0; - diff --git a/tests/host/common/MockWiFiServerSocket.cpp b/tests/host/common/MockWiFiServerSocket.cpp index 9ab344bf50..1dd50b644f 100644 --- a/tests/host/common/MockWiFiServerSocket.cpp +++ b/tests/host/common/MockWiFiServerSocket.cpp @@ -44,26 +44,26 @@ // 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; @@ -71,85 +71,86 @@ void WiFiServer::begin (uint16_t port, uint8_t backlog) 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, // so the code has to act as if the tcp backlog list is full, // and nothing is known about potential further clients. - // It could be implemented by accepting new clients and store their data until the current one is closed. + // It could be implemented by accepting new clients and store their data until the current one + // is closed. 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..47b62ebb46 100644 --- a/tests/host/common/MocklwIP.cpp +++ b/tests/host/common/MocklwIP.cpp @@ -7,58 +7,54 @@ 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 "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 "C" diff --git a/tests/host/common/MocklwIP.h b/tests/host/common/MocklwIP.h index e7fead4cb7..9f0b4718f5 100644 --- a/tests/host/common/MocklwIP.h +++ b/tests/host/common/MocklwIP.h @@ -4,12 +4,11 @@ extern "C" { - #include #include -extern netif netif0; + 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 4212bb0ee4..c598460180 100644 --- a/tests/host/common/UdpContextSocket.cpp +++ b/tests/host/common/UdpContextSocket.cpp @@ -39,176 +39,189 @@ #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..bc0016658b 100644 --- a/tests/host/common/WMath.cpp +++ b/tests/host/common/WMath.cpp @@ -4,59 +4,69 @@ 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" { +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..9ba8968aeb 100644 --- a/tests/host/common/c_types.h +++ b/tests/host/common/c_types.h @@ -36,45 +36,46 @@ #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 */ -typedef enum { +typedef enum +{ OK = 0, FAIL, PENDING, @@ -82,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 @@ -93,9 +94,15 @@ 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 @@ -108,10 +115,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/esp8266_peri.h b/tests/host/common/esp8266_peri.h index 4a1a3cd031..4dcd6cb9cd 100644 --- a/tests/host/common/esp8266_peri.h +++ b/tests/host/common/esp8266_peri.h @@ -2,8 +2,8 @@ #ifndef FAKE_ESP8266_PERI_H #define FAKE_ESP8266_PERI_H -const int GPI = 0; -const int GPO = 0; +const int GPI = 0; +const int GPO = 0; const int GP16I = 0; #endif diff --git a/tests/host/common/flash_hal.h b/tests/host/common/flash_hal.h index e20edc4bcd..dddaa65523 100644 --- a/tests/host/common/flash_hal.h +++ b/tests/host/common/flash_hal.h @@ -11,17 +11,15 @@ extern "C" { + extern uint32_t s_phys_addr; + extern uint32_t s_phys_size; + extern uint32_t s_phys_page; + extern uint32_t s_phys_block; + extern uint8_t* s_phys_data; -extern uint32_t s_phys_addr; -extern uint32_t s_phys_size; -extern uint32_t s_phys_page; -extern uint32_t s_phys_block; -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_erase(uint32_t addr, uint32_t size); - + 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/flash_hal_mock.cpp b/tests/host/common/flash_hal_mock.cpp index aff589e02d..60b2620f1b 100644 --- a/tests/host/common/flash_hal_mock.cpp +++ b/tests/host/common/flash_hal_mock.cpp @@ -7,31 +7,35 @@ extern "C" { - uint32_t s_phys_addr = 0; - uint32_t s_phys_size = 0; - uint32_t s_phys_page = 0; + uint32_t s_phys_addr = 0; + uint32_t s_phys_size = 0; + uint32_t s_phys_page = 0; uint32_t s_phys_block = 0; - uint8_t* s_phys_data = nullptr; + 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) { - if ((size & (FLASH_SECTOR_SIZE - 1)) != 0 || - (addr & (FLASH_SECTOR_SIZE - 1)) != 0) { +int32_t flash_hal_erase(uint32_t addr, uint32_t size) +{ + if ((size & (FLASH_SECTOR_SIZE - 1)) != 0 || (addr & (FLASH_SECTOR_SIZE - 1)) != 0) + { abort(); } - const uint32_t sector = addr / FLASH_SECTOR_SIZE; + 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..4c8afb6b0b 100644 --- a/tests/host/common/include/ClientContext.h +++ b/tests/host/common/include/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,12 @@ 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; } @@ -172,10 +173,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,10 +190,10 @@ 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) + size_t peekBytes(char* dst, size_t size) { ssize_t ret = mockPeekBytes(_sock, dst, size, _timeout_ms, _inbuf, _inbufsize); if (ret < 0) @@ -216,60 +217,62 @@ 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; - (void) count; + (void)idle_sec; + (void)intv_sec; + (void)count; 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 +280,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 +298,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); @@ -303,22 +306,21 @@ class ClientContext } private: + discard_cb_t _discard_cb = nullptr; + void* _discard_cb_arg = nullptr; - discard_cb_t _discard_cb = nullptr; - void* _discard_cb_arg = nullptr; - - int8_t _refcnt; + int8_t _refcnt; ClientContext* _next; - + bool _sync; - + // MOCK - - int _sock = -1; + + 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 bf104bc40f..88cb46f9ae 100644 --- a/tests/host/common/include/UdpContext.h +++ b/tests/host/common/include/UdpContext.h @@ -37,17 +37,14 @@ extern netif netif0; class UdpContext { public: - typedef std::function rxhandler_t; - UdpContext(): _on_rx(nullptr), _refcnt(0) + UdpContext() : _on_rx(nullptr), _refcnt(0) { _sock = mockUDPSocket(); } - ~UdpContext() - { - } + ~UdpContext() { } void ref() { @@ -64,7 +61,7 @@ class UdpContext bool connect(const ip_addr_t* addr, uint16_t port) { - _dst = *addr; + _dst = *addr; _dstport = port; return true; } @@ -103,7 +100,7 @@ class UdpContext void setMulticastTTL(int ttl) { (void)ttl; - //mockverbose("TODO: UdpContext::setMulticastTTL\n"); + // mockverbose("TODO: UdpContext::setMulticastTTL\n"); } netif* getInputNetif() const @@ -156,13 +153,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,14 +188,14 @@ 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() { - //mockverbose("UdpContext::flush() does not follow arduino's flush concept\n"); - //exit(EXIT_FAILURE); - // would be: + // mockverbose("UdpContext::flush() does not follow arduino's flush concept\n"); + // exit(EXIT_FAILURE); + // would be: _inbufsize = 0; } @@ -206,7 +203,8 @@ class UdpContext { if (size + _outbufsize > sizeof _outbuf) { - mockverbose("UdpContext::append: increase CCBUFSIZE (%d -> %zd)\n", CCBUFSIZE, (size + _outbufsize)); + mockverbose("UdpContext::append: increase CCBUFSIZE (%d -> %zd)\n", CCBUFSIZE, + (size + _outbufsize)); exit(EXIT_FAILURE); } @@ -217,9 +215,10 @@ 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; - size_t wrt = mockUDPWrite(_sock, (const uint8_t*)_outbuf, _outbufsize, _timeout_ms, dst, dstport); + uint32_t dst = addr ? addr->addr : _dst.addr; + 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) cancelBuffer(); @@ -239,7 +238,7 @@ class UdpContext bool sendTimeout(ip_addr_t* addr, uint16_t port, esp8266::polledTimeout::oneShotFastMs::timeType timeoutMs) { - err_t err; + err_t err; esp8266::polledTimeout::oneShotFastMs timeout(timeoutMs); while (((err = trySend(addr, port)) != ERR_OK) && !timeout) delay(0); @@ -250,15 +249,14 @@ class UdpContext void mock_cb(void) { - if (_on_rx) _on_rx(); + if (_on_rx) + _on_rx(); } public: - static uint32_t staticMCastAddr; private: - void translate_addr() { if (addrsize == 4) @@ -267,22 +265,22 @@ class UdpContext memcpy(&ipv4, addr, 4); ip4_addr_set_u32(&ip_2_ip4(_dst), ipv4); // ^ this is a workaround for "type-punned pointer" with "*(uint32*)addr" - //ip4_addr_set_u32(&ip_2_ip4(_dst), *(uint32_t*)addr); + // 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; + int _sock = -1; rxhandler_t _on_rx; - int _refcnt = 0; + int _refcnt = 0; ip_addr_t _dst; - uint16_t _dstport; + 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; @@ -291,11 +289,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 2093cb5a1a..d7521d4589 100644 --- a/tests/host/common/littlefs_mock.cpp +++ b/tests/host/common/littlefs_mock.cpp @@ -16,7 +16,6 @@ all copies or substantial portions of the Software. */ - #include "littlefs_mock.h" #include "spiffs_mock.h" #include "spiffs/spiffs.h" @@ -56,7 +55,8 @@ LittleFSMock::LittleFSMock(ssize_t fs_size, size_t fs_block, size_t fs_page, con void LittleFSMock::reset() { - LittleFS = FS(FSImplPtr(new littlefs_impl::LittleFSImpl(0, s_phys_size, s_phys_page, s_phys_block, 5))); + LittleFS = FS( + FSImplPtr(new littlefs_impl::LittleFSImpl(0, s_phys_size, s_phys_page, s_phys_block, 5))); load(); } @@ -72,47 +72,52 @@ 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) { - fprintf(stderr, "LittleFS: checking size of '%s': %s\n", m_storage.c_str(), strerror(errno)); + 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()); + fprintf(stderr, "LittleFS: size of '%s': %d does not match requested size %zd\n", + m_storage.c_str(), (int)flen, m_fs.size()); if (!m_overwrite && flen > 0) { fprintf(stderr, "LittleFS: aborting at user request\n"); exit(1); } - fprintf(stderr, "LittleFS: continuing without loading at user request, '%s' will be overwritten\n", m_storage.c_str()); + fprintf(stderr, + "LittleFS: continuing without loading at user request, '%s' will be overwritten\n", + m_storage.c_str()); } else { 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)); + 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; diff --git a/tests/host/common/littlefs_mock.h b/tests/host/common/littlefs_mock.h index b05cc8c615..af027e7488 100644 --- a/tests/host/common/littlefs_mock.h +++ b/tests/host/common/littlefs_mock.h @@ -4,14 +4,14 @@ 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. */ @@ -27,22 +27,25 @@ #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); + 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; - bool m_overwrite; + String m_storage; + bool m_overwrite; }; -#define LITTLEFS_MOCK_DECLARE(size_kb, block_kb, page_b, storage) LittleFSMock littlefs_mock(size_kb * 1024, block_kb * 1024, page_b, storage) +#define LITTLEFS_MOCK_DECLARE(size_kb, block_kb, page_b, storage) \ + LittleFSMock littlefs_mock(size_kb * 1024, block_kb * 1024, page_b, storage) #define LITTLEFS_MOCK_RESET() littlefs_mock.reset() #endif /* littlefs_mock_hpp */ diff --git a/tests/host/common/md5.c b/tests/host/common/md5.c index 4b58f261f3..b41c49afae 100644 --- a/tests/host/common/md5.c +++ b/tests/host/common/md5.c @@ -1,18 +1,18 @@ /* * Copyright (c) 2007, Cameron Rich - * + * * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without + * + * 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, + * * 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 + * * 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 + * * 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 @@ -39,16 +39,15 @@ #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. */ #define S11 7 @@ -70,15 +69,13 @@ 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 -}; +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. */ @@ -88,35 +85,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,10 +132,10 @@ 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; + int i, partLen; /* Compute number of bytes mod 64 */ x = (uint32_t)((ctx->count[0] >> 3) & 0x3F); @@ -147,7 +148,7 @@ EXP_FUNC void STDCALL MD5Update(MD5_CTX *ctx, const uint8_t * msg, int len) 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); @@ -161,15 +162,15 @@ EXP_FUNC void STDCALL MD5Update(MD5_CTX *ctx, const uint8_t * msg, int len) 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 */ -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]; + uint8_t bits[8]; uint32_t x, padLen; /* Save number of bits */ @@ -177,7 +178,7 @@ EXP_FUNC void STDCALL MD5Final(uint8_t *digest, MD5_CTX *ctx) /* Pad out to 56 mod 64. */ - x = (uint32_t)((ctx->count[0] >> 3) & 0x3f); + x = (uint32_t)((ctx->count[0] >> 3) & 0x3f); padLen = (x < 56) ? (56 - x) : (120 - x); MD5Update(ctx, PADDING, padLen); @@ -193,82 +194,81 @@ EXP_FUNC void STDCALL MD5Final(uint8_t *digest, MD5_CTX *ctx) */ static void MD5Transform(uint32_t state[4], const uint8_t block[64]) { - uint32_t a = state[0], b = state[1], c = state[2], - d = state[3], x[MD5_SIZE]; + 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; @@ -280,16 +280,16 @@ 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; - 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] = (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); } } @@ -297,11 +297,11 @@ 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; 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..a8dc3e2bdc 100644 --- a/tests/host/common/mock.h +++ b/tests/host/common/mock.h @@ -30,7 +30,8 @@ */ #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 +58,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 } @@ -74,7 +75,7 @@ size_t strlcpy(char *dst, const char *src, size_t size); // exotic typedefs used in the sdk #include -typedef uint8_t uint8; +typedef uint8_t uint8; typedef uint32_t uint32; // @@ -97,26 +98,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 } @@ -132,41 +137,48 @@ 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); -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(); // @@ -174,4 +186,4 @@ void mock_stop_littlefs (); // -#endif // __cplusplus +#endif // __cplusplus diff --git a/tests/host/common/noniso.c b/tests/host/common/noniso.c index 869a4b7f8e..eacb2b14fd 100644 --- a/tests/host/common/noniso.c +++ b/tests/host/common/noniso.c @@ -1,19 +1,18 @@ /* 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 @@ -21,61 +20,69 @@ #include #include "stdlib_noniso.h" - -void reverse(char* begin, char* end) { - char *is = begin; - char *ie = end - 1; - while(is < ie) { +void reverse(char* begin, char* end) +{ + char* is = begin; + char* ie = end - 1; + while (is < ie) + { char tmp = *ie; - *ie = *is; - *is = tmp; + *ie = *is; + *is = tmp; ++is; --ie; } } -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; } - char* out = result; + char* out = result; unsigned quotient = value; - do { + do + { const unsigned tmp = quotient / base; - *out = "0123456789abcdef"[quotient - (tmp * 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); + char* out = result; + int quotient = abs(value); - do { + do + { const int tmp = quotient / base; - *out = "0123456789abcdef"[quotient - (tmp * 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); @@ -83,17 +90,19 @@ char* itoa(int value, char* result, int base) { return result; } -int atoi(const char* s) { - return (int) atol(s); +int atoi(const char* s) +{ + return (int)atol(s); } -long atol(const char* s) { - char * tmp; +long atol(const char* s) +{ + char* tmp; return strtol(s, &tmp, 10); } -double atof(const char* s) { - char * tmp; +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..5674fc61c8 100644 --- a/tests/host/common/pins_arduino.h +++ b/tests/host/common/pins_arduino.h @@ -1,19 +1,18 @@ /* 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 - #endif /* pins_arduino_h */ diff --git a/tests/host/common/queue.h b/tests/host/common/queue.h index af637ca030..0bc4ee7bd5 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,373 @@ /* * Singly-linked List declarations. */ -#define SLIST_HEAD(name, type) \ -struct name { \ - struct type *slh_first; /* first 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 */ \ + } -#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 @@ -430,39 +481,37 @@ struct { \ * 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__ +#ifdef __GNUC__ -static __inline void -insque(void *a, void *b) +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) +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__ */ -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 ef2ae44152..3a7c948b6a 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 611474701a..fd33b2f9c3 100644 --- a/tests/host/common/sdfs_mock.h +++ b/tests/host/common/sdfs_mock.h @@ -21,22 +21,32 @@ #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() { } }; 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 59a0ff9c91..e2d5fe341c 100644 --- a/tests/host/common/spiffs_mock.cpp +++ b/tests/host/common/spiffs_mock.cpp @@ -13,7 +13,6 @@ all copies or substantial portions of the Software. */ - #include "spiffs_mock.h" #include "spiffs/spiffs.h" #include "debug.h" @@ -54,7 +53,8 @@ SpiffsMock::SpiffsMock(ssize_t fs_size, size_t fs_block, size_t fs_page, const S void SpiffsMock::reset() { - SPIFFS = FS(FSImplPtr(new spiffs_impl::SPIFFSImpl(0, s_phys_size, s_phys_page, s_phys_block, 5))); + SPIFFS + = FS(FSImplPtr(new spiffs_impl::SPIFFSImpl(0, s_phys_size, s_phys_page, s_phys_block, 5))); load(); } @@ -70,18 +70,18 @@ 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) { @@ -89,28 +89,32 @@ void SpiffsMock::load () 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()); + fprintf(stderr, "SPIFFS: size of '%s': %d does not match requested size %zd\n", + m_storage.c_str(), (int)flen, m_fs.size()); if (!m_overwrite && flen > 0) { fprintf(stderr, "SPIFFS: aborting at user request\n"); exit(1); } - fprintf(stderr, "SPIFFS: continuing without loading at user request, '%s' will be overwritten\n", m_storage.c_str()); + fprintf(stderr, + "SPIFFS: continuing without loading at user request, '%s' will be overwritten\n", + m_storage.c_str()); } else { 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)); + 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; @@ -130,4 +134,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 7bbaf43ec5..7c7bb4e034 100644 --- a/tests/host/common/spiffs_mock.h +++ b/tests/host/common/spiffs_mock.h @@ -1,14 +1,14 @@ /* 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. */ @@ -24,22 +24,25 @@ #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); + 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; - bool m_overwrite; + String m_storage; + bool m_overwrite; }; -#define SPIFFS_MOCK_DECLARE(size_kb, block_kb, page_b, storage) SpiffsMock spiffs_mock(size_kb * 1024, block_kb * 1024, page_b, storage) +#define SPIFFS_MOCK_DECLARE(size_kb, block_kb, page_b, storage) \ + SpiffsMock spiffs_mock(size_kb * 1024, block_kb * 1024, page_b, storage) #define SPIFFS_MOCK_RESET() spiffs_mock.reset() #endif /* spiffs_mock_hpp */ diff --git a/tests/host/common/strl.cpp b/tests/host/common/strl.cpp index 529b9a1edb..0b0725b046 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 /* 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 4e03d77786..05f90c704a 100644 --- a/tests/host/common/user_interface.cpp +++ b/tests/host/common/user_interface.cpp @@ -43,7 +43,7 @@ #include -bool DhcpServer::set_dhcps_lease(struct dhcps_lease *please) +bool DhcpServer::set_dhcps_lease(struct dhcps_lease* please) { (void)please; return false; @@ -62,22 +62,20 @@ 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(); } @@ -86,7 +84,6 @@ DhcpServer dhcpSoftAP(nullptr); extern "C" { - #include #include @@ -120,14 +117,14 @@ 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"); config->bssid_set = 0; for (int i = 0; i < 6; i++) config->bssid[i] = i; - config->threshold.rssi = 1; + config->threshold.rssi = 1; config->threshold.authmode = AUTH_WPA_PSK; #ifdef NONOSDK3V0 config->open_and_wep_mode_disable = true; @@ -135,9 +132,7 @@ extern "C" return true; } - void wifi_fpm_close(void) - { - } + void wifi_fpm_close(void) { } sint8 wifi_fpm_do_sleep(uint32 sleep_time_in_us) { @@ -145,34 +140,30 @@ extern "C" return 1; } - void wifi_fpm_do_wakeup(void) - { - } + void wifi_fpm_do_wakeup(void) { } - void wifi_fpm_open(void) - { - } + void wifi_fpm_open(void) { } void wifi_fpm_set_sleep_type(sleep_type_t type) { (void)type; } - uint32_t global_ipv4_netfmt = 0; // global binding + uint32_t global_ipv4_netfmt = 0; // global binding - netif netif0; + 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; - uint32_t ipv4 = lwip_htonl(0x7f000001); - uint32_t mask = lwip_htonl(0xff000000); - global_source_address = INADDR_ANY; // =0 + struct ifaddrs *ifAddrStruct = NULL, *ifa = NULL; + uint32_t ipv4 = lwip_htonl(0x7f000001); + uint32_t mask = lwip_htonl(0xff000000); + global_source_address = INADDR_ANY; // =0 if (getifaddrs(&ifAddrStruct) != 0) { @@ -186,22 +177,24 @@ 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 mockverbose(" (local, ignored)"); else { - if (!host_interface || (host_interface && strcmp(ifa->ifa_name, host_interface) == 0)) + 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; + // 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; mockverbose(" (selected)\n"); if (host_interface) global_source_address = ntohl(ipv4); @@ -216,7 +209,7 @@ extern "C" freeifaddrs(ifAddrStruct); (void)if_index; - //if (if_index != STATION_IF) + // if (if_index != STATION_IF) // fprintf(stderr, "we are not AP"); if (global_ipv4_netfmt == NO_GLOBAL_BINDING) @@ -224,15 +217,15 @@ extern "C" if (info) { - info->ip.addr = ipv4; + info->ip.addr = ipv4; info->netmask.addr = mask; - info->gw.addr = ipv4; + info->gw.addr = ipv4; netif0.ip_addr.addr = ipv4; netif0.netmask.addr = mask; - netif0.gw.addr = ipv4; - netif0.flags = NETIF_FLAG_IGMP | NETIF_FLAG_UP | NETIF_FLAG_LINK_UP; - netif0.next = nullptr; + netif0.gw.addr = ipv4; + netif0.flags = NETIF_FLAG_IGMP | NETIF_FLAG_UP | NETIF_FLAG_LINK_UP; + netif0.next = nullptr; } return true; @@ -243,7 +236,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; @@ -267,7 +260,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) { @@ -281,13 +274,13 @@ extern "C" } wifi_event_handler_cb_t wifi_event_handler_cb_emu = nullptr; - void wifi_set_event_handler_cb(wifi_event_handler_cb_t cb) + void wifi_set_event_handler_cb(wifi_event_handler_cb_t cb) { wifi_event_handler_cb_emu = cb; 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; @@ -352,12 +345,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"); @@ -378,19 +371,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; @@ -422,20 +415,20 @@ 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"); - config->ssid_len = strlen("appasswd"); - config->channel = 1; - config->authmode = AUTH_WPA2_PSK; - config->ssid_hidden = 0; - config->max_connection = 4; + config->ssid_len = strlen("appasswd"); + config->channel = 1; + config->authmode = AUTH_WPA2_PSK; + config->ssid_hidden = 0; + config->max_connection = 4; config->beacon_interval = 100; 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); } @@ -445,19 +438,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; @@ -476,7 +469,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); @@ -498,7 +491,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; @@ -511,11 +504,10 @@ extern "C" return addr; } - #include bool smartconfig_start(sc_callback_t cb, ...) { - //XXXFIXME ... -> ptr + // XXXFIXME ... -> ptr cb(SC_STATUS_LINK, NULL); return true; } @@ -530,4 +522,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 37b31d8544..180a53d68e 100644 --- a/tests/host/core/test_PolledTimeout.cpp +++ b/tests/host/core/test_PolledTimeout.cpp @@ -2,245 +2,239 @@ #include "PolledTimeout.h" #define mockverbose printf -#include "common/MockEsp.cpp" // getCycleCount +#include "common/MockEsp.cpp" // getCycleCount -//This won't work for +// This won't work for template -inline bool -fuzzycomp(argT a, argT b) +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; - - Serial.println("OneShot Timeout 3000000us"); + using esp8266::polledTimeout::oneShotFastUs; + using timeType = oneShotFastUs::timeType; + timeType before, after, delta; - oneShotFastUs timeout(3000000); - before = micros(); - while(!timeout.expired()) - yield(); - after = micros(); + Serial.println("OneShot Timeout 3000000us"); - delta = after - before; - Serial.printf("delta = %u\n", delta); + oneShotFastUs timeout(3000000); + before = micros(); + while (!timeout.expired()) + yield(); + after = micros(); - REQUIRE(fuzzycomp(delta/1000, (timeType)3000)); + delta = after - before; + Serial.printf("delta = %u\n", delta); + 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; - - Serial.println("OneShot Timeout 3000ms"); + using esp8266::polledTimeout::oneShotMs; + using timeType = oneShotMs::timeType; + timeType before, after, delta; - oneShotMs timeout(3000); - before = millis(); - while(!timeout.expired()) - yield(); - after = millis(); + Serial.println("OneShot Timeout 3000ms"); - delta = after - before; - Serial.printf("delta = %lu\n", delta); + oneShotMs timeout(3000); + before = millis(); + while (!timeout.expired()) + yield(); + after = millis(); - REQUIRE(fuzzycomp(delta, (timeType)3000)); + delta = after - before; + Serial.printf("delta = %lu\n", delta); + 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"); + timeout.reset(1000); + before = millis(); + while (!timeout) + ; + after = millis(); - Serial.print("reset\n"); + delta = after - before; + Serial.printf("delta = %lu\n", delta); - timeout.reset(1000); - before = millis(); - while(!timeout); - after = millis(); - - 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..9926756a24 100644 --- a/tests/host/core/test_Print.cpp +++ b/tests/host/core/test_Print.cpp @@ -27,19 +27,19 @@ 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; - unsigned char uc = 20; - unsigned int ui = 21; - unsigned long ul = 22; + 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 long ul = 22; p.write(uint8); p.write(uint16); p.write(uint32); @@ -60,7 +60,7 @@ TEST_CASE("Print::write overrides all compile properly", "[core][Print]") p = LittleFS.open("test.bin", "r"); REQUIRE(p); uint8_t buff[16]; - int len = p.read(buff, 16); + int len = p.read(buff, 16); p.close(); REQUIRE(len == 15); REQUIRE(buff[0] == 1); diff --git a/tests/host/core/test_Updater.cpp b/tests/host/core/test_Updater.cpp index f3b850e130..8a1ec92bd8 100644 --- a/tests/host/core/test_Updater.cpp +++ b/tests/host/core/test_Updater.cpp @@ -16,12 +16,11 @@ #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; - uint8_t buff[6000]; + UpdaterClass* u; + uint8_t buff[6000]; memset(buff, 0, sizeof(buff)); u = new UpdaterClass(); REQUIRE(u->begin(6000)); diff --git a/tests/host/core/test_md5builder.cpp b/tests/host/core/test_md5builder.cpp index 0041c2eb72..b0a521cb8e 100644 --- a/tests/host/core/test_md5builder.cpp +++ b/tests/host/core/test_md5builder.cpp @@ -32,30 +32,35 @@ 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"; - builder.addHexString(myPayload); - builder.calculate(); - REQUIRE(builder.toString() == "47b937a6f9f12a4c389fa5854e023efb"); + WHEN("A char array is parsed") + { + MD5Builder builder; + builder.begin(); + const char* myPayload = "1234567890abcdeffedcba98765432106469676974616c7369676e617475726561" + "70706c69636174696F6e73"; + 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("1234567890abcdeffedcba98765432106469676974616c7369676e61747572" + "656170706c69636174696f6e73")); + builder.calculate(); + REQUIRE(builder.toString() == "47b937a6f9f12a4c389fa5854e023efb"); } } -TEST_CASE("MD5Builder::addStream works", "[core][MD5Builder]"){ - MD5Builder builder; - const char* str = "MD5Builder::addStream_works_longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglong"; +TEST_CASE("MD5Builder::addStream works", "[core][MD5Builder]") +{ + MD5Builder builder; + const char* str = "MD5Builder::addStream_works_" + "longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglong"; { StreamString stream; stream.print(str); diff --git a/tests/host/core/test_pgmspace.cpp b/tests/host/core/test_pgmspace.cpp index f44221c2b4..fd89dbe6db 100644 --- a/tests/host/core/test_pgmspace.cpp +++ b/tests/host/core/test_pgmspace.cpp @@ -19,15 +19,16 @@ 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); + const char* strstr_result = strstr(h, n); REQUIRE(strstr_P_result == strstr_result); }; // 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..25de913108 100644 --- a/tests/host/core/test_string.cpp +++ b/tests/host/core/test_string.cpp @@ -43,8 +43,8 @@ TEST_CASE("String::trim", "[core][String]") TEST_CASE("String::replace", "[core][String]") { String str; - str = "The quick brown fox jumped over the lazy dog."; - String find = "fox"; + str = "The quick brown fox jumped over the lazy dog."; + String find = "fox"; String replace = "vulpes vulpes"; str.replace(find, replace); REQUIRE(str == "The quick brown vulpes vulpes jumped over the lazy dog."); @@ -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"); } @@ -83,8 +83,8 @@ TEST_CASE("String constructors", "[core][String]") String s1("abcd"); String s2(s1); REQUIRE(s1 == s2); - String *s3 = new String("manos"); - s2 = *s3; + String* s3 = new String("manos"); + s2 = *s3; delete s3; REQUIRE(s2 == "manos"); s3 = new String("thisismuchlongerthantheother"); @@ -97,8 +97,8 @@ 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}; - String hello(textarray); + const char textarray[6] = { 'h', 'e', 'l', 'l', 'o', 0 }; + String hello(textarray); REQUIRE(hello == "hello"); String hello2; hello2 = textarray; @@ -135,13 +135,21 @@ TEST_CASE("String concantenation", "[core][String]") str += LLONG_MIN; REQUIRE(str == "abcdeabcde9872147483647-2147483648691969-123321-1.011.01-9223372036854775808"); str += String(LLONG_MIN, 10); - REQUIRE(str == "abcdeabcde9872147483647-2147483648691969-123321-1.011.01-9223372036854775808-9223372036854775808"); + REQUIRE(str + == "abcdeabcde9872147483647-2147483648691969-123321-1.011.01-9223372036854775808-" + "9223372036854775808"); str += LLONG_MAX; - REQUIRE(str == "abcdeabcde9872147483647-2147483648691969-123321-1.011.01-9223372036854775808-92233720368547758089223372036854775807"); + REQUIRE(str + == "abcdeabcde9872147483647-2147483648691969-123321-1.011.01-9223372036854775808-" + "92233720368547758089223372036854775807"); str += ULLONG_MAX; - REQUIRE(str == "abcdeabcde9872147483647-2147483648691969-123321-1.011.01-9223372036854775808-9223372036854775808922337203685477580718446744073709551615"); + REQUIRE(str + == "abcdeabcde9872147483647-2147483648691969-123321-1.011.01-9223372036854775808-" + "9223372036854775808922337203685477580718446744073709551615"); str += String(ULLONG_MAX, 16); - REQUIRE(str == "abcdeabcde9872147483647-2147483648691969-123321-1.011.01-9223372036854775808-9223372036854775808922337203685477580718446744073709551615ffffffffffffffff"); + REQUIRE(str + == "abcdeabcde9872147483647-2147483648691969-123321-1.011.01-9223372036854775808-" + "9223372036854775808922337203685477580718446744073709551615ffffffffffffffff"); str = "clean"; REQUIRE(str.concat(str) == true); REQUIRE(str == "cleanclean"); @@ -156,19 +164,19 @@ TEST_CASE("String concantenation", "[core][String]") 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 + 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.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 == "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++) + for (int i = 0; i <= 5; i++) 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"); } @@ -211,7 +219,7 @@ TEST_CASE("String byte access", "[core][String]") TEST_CASE("String conversion", "[core][String]") { String s = "12345"; - long l = s.toInt(); + long l = s.toInt(); REQUIRE(l == 12345); s = "2147483647"; l = s.toInt(); @@ -222,9 +230,9 @@ TEST_CASE("String conversion", "[core][String]") s = "-2147483648"; l = s.toInt(); REQUIRE(l == INT_MIN); - s = "3.14159"; + 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 +254,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 +276,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 +307,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 == "0123456789a"); - REQUIRE(s.length() == 11); - s += "bcde"; + REQUIRE(s == "0123456"); + REQUIRE(s.length() == 7); + s += "7"; 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 == "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"; + 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 @@ -426,70 +437,67 @@ 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; - 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"); } - TEST_CASE("Issue #2736 - StreamString SSO fix", "[core][StreamString]") { StreamString s; @@ -502,102 +510,101 @@ 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]") { - 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 fb73a6a271..900521b47e 100644 --- a/tests/host/fs/test_fs.cpp +++ b/tests/host/fs/test_fs.cpp @@ -24,8 +24,8 @@ #include "../../../libraries/SDFS/src/SDFS.h" #include "../../../libraries/SD/src/SD.h" - -namespace spiffs_test { +namespace spiffs_test +{ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" @@ -47,9 +47,9 @@ namespace spiffs_test { TEST_CASE("SPIFFS checks the config object passed in", "[fs]") { SPIFFS_MOCK_DECLARE(64, 8, 512, ""); - FSConfig f; - SPIFFSConfig s; - SDFSConfig d; + FSConfig f; + SPIFFSConfig s; + SDFSConfig d; LittleFSConfig l; REQUIRE_FALSE(SPIFFS.setConfig(f)); @@ -59,14 +59,15 @@ TEST_CASE("SPIFFS checks the config object passed in", "[fs]") } #pragma GCC diagnostic pop -}; - +}; // namespace spiffs_test -namespace littlefs_test { +namespace littlefs_test +{ #define FSTYPE LittleFS #define TESTPRE "LittleFS - " #define TESTPAT "[lfs]" -// LittleFS routines strip leading slashes before doing anything, so up to 31 char names are allowable +// LittleFS routines strip leading slashes before doing anything, so up to 31 char names are +// allowable #define TOOLONGFILENAME "/12345678901234567890123456789012" #define FS_MOCK_DECLARE LITTLEFS_MOCK_DECLARE #define FS_MOCK_RESET LITTLEFS_MOCK_RESET @@ -82,9 +83,9 @@ namespace littlefs_test { TEST_CASE("LittleFS checks the config object passed in", "[fs]") { LITTLEFS_MOCK_DECLARE(64, 8, 512, ""); - FSConfig f; - SPIFFSConfig s; - SDFSConfig d; + FSConfig f; + SPIFFSConfig s; + SDFSConfig d; LittleFSConfig l; REQUIRE_FALSE(LittleFS.setConfig(f)); @@ -93,17 +94,21 @@ TEST_CASE("LittleFS checks the config object passed in", "[fs]") REQUIRE(LittleFS.setConfig(l)); } -}; +}; // namespace littlefs_test -namespace sdfs_test { +namespace sdfs_test +{ #define FSTYPE SDFS #define TESTPRE "SDFS - " #define TESTPAT "[sdfs]" // SDFS supports long paths (MAXPATH) -#define TOOLONGFILENAME "/" \ - "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" \ - "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" \ - "12345678901234567890123456789012345678901234567890123456" +#define TOOLONGFILENAME \ + "/" \ + "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012" \ + "34567890" \ + "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012" \ + "34567890" \ + "12345678901234567890123456789012345678901234567890123456" #define FS_MOCK_DECLARE SDFS_MOCK_DECLARE #define FS_MOCK_RESET SDFS_MOCK_RESET #define FS_HAS_DIRS @@ -118,9 +123,9 @@ namespace sdfs_test { TEST_CASE("SDFS checks the config object passed in", "[fs]") { SDFS_MOCK_DECLARE(64, 8, 512, ""); - FSConfig f; - SPIFFSConfig s; - SDFSConfig d; + FSConfig f; + SPIFFSConfig s; + SDFSConfig d; LittleFSConfig l; REQUIRE_FALSE(SDFS.setConfig(f)); @@ -142,7 +147,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); @@ -155,11 +160,11 @@ TEST_CASE("SD.h FILE_WRITE macro is append", "[fs]") File g = SD.open("/file2.txt", FILE_WRITE); g.write(0); g.close(); - g = SD.open("/file2.txt", FILE_READ); + g = SD.open("/file2.txt", FILE_READ); uint8_t u = 0x66; g.read(&u, 1); g.close(); REQUIRE(u == 0); } -}; +}; // namespace sdfs_test diff --git a/tests/host/sys/pgmspace.h b/tests/host/sys/pgmspace.h index ecc4558351..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,37 +27,49 @@ #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) { 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-examples-only.sh b/tests/restyle-examples-only.sh deleted file mode 100755 index 513a891900..0000000000 --- a/tests/restyle-examples-only.sh +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/sh - -set -e - -org=$(cd ${0%/*}; pwd) -cd ${org}/.. -pwd -test -d cores/esp8266 -test -d libraries - -# in a near future, restyle-all.sh will be renamed to restyle.sh -# and will be checked against CI - -for d in libraries; do - find $d -name "*.ino" -exec \ - astyle \ - --suffix=none \ - --options=${org}/astyle_examples.conf {} \; -done diff --git a/tests/restyle.sh b/tests/restyle.sh index ea454069c5..5460ca25a0 100755 --- a/tests/restyle.sh +++ b/tests/restyle.sh @@ -1,50 +1,64 @@ #!/bin/sh +# requires clang-format, git, python3 with pyyaml -set -e +set -e -x -org=$(cd ${0%/*}; pwd) -cd ${org}/.. -pwd -test -d cores/esp8266 -test -d libraries +root=$(git rev-parse --show-toplevel) +test -d ${root}/cores/esp8266 +test -d ${root}/libraries -# should be: all="cores/esp8266 libraries" +# allow `env CLANG_FORMAT=clang-format-13`, or some other version +# default to v13, latest stable version from https://apt.llvm.org +CLANG_FORMAT=${CLANG_FORMAT:-clang-format-13} -all=" +# TODO: waiting for llvm-14 to allow --style=file: +makeClangFormatStyle() { + python3 -c 'import sys,yaml; sys.stdout.write(yaml.dump(yaml.safe_load(open(sys.argv[1], "r")), default_flow_style=True)); sys.stdout.flush();' $1 +} + +######################################### +# 'all' variable should be "cores/esp8266 libraries" + +all=${1:-" +cores/esp8266/Lwip* libraries/ESP8266mDNS libraries/Wire libraries/lwIP* -cores/esp8266/Lwip* cores/esp8266/debug* cores/esp8266/core_esp8266_si2c.cpp cores/esp8266/StreamString.* cores/esp8266/StreamSend.* libraries/Netdump -" - -# core - -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 {} \; - done +tests +"} + +######################################### +# restyling core & libraries + +cd $root + +style=$(makeClangFormatStyle ${root}/tests/clang-format-core.yaml) +for target in $all; do + if [ -d "$target" ]; then + find $target \ + '(' -name "*.cpp" -o -name "*.c" -o -name "*.h" ')' \ + -exec $CLANG_FORMAT --verbose --style="$style" -i {} \; else - echo "-------- file $d:" - astyle --suffix=none --options=${org}/astyle_core.conf "$d" + $CLANG_FORMAT --verbose --style="$style" -i $target fi done -# examples +######################################### +# restyling arduino examples -for d in libraries; do - echo "-------- examples in $d:" - find $d -name "*.ino" -exec \ - astyle \ - --suffix=none \ - --options=${org}/astyle_examples.conf {} \; -done +# TODO should not be matched, these are formatted externally +# exclude=$(git submodule --quiet foreach git rev-parse --show-toplevel | grep libraries) + +style=$(makeClangFormatStyle ${root}/tests/clang-format-arduino.yaml) +find libraries \ + -path libraries/ESP8266SdFat -prune -o \ + -path libraries/Ethernet -prune -o \ + -path libraries/SoftwareSerial -prune -o \ + -name '*.ino' -exec $CLANG_FORMAT --verbose --style="$style" -i {} \; + +######################################### diff --git a/tests/run_CI_locally.sh b/tests/run_CI_locally.sh index 6d0a97093f..ee9dc39cb0 100755 --- a/tests/run_CI_locally.sh +++ b/tests/run_CI_locally.sh @@ -115,7 +115,8 @@ elif [ "$BUILD_TYPE" = host ]; then tests/ci/host_test.sh elif [ "$BUILD_TYPE" = style ]; then - tests/ci/install_astyle.sh + tests/ci/check_restyle.sh + tests/restyle.sh else echo "BUILD_TYPE not set or invalid"