diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 74f1b43063..62e7e0e09f 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -242,7 +242,7 @@ jobs: TRAVIS_TAG: ${{ github.ref }} run: | sudo apt update - sudo apt install astyle + sudo apt install clang-format-12 bash ./tests/ci/style_check.sh diff --git a/cores/esp8266/LwipDhcpServer-NonOS.cpp b/cores/esp8266/LwipDhcpServer-NonOS.cpp index 0bd04ebcfe..29f125427f 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/init.h> // LWIP_VERSION +#include <lwip/init.h> // LWIP_VERSION #include <lwip/netif.h> #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 @@ -56,9 +55,6 @@ extern "C" #endif } - void dhcps_stop() - { - dhcpSoftAP.end(); - } + void dhcps_stop() { dhcpSoftAP.end(); } -} // extern "C" +} // extern "C" diff --git a/cores/esp8266/LwipDhcpServer.cpp b/cores/esp8266/LwipDhcpServer.cpp index 86f8849a91..8d0eefb9ef 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/init.h> // LWIP_VERSION +#include <lwip/init.h> // 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,42 @@ 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 +197,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 +225,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 +253,7 @@ void DhcpServer::node_insert_to_list(list_node **phead, list_node* pinsert) if (pdhcps_node->ip.addr < pdhcps_pool->ip.addr) { pinsert->pnext = plist->pnext; - plist->pnext = pinsert; + plist->pnext = pinsert; break; } plist = plist->pnext; @@ -266,9 +274,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 +287,7 @@ void DhcpServer::node_remove_from_list(list_node **phead, list_node* pdelete) { if (plist == pdelete) { - *phead = plist->pnext; + *phead = plist->pnext; pdelete->pnext = nullptr; } else @@ -288,7 +296,7 @@ void DhcpServer::node_remove_from_list(list_node **phead, list_node* pdelete) { if (plist->pnext == pdelete) { - plist->pnext = pdelete->pnext; + plist->pnext = pdelete->pnext; pdelete->pnext = nullptr; } plist = plist->pnext; @@ -303,13 +311,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 +343,15 @@ bool DhcpServer::add_dhcps_lease(uint8 *macaddr) return false; } - pdhcps_pool = (struct dhcps_pool *)zalloc(sizeof(struct dhcps_pool)); + pdhcps_pool = (struct dhcps_pool*)zalloc(sizeof(struct dhcps_pool)); pdhcps_pool->ip.addr = start_ip; memcpy(pdhcps_pool->mac, macaddr, sizeof(pdhcps_pool->mac)); pdhcps_pool->lease_timer = DHCPS_LEASE_TIMER; - pdhcps_pool->type = DHCPS_TYPE_STATIC; - pdhcps_pool->state = DHCPS_STATE_ONLINE; - pback_node = (list_node *)zalloc(sizeof(list_node)); - pback_node->pnode = pdhcps_pool; - pback_node->pnext = nullptr; + pdhcps_pool->type = DHCPS_TYPE_STATIC; + pdhcps_pool->state = DHCPS_STATE_ONLINE; + pback_node = (list_node*)zalloc(sizeof(list_node)); + pback_node->pnode = pdhcps_pool; + pback_node->pnext = nullptr; node_insert_to_list(&plist, pback_node); return true; @@ -359,9 +367,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 +383,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 +455,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 +490,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 +526,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 +545,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 +553,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 +564,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 +590,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 +608,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 +616,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 +627,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 +648,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 +667,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 +675,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 +686,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 +717,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 +735,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 +775,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 +799,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 +820,9 @@ uint8_t DhcpServer::parse_options(uint8_t *optptr, sint16_t len) } /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// -sint16_t DhcpServer::parse_msg(struct dhcps_msg *m, u16_t len) +sint16_t DhcpServer::parse_msg(struct dhcps_msg* m, u16_t len) { - if (memcmp((char *)m->options, - &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 +832,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 +853,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<DhcpServer*>(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 +882,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 +923,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 +939,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 +960,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 +976,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 +994,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 +1009,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 +1029,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,22 +1037,20 @@ 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; } -DhcpServer::~DhcpServer() -{ - end(); -} +DhcpServer::~DhcpServer() { end(); } void DhcpServer::end() { @@ -1076,21 +1063,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); @@ -1102,11 +1089,7 @@ void DhcpServer::end() } } -bool DhcpServer::isRunning() -{ - return !!_netif->state; -} - +bool DhcpServer::isRunning() { return !!_netif->state; } /****************************************************************************** FunctionName : set_dhcps_lease @@ -1115,11 +1098,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 +1124,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 +1134,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 +1148,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 +1162,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 +1201,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 +1236,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 +1260,8 @@ void DhcpServer::dhcps_coarse_tmr(void) } else { - pnode = pnode ->pnext; - num_dhcps_pool ++; + pnode = pnode->pnext; + num_dhcps_pool++; } } @@ -1291,7 +1274,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 +1288,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 +1341,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 +1395,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 +1430,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 +1479,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 +1508,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 +1526,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 +1549,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 +1563,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 +1575,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/init.h> // LWIP_VERSION +#include <lwip/init.h> // 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..e03d4870e6 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 <user_interface.h> @@ -24,19 +25,24 @@ 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 +52,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; @@ -59,19 +65,13 @@ bool LwipIntf::ipAddressReorder(const IPAddress& local_ip, const IPAddress& arg1 Get ESP8266 station DHCP hostname @return hostname */ -String LwipIntf::hostname(void) -{ - return wifi_station_get_hostname(); -} +String LwipIntf::hostname(void) { return wifi_station_get_hostname(); } /** Get ESP8266 station DHCP hostname @return hostname */ -const char* LwipIntf::getHostname(void) -{ - return wifi_station_get_hostname(); -} +const char* LwipIntf::getHostname(void) { return wifi_station_get_hostname(); } /** Set ESP8266 station DHCP hostname @@ -143,7 +143,6 @@ bool LwipIntf::hostname(const char* aHostname) // harmless for AP, also compatible with ethernet adapters (to come) for (netif* intf = netif_list; intf; intf = intf->next) { - // unconditionally update all known interfaces intf->hostname = wifi_station_get_hostname(); @@ -162,4 +161,3 @@ bool LwipIntf::hostname(const char* aHostname) return ret && compliant; } - diff --git a/cores/esp8266/LwipIntf.h b/cores/esp8266/LwipIntf.h index d73c2d825a..d284bddfcc 100644 --- a/cores/esp8266/LwipIntf.h +++ b/cores/esp8266/LwipIntf.h @@ -10,8 +10,7 @@ class LwipIntf { public: - - using CBType = std::function <void(netif*)>; + using CBType = std::function<void(netif*)>; static bool stateUpCB(LwipIntf::CBType&& cb); @@ -24,26 +23,19 @@ 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) - { - return hostname(aHostname.c_str()); - } - bool hostname(const char* aHostname); + bool hostname(const String& aHostname) { return hostname(aHostname.c_str()); } + bool hostname(const char* aHostname); // ESP32 API compatibility - bool setHostname(const char* aHostName) - { - return hostname(aHostName); - } + bool setHostname(const char* aHostName) { return hostname(aHostName); } 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..f829723bad 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,10 @@ bool LwipIntf::stateChangeSysCB(LwipIntf::CBType&& cb) bool LwipIntf::stateUpCB(LwipIntf::CBType&& cb) { - return stateChangeSysCB([cb](netif * nif) - { - if (netif_is_up(nif)) - schedule_function([cb, nif]() + 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..f3a2006b65 100644 --- a/cores/esp8266/LwipIntfDev.h +++ b/cores/esp8266/LwipIntfDev.h @@ -14,7 +14,7 @@ #include <lwip/dns.h> #include <lwip/apps/sntp.h> -#include <user_interface.h> // wifi_get_macaddr() +#include <user_interface.h> // wifi_get_macaddr() #include "SPI.h" #include "Schedule.h" @@ -25,64 +25,42 @@ #define DEFAULT_MTU 1500 #endif -template <class RawDev> -class LwipIntfDev: public LwipIntf, public RawDev +template <class RawDev> class LwipIntfDev: public LwipIntf, public RawDev { - public: - - LwipIntfDev(int8_t cs = SS, SPIClass& spi = SPI, int8_t intr = -1): - RawDev(cs, spi, intr), - _mtu(DEFAULT_MTU), - _intrPin(intr), - _started(false), - _default(false) + 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; - } + const netif* getNetIf() const { return &_netif; } - IPAddress localIP() const - { - return IPAddress(ip4_addr_get_u32(ip_2_ip4(&_netif.ip_addr))); - } - IPAddress subnetMask() const - { - return IPAddress(ip4_addr_get_u32(ip_2_ip4(&_netif.netmask))); - } - IPAddress gatewayIP() const - { - return IPAddress(ip4_addr_get_u32(ip_2_ip4(&_netif.gw))); - } + IPAddress localIP() const { return IPAddress(ip4_addr_get_u32(ip_2_ip4(&_netif.ip_addr))); } + IPAddress subnetMask() const { return IPAddress(ip4_addr_get_u32(ip_2_ip4(&_netif.netmask))); } + IPAddress gatewayIP() const { return IPAddress(ip4_addr_get_u32(ip_2_ip4(&_netif.gw))); } void setDefault(); // true if interface has a valid IPv4 address - bool connected() - { - return !!ip4_addr_get_u32(ip_2_ip4(&_netif.ip_addr)); - } + bool connected() { return !!ip4_addr_get_u32(ip_2_ip4(&_netif.ip_addr)); } // ESP8266WiFi API compatibility 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 +68,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 <class RawDev> -boolean LwipIntfDev<RawDev>::config(const IPAddress& localIP, const IPAddress& gateway, const IPAddress& netmask, const IPAddress& dns1, const IPAddress& dns2) +boolean LwipIntfDev<RawDev>::config(const IPAddress& localIP, const IPAddress& gateway, + const IPAddress& netmask, const IPAddress& dns1, + const IPAddress& dns2) { if (_started) { @@ -162,9 +141,9 @@ boolean LwipIntfDev<RawDev>::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 +162,8 @@ boolean LwipIntfDev<RawDev>::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 +192,24 @@ boolean LwipIntfDev<RawDev>::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 +218,12 @@ boolean LwipIntfDev<RawDev>::begin(const uint8_t* macAddress, const uint16_t mtu return true; } -template <class RawDev> -wl_status_t LwipIntfDev<RawDev>::status() +template <class RawDev> wl_status_t LwipIntfDev<RawDev>::status() { return _started ? (connected() ? WL_CONNECTED : WL_DISCONNECTED) : WL_NO_SHIELD; } -template <class RawDev> -err_t LwipIntfDev<RawDev>::linkoutput_s(netif *netif, struct pbuf *pbuf) +template <class RawDev> err_t LwipIntfDev<RawDev>::linkoutput_s(netif* netif, struct pbuf* pbuf) { LwipIntfDev* ths = (LwipIntfDev*)netif->state; @@ -255,37 +237,31 @@ err_t LwipIntfDev<RawDev>::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 <class RawDev> -err_t LwipIntfDev<RawDev>::netif_init_s(struct netif* netif) +template <class RawDev> err_t LwipIntfDev<RawDev>::netif_init_s(struct netif* netif) { return ((LwipIntfDev*)netif->state)->netif_init(); } -template <class RawDev> -void LwipIntfDev<RawDev>::netif_status_callback_s(struct netif* netif) +template <class RawDev> void LwipIntfDev<RawDev>::netif_status_callback_s(struct netif* netif) { ((LwipIntfDev*)netif->state)->netif_status_callback(); } -template <class RawDev> -err_t LwipIntfDev<RawDev>::netif_init() +template <class RawDev> err_t LwipIntfDev<RawDev>::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,8 +277,7 @@ err_t LwipIntfDev<RawDev>::netif_init() return ERR_OK; } -template <class RawDev> -void LwipIntfDev<RawDev>::netif_status_callback() +template <class RawDev> void LwipIntfDev<RawDev>::netif_status_callback() { if (connected()) { @@ -321,14 +296,13 @@ void LwipIntfDev<RawDev>::netif_status_callback() } } -template <class RawDev> -err_t LwipIntfDev<RawDev>::handlePackets() +template <class RawDev> err_t LwipIntfDev<RawDev>::handlePackets() { int pkt = 0; while (1) { if (++pkt == 10) - // prevent starvation + // prevent starvation { return ERR_OK; } @@ -374,7 +348,8 @@ err_t LwipIntfDev<RawDev>::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,12 +359,10 @@ err_t LwipIntfDev<RawDev>::handlePackets() return err; } // (else) allocated pbuf is now lwIP's responsibility - } } -template <class RawDev> -void LwipIntfDev<RawDev>::setDefault() +template <class RawDev> void LwipIntfDev<RawDev>::setDefault() { _default = true; if (connected()) @@ -398,4 +371,4 @@ void LwipIntfDev<RawDev>::setDefault() } } -#endif // _LWIPINTFDEV_H +#endif // _LWIPINTFDEV_H diff --git a/cores/esp8266/StreamSend.cpp b/cores/esp8266/StreamSend.cpp index 693e340cff..250aca7759 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 <Arduino.h> #include <StreamDev.h> -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..8a68a70a56 100644 --- a/cores/esp8266/StreamString.h +++ b/cores/esp8266/StreamString.h @@ -35,26 +35,13 @@ class S2Stream: public Stream { public: + S2Stream(String& string, int peekPointer = -1) : string(&string), peekPointer(peekPointer) { } - S2Stream(String& string, int peekPointer = -1): - string(&string), peekPointer(peekPointer) - { - } - - S2Stream(String* string, int peekPointer = -1): - string(string), peekPointer(peekPointer) - { - } + S2Stream(String* string, int peekPointer = -1) : string(string), peekPointer(peekPointer) { } - virtual int available() override - { - return string->length(); - } + virtual int available() override { return string->length(); } - virtual int availableForWrite() override - { - return std::numeric_limits<int16_t>::max(); - } + virtual int availableForWrite() override { return std::numeric_limits<int16_t>::max(); } virtual int read() override { @@ -78,10 +65,7 @@ class S2Stream: public Stream return -1; } - virtual size_t write(uint8_t data) override - { - return string->concat((char)data); - } + virtual size_t write(uint8_t data) override { return string->concat((char)data); } virtual int read(uint8_t* buffer, size_t len) override { @@ -133,22 +117,13 @@ class S2Stream: public Stream // nothing to do } - virtual bool inputCanTimeout() override - { - return false; - } + virtual bool inputCanTimeout() override { return false; } - virtual bool outputCanTimeout() override - { - return false; - } + virtual bool outputCanTimeout() override { return false; } //// Stream's peekBufferAPI - virtual bool hasPeekBufferAPI() const override - { - return true; - } + virtual bool hasPeekBufferAPI() const override { return true; } virtual size_t peekAvailable() { @@ -193,32 +168,23 @@ class S2Stream: public Stream // calling setConsume() will consume bytes as the stream is read // (enabled by default) - void setConsume() - { - peekPointer = -1; - } + void setConsume() { peekPointer = -1; } // Reading this stream will mark the string as read without consuming // (not enabled by default) // Calling resetPointer() resets the read state and allows rereading. - void resetPointer(int pointer = 0) - { - peekPointer = pointer; - } + void resetPointer(int pointer = 0) { peekPointer = pointer; } 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 +194,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 +263,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..a6849c1aff 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,89 @@ 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. + 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 +149,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 +188,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,17 +198,13 @@ 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 } -void Twi::setClockStretchLimit(uint32_t limit) -{ - twi_clockStretchLimit = limit; -} - - +void Twi::setClockStretchLimit(uint32_t limit) { twi_clockStretchLimit = limit; } void Twi::init(unsigned char sda, unsigned char scl) { @@ -210,7 +219,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 +243,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 +260,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 +319,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 +334,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 +348,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 +358,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 +380,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 +394,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 +433,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; @@ -466,68 +483,61 @@ uint8_t Twi::transmit(const uint8_t* data, uint8_t length) return 0; } -void Twi::attachSlaveRxEvent(void (*function)(uint8_t*, size_t)) -{ - twi_onSlaveReceive = function; -} +void Twi::attachSlaveRxEvent(void (*function)(uint8_t*, size_t)) { twi_onSlaveReceive = function; } -void Twi::attachSlaveTxEvent(void (*function)(void)) -{ - twi_onSlaveTransmit = function; -} +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 +551,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 +586,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 +612,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 +652,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 +672,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 +686,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 +761,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 +779,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 +846,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 +857,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 +867,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 +884,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 +895,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 +915,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 +930,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 +943,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,71 +972,39 @@ 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); } - void twi_init(unsigned char sda, unsigned char scl) - { - return twi.init(sda, scl); - } + void twi_setAddress(uint8_t a) { return twi.setAddress(a); } - void twi_setAddress(uint8_t a) - { - return twi.setAddress(a); - } - - void twi_setClock(unsigned int freq) - { - twi.setClock(freq); - } + void twi_setClock(unsigned int freq) { twi.setClock(freq); } - void twi_setClockStretchLimit(uint32_t limit) - { - twi.setClockStretchLimit(limit); - } + void twi_setClockStretchLimit(uint32_t limit) { 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); } - uint8_t twi_status() - { - return twi.status(); - } - - uint8_t twi_transmit(const uint8_t * buf, uint8_t len) - { - return twi.transmit(buf, len); - } + uint8_t twi_status() { return twi.status(); } - void twi_attachSlaveRxEvent(void (*cb)(uint8_t*, size_t)) - { - twi.attachSlaveRxEvent(cb); - } + uint8_t twi_transmit(const uint8_t* buf, uint8_t len) { return twi.transmit(buf, len); } - void twi_attachSlaveTxEvent(void (*cb)(void)) - { - twi.attachSlaveTxEvent(cb); - } + void twi_attachSlaveRxEvent(void (*cb)(uint8_t*, size_t)) { twi.attachSlaveRxEvent(cb); } - void twi_reply(uint8_t r) - { - twi.reply(r); - } + void twi_attachSlaveTxEvent(void (*cb)(void)) { twi.attachSlaveTxEvent(cb); } - void twi_releaseBus(void) - { - twi.releaseBus(); - } + void twi_reply(uint8_t r) { twi.reply(r); } - void twi_enableSlaveMode(void) - { - twi.enableSlave(); - } + void twi_releaseBus(void) { twi.releaseBus(); } + void twi_enableSlaveMode(void) { 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 <stdint.h> #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..4a61302392 100644 --- a/libraries/ArduinoOTA/examples/BasicOTA/BasicOTA.ino +++ b/libraries/ArduinoOTA/examples/BasicOTA/BasicOTA.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; void setup() { @@ -39,16 +39,14 @@ void setup() { String type; if (ArduinoOTA.getCommand() == U_FLASH) { type = "sketch"; - } else { // U_FS + } else { // U_FS type = "filesystem"; } // NOTE: if updating FS this would be the place to unmount FS using FS.end() Serial.println("Start updating " + type); }); - ArduinoOTA.onEnd([]() { - Serial.println("\nEnd"); - }); + ArduinoOTA.onEnd([]() { Serial.println("\nEnd"); }); ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { Serial.printf("Progress: %u%%\r", (progress / (total / 100))); }); @@ -72,6 +70,4 @@ void setup() { Serial.println(WiFi.localIP()); } -void loop() { - ArduinoOTA.handle(); -} +void loop() { ArduinoOTA.handle(); } diff --git a/libraries/ArduinoOTA/examples/OTALeds/OTALeds.ino b/libraries/ArduinoOTA/examples/OTALeds/OTALeds.ino index 7d05074e15..9bc6f74b22 100644 --- a/libraries/ArduinoOTA/examples/OTALeds/OTALeds.ino +++ b/libraries/ArduinoOTA/examples/OTALeds/OTALeds.ino @@ -5,16 +5,16 @@ #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 = "OTA-LEDS"; +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,9 +67,6 @@ void setup() { /* setup the OTA server */ ArduinoOTA.begin(); Serial.println("Ready"); - } -void loop() { - ArduinoOTA.handle(); -} +void loop() { ArduinoOTA.handle(); } diff --git a/libraries/DNSServer/examples/CaptivePortal/CaptivePortal.ino b/libraries/DNSServer/examples/CaptivePortal/CaptivePortal.ino index b59cda2d92..5b7b3f6b16 100644 --- a/libraries/DNSServer/examples/CaptivePortal/CaptivePortal.ino +++ b/libraries/DNSServer/examples/CaptivePortal/CaptivePortal.ino @@ -2,9 +2,9 @@ #include <DNSServer.h> #include <ESP8266WebServer.h> -const byte DNS_PORT = 53; -IPAddress apIP(172, 217, 28, 1); -DNSServer dnsServer; +const byte DNS_PORT = 53; +IPAddress apIP(172, 217, 28, 1); +DNSServer dnsServer; ESP8266WebServer webServer(80); String responseHTML = "" @@ -24,9 +24,7 @@ void setup() { dnsServer.start(DNS_PORT, "*", apIP); // replay to all requests with same HTML - webServer.onNotFound([]() { - webServer.send(200, "text/html", responseHTML); - }); + webServer.onNotFound([]() { webServer.send(200, "text/html", responseHTML); }); webServer.begin(); } diff --git a/libraries/DNSServer/examples/CaptivePortalAdvanced/CaptivePortalAdvanced.ino b/libraries/DNSServer/examples/CaptivePortalAdvanced/CaptivePortalAdvanced.ino index 5f1f5020a1..88bb95852c 100644 --- a/libraries/DNSServer/examples/CaptivePortalAdvanced/CaptivePortalAdvanced.ino +++ b/libraries/DNSServer/examples/CaptivePortalAdvanced/CaptivePortalAdvanced.ino @@ -7,35 +7,41 @@ /* This example serves a "hello world" on a WLAN and a SoftAP at the same time. - The SoftAP allow you to configure WLAN parameters at run time. They are not setup in the sketch but saved on EEPROM. + The SoftAP allow you to configure WLAN parameters at run time. They are not setup in the sketch + but saved on EEPROM. - Connect your computer or cell phone to wifi network ESP_ap with password 12345678. A popup may appear and it allow you to go to WLAN config. If it does not then navigate to http://192.168.4.1/wifi and config it there. - Then wait for the module to connect to your wifi and take note of the WLAN IP it got. Then you can disconnect from ESP_ap and return to your regular WLAN. + Connect your computer or cell phone to wifi network ESP_ap with password 12345678. A popup may + appear and it allow you to go to WLAN config. If it does not then navigate to + http://192.168.4.1/wifi and config it there. Then wait for the module to connect to your wifi and + take note of the WLAN IP it got. Then you can disconnect from ESP_ap and return to your regular + WLAN. - Now the ESP8266 is in your network. You can reach it through http://192.168.x.x/ (the IP you took note of) or maybe at http://esp8266.local too. + Now the ESP8266 is in your network. You can reach it through http://192.168.x.x/ (the IP you took + note of) or maybe at http://esp8266.local too. - This is a captive portal because through the softAP it will redirect any http request to http://192.168.4.1/ + This is a captive portal because through the softAP it will redirect any http request to + http://192.168.4.1/ */ /* Set these to your desired softAP credentials. They are not configurable at runtime */ #ifndef APSSID #define APSSID "ESP_ap" -#define APPSK "12345678" +#define APPSK "12345678" #endif -const char *softAP_ssid = APSSID; -const char *softAP_password = APPSK; +const char* softAP_ssid = APSSID; +const char* softAP_password = APPSK; /* hostname for mDNS. Should work at least on windows. Try http://esp8266.local */ -const char *myHostname = "esp8266"; +const char* myHostname = "esp8266"; /* Don't set this wifi credentials. They are configurated at runtime and stored on EEPROM */ -char ssid[33] = ""; +char ssid[33] = ""; char password[65] = ""; // DNS server const byte DNS_PORT = 53; -DNSServer dnsServer; +DNSServer dnsServer; // Web server ESP8266WebServer server(80); @@ -44,7 +50,6 @@ ESP8266WebServer server(80); IPAddress apIP(172, 217, 28, 1); IPAddress netMsk(255, 255, 255, 0); - /** Should I connect to WLAN asap? */ boolean connect; @@ -62,7 +67,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 +79,15 @@ 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 +113,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; @@ -135,8 +142,8 @@ void loop() { } } // Do work: - //DNS + // DNS dnsServer.processNextRequest(); - //HTTP + // HTTP server.handleClient(); } diff --git a/libraries/DNSServer/examples/CaptivePortalAdvanced/credentials.ino b/libraries/DNSServer/examples/CaptivePortalAdvanced/credentials.ino index a5e76fb7c4..844460e8c5 100644 --- a/libraries/DNSServer/examples/CaptivePortalAdvanced/credentials.ino +++ b/libraries/DNSServer/examples/CaptivePortalAdvanced/credentials.ino @@ -7,7 +7,7 @@ void loadCredentials() { EEPROM.get(0 + sizeof(ssid) + sizeof(password), ok); EEPROM.end(); if (String(ok) != String("OK")) { - ssid[0] = 0; + ssid[0] = 0; password[0] = 0; } Serial.println("Recovered credentials:"); diff --git a/libraries/DNSServer/examples/CaptivePortalAdvanced/handleHttp.ino b/libraries/DNSServer/examples/CaptivePortalAdvanced/handleHttp.ino index dc286c1840..8cdf427411 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( - "<!DOCTYPE html><html lang='en'><head>" + Page += F("<!DOCTYPE html><html lang='en'><head>" "<meta name='viewport' content='width=device-width'>" "<title>CaptivePortal</title></head><body>" "<h1>HELLO WORLD!!</h1>"); @@ -18,20 +17,21 @@ void handleRoot() { } else { Page += String(F("<p>You are connected through the wifi network: ")) + ssid + F("</p>"); } - Page += F( - "<p>You may want to <a href='/wifi'>config the wifi connection</a>.</p>" + Page += F("<p>You may want to <a href='/wifi'>config the wifi connection</a>.</p>" "</body></html>"); server.send(200, "text/html", Page); } -/** Redirect to captive portal if we got a request for another domain. Return true in that case so the page handler do not try to handle the request again. */ +/** Redirect to captive portal if we got a request for another domain. Return true in that case so + * the page handler do not try to handle the request again. */ boolean captivePortal() { if (!isIp(server.hostHeader()) && server.hostHeader() != (String(myHostname) + ".local")) { 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 +44,7 @@ void handleWifi() { server.sendHeader("Expires", "-1"); String Page; - Page += F( - "<!DOCTYPE html><html lang='en'><head>" + Page += F("<!DOCTYPE html><html lang='en'><head>" "<meta name='viewport' content='width=device-width'>" "<title>CaptivePortal</title></head><body>" "<h1>Wifi config</h1>"); @@ -54,40 +53,39 @@ void handleWifi() { } else { Page += String(F("<p>You are connected through the wifi network: ")) + ssid + F("</p>"); } - Page += - String(F( - "\r\n<br />" - "<table><tr><th align='left'>SoftAP config</th></tr>" - "<tr><td>SSID ")) + - String(softAP_ssid) + - F("</td></tr>" - "<tr><td>IP ") + - toStringIp(WiFi.softAPIP()) + - F("</td></tr>" - "</table>" - "\r\n<br />" - "<table><tr><th align='left'>WLAN config</th></tr>" - "<tr><td>SSID ") + - String(ssid) + - F("</td></tr>" - "<tr><td>IP ") + - toStringIp(WiFi.localIP()) + - F("</td></tr>" - "</table>" - "\r\n<br />" - "<table><tr><th align='left'>WLAN list (refresh if any missing)</th></tr>"); + Page += String(F("\r\n<br />" + "<table><tr><th align='left'>SoftAP config</th></tr>" + "<tr><td>SSID ")) + + String(softAP_ssid) + + F("</td></tr>" + "<tr><td>IP ") + + toStringIp(WiFi.softAPIP()) + + F("</td></tr>" + "</table>" + "\r\n<br />" + "<table><tr><th align='left'>WLAN config</th></tr>" + "<tr><td>SSID ") + + String(ssid) + + F("</td></tr>" + "<tr><td>IP ") + + toStringIp(WiFi.localIP()) + + F("</td></tr>" + "</table>" + "\r\n<br />" + "<table><tr><th align='left'>WLAN list (refresh if any missing)</th></tr>"); 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<tr><td>SSID ")) + WiFi.SSID(i) + ((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? F(" ") : F(" *")) + F(" (") + WiFi.RSSI(i) + F(")</td></tr>"); + Page += String(F("\r\n<tr><td>SSID ")) + WiFi.SSID(i) + + ((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? F(" ") : F(" *")) + F(" (") + + WiFi.RSSI(i) + F(")</td></tr>"); } } else { Page += F("<tr><td>No WLAN found</td></tr>"); } - Page += F( - "</table>" + Page += F("</table>" "\r\n<br /><form method='POST' action='wifisave'><h4>Connect to network:</h4>" "<input type='text' placeholder='network' name='n'/>" "<br /><input type='password' placeholder='password' name='p'/>" @@ -95,7 +93,7 @@ void handleWifi() { "<p>You may want to <a href='/'>return to the home page</a>.</p>" "</body></html>"); 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 +105,15 @@ 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"); diff --git a/libraries/DNSServer/examples/CaptivePortalAdvanced/tools.ino b/libraries/DNSServer/examples/CaptivePortalAdvanced/tools.ino index e4840a1c12..6ed7b05b7d 100644 --- a/libraries/DNSServer/examples/CaptivePortalAdvanced/tools.ino +++ b/libraries/DNSServer/examples/CaptivePortalAdvanced/tools.ino @@ -18,4 +18,3 @@ String toStringIp(IPAddress ip) { res += String(((ip >> 8 * 3)) & 0xFF); return res; } - diff --git a/libraries/DNSServer/examples/DNSServer/DNSServer.ino b/libraries/DNSServer/examples/DNSServer/DNSServer.ino index 2916d5ab3c..f3b65d5bee 100644 --- a/libraries/DNSServer/examples/DNSServer/DNSServer.ino +++ b/libraries/DNSServer/examples/DNSServer/DNSServer.ino @@ -2,9 +2,9 @@ #include <DNSServer.h> #include <ESP8266WebServer.h> -const byte DNS_PORT = 53; -IPAddress apIP(192, 168, 1, 1); -DNSServer dnsServer; +const byte DNS_PORT = 53; +IPAddress apIP(192, 168, 1, 1); +DNSServer dnsServer; ESP8266WebServer webServer(80); void setup() { diff --git a/libraries/EEPROM/examples/eeprom_clear/eeprom_clear.ino b/libraries/EEPROM/examples/eeprom_clear/eeprom_clear.ino index bb7d887c57..81377757b0 100644 --- a/libraries/EEPROM/examples/eeprom_clear/eeprom_clear.ino +++ b/libraries/EEPROM/examples/eeprom_clear/eeprom_clear.ino @@ -21,5 +21,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..212eff9952 100644 --- a/libraries/EEPROM/examples/eeprom_read/eeprom_read.ino +++ b/libraries/EEPROM/examples/eeprom_read/eeprom_read.ino @@ -9,7 +9,7 @@ #include <EEPROM.h> // start reading from the first byte (address 0) of the EEPROM -int address = 0; +int address = 0; byte value; void setup() { 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..e0682b220b 100644 --- a/libraries/ESP8266AVRISP/examples/Arduino_Wifi_AVRISP/Arduino_Wifi_AVRISP.ino +++ b/libraries/ESP8266AVRISP/examples/Arduino_Wifi_AVRISP/Arduino_Wifi_AVRISP.ino @@ -5,14 +5,14 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char* host = "esp8266-avrisp"; -const char* ssid = STASSID; -const char* pass = STAPSK; -const uint16_t port = 328; -const uint8_t reset_pin = 5; +const char* host = "esp8266-avrisp"; +const char* ssid = STASSID; +const char* pass = STAPSK; +const uint16_t port = 328; +const uint8_t reset_pin = 5; ESP8266AVRISP avrprog(port, reset_pin); @@ -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); @@ -48,24 +48,24 @@ void setup() { void loop() { static AVRISPState_t last_state = AVRISP_STATE_IDLE; - AVRISPState_t new_state = avrprog.update(); + AVRISPState_t new_state = avrprog.update(); if (last_state != new_state) { switch (new_state) { case AVRISP_STATE_IDLE: { - Serial.printf("[AVRISP] now idle\r\n"); - // Use the SPI bus for other purposes - break; - } + Serial.printf("[AVRISP] now idle\r\n"); + // Use the SPI bus for other purposes + break; + } case AVRISP_STATE_PENDING: { - Serial.printf("[AVRISP] connection pending\r\n"); - // Clean up your other purposes and prepare for programming mode - break; - } + Serial.printf("[AVRISP] connection pending\r\n"); + // Clean up your other purposes and prepare for programming mode + break; + } case AVRISP_STATE_ACTIVE: { - Serial.printf("[AVRISP] programming mode\r\n"); - // Stand by for completion - break; - } + Serial.printf("[AVRISP] programming mode\r\n"); + // Stand by for completion + break; + } } last_state = new_state; } diff --git a/libraries/ESP8266HTTPClient/examples/Authorization/Authorization.ino b/libraries/ESP8266HTTPClient/examples/Authorization/Authorization.ino index 9de3077ff4..59a459a52c 100644 --- a/libraries/ESP8266HTTPClient/examples/Authorization/Authorization.ino +++ b/libraries/ESP8266HTTPClient/examples/Authorization/Authorization.ino @@ -17,7 +17,6 @@ ESP8266WiFiMulti WiFiMulti; void setup() { - Serial.begin(115200); // Serial.setDebugOutput(true); @@ -33,13 +32,11 @@ void setup() { WiFi.mode(WIFI_STA); WiFiMulti.addAP("SSID", "PASSWORD"); - } void loop() { // wait for WiFi connection if ((WiFiMulti.run() == WL_CONNECTED)) { - WiFiClient client; HTTPClient http; @@ -47,7 +44,6 @@ void loop() { Serial.print("[HTTP] begin...\n"); // configure traged server and url - http.begin(client, "http://guest:guest@jigsaw.w3.org/HTTP/Basic/"); /* @@ -60,7 +56,6 @@ void loop() { http.setAuthorization("Z3Vlc3Q6Z3Vlc3Q="); */ - Serial.print("[HTTP] GET...\n"); // start connection and send HTTP header int httpCode = http.GET(); diff --git a/libraries/ESP8266HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino b/libraries/ESP8266HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino index 21a97172ef..85190df74d 100644 --- a/libraries/ESP8266HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino +++ b/libraries/ESP8266HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino @@ -17,7 +17,6 @@ ESP8266WiFiMulti WiFiMulti; void setup() { - Serial.begin(115200); // Serial.setDebugOutput(true); @@ -33,13 +32,11 @@ void setup() { WiFi.mode(WIFI_STA); WiFiMulti.addAP("SSID", "PASSWORD"); - } void loop() { // wait for WiFi connection if ((WiFiMulti.run() == WL_CONNECTED)) { - WiFiClient client; HTTPClient http; @@ -47,7 +44,6 @@ void loop() { Serial.print("[HTTP] begin...\n"); if (http.begin(client, "http://jigsaw.w3.org/HTTP/connection.html")) { // HTTP - Serial.print("[HTTP] GET...\n"); // start connection and send HTTP header int httpCode = http.GET(); diff --git a/libraries/ESP8266HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino b/libraries/ESP8266HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino index aaa4af2b4d..9f5fa91887 100644 --- a/libraries/ESP8266HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino +++ b/libraries/ESP8266HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino @@ -14,12 +14,12 @@ #include <WiFiClientSecureBearSSL.h> // Fingerprint for demo URL, expires on June 2, 2021, needs to be updated well before this date -const uint8_t fingerprint[20] = {0x40, 0xaf, 0x00, 0x6b, 0xec, 0x90, 0x22, 0x41, 0x8e, 0xa3, 0xad, 0xfa, 0x1a, 0xe8, 0x25, 0x41, 0x1d, 0x1a, 0x54, 0xb3}; +const uint8_t fingerprint[20] = { 0x40, 0xaf, 0x00, 0x6b, 0xec, 0x90, 0x22, 0x41, 0x8e, 0xa3, + 0xad, 0xfa, 0x1a, 0xe8, 0x25, 0x41, 0x1d, 0x1a, 0x54, 0xb3 }; ESP8266WiFiMulti WiFiMulti; void setup() { - Serial.begin(115200); // Serial.setDebugOutput(true); @@ -40,8 +40,7 @@ void setup() { void loop() { // wait for WiFi connection if ((WiFiMulti.run() == WL_CONNECTED)) { - - std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure); + std::unique_ptr<BearSSL::WiFiClientSecure> 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..5a655320d0 100644 --- a/libraries/ESP8266HTTPClient/examples/DigestAuthorization/DigestAuthorization.ino +++ b/libraries/ESP8266HTTPClient/examples/DigestAuthorization/DigestAuthorization.ino @@ -13,31 +13,31 @@ #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* 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 ""; } - return authReq.substring(_begin + param.length(), authReq.indexOf(delimit, _begin + param.length())); + 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) { @@ -47,10 +47,11 @@ String getCNonce(const int len) { return s; } -String getDigestAuth(String& authReq, const String& username, const String& password, const String& method, const String& uri, unsigned int counter) { +String getDigestAuth(String& authReq, const String& username, const String& password, + const String& method, const String& uri, unsigned int counter) { // extracting required parameters for RFC 2069 simpler Digest - String realm = exractParam(authReq, "realm=\"", '"'); - String nonce = exractParam(authReq, "nonce=\"", '"'); + String realm = exractParam(authReq, "realm=\"", '"'); + String nonce = exractParam(authReq, "nonce=\"", '"'); String cNonce = getCNonce(8); char nc[9]; @@ -73,8 +74,10 @@ 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,15 +103,15 @@ 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"); // configure traged server and url http.begin(client, String(server) + String(uri)); - - const char *keys[] = {"WWW-Authenticate"}; + const char* keys[] = { "WWW-Authenticate" }; http.collectHeaders(keys, 1); Serial.print("[HTTP] GET...\n"); @@ -119,7 +122,8 @@ void loop() { String authReq = http.header("WWW-Authenticate"); Serial.println(authReq); - String authorization = getDigestAuth(authReq, String(username), String(password), "GET", String(uri), 1); + String authorization + = getDigestAuth(authReq, String(username), String(password), "GET", String(uri), 1); http.end(); http.begin(client, String(server) + String(uri)); diff --git a/libraries/ESP8266HTTPClient/examples/PostHttpClient/PostHttpClient.ino b/libraries/ESP8266HTTPClient/examples/PostHttpClient/PostHttpClient.ino index 936e235eeb..317ba12aff 100644 --- a/libraries/ESP8266HTTPClient/examples/PostHttpClient/PostHttpClient.ino +++ b/libraries/ESP8266HTTPClient/examples/PostHttpClient/PostHttpClient.ino @@ -20,11 +20,10 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif void setup() { - Serial.begin(115200); Serial.println(); @@ -40,19 +39,17 @@ void setup() { Serial.println(""); Serial.print("Connected! IP address: "); Serial.println(WiFi.localIP()); - } void loop() { // wait for WiFi connection if ((WiFi.status() == WL_CONNECTED)) { - WiFiClient client; HTTPClient http; Serial.print("[HTTP] begin...\n"); // configure traged server and url - http.begin(client, "http://" SERVER_IP "/postplain/"); //HTTP + http.begin(client, "http://" SERVER_IP "/postplain/"); // HTTP http.addHeader("Content-Type", "application/json"); Serial.print("[HTTP] POST...\n"); diff --git a/libraries/ESP8266HTTPClient/examples/ReuseConnectionV2/ReuseConnectionV2.ino b/libraries/ESP8266HTTPClient/examples/ReuseConnectionV2/ReuseConnectionV2.ino index 42a89beced..94f710180b 100644 --- a/libraries/ESP8266HTTPClient/examples/ReuseConnectionV2/ReuseConnectionV2.ino +++ b/libraries/ESP8266HTTPClient/examples/ReuseConnectionV2/ReuseConnectionV2.ino @@ -3,17 +3,17 @@ Created on: 22.11.2015 - This example reuses the http connection and also restores the connection if the connection is lost + This example reuses the http connection and also restores the connection if the connection is + lost */ - #include <ESP8266WiFi.h> #include <ESP8266WiFiMulti.h> #include <ESP8266HTTPClient.h> #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif ESP8266WiFiMulti WiFiMulti; @@ -22,7 +22,6 @@ HTTPClient http; WiFiClient client; void setup() { - Serial.begin(115200); // Serial.setDebugOutput(true); @@ -43,9 +42,8 @@ void setup() { // allow reuse (if server supports it) http.setReuse(true); - http.begin(client, "http://jigsaw.w3.org/HTTP/connection.html"); - //http.begin(client, "jigsaw.w3.org", 80, "/HTTP/connection.html"); + // http.begin(client, "jigsaw.w3.org", 80, "/HTTP/connection.html"); } int pass = 0; @@ -68,7 +66,7 @@ void loop() { // 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..19fed7b8fe 100644 --- a/libraries/ESP8266HTTPClient/examples/StreamHttpClient/StreamHttpClient.ino +++ b/libraries/ESP8266HTTPClient/examples/StreamHttpClient/StreamHttpClient.ino @@ -15,7 +15,6 @@ ESP8266WiFiMulti WiFiMulti; void setup() { - Serial.begin(115200); // Serial.setDebugOutput(true); @@ -31,21 +30,20 @@ void setup() { WiFi.mode(WIFI_STA); WiFiMulti.addAP("SSID", "PASSWORD"); - } void loop() { // wait for WiFi connection 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 @@ -56,7 +54,6 @@ void loop() { // file found at server if (httpCode == HTTP_CODE_OK) { - // get length of document (is -1 when Server sends no Content-Length header) int len = http.getSize(); @@ -70,7 +67,7 @@ void loop() { // or "by hand" // get tcp stream - WiFiClient * stream = &client; + WiFiClient* stream = &client; // read all data from server while (http.connected() && (len > 0 || len == -1)) { diff --git a/libraries/ESP8266HTTPClient/examples/StreamHttpsClient/StreamHttpsClient.ino b/libraries/ESP8266HTTPClient/examples/StreamHttpsClient/StreamHttpsClient.ino index 8098986650..b89d084abe 100644 --- a/libraries/ESP8266HTTPClient/examples/StreamHttpsClient/StreamHttpsClient.ino +++ b/libraries/ESP8266HTTPClient/examples/StreamHttpsClient/StreamHttpsClient.ino @@ -15,7 +15,6 @@ ESP8266WiFiMulti WiFiMulti; void setup() { - Serial.begin(115200); // Serial.setDebugOutput(true); @@ -31,13 +30,11 @@ void setup() { WiFi.mode(WIFI_STA); WiFiMulti.addAP("SSID", "PASSWORD"); - } void loop() { // wait for WiFi connection if ((WiFiMulti.run() == WL_CONNECTED)) { - std::unique_ptr<BearSSL::WiFiClientSecure> client(new BearSSL::WiFiClientSecure); bool mfln = client->probeMaxFragmentLength("tls.mbed.org", 443, 1024); @@ -50,14 +47,14 @@ void loop() { Serial.print("[HTTPS] begin...\n"); // configure server and url - const uint8_t fingerprint[20] = {0x15, 0x77, 0xdc, 0x04, 0x7c, 0x00, 0xf8, 0x70, 0x09, 0x34, 0x24, 0xf4, 0xd3, 0xa1, 0x7a, 0x6c, 0x1e, 0xa3, 0xe0, 0x2a}; + const uint8_t fingerprint[20] = { 0x15, 0x77, 0xdc, 0x04, 0x7c, 0x00, 0xf8, 0x70, 0x09, 0x34, + 0x24, 0xf4, 0xd3, 0xa1, 0x7a, 0x6c, 0x1e, 0xa3, 0xe0, 0x2a }; client->setFingerprint(fingerprint); HTTPClient https; if (https.begin(*client, "https://tls.mbed.org/")) { - Serial.print("[HTTPS] GET...\n"); // start connection and send HTTP header int httpCode = https.GET(); @@ -67,7 +64,6 @@ void loop() { // file found at server if (httpCode == HTTP_CODE_OK) { - // get length of document (is -1 when Server sends no Content-Length header) int len = https.getSize(); @@ -95,7 +91,6 @@ void loop() { Serial.println(); Serial.print("[HTTPS] connection closed or file end.\n"); - } } else { Serial.printf("[HTTPS] GET... failed, error: %s\n", https.errorToString(httpCode).c_str()); diff --git a/libraries/ESP8266HTTPUpdateServer/examples/SecureBearSSLUpdater/SecureBearSSLUpdater.ino b/libraries/ESP8266HTTPUpdateServer/examples/SecureBearSSLUpdater/SecureBearSSLUpdater.ino index a2514e171d..930988de06 100644 --- a/libraries/ESP8266HTTPUpdateServer/examples/SecureBearSSLUpdater/SecureBearSSLUpdater.ino +++ b/libraries/ESP8266HTTPUpdateServer/examples/SecureBearSSLUpdater/SecureBearSSLUpdater.ino @@ -21,17 +21,17 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char* host = "esp8266-webupdate"; -const char* update_path = "/firmware"; +const char* host = "esp8266-webupdate"; +const char* update_path = "/firmware"; const char* update_username = "admin"; const char* update_password = "admin"; -const char* ssid = STASSID; -const char* password = STAPSK; +const char* ssid = STASSID; +const char* password = STAPSK; -ESP8266WebServerSecure httpServer(443); +ESP8266WebServerSecure httpServer(443); ESP8266HTTPUpdateServerSecure httpUpdater; static const char serverCert[] PROGMEM = R"EOF( @@ -57,7 +57,7 @@ JfUvYadSYxh3nblvA4OL+iEZiW8NE3hbW6WPXxvS7Euge0uWMPc4uEcnsE0ZVG3m -----END CERTIFICATE----- )EOF"; -static const char serverKey[] PROGMEM = R"EOF( +static const char serverKey[] PROGMEM = R"EOF( -----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEA9UoHBtn4oNKXjRgIOQ/rLxK/iI0a8Q5mDxhfuwa9//FkftSI IFY8UhGk2YNJpnfKOyYWqbqwuJhIZJ2sEIWp2301OnavuGBrpKOgBJJljgH2l/4Z @@ -87,17 +87,14 @@ gz5JWYhbD6c38khSzJb0pNXCo3EuYAVa36kDM96k1BtWuhRS10Q1VXk= -----END RSA PRIVATE KEY----- )EOF"; - -void setup() -{ - +void setup() { Serial.begin(115200); Serial.println(); Serial.println("Booting Sketch..."); WiFi.mode(WIFI_AP_STA); WiFi.begin(ssid, password); - while(WiFi.waitForConnectResult() != WL_CONNECTED){ + while (WiFi.waitForConnectResult() != WL_CONNECTED) { WiFi.begin(ssid, password); Serial.println("WiFi failed, retrying."); } @@ -106,18 +103,19 @@ void setup() MDNS.begin(host); - httpServer.getServer().setRSACert(new BearSSL::X509List(serverCert), new BearSSL::PrivateKey(serverKey)); + httpServer.getServer().setRSACert(new BearSSL::X509List(serverCert), + new BearSSL::PrivateKey(serverKey)); httpUpdater.setup(&httpServer, update_path, update_username, update_password); 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..a718c5565d 100644 --- a/libraries/ESP8266HTTPUpdateServer/examples/SecureWebUpdater/SecureWebUpdater.ino +++ b/libraries/ESP8266HTTPUpdateServer/examples/SecureWebUpdater/SecureWebUpdater.ino @@ -1,5 +1,6 @@ /* - To upload through terminal you can use: curl -u admin:admin -F "image=@firmware.bin" esp8266-webupdate.local/firmware + To upload through terminal you can use: curl -u admin:admin -F "image=@firmware.bin" + esp8266-webupdate.local/firmware */ #include <ESP8266WiFi.h> @@ -10,21 +11,20 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char* host = "esp8266-webupdate"; -const char* update_path = "/firmware"; +const char* host = "esp8266-webupdate"; +const char* update_path = "/firmware"; const char* update_username = "admin"; const char* update_password = "admin"; -const char* ssid = STASSID; -const char* password = STAPSK; +const char* ssid = STASSID; +const char* password = STAPSK; -ESP8266WebServer httpServer(80); +ESP8266WebServer httpServer(80); ESP8266HTTPUpdateServer httpUpdater; void setup(void) { - Serial.begin(115200); Serial.println(); Serial.println("Booting Sketch..."); @@ -42,7 +42,9 @@ void setup(void) { httpServer.begin(); MDNS.addService("http", "tcp", 80); - Serial.printf("HTTPUpdateServer ready! Open http://%s.local%s in your browser and login with username '%s' and password '%s'\n", host, update_path, update_username, update_password); + Serial.printf("HTTPUpdateServer ready! Open http://%s.local%s in your browser and login with " + "username '%s' and password '%s'\n", + host, update_path, update_username, update_password); } void loop(void) { diff --git a/libraries/ESP8266HTTPUpdateServer/examples/WebUpdater/WebUpdater.ino b/libraries/ESP8266HTTPUpdateServer/examples/WebUpdater/WebUpdater.ino index fea3c4023a..e3a7725793 100644 --- a/libraries/ESP8266HTTPUpdateServer/examples/WebUpdater/WebUpdater.ino +++ b/libraries/ESP8266HTTPUpdateServer/examples/WebUpdater/WebUpdater.ino @@ -1,5 +1,6 @@ /* - To upload through terminal you can use: curl -F "image=@firmware.bin" esp8266-webupdate.local/update + To upload through terminal you can use: curl -F "image=@firmware.bin" + esp8266-webupdate.local/update */ #include <ESP8266WiFi.h> @@ -10,18 +11,17 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char* host = "esp8266-webupdate"; -const char* ssid = STASSID; +const char* host = "esp8266-webupdate"; +const char* ssid = STASSID; const char* password = STAPSK; -ESP8266WebServer httpServer(80); +ESP8266WebServer httpServer(80); ESP8266HTTPUpdateServer httpUpdater; void setup(void) { - Serial.begin(115200); Serial.println(); Serial.println("Booting Sketch..."); 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..6c01afa458 100644 --- a/libraries/ESP8266LLMNR/examples/LLMNR_Web_Server/LLMNR_Web_Server.ino +++ b/libraries/ESP8266LLMNR/examples/LLMNR_Web_Server/LLMNR_Web_Server.ino @@ -62,21 +62,17 @@ #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 web_server(80); -void handle_http_not_found() { - web_server.send(404, "text/plain", "Not Found"); -} +void handle_http_not_found() { web_server.send(404, "text/plain", "Not Found"); } -void handle_http_root() { - web_server.send(200, "text/plain", "It works!"); -} +void handle_http_root() { web_server.send(200, "text/plain", "It works!"); } void setup(void) { Serial.begin(115200); @@ -107,6 +103,4 @@ void setup(void) { Serial.println("HTTP server started"); } -void loop(void) { - web_server.handleClient(); -} +void loop(void) { web_server.handleClient(); } diff --git a/libraries/ESP8266NetBIOS/examples/ESP_NBNST/ESP_NBNST.ino b/libraries/ESP8266NetBIOS/examples/ESP_NBNST/ESP_NBNST.ino old mode 100755 new mode 100644 index 57f5529850..d93adf89b6 --- a/libraries/ESP8266NetBIOS/examples/ESP_NBNST/ESP_NBNST.ino +++ b/libraries/ESP8266NetBIOS/examples/ESP_NBNST/ESP_NBNST.ino @@ -4,14 +4,14 @@ #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 wwwserver(80); -String content; +String content; static void handleRoot(void) { content = F("<!DOCTYPE HTML>\n<html>Hello world from ESP8266"); @@ -40,13 +40,10 @@ void setup() { Serial.print("IP address: "); Serial.println(WiFi.localIP()); - wwwserver.on("/", handleRoot); wwwserver.begin(); NBNS.begin("ESP"); } -void loop() { - wwwserver.handleClient(); -} +void loop() { wwwserver.handleClient(); } diff --git a/libraries/ESP8266SSDP/examples/SSDP/SSDP.ino b/libraries/ESP8266SSDP/examples/SSDP/SSDP.ino index 28b0ca977b..081a41f154 100644 --- a/libraries/ESP8266SSDP/examples/SSDP/SSDP.ino +++ b/libraries/ESP8266SSDP/examples/SSDP/SSDP.ino @@ -4,10 +4,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 HTTP(80); @@ -20,14 +20,9 @@ void setup() { WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); if (WiFi.waitForConnectResult() == WL_CONNECTED) { - Serial.printf("Starting HTTP...\n"); - HTTP.on("/index.html", HTTP_GET, []() { - HTTP.send(200, "text/plain", "Hello World!"); - }); - HTTP.on("/description.xml", HTTP_GET, []() { - SSDP.schema(HTTP.client()); - }); + HTTP.on("/index.html", HTTP_GET, []() { HTTP.send(200, "text/plain", "Hello World!"); }); + HTTP.on("/description.xml", HTTP_GET, []() { SSDP.schema(HTTP.client()); }); HTTP.begin(); Serial.printf("Starting SSDP...\n"); diff --git a/libraries/ESP8266WebServer/examples/AdvancedWebServer/AdvancedWebServer.ino b/libraries/ESP8266WebServer/examples/AdvancedWebServer/AdvancedWebServer.ino index 2fc8508ca0..289dfee8b6 100644 --- a/libraries/ESP8266WebServer/examples/AdvancedWebServer/AdvancedWebServer.ino +++ b/libraries/ESP8266WebServer/examples/AdvancedWebServer/AdvancedWebServer.ino @@ -35,11 +35,11 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char *ssid = STASSID; -const char *password = STAPSK; +const char* ssid = STASSID; +const char* password = STAPSK; ESP8266WebServer server(80); @@ -48,9 +48,9 @@ const int led = 13; void handleRoot() { digitalWrite(led, 1); char temp[400]; - int sec = millis() / 1000; - int min = sec / 60; - int hr = min / 60; + int sec = millis() / 1000; + int min = sec / 60; + int hr = min / 60; snprintf(temp, 400, @@ -69,8 +69,7 @@ void handleRoot() { </body>\ </html>", - hr, min % 60, sec % 60 - ); + hr, min % 60, sec % 60); server.send(200, "text/html", temp); digitalWrite(led, 0); } @@ -98,13 +97,16 @@ void drawGraph() { String out; out.reserve(2600); char temp[70]; - out += "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" width=\"400\" height=\"150\">\n"; - out += "<rect width=\"400\" height=\"150\" fill=\"rgb(250, 230, 210)\" stroke-width=\"1\" stroke=\"rgb(0, 0, 0)\" />\n"; + out += "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" width=\"400\" " + "height=\"150\">\n"; + out += "<rect width=\"400\" height=\"150\" fill=\"rgb(250, 230, 210)\" stroke-width=\"1\" " + "stroke=\"rgb(0, 0, 0)\" />\n"; out += "<g stroke=\"black\">\n"; int y = rand() % 130; for (int x = 10; x < 390; x += 10) { int y2 = rand() % 130; - sprintf(temp, "<line x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" stroke-width=\"1\" />\n", x, 140 - y, x + 10, 140 - y2); + sprintf(temp, "<line x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" stroke-width=\"1\" />\n", x, + 140 - y, x + 10, 140 - y2); out += temp; y = y2; } @@ -139,9 +141,7 @@ void setup(void) { server.on("/", handleRoot); server.on("/test.svg", drawGraph); - server.on("/inline", []() { - server.send(200, "text/plain", "this works as well"); - }); + server.on("/inline", []() { server.send(200, "text/plain", "this works as well"); }); server.onNotFound(handleNotFound); server.begin(); Serial.println("HTTP server started"); @@ -151,4 +151,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..6a4e4ffb40 100644 --- a/libraries/ESP8266WebServer/examples/FSBrowser/FSBrowser.ino +++ b/libraries/ESP8266WebServer/examples/FSBrowser/FSBrowser.ino @@ -49,61 +49,54 @@ #if defined USE_SPIFFS #include <FS.h> -const char* fsName = "SPIFFS"; -FS* fileSystem = &SPIFFS; -SPIFFSConfig fileSystemConfig = SPIFFSConfig(); +const char* fsName = "SPIFFS"; +FS* fileSystem = &SPIFFS; +SPIFFSConfig fileSystemConfig = SPIFFSConfig(); #elif defined USE_LITTLEFS #include <LittleFS.h> -const char* fsName = "LittleFS"; -FS* fileSystem = &LittleFS; +const char* fsName = "LittleFS"; +FS* fileSystem = &LittleFS; LittleFSConfig fileSystemConfig = LittleFSConfig(); #elif defined USE_SDFS #include <SDFS.h> -const char* fsName = "SDFS"; -FS* fileSystem = &SDFS; -SDFSConfig fileSystemConfig = SDFSConfig(); +const char* fsName = "SDFS"; +FS* fileSystem = &SDFS; +SDFSConfig fileSystemConfig = SDFSConfig(); // fileSystemConfig.setCSPin(chipSelectPin); #else #error Please select a filesystem first by uncommenting one of the "#define USE_xxx" lines at the beginning of the sketch. #endif - #define DBG_OUTPUT_PORT Serial #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char* ssid = STASSID; +const char* ssid = STASSID; const char* password = STAPSK; -const char* host = "fsbrowser"; +const char* host = "fsbrowser"; ESP8266WebServer server(80); static bool fsOK; -String unsupportedFiles = String(); +String unsupportedFiles = String(); File uploadFile; -static const char TEXT_PLAIN[] PROGMEM = "text/plain"; -static const char FS_INIT_ERROR[] PROGMEM = "FS INIT ERROR"; +static const char TEXT_PLAIN[] PROGMEM = "text/plain"; +static const char FS_INIT_ERROR[] PROGMEM = "FS INIT ERROR"; static const char FILE_NOT_FOUND[] PROGMEM = "FileNotFound"; //////////////////////////////// // Utils to return HTTP codes, and determine content-type -void replyOK() { - server.send(200, FPSTR(TEXT_PLAIN), ""); -} +void replyOK() { server.send(200, FPSTR(TEXT_PLAIN), ""); } -void replyOKWithMsg(String msg) { - server.send(200, FPSTR(TEXT_PLAIN), msg); -} +void replyOKWithMsg(String msg) { server.send(200, FPSTR(TEXT_PLAIN), msg); } -void replyNotFound(String msg) { - server.send(404, FPSTR(TEXT_PLAIN), msg); -} +void replyNotFound(String msg) { server.send(404, FPSTR(TEXT_PLAIN), msg); } void replyBadRequest(String msg) { DBG_OUTPUT_PORT.println(msg); @@ -117,8 +110,8 @@ void replyServerError(String msg) { #ifdef USE_SPIFFS /* - Checks filename for character combinations that are not supported by FSBrowser (alhtough valid on SPIFFS). - Returns an empty String if supported, or detail of error(s) if unsupported + Checks filename for character combinations that are not supported by FSBrowser (alhtough valid on + SPIFFS). Returns an empty String if supported, or detail of error(s) if unsupported */ String checkForUnsupportedPath(String filename) { String error = String(); @@ -135,7 +128,6 @@ String checkForUnsupportedPath(String filename) { } #endif - //////////////////////////////// // Request handlers @@ -168,7 +160,6 @@ void handleStatus() { server.send(200, "application/json", json); } - /* Return the list of files in the directory specified by the "dir" query string parameter. Also demonstrates the use of chunked responses. @@ -242,7 +233,6 @@ void handleFileList() { server.chunkedResponseFinalize(); } - /* Read the given file from the filesystem and stream it back to the client */ @@ -280,7 +270,6 @@ bool handleFileRead(String path) { return false; } - /* As some FS (e.g. LittleFS) delete the parent folder when the last child has been removed, return the path of the closest parent still existing @@ -345,7 +334,7 @@ void handleFileCreate() { // Create a file File file = fileSystem->open(path, "w"); if (file) { - file.write((const char *)0); + file.write((const char*)0); file.close(); } else { return replyServerError(F("CREATE FAILED")); @@ -379,18 +368,17 @@ void handleFileCreate() { } } - /* Delete the file or folder designed by the given path. If it's a file, delete it. If it's a folder, delete all nested contents first then the folder itself - IMPORTANT NOTE: using recursion is generally not recommended on embedded devices and can lead to crashes (stack overflow errors). - This use is just for demonstration purpose, and FSBrowser might crash in case of deeply nested filesystems. - Please don't do this on a production system. + IMPORTANT NOTE: using recursion is generally not recommended on embedded devices and can lead to + crashes (stack overflow errors). This use is just for demonstration purpose, and FSBrowser might + crash in case of deeply nested filesystems. Please don't do this on a production system. */ void deleteRecursive(String path) { - File file = fileSystem->open(path, "r"); + File file = fileSystem->open(path, "r"); bool isDir = file.isDirectory(); file.close(); @@ -411,7 +399,6 @@ void deleteRecursive(String path) { fileSystem->rmdir(path); } - /* Handle a file deletion request Operation | req.responseText @@ -477,7 +464,6 @@ void handleFileUpload() { } } - /* The "Not Found" handler catches all URI not explicitly declared in code First try to find and return the requested file from the filesystem, @@ -488,7 +474,7 @@ void handleNotFound() { 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; @@ -521,9 +507,8 @@ void handleNotFound() { /* This specific handler returns the index.htm (or a gzipped version) from the /edit folder. - If the file is not present but the flag INCLUDE_FALLBACK_INDEX_HTM has been set, falls back to the version - embedded in the program code. - Otherwise, fails with a 404 page with debug information + If the file is not present but the flag INCLUDE_FALLBACK_INDEX_HTM has been set, falls back to + the version embedded in the program code. Otherwise, fails with a 404 page with debug information */ void handleGetEdit() { if (handleFileRead(F("/edit/index.htm"))) { @@ -536,7 +521,6 @@ void handleGetEdit() { #else replyNotFound(FPSTR(FILE_NOT_FOUND)); #endif - } void setup(void) { @@ -560,7 +544,8 @@ void setup(void) { DBG_OUTPUT_PORT.println(F("List of files at root of filesystem:")); while (dir.next()) { String error = checkForUnsupportedPath(dir.fileName()); - String fileInfo = dir.fileName() + (dir.isDirectory() ? " [DIR]" : String(" (") + dir.fileSize() + "b)"); + 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'; @@ -609,15 +594,15 @@ void setup(void) { server.on("/edit", HTTP_GET, handleGetEdit); // Create file - server.on("/edit", HTTP_PUT, handleFileCreate); + server.on("/edit", HTTP_PUT, handleFileCreate); // Delete file - server.on("/edit", HTTP_DELETE, handleFileDelete); + server.on("/edit", HTTP_DELETE, handleFileDelete); // Upload file // - first callback is called after the request has ended with all parsed arguments // - second callback handles file upload at that location - server.on("/edit", HTTP_POST, replyOK, handleFileUpload); + server.on("/edit", HTTP_POST, replyOK, handleFileUpload); // Default handler for all URIs not defined above // Use it to read files from filesystem @@ -628,7 +613,6 @@ void setup(void) { DBG_OUTPUT_PORT.println("HTTP server started"); } - void loop(void) { server.handleClient(); MDNS.update(); diff --git a/libraries/ESP8266WebServer/examples/Graph/Graph.ino b/libraries/ESP8266WebServer/examples/Graph/Graph.ino index b0eb5f847b..0b162775b1 100644 --- a/libraries/ESP8266WebServer/examples/Graph/Graph.ino +++ b/libraries/ESP8266WebServer/examples/Graph/Graph.ino @@ -38,27 +38,26 @@ #if defined USE_SPIFFS #include <FS.h> -FS* fileSystem = &SPIFFS; -SPIFFSConfig fileSystemConfig = SPIFFSConfig(); +FS* fileSystem = &SPIFFS; +SPIFFSConfig fileSystemConfig = SPIFFSConfig(); #elif defined USE_LITTLEFS #include <LittleFS.h> -FS* fileSystem = &LittleFS; +FS* fileSystem = &LittleFS; LittleFSConfig fileSystemConfig = LittleFSConfig(); #elif defined USE_SDFS #include <SDFS.h> -FS* fileSystem = &SDFS; +FS* fileSystem = &SDFS; SDFSConfig fileSystemConfig = SDFSConfig(); // fileSystemConfig.setCSPin(chipSelectPin); #else #error Please select a filesystem first by uncommenting one of the "#define USE_xxx" lines at the beginning of the sketch. #endif - #define DBG_OUTPUT_PORT Serial #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif // Indicate which digital I/Os should be displayed on the chart. @@ -66,30 +65,24 @@ SDFSConfig fileSystemConfig = SDFSConfig(); // e.g. 0b11111000000111111 unsigned int gpioMask; -const char* ssid = STASSID; +const char* ssid = STASSID; const char* password = STAPSK; -const char* host = "graph"; +const char* host = "graph"; ESP8266WebServer server(80); -static const char TEXT_PLAIN[] PROGMEM = "text/plain"; -static const char FS_INIT_ERROR[] PROGMEM = "FS INIT ERROR"; +static const char TEXT_PLAIN[] PROGMEM = "text/plain"; +static const char FS_INIT_ERROR[] PROGMEM = "FS INIT ERROR"; static const char FILE_NOT_FOUND[] PROGMEM = "FileNotFound"; //////////////////////////////// // Utils to return HTTP codes -void replyOK() { - server.send(200, FPSTR(TEXT_PLAIN), ""); -} +void replyOK() { server.send(200, FPSTR(TEXT_PLAIN), ""); } -void replyOKWithMsg(String msg) { - server.send(200, FPSTR(TEXT_PLAIN), msg); -} +void replyOKWithMsg(String msg) { server.send(200, FPSTR(TEXT_PLAIN), msg); } -void replyNotFound(String msg) { - server.send(404, FPSTR(TEXT_PLAIN), msg); -} +void replyNotFound(String msg) { server.send(404, FPSTR(TEXT_PLAIN), msg); } void replyBadRequest(String msg) { DBG_OUTPUT_PORT.println(msg); @@ -132,14 +125,13 @@ bool handleFileRead(String path) { return false; } - /* The "Not Found" handler catches all URI not explicitly declared in code First try to find and return the requested file from the filesystem, 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; @@ -218,7 +210,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); @@ -240,7 +232,6 @@ void setup(void) { // Use it to read files from filesystem server.onNotFound(handleNotFound); - // Start server server.begin(); DBG_OUTPUT_PORT.println("HTTP server started"); @@ -249,7 +240,6 @@ void setup(void) { DBG_OUTPUT_PORT.println(" 0 (OFF): outputs are off and hidden from chart"); DBG_OUTPUT_PORT.println(" 1 (AUTO): outputs are rotated automatically every second"); DBG_OUTPUT_PORT.println(" 2 (MANUAL): outputs can be toggled from the web page"); - } // Return default GPIO mask, that is all I/Os except SD card ones @@ -263,10 +253,10 @@ unsigned int defaultMask() { return mask; } -int rgbMode = 1; // 0=off - 1=auto - 2=manual -int rgbValue = 0; +int rgbMode = 1; // 0=off - 1=auto - 2=manual +int rgbValue = 0; esp8266::polledTimeout::periodicMs timeToChange(1000); -bool modeChangeRequested = false; +bool modeChangeRequested = false; void loop(void) { server.handleClient(); @@ -295,11 +285,11 @@ void loop(void) { // 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,7 +297,7 @@ void loop(void) { digitalWrite(15, 0); break; - case 1: // auto + case 1: // auto gpioMask = defaultMask(); // increment value (reset after 7) @@ -322,11 +312,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..de0e44351e 100644 --- a/libraries/ESP8266WebServer/examples/HelloServer/HelloServer.ino +++ b/libraries/ESP8266WebServer/examples/HelloServer/HelloServer.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); @@ -63,18 +63,15 @@ void setup(void) { server.on("/", handleRoot); - server.on("/inline", []() { - server.send(200, "text/plain", "this works as well"); - }); + server.on("/inline", []() { server.send(200, "text/plain", "this works as well"); }); server.on("/gif", []() { - static const uint8_t gif[] PROGMEM = { - 0x47, 0x49, 0x46, 0x38, 0x37, 0x61, 0x10, 0x00, 0x10, 0x00, 0x80, 0x01, - 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x2c, 0x00, 0x00, 0x00, 0x00, - 0x10, 0x00, 0x10, 0x00, 0x00, 0x02, 0x19, 0x8c, 0x8f, 0xa9, 0xcb, 0x9d, - 0x00, 0x5f, 0x74, 0xb4, 0x56, 0xb0, 0xb0, 0xd2, 0xf2, 0x35, 0x1e, 0x4c, - 0x0c, 0x24, 0x5a, 0xe6, 0x89, 0xa6, 0x4d, 0x01, 0x00, 0x3b - }; + static const uint8_t gif[] PROGMEM + = { 0x47, 0x49, 0x46, 0x38, 0x37, 0x61, 0x10, 0x00, 0x10, 0x00, 0x80, 0x01, + 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x2c, 0x00, 0x00, 0x00, 0x00, + 0x10, 0x00, 0x10, 0x00, 0x00, 0x02, 0x19, 0x8c, 0x8f, 0xa9, 0xcb, 0x9d, + 0x00, 0x5f, 0x74, 0xb4, 0x56, 0xb0, 0xb0, 0xd2, 0xf2, 0x35, 0x1e, 0x4c, + 0x0c, 0x24, 0x5a, 0xe6, 0x89, 0xa6, 0x4d, 0x01, 0x00, 0x3b }; char gif_colored[sizeof(gif)]; memcpy_P(gif_colored, gif, sizeof(gif)); // Set the background to a random set of colors @@ -89,25 +86,29 @@ 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()); + Serial.printf("(this hook is in 0x%08x area (401x=IRAM 402x=FLASH))\n", + esp_get_program_counter()); return ESP8266WebServer::CLIENT_REQUEST_CAN_CONTINUE; }); - server.addHook([](const String&, const String & url, WiFiClient*, ESP8266WebServer::ContentTypeFunction) { - if (url.startsWith("/fail")) { - Serial.printf("An always failing web hook has been triggered\n"); - return ESP8266WebServer::CLIENT_MUST_STOP; - } - return ESP8266WebServer::CLIENT_REQUEST_CAN_CONTINUE; - }); + server.addHook( + [](const String&, const String& url, WiFiClient*, ESP8266WebServer::ContentTypeFunction) { + if (url.startsWith("/fail")) { + Serial.printf("An always failing web hook has been triggered\n"); + return ESP8266WebServer::CLIENT_MUST_STOP; + } + return ESP8266WebServer::CLIENT_REQUEST_CAN_CONTINUE; + }); - server.addHook([](const String&, const String & url, WiFiClient * client, ESP8266WebServer::ContentTypeFunction) { + 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"); @@ -121,7 +122,7 @@ void setup(void) { #else auto last = millis(); while ((millis() - last) < 500) { - char buf[32]; + char buf[32]; size_t len = client->read((uint8_t*)buf, sizeof(buf)); if (len > 0) { Serial.printf("(<%d> chars)", (int)len); @@ -137,7 +138,8 @@ 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..1d8d64b178 100644 --- a/libraries/ESP8266WebServer/examples/HelloServerBearSSL/HelloServerBearSSL.ino +++ b/libraries/ESP8266WebServer/examples/HelloServerBearSSL/HelloServerBearSSL.ino @@ -18,14 +18,14 @@ #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; BearSSL::ESP8266WebServerSecure server(443); -BearSSL::ServerSessions serverCache(5); +BearSSL::ServerSessions serverCache(5); static const char serverCert[] PROGMEM = R"EOF( -----BEGIN CERTIFICATE----- @@ -50,7 +50,7 @@ JfUvYadSYxh3nblvA4OL+iEZiW8NE3hbW6WPXxvS7Euge0uWMPc4uEcnsE0ZVG3m -----END CERTIFICATE----- )EOF"; -static const char serverKey[] PROGMEM = R"EOF( +static const char serverKey[] PROGMEM = R"EOF( -----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEA9UoHBtn4oNKXjRgIOQ/rLxK/iI0a8Q5mDxhfuwa9//FkftSI IFY8UhGk2YNJpnfKOyYWqbqwuJhIZJ2sEIWp2301OnavuGBrpKOgBJJljgH2l/4Z @@ -80,7 +80,6 @@ gz5JWYhbD6c38khSzJb0pNXCo3EuYAVa36kDM96k1BtWuhRS10Q1VXk= -----END RSA PRIVATE KEY----- )EOF"; - const int led = 13; void handleRoot() { @@ -89,24 +88,24 @@ void handleRoot() { digitalWrite(led, 0); } -void handleNotFound(){ +void handleNotFound() { digitalWrite(led, 1); String message = "File Not Found\n\n"; message += "URI: "; message += server.uri(); message += "\nMethod: "; - message += (server.method() == HTTP_GET)?"GET":"POST"; + message += (server.method() == HTTP_GET) ? "GET" : "POST"; message += "\nArguments: "; message += server.args(); message += "\n"; - for (uint8_t i=0; i<server.args(); i++){ + for (uint8_t i = 0; i < server.args(); i++) { message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; } server.send(404, "text/plain", message); digitalWrite(led, 0); } -void setup(void){ +void setup(void) { pinMode(led, OUTPUT); digitalWrite(led, 0); Serial.begin(115200); @@ -131,16 +130,15 @@ void setup(void){ Serial.println("MDNS responder started"); } - server.getServer().setRSACert(new BearSSL::X509List(serverCert), new BearSSL::PrivateKey(serverKey)); + server.getServer().setRSACert(new BearSSL::X509List(serverCert), + new BearSSL::PrivateKey(serverKey)); // Cache SSL sessions to accelerate the TLS handshake. server.getServer().setCache(&serverCache); server.on("/", handleRoot); - server.on("/inline", [](){ - server.send(200, "text/plain", "this works as well"); - }); + server.on("/inline", []() { server.send(200, "text/plain", "this works as well"); }); server.onNotFound(handleNotFound); @@ -153,26 +151,26 @@ extern "C" void stack_thunk_dump_stack(); void processKey(Print& out, int hotKey) { switch (hotKey) { case 'd': { - HeapSelectDram ephemeral; - umm_info(NULL, true); - break; - } + HeapSelectDram ephemeral; + umm_info(NULL, true); + break; + } case 'i': { + HeapSelectIram ephemeral; + umm_info(NULL, true); + break; + } + case 'h': { + { HeapSelectIram ephemeral; - umm_info(NULL, true); - break; + Serial.printf(PSTR("IRAM ESP.getFreeHeap: %u\n"), ESP.getFreeHeap()); } - case 'h': { - { - HeapSelectIram ephemeral; - Serial.printf(PSTR("IRAM ESP.getFreeHeap: %u\n"), ESP.getFreeHeap()); - } - { - HeapSelectDram ephemeral; - Serial.printf(PSTR("DRAM ESP.getFreeHeap: %u\n"), ESP.getFreeHeap()); - } - break; + { + HeapSelectDram ephemeral; + Serial.printf(PSTR("DRAM ESP.getFreeHeap: %u\n"), ESP.getFreeHeap()); } + break; + } #ifdef DEBUG_ESP_PORT // From this context stack_thunk_dump_stack() will only work when Serial // debug is enabled. @@ -210,8 +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..0518cc6f16 100644 --- a/libraries/ESP8266WebServer/examples/HttpAdvancedAuth/HttpAdvancedAuth.ino +++ b/libraries/ESP8266WebServer/examples/HttpAdvancedAuth/HttpAdvancedAuth.ino @@ -11,10 +11,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); @@ -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..565bb027d1 100644 --- a/libraries/ESP8266WebServer/examples/HttpBasicAuth/HttpBasicAuth.ino +++ b/libraries/ESP8266WebServer/examples/HttpBasicAuth/HttpBasicAuth.ino @@ -5,10 +5,10 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char* ssid = STASSID; +const char* ssid = STASSID; const char* password = STAPSK; ESP8266WebServer server(80); diff --git a/libraries/ESP8266WebServer/examples/HttpHashCredAuth/HttpHashCredAuth.ino b/libraries/ESP8266WebServer/examples/HttpHashCredAuth/HttpHashCredAuth.ino index c2ceaca53d..57cb0c63cc 100644 --- a/libraries/ESP8266WebServer/examples/HttpHashCredAuth/HttpHashCredAuth.ino +++ b/libraries/ESP8266WebServer/examples/HttpHashCredAuth/HttpHashCredAuth.ino @@ -7,7 +7,8 @@ 1. Creating a secure web server using ESP8266ESP8266WebServerSecure 2. Use of HTTP authentication on this secure server 3. A simple web interface to allow an authenticated user to change Credentials - 4. Persisting those credentials through a reboot of the ESP by saving them to LittleFS without storing them as plain text + 4. Persisting those credentials through a reboot of the ESP by saving them to LittleFS without + storing them as plain text */ #include <FS.h> @@ -15,21 +16,24 @@ #include <ESP8266WiFi.h> #include <ESP8266WebServerSecure.h> -//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* 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 +56,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,25 +88,26 @@ gz5JWYhbD6c38khSzJb0pNXCo3EuYAVa36kDM96k1BtWuhRS10Q1VXk= ESP8266WebServerSecure server(443); -//These are temporary credentials that will only be used if none are found saved in LittleFS. -String login = "admin"; -const String realm = "global"; -String H1 = ""; -String authentication_failed = "User authentication has failed."; +// These are temporary credentials that will only be used if none are found saved in LittleFS. +String login = "admin"; +const String realm = "global"; +String H1 = ""; +String authentication_failed = "User authentication has failed."; 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) { @@ -111,9 +116,12 @@ void setup() { ESP.restart(); } - server.getServer().setRSACert(new BearSSL::X509List(serverCert), new BearSSL::PrivateKey(serverKey)); - server.on("/",showcredentialpage); //for this simple example, just show a simple page for changing credentials at the root - server.on("/" + change_creds,handlecredentialchange); //handles submission of credentials from the client + server.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.onNotFound(redirect); server.begin(); @@ -127,36 +135,38 @@ 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()){ + if (!session_authenticated()) { return; } @@ -165,11 +175,12 @@ void showcredentialpage(){ String page; page = R"(<html>)"; - page+= - R"( + page += + R"( <h2>Login Credentials</h2><br> - <form action=")" + change_creds + R"(" method="post"> + <form action=")" + + change_creds + R"(" method="post"> Login:<br> <input type="text" name="login"><br> Password:<br> @@ -178,8 +189,7 @@ void showcredentialpage(){ <input type="password" name="password_duplicate"><br> <p><button type="submit" name="newcredentials">Change Credentials</button></p> </form><br> - )" - ; + )"; page += R"(</html>)"; @@ -188,17 +198,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,47 +218,45 @@ 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"; + String default_login = "admin"; String default_password = "changeme"; Serial.println("None found. Setting to default credentials."); Serial.println("user:" + default_login); Serial.println("password:" + default_password); - login=default_login; - H1=ESP8266WebServer::credentialHash(default_login,realm,default_password); + 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()){ + if (!session_authenticated()) { return; } Serial.println("Handling credential change request from client."); String login = server.arg("login"); - String pw1 = server.arg("password"); - String pw2 = server.arg("password_duplicate"); - - if(login != "" && pw1 != "" && pw1 == pw2){ + String pw1 = server.arg("password"); + String pw2 = server.arg("password_duplicate"); - savecredentials(login,pw1); + if (login != "" && pw1 != "" && pw1 == pw2) { + 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..baaee5b936 100644 --- a/libraries/ESP8266WebServer/examples/PathArgServer/PathArgServer.ino +++ b/libraries/ESP8266WebServer/examples/PathArgServer/PathArgServer.ino @@ -8,11 +8,11 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char *ssid = STASSID; -const char *password = STAPSK; +const char* ssid = STASSID; +const char* password = STAPSK; ESP8266WebServer server(80); @@ -37,9 +37,7 @@ void setup(void) { Serial.println("MDNS responder started"); } - server.on(F("/"), []() { - server.send(200, "text/plain", "hello from esp8266!"); - }); + server.on(F("/"), []() { server.send(200, "text/plain", "hello from esp8266!"); }); server.on(UriBraces("/users/{}"), []() { String user = server.pathArg(0); @@ -47,7 +45,7 @@ void setup(void) { }); server.on(UriRegex("^\\/users\\/([0-9]+)\\/devices\\/([0-9]+)$"), []() { - String user = server.pathArg(0); + String user = server.pathArg(0); String device = server.pathArg(1); server.send(200, "text/plain", "User: '" + user + "' and Device: '" + device + "'"); }); @@ -56,6 +54,4 @@ void setup(void) { Serial.println("HTTP server started"); } -void loop(void) { - server.handleClient(); -} +void loop(void) { server.handleClient(); } diff --git a/libraries/ESP8266WebServer/examples/PostServer/PostServer.ino b/libraries/ESP8266WebServer/examples/PostServer/PostServer.ino index da1703807a..f9b1ad3693 100644 --- a/libraries/ESP8266WebServer/examples/PostServer/PostServer.ino +++ b/libraries/ESP8266WebServer/examples/PostServer/PostServer.ino @@ -5,7 +5,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* ssid = STASSID; @@ -121,6 +121,4 @@ void setup(void) { Serial.println("HTTP server started"); } -void loop(void) { - server.handleClient(); -} +void loop(void) { server.handleClient(); } diff --git a/libraries/ESP8266WebServer/examples/ServerSentEvents/ServerSentEvents.ino b/libraries/ESP8266WebServer/examples/ServerSentEvents/ServerSentEvents.ino index 77ae1e958e..1356219b10 100644 --- a/libraries/ESP8266WebServer/examples/ServerSentEvents/ServerSentEvents.ino +++ b/libraries/ESP8266WebServer/examples/ServerSentEvents/ServerSentEvents.ino @@ -3,19 +3,20 @@ 1. set SSID, password and ports, compile and run program you should see (random) updates of sensors A and B - 2. on the client(s), register it for the event bus using a REST API call: curl -sS "http://<your ESP IP>:<your port>/rest/events/subscribe" - on both server and client, you should now see that your client is registered - the server sends back the location of the event bus (channel) to the client: - subscription for client IP <your client's IP address>: event bus location: http://<your ESP IP>:<your port>/rest/events/<channel> + 2. on the client(s), register it for the event bus using a REST API call: curl -sS "http://<your + ESP IP>:<your port>/rest/events/subscribe" on both server and client, you should now see that your + client is registered the server sends back the location of the event bus (channel) to the client: + subscription for client IP <your client's IP address>: event bus location: http://<your ESP + IP>:<your port>/rest/events/<channel> - you will also see that the sensors are ready to broadcast state changes, but the client is not yet listening: - SSEBroadcastState - client <your client IP>> registered but not listening + you will also see that the sensors are ready to broadcast state changes, but the client is not + yet listening: SSEBroadcastState - client <your client IP>> registered but not listening - 3. on the client(s), start listening for events with: curl -sS "http://<your ESP IP>:<your port>/rest/events/<channel>" - if all is well, the following is being displayed on the ESP console + 3. on the client(s), start listening for events with: curl -sS "http://<your ESP IP>:<your + port>/rest/events/<channel>" if all is well, the following is being displayed on the ESP console SSEHandler - registered client with IP <your client IP address> is listening... - broadcast status change to client IP <your client IP>> for sensor[A|B] with new state <some number>> - every minute you will see on the ESP: SSEKeepAlive - client is still connected + broadcast status change to client IP <your client IP>> for sensor[A|B] with new state <some + number>> every minute you will see on the ESP: SSEKeepAlive - client is still connected on the client, you should see the SSE messages coming in: event: event @@ -26,9 +27,10 @@ data: { "TYPE":"STATE", "sensorA": {"state" : 17664, "prevState": 49362} } 4. on the client, stop listening by hitting control-C - on the ESP, after maximum one minute, the following message is displayed: SSEKeepAlive - client no longer connected, remove subscription - if you start listening again after the time expired, the "/rest/events" handle becomes stale and "Handle not found" is returned - you can also try to start listening again before the KeepAliver timer expires or simply register your client again + on the ESP, after maximum one minute, the following message is displayed: SSEKeepAlive - client + no longer connected, remove subscription if you start listening again after the time expired, the + "/rest/events" handle becomes stale and "Handle not found" is returned you can also try to start + listening again before the KeepAliver timer expires or simply register your client again */ extern "C" { @@ -42,27 +44,28 @@ 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 unsigned int port = 80; +const char* ssid = STASSID; +const char* password = STAPSK; +const unsigned int port = 80; ESP8266WebServer server(port); -#define SSE_MAX_CHANNELS 8 // in this simplified example, only eight SSE clients subscription allowed +#define SSE_MAX_CHANNELS \ + 8 // in this simplified example, only eight SSE clients subscription allowed struct SSESubscription { - IPAddress clientIP; + IPAddress clientIP; WiFiClient client; - Ticker keepAliveTimer; + Ticker keepAliveTimer; } subscription[SSE_MAX_CHANNELS]; uint8_t subscriptionCount = 0; typedef struct { - const char *name; + const char* name; unsigned short value; - Ticker update; + Ticker update; } sensorType; sensorType sensor[2]; @@ -89,9 +92,12 @@ void SSEKeepAlive() { } if (subscription[i].client.connected()) { Serial.printf_P(PSTR("SSEKeepAlive - client is still listening on channel %d\n"), i); - subscription[i].client.println(F("event: event\ndata: { \"TYPE\":\"KEEP-ALIVE\" }\n")); // Extra newline required by SSE standard + subscription[i].client.println( + F("event: event\ndata: { \"TYPE\":\"KEEP-ALIVE\" }\n")); // Extra newline required by SSE + // standard } else { - Serial.printf_P(PSTR("SSEKeepAlive - client not listening on channel %d, remove subscription\n"), i); + Serial.printf_P( + PSTR("SSEKeepAlive - client not listening on channel %d, remove subscription\n"), i); subscription[i].keepAliveTimer.detach(); subscription[i].client.flush(); subscription[i].client.stop(); @@ -104,28 +110,32 @@ void SSEKeepAlive() { // SSEHandler handles the client connection to the event bus (client event listener) // every 60 seconds it sends a keep alive event via Ticker 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 - Serial.printf_P(PSTR("SSEHandler - unregistered client with IP %s tries to listen\n"), server.client().remoteIP().toString().c_str()); + WiFiClient client = server.client(); + SSESubscription& s = subscription[channel]; + if (s.clientIP != client.remoteIP()) { // IP addresses don't match, reject this client + Serial.printf_P(PSTR("SSEHandler - unregistered client with IP %s tries to listen\n"), + server.client().remoteIP().toString().c_str()); return handleNotFound(); } 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 - 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")); + 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 + 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 } void handleAll() { - const char *uri = server.uri().c_str(); - const char *restEvents = PSTR("/rest/events/"); + const char* uri = server.uri().c_str(); + const char* restEvents = PSTR("/rest/events/"); if (strncmp_P(uri, restEvents, strlen_P(restEvents))) { return handleNotFound(); } - uri += strlen_P(restEvents); // Skip the "/rest/events/" and get to the channel number + 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); @@ -133,27 +143,34 @@ void handleAll() { handleNotFound(); }; -void SSEBroadcastState(const char *sensorName, unsigned short prevSensorValue, unsigned short sensorValue) { +void SSEBroadcastState(const char* sensorName, unsigned short prevSensorValue, + unsigned short sensorValue) { for (uint8_t i = 0; i < SSE_MAX_CHANNELS; i++) { if (!(subscription[i].clientIP)) { continue; } 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"), + 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); + Serial.printf_P( + PSTR("SSEBroadcastState - client %s registered on channel %d but not listening\n"), + IPaddrstr.c_str(), i); } } } // Simulate sensors -void updateSensor(sensorType &sensor) { - unsigned short newVal = (unsigned short)RANDOM_REG32; // (not so good) random value for the sensor - Serial.printf_P(PSTR("update sensor %s - previous state: %d, new state: %d\n"), sensor.name, sensor.value, newVal); +void updateSensor(sensorType& sensor) { + unsigned short newVal + = (unsigned short)RANDOM_REG32; // (not so good) random value for the sensor + Serial.printf_P(PSTR("update sensor %s - previous state: %d, new state: %d\n"), sensor.name, + sensor.value, newVal); if (sensor.value != newVal) { SSEBroadcastState(sensor.name, sensor.value, newVal); // only broadcast if state is different } @@ -166,9 +183,9 @@ void handleSubscribe() { return handleNotFound(); // We ran out of channels } - uint8_t channel; - IPAddress clientIP = server.client().remoteIP(); // get IP address of client - String SSEurl = F("http://"); + uint8_t channel; + IPAddress clientIP = server.client().remoteIP(); // get IP address of client + String SSEurl = F("http://"); SSEurl += WiFi.localIP().toString(); SSEurl += F(":"); SSEurl += port; @@ -176,15 +193,17 @@ void handleSubscribe() { SSEurl += F("/rest/events/"); ++subscriptionCount; - for (channel = 0; channel < SSE_MAX_CHANNELS; channel++) // Find first free slot + for (channel = 0; channel < SSE_MAX_CHANNELS; channel++) // Find first free slot if (!subscription[channel].clientIP) { break; } - subscription[channel] = {clientIP, server.client(), Ticker()}; + subscription[channel] = { clientIP, server.client(), Ticker() }; SSEurl += channel; - Serial.printf_P(PSTR("Allocated channel %d, on uri %s\n"), channel, SSEurl.substring(offset).c_str()); - //server.on(SSEurl.substring(offset), std::bind(SSEHandler, &(subscription[channel]))); - Serial.printf_P(PSTR("subscription for client IP %s: event bus location: %s\n"), clientIP.toString().c_str(), SSEurl.c_str()); + 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]))); + 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 +219,17 @@ 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()); + 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"); } - 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..0a9756b2ac 100644 --- a/libraries/ESP8266WebServer/examples/SimpleAuthentication/SimpleAuthentication.ino +++ b/libraries/ESP8266WebServer/examples/SimpleAuthentication/SimpleAuthentication.ino @@ -4,15 +4,15 @@ #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); -//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"); @@ -56,7 +56,8 @@ void handleLogin() { msg = "Wrong username/password! try again."; Serial.println("Log in Failed"); } - String content = "<html><body><form action='/login' method='POST'>To log in, please use : admin/admin<br>"; + String content + = "<html><body><form action='/login' method='POST'>To log in, please use : admin/admin<br>"; content += "User:<input type='text' name='USERNAME' placeholder='user name'><br>"; content += "Password:<input type='password' name='PASSWORD' placeholder='password'><br>"; content += "<input type='submit' name='SUBMIT' value='Submit'></form>" + msg + "<br>"; @@ -64,7 +65,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; @@ -78,11 +79,12 @@ void handleRoot() { if (server.hasHeader("User-Agent")) { content += "the user agent used is : " + server.header("User-Agent") + "<br><br>"; } - content += "You can access this page until you <a href=\"/login?DISCONNECT=YES\">disconnect</a></body></html>"; + content += "You can access this page until you <a " + "href=\"/login?DISCONNECT=YES\">disconnect</a></body></html>"; server.send(200, "text/html", content); } -//no need authentication +// no need authentication void handleNotFound() { String message = "File Not Found\n\n"; message += "URI: "; @@ -115,20 +117,16 @@ void setup(void) { Serial.print("IP address: "); Serial.println(WiFi.localIP()); - server.on("/", handleRoot); server.on("/login", handleLogin); - server.on("/inline", []() { - server.send(200, "text/plain", "this works without need of authentication"); - }); + server.on("/inline", + []() { server.send(200, "text/plain", "this works without need of authentication"); }); 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"); } -void loop(void) { - server.handleClient(); -} +void loop(void) { server.handleClient(); } diff --git a/libraries/ESP8266WebServer/examples/WebServer/WebServer.ino b/libraries/ESP8266WebServer/examples/WebServer/WebServer.ino index 08107586fd..4edee4060f 100644 --- a/libraries/ESP8266WebServer/examples/WebServer/WebServer.ino +++ b/libraries/ESP8266WebServer/examples/WebServer/WebServer.ino @@ -9,10 +9,10 @@ #include <Arduino.h> #include <ESP8266WebServer.h> -#include "secrets.h" // add WLAN Credentials in here. +#include "secrets.h" // add WLAN Credentials in here. -#include <FS.h> // File System for Web Server Files -#include <LittleFS.h> // This file system is used. +#include <FS.h> // File System for Web Server Files +#include <LittleFS.h> // This file system is used. // mark parameters not used in example #define UNUSED __attribute__((unused)) @@ -32,11 +32,11 @@ ESP8266WebServer server(80); // The text of builtin files are in this header file #include "builtinfiles.h" - // ===== Simple functions used to answer simple GET requests ===== // This function is called when the WebServer was requested without giving a filename. -// This will redirect to the file index.htm when it is existing otherwise to the built-in $upload.htm page +// This will redirect to the file index.htm when it is existing otherwise to the built-in +// $upload.htm page void handleRedirect() { TRACE("Redirect..."); String url = "/index.htm"; @@ -47,13 +47,12 @@ void handleRedirect() { 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. -// a JSON array with file information is returned. +// This function is called when the WebServer was requested to list all existing files in the +// filesystem. a JSON array with file information is returned. void handleListFiles() { - Dir dir = LittleFS.openDir("/"); + Dir dir = LittleFS.openDir("/"); String result; result += "[\n"; @@ -67,12 +66,11 @@ void handleListFiles() { 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. void handleSysInfo() { @@ -90,96 +88,92 @@ 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 { +// 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 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. - // @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; + } else if (requestMethod == HTTP_DELETE) { + if (LittleFS.exists(fName)) { + LittleFS.remove(fName); } + } // if + + server.send(200); // all done. + return (true); + } // handle() + + // uploading process + void upload(ESP8266WebServer UNUSED& server, const String UNUSED& _requestUri, + HTTPUpload& upload) override { + // ensure that filename starts with '/' + String fName = upload.filename; + if (!fName.startsWith("/")) { + fName = "/" + fName; + } - if (requestMethod == HTTP_POST) { - // all done in upload. no other forms. - - } else if (requestMethod == HTTP_DELETE) { - if (LittleFS.exists(fName)) { - LittleFS.remove(fName); - } - } // if - - 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); } - if (upload.status == UPLOAD_FILE_START) { - // Open the file - if (LittleFS.exists(fName)) { - LittleFS.remove(fName); - } // if - _fsUploadFile = LittleFS.open(fName, "w"); - - } else if (upload.status == UPLOAD_FILE_WRITE) { - // Write received bytes - if (_fsUploadFile) { - _fsUploadFile.write(upload.buf, upload.currentSize); - } - - } else if (upload.status == UPLOAD_FILE_END) { - // Close the file - if (_fsUploadFile) { - _fsUploadFile.close(); - } - } // if - } // upload() + } else if (upload.status == UPLOAD_FILE_END) { + // Close the file + if (_fsUploadFile) { + _fsUploadFile.close(); + } + } // if + } // upload() protected: - File _fsUploadFile; + File _fsUploadFile; }; - // Setup everything to make the webserver work. void setup(void) { - delay(3000); // wait for serial monitor to start completely. + delay(3000); // wait for serial monitor to start completely. // Use Serial port for some trace information from the example Serial.begin(115200); @@ -219,9 +213,7 @@ void setup(void) { TRACE("Register service handlers...\n"); // serve a built-in htm page - server.on("/$upload.htm", []() { - server.send(200, "text/html", FPSTR(uploadContent)); - }); + server.on("/$upload.htm", []() { server.send(200, "text/html", FPSTR(uploadContent)); }); // register a redirect handler when only domain name is given. server.on("/", HTTP_GET, handleRedirect); @@ -250,12 +242,9 @@ void setup(void) { server.begin(); TRACE("hostname=%s\n", WiFi.getHostname()); -} // setup - +} // setup // run the server... -void loop(void) { - server.handleClient(); -} // loop() +void loop(void) { server.handleClient(); } // loop() // end. diff --git a/libraries/ESP8266WebServer/examples/WebUpdate/WebUpdate.ino b/libraries/ESP8266WebServer/examples/WebUpdate/WebUpdate.ino index 17646fd172..1210d7fed5 100644 --- a/libraries/ESP8266WebServer/examples/WebUpdate/WebUpdate.ino +++ b/libraries/ESP8266WebServer/examples/WebUpdate/WebUpdate.ino @@ -1,5 +1,6 @@ /* - To upload through terminal you can use: curl -F "image=@firmware.bin" esp8266-webupdate.local/update + To upload through terminal you can use: curl -F "image=@firmware.bin" + esp8266-webupdate.local/update */ #include <ESP8266WiFi.h> @@ -9,15 +10,17 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char* host = "esp8266-webupdate"; -const char* ssid = STASSID; +const char* host = "esp8266-webupdate"; +const char* ssid = STASSID; const char* password = STAPSK; ESP8266WebServer server(80); -const char* serverIndex = "<form method='POST' action='/update' enctype='multipart/form-data'><input type='file' name='update'><input type='submit' value='Update'></form>"; +const char* serverIndex + = "<form method='POST' action='/update' enctype='multipart/form-data'><input type='file' " + "name='update'><input type='submit' value='Update'></form>"; void setup(void) { Serial.begin(115200); @@ -31,34 +34,37 @@ 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); - } - } 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(); - }); + 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); + } + 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..bf84aabc59 100644 --- a/libraries/ESP8266WiFi/examples/BearSSL_CertStore/BearSSL_CertStore.ino +++ b/libraries/ESP8266WiFi/examples/BearSSL_CertStore/BearSSL_CertStore.ino @@ -41,11 +41,11 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char *ssid = STASSID; -const char *pass = STAPSK; +const char* ssid = STASSID; +const char* pass = STAPSK; // A single, global CertStore which can be used by all // connections. Needs to stay live the entire time any of @@ -71,7 +71,8 @@ void setClock() { } // Try and connect using a WiFiClientBearSSL to specified host:port and dump URL -void fetchURL(BearSSL::WiFiClientSecure *client, const char *host, const uint16_t port, const char *path) { +void fetchURL(BearSSL::WiFiClientSecure* client, const char* host, const uint16_t port, + const char* path) { if (!path) { path = "/"; } @@ -100,7 +101,7 @@ void fetchURL(BearSSL::WiFiClientSecure *client, const char *host, const uint16_ break; } // Only print out first line up to \r, then abort connection - char *nl = strchr(tmp, '\r'); + char* nl = strchr(tmp, '\r'); if (nl) { *nl = 0; Serial.print(tmp); @@ -136,16 +137,17 @@ 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! + 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! } - BearSSL::WiFiClientSecure *bear = new BearSSL::WiFiClientSecure(); + BearSSL::WiFiClientSecure* bear = new BearSSL::WiFiClientSecure(); // Integrate the cert store with this connection bear->setCertStore(&certStore); Serial.printf("Attempting to fetch https://github.com/...\n"); @@ -164,10 +166,9 @@ void loop() { site.replace(String("\n"), emptyString); Serial.printf("https://%s/\n", site.c_str()); - BearSSL::WiFiClientSecure *bear = new BearSSL::WiFiClientSecure(); + BearSSL::WiFiClientSecure* bear = new BearSSL::WiFiClientSecure(); // Integrate the cert store with this connection bear->setCertStore(&certStore); fetchURL(bear, site.c_str(), 443, "/"); delete bear; } - diff --git a/libraries/ESP8266WiFi/examples/BearSSL_MaxFragmentLength/BearSSL_MaxFragmentLength.ino b/libraries/ESP8266WiFi/examples/BearSSL_MaxFragmentLength/BearSSL_MaxFragmentLength.ino index 708d906eb1..965f07b0b5 100644 --- a/libraries/ESP8266WiFi/examples/BearSSL_MaxFragmentLength/BearSSL_MaxFragmentLength.ino +++ b/libraries/ESP8266WiFi/examples/BearSSL_MaxFragmentLength/BearSSL_MaxFragmentLength.ino @@ -9,26 +9,26 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char *ssid = STASSID; -const char *pass = STAPSK; +const char* ssid = STASSID; +const char* pass = STAPSK; -void fetch(BearSSL::WiFiClientSecure *client) { +void fetch(BearSSL::WiFiClientSecure* client) { client->write("GET / HTTP/1.0\r\nHost: tls.mbed.org\r\nUser-Agent: ESP8266\r\n\r\n"); client->flush(); using oneShot = esp8266::polledTimeout::oneShot; 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) { - delay(10); // Give background processes some time + delay(10); // Give background processes some time continue; } tmp[rlen] = '\0'; diff --git a/libraries/ESP8266WiFi/examples/BearSSL_Server/BearSSL_Server.ino b/libraries/ESP8266WiFi/examples/BearSSL_Server/BearSSL_Server.ino index 160b6a981e..546fc263a6 100644 --- a/libraries/ESP8266WiFi/examples/BearSSL_Server/BearSSL_Server.ino +++ b/libraries/ESP8266WiFi/examples/BearSSL_Server/BearSSL_Server.ino @@ -39,11 +39,11 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char *ssid = STASSID; -const char *pass = STAPSK; +const char* ssid = STASSID; +const char* pass = STAPSK; // The HTTPS server BearSSL::WiFiServerSecure server(443); @@ -138,11 +138,13 @@ 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. + +// Caching SSL sessions shortens the length of the SSL handshake. +// You can see the performance improvement by looking at the +// Network tab of the developer tools of your browser. +#define USE_CACHE // Enable SSL session caching. + //#define DYNAMIC_CACHE // Whether to dynamically allocate the cache. #if defined(USE_CACHE) && defined(DYNAMIC_CACHE) @@ -150,7 +152,7 @@ GBEnkz4KpKv7TkHoW+j7F5EMcLcSrUIpyw== BearSSL::ServerSessions serverCache(CACHE_SIZE); #elif defined(USE_CACHE) // Statically allocated cache. -ServerSession store[CACHE_SIZE]; +ServerSession store[CACHE_SIZE]; BearSSL::ServerSessions serverCache(store, CACHE_SIZE); #endif @@ -176,12 +178,12 @@ void setup() { Serial.println(WiFi.localIP()); // Attach the server private cert/key combo - BearSSL::X509List *serverCertList = new BearSSL::X509List(server_cert); - BearSSL::PrivateKey *serverPrivKey = new BearSSL::PrivateKey(server_private_key); + BearSSL::X509List* serverCertList = new BearSSL::X509List(server_cert); + BearSSL::PrivateKey* serverPrivKey = new BearSSL::PrivateKey(server_private_key); #ifndef USE_EC server.setRSACert(serverCertList, serverPrivKey); #else - server.setECCert(serverCertList, BR_KEYTYPE_KEYX|BR_KEYTYPE_SIGN, serverPrivKey); + server.setECCert(serverCertList, BR_KEYTYPE_KEYX | BR_KEYTYPE_SIGN, serverPrivKey); #endif // Set the server's cache @@ -193,31 +195,30 @@ 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" - "<html>\r\n" - "<body>\r\n" - "<p>Hello from ESP8266!</p>\r\n" - "</body>\r\n" - "</html>\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" + "<html>\r\n" + "<body>\r\n" + "<p>Hello from ESP8266!</p>\r\n" + "</body>\r\n" + "</html>\r\n"; void loop() { - static int cnt; + static int cnt; BearSSL::WiFiClientSecure incoming = server.accept(); if (!incoming) { return; } - Serial.printf("Incoming connection...%d\n",cnt++); - + Serial.printf("Incoming connection...%d\n", cnt++); + // Ugly way to wait for \r\n (i.e. end of HTTP request which we don't actually parse here) - uint32_t timeout=millis() + 1000; - int lcwn = 0; + uint32_t timeout = millis() + 1000; + int lcwn = 0; for (;;) { - unsigned char x=0; + unsigned char x = 0; if ((millis() > timeout) || (incoming.available() && incoming.read(&x, 1) < 0)) { incoming.stop(); Serial.printf("Connection error, closed\n"); diff --git a/libraries/ESP8266WiFi/examples/BearSSL_ServerClientCert/BearSSL_ServerClientCert.ino b/libraries/ESP8266WiFi/examples/BearSSL_ServerClientCert/BearSSL_ServerClientCert.ino index 3e88019cf4..e88d3d2672 100644 --- a/libraries/ESP8266WiFi/examples/BearSSL_ServerClientCert/BearSSL_ServerClientCert.ino +++ b/libraries/ESP8266WiFi/examples/BearSSL_ServerClientCert/BearSSL_ServerClientCert.ino @@ -30,7 +30,8 @@ self-signed CA or any other CA you'd like) openssl genrsa -out server_key.pem 2048 openssl req -out server_req.csr -key server_key.pem -new -config server.conf - openssl x509 -req -in server_req.csr -out server_cer.pem -sha256 -CAcreateserial -days 4000 -CA ca_cer.pem -CAkey ca_key.pem + openssl x509 -req -in server_req.csr -out server_cer.pem -sha256 -CAcreateserial -days 4000 + -CA ca_cer.pem -CAkey ca_key.pem KEEP server_key.pem SECURE, IT IS YOUR SERVER'S PRIVATE KEY. THIS WILL BE STORED IN THE SERVER ALONE. CLIENTS DO NOT NEED IT! @@ -42,7 +43,8 @@ private CA above) openssl genrsa -out client1_key.pem 2048 openssl req -out client1_req.csr -key client1_key.pem -new -config client.conf - openssl x509 -req -in client1_req.csr -out client1_cer.pem -sha256 -CAcreateserial -days 4000 -CA ca_cer.pem -CAkey ca_key.pem + openssl x509 -req -in client1_req.csr -out client1_cer.pem -sha256 -CAcreateserial -days 4000 + -CA ca_cer.pem -CAkey ca_key.pem Every client should have its own unique certificate generated and a copy of that specific client's private key. @@ -57,7 +59,8 @@ If you don't specify the client cert and key on the WGET command line, you will not get connected. - ex: wget --quiet --O - --no-check-certificate --certificate=client1_cer.pem --private-key=client1_key.pem https://esp.ip.add.ress/ + ex: wget --quiet --O - --no-check-certificate --certificate=client1_cer.pem + --private-key=client1_key.pem https://esp.ip.add.ress/ This example is released into the public domain. */ @@ -67,11 +70,11 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char *ssid = STASSID; -const char *pass = STAPSK; +const char* ssid = STASSID; +const char* pass = STAPSK; // The server which will require a client cert signed by the trusted CA BearSSL::WiFiServerSecure server(443); @@ -160,8 +163,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,32 +201,31 @@ 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); - BearSSL::PrivateKey *serverPrivKey = new BearSSL::PrivateKey(server_private_key); + BearSSL::X509List* serverCertList = new BearSSL::X509List(server_cert); + BearSSL::PrivateKey* serverPrivKey = new BearSSL::PrivateKey(server_private_key); server.setRSACert(serverCertList, serverPrivKey); // Require a certificate validated by the trusted CA - BearSSL::X509List *serverTrustedCA = new BearSSL::X509List(ca_cert); + BearSSL::X509List* serverTrustedCA = new BearSSL::X509List(ca_cert); server.setClientTrustAnchor(serverTrustedCA); // Actually start accepting connections server.begin(); } -static const char *HTTP_RES = - "HTTP/1.0 200 OK\r\n" - "Connection: close\r\n" - "Content-Length: 59\r\n" - "Content-Type: text/html; charset=iso-8859-1\r\n" - "\r\n" - "<html>\r\n" - "<body>\r\n" - "<p>Hello my friend!</p>\r\n" - "</body>\r\n" - "</html>\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" + "<html>\r\n" + "<body>\r\n" + "<p>Hello my friend!</p>\r\n" + "</body>\r\n" + "</html>\r\n"; void loop() { BearSSL::WiFiClientSecure incoming = server.accept(); @@ -232,12 +233,12 @@ void loop() { return; } Serial.println("Incoming connection...\n"); - + // Ugly way to wait for \r\n (i.e. end of HTTP request which we don't actually parse here) - uint32_t timeout=millis() + 1000; - int lcwn = 0; + uint32_t timeout = millis() + 1000; + int lcwn = 0; for (;;) { - unsigned char x=0; + unsigned char x = 0; if ((millis() > timeout) || (incoming.available() && incoming.read(&x, 1) < 0)) { incoming.stop(); Serial.printf("Connection error, closed\n"); diff --git a/libraries/ESP8266WiFi/examples/BearSSL_Sessions/BearSSL_Sessions.ino b/libraries/ESP8266WiFi/examples/BearSSL_Sessions/BearSSL_Sessions.ino index fa03c7fa38..2fc3a2b38e 100644 --- a/libraries/ESP8266WiFi/examples/BearSSL_Sessions/BearSSL_Sessions.ino +++ b/libraries/ESP8266WiFi/examples/BearSSL_Sessions/BearSSL_Sessions.ino @@ -9,13 +9,13 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char *ssid = STASSID; -const char *pass = STAPSK; +const char* ssid = STASSID; +const char* pass = STAPSK; -const char * path = "/"; +const char* path = "/"; void setup() { Serial.begin(115200); @@ -52,7 +52,8 @@ void setup() { } // Try and connect using a WiFiClientBearSSL to specified host:port and dump HTTP response -void fetchURL(BearSSL::WiFiClientSecure *client, const char *host, const uint16_t port, const char *path) { +void fetchURL(BearSSL::WiFiClientSecure* client, const char* host, const uint16_t port, + const char* path) { if (!path) { path = "/"; } @@ -81,7 +82,7 @@ void fetchURL(BearSSL::WiFiClientSecure *client, const char *host, const uint16_ break; } // Only print out first line up to \r, then abort connection - char *nl = strchr(tmp, '\r'); + char* nl = strchr(tmp, '\r'); if (nl) { *nl = 0; Serial.print(tmp); @@ -94,11 +95,10 @@ void fetchURL(BearSSL::WiFiClientSecure *client, const char *host, const uint16_ Serial.printf("\n-------\n\n"); } - void loop() { - uint32_t start, finish; + uint32_t start, finish; BearSSL::WiFiClientSecure client; - BearSSL::X509List cert(cert_DigiCert_High_Assurance_EV_Root_CA); + BearSSL::X509List cert(cert_DigiCert_High_Assurance_EV_Root_CA); Serial.printf("Connecting without sessions..."); start = millis(); @@ -130,6 +130,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..4828d44c3f 100644 --- a/libraries/ESP8266WiFi/examples/BearSSL_Validation/BearSSL_Validation.ino +++ b/libraries/ESP8266WiFi/examples/BearSSL_Validation/BearSSL_Validation.ino @@ -12,13 +12,13 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char *ssid = STASSID; -const char *pass = STAPSK; +const char* ssid = STASSID; +const char* pass = STAPSK; -const char * path = "/"; +const char* path = "/"; // Set time via NTP, as required for x.509 validation void setClock() { @@ -39,7 +39,8 @@ void setClock() { } // Try and connect using a WiFiClientBearSSL to specified host:port and dump HTTP response -void fetchURL(BearSSL::WiFiClientSecure *client, const char *host, const uint16_t port, const char *path) { +void fetchURL(BearSSL::WiFiClientSecure* client, const char* host, const uint16_t port, + const char* path) { if (!path) { path = "/"; } @@ -70,7 +71,7 @@ void fetchURL(BearSSL::WiFiClientSecure *client, const char *host, const uint16_ break; } // Only print out first line up to \r, then abort connection - char *nl = strchr(tmp, '\r'); + char* nl = strchr(tmp, '\r'); if (nl) { *nl = 0; Serial.print(tmp); @@ -141,7 +142,7 @@ private and not shared. A MITM without the private key would not be able to establish communications. )EOF"); BearSSL::WiFiClientSecure client; - BearSSL::PublicKey key(pubkey_gitlab_com); + BearSSL::PublicKey key(pubkey_gitlab_com); client.setKnownKey(&key); fetchURL(&client, gitlab_host, gitlab_port, path); } @@ -157,7 +158,7 @@ BearSSL does verify the notValidBefore/After fields. )EOF"); BearSSL::WiFiClientSecure client; - BearSSL::X509List cert(cert_USERTrust_RSA_Certification_Authority); + BearSSL::X509List cert(cert_USERTrust_RSA_Certification_Authority); client.setTrustAnchors(&cert); Serial.printf("Try validating without setting the time (should fail)\n"); fetchURL(&client, gitlab_host, gitlab_port, path); @@ -183,14 +184,18 @@ may make sense client.setCiphersLessSecure(); now = millis(); fetchURL(&client, gitlab_host, gitlab_port, path); - uint32_t delta2 = millis() - now; - std::vector<uint16_t> myCustomList = { BR_TLS_RSA_WITH_AES_256_CBC_SHA256, BR_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, BR_TLS_RSA_WITH_3DES_EDE_CBC_SHA }; + uint32_t delta2 = millis() - now; + std::vector<uint16_t> myCustomList + = { BR_TLS_RSA_WITH_AES_256_CBC_SHA256, BR_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, + BR_TLS_RSA_WITH_3DES_EDE_CBC_SHA }; client.setInsecure(); client.setCiphers(myCustomList); now = millis(); fetchURL(&client, gitlab_host, gitlab_port, path); uint32_t delta3 = millis() - now; - Serial.printf("Using more secure: %dms\nUsing less secure ciphers: %dms\nUsing custom cipher list: %dms\n", delta, delta2, delta3); + Serial.printf( + "Using more secure: %dms\nUsing less secure ciphers: %dms\nUsing custom cipher list: %dms\n", + delta, delta2, delta3); } void setup() { @@ -223,7 +228,6 @@ void setup() { fetchFaster(); } - void loop() { // Nothing to do here } diff --git a/libraries/ESP8266WiFi/examples/HTTPSRequest/HTTPSRequest.ino b/libraries/ESP8266WiFi/examples/HTTPSRequest/HTTPSRequest.ino index 9ccf3b6b37..4eaf735544 100644 --- a/libraries/ESP8266WiFi/examples/HTTPSRequest/HTTPSRequest.ino +++ b/libraries/ESP8266WiFi/examples/HTTPSRequest/HTTPSRequest.ino @@ -17,10 +17,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; X509List cert(cert_DigiCert_High_Assurance_EV_Root_CA); @@ -74,10 +74,8 @@ 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 +98,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..31f5c0eeb9 100644 --- a/libraries/ESP8266WiFi/examples/IPv6/IPv6.ino +++ b/libraries/ESP8266WiFi/examples/IPv6/IPv6.ino @@ -8,8 +8,8 @@ dns0=10.43.1.254 Try me at these addresses: (with 'telnet <addr> or 'nc -u <addr> 23') - IF='st'(0) IPv6=0 local=0 hostname='ipv6test' addr= 10.43.1.244 / mask:255.255.255.0 / gw:10.43.1.254 - IF='st'(0) IPv6=1 local=1 hostname='ipv6test' addr= fe80::1afe:34ff:fed1:cec7 + IF='st'(0) IPv6=0 local=0 hostname='ipv6test' addr= 10.43.1.244 / mask:255.255.255.0 / + gw:10.43.1.254 IF='st'(0) IPv6=1 local=1 hostname='ipv6test' addr= fe80::1afe:34ff:fed1:cec7 IF='st'(0) IPV6=1 local=0 hostname='ipv6test' addr= 2xxx:xxxx:xxxx:xxxx:1afe:34ff:fed1:cec7 resolving www.google.com: 216.58.205.100 resolving ipv6.google.com: 2a00:1450:4002:808::200e @@ -23,18 +23,18 @@ #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 -WiFiServer statusServer(TCP_PORT); -WiFiUDP udp; +WiFiServer statusServer(TCP_PORT); +WiFiUDP udp; esp8266::polledTimeout::periodicMs showStatusOnSerialNow(STATUSDELAY_MS); void fqdn(Print& out, const String& fqdn) { @@ -79,21 +79,14 @@ void status(Print& out) { out.println(F("Try me at these addresses:")); out.println(F("(with 'telnet <addr> or 'nc -u <addr> 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()); + 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(" / 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 +94,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 +118,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,9 +139,9 @@ void setup() { for (bool configured = false; !configured;) { for (auto addr : addrList) if ((configured = !addr.isLocal() - // && addr.isV6() // uncomment when IPv6 is mandatory - // && addr.ifnumber() == STATION_IF - )) { + // && addr.isV6() // uncomment when IPv6 is mandatory + // && addr.ifnumber() == STATION_IF + )) { break; } Serial.print('.'); @@ -173,7 +166,6 @@ void setup() { unsigned long statusTimeMs = 0; void loop() { - if (statusServer.hasClient()) { WiFiClient cli = statusServer.accept(); status(cli); @@ -188,7 +180,7 @@ void loop() { udp.remoteIP().printTo(Serial); Serial.print(F(" :")); Serial.println(udp.remotePort()); - int c; + int c; while ((c = udp.read()) >= 0) { Serial.write(c); } @@ -199,9 +191,7 @@ void loop() { udp.endPacket(); } - if (showStatusOnSerialNow) { status(Serial); } - } diff --git a/libraries/ESP8266WiFi/examples/NTPClient/NTPClient.ino b/libraries/ESP8266WiFi/examples/NTPClient/NTPClient.ino index 927e78fee9..fa20f8ca6d 100644 --- a/libraries/ESP8266WiFi/examples/NTPClient/NTPClient.ino +++ b/libraries/ESP8266WiFi/examples/NTPClient/NTPClient.ino @@ -23,24 +23,23 @@ #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 +72,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,13 +86,13 @@ 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, + // 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]); + unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]); // combine the four bytes (two words) into a long integer // this is NTP time (seconds since Jan 1 1900): unsigned long secsSince1900 = highWord << 16 | lowWord; @@ -109,22 +108,21 @@ void loop() { // print Unix time: Serial.println(epoch); - // print the hour, minute and second: Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT) - Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day) + Serial.print((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 +135,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..429eb69191 100644 --- a/libraries/ESP8266WiFi/examples/PagerServer/PagerServer.ino +++ b/libraries/ESP8266WiFi/examples/PagerServer/PagerServer.ino @@ -25,7 +25,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif const char* ssid = STASSID; @@ -34,7 +34,6 @@ const char* password = STAPSK; ArduinoWiFiServer server(2323); void setup() { - Serial.begin(115200); Serial.println(); @@ -59,14 +58,14 @@ 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..86c50a636a 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 <ESP8266WiFi.h> @@ -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,15 @@ 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()); @@ -74,7 +70,8 @@ void setup() { 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); + 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()); @@ -92,6 +89,4 @@ void setup() { #endif -void loop() { -} - +void loop() { } diff --git a/libraries/ESP8266WiFi/examples/StaticLease/StaticLease.ino b/libraries/ESP8266WiFi/examples/StaticLease/StaticLease.ino index e4520c4720..42dd215751 100644 --- a/libraries/ESP8266WiFi/examples/StaticLease/StaticLease.ino +++ b/libraries/ESP8266WiFi/examples/StaticLease/StaticLease.ino @@ -7,8 +7,8 @@ #include <LwipDhcpServer.h> /* Set these to your desired credentials. */ -const char *ssid = "ESPap"; -const char *password = "thereisnospoon"; +const char* ssid = "ESPap"; +const char* password = "thereisnospoon"; ESP8266WebServer server(80); @@ -17,21 +17,20 @@ IPAddress apIP(192, 168, 0, 1); /* Go to http://192.168.0.1 in a web browser to see current lease */ void handleRoot() { - String result; - char wifiClientMac[18]; - unsigned char number_client; - struct station_info *stat_info; + String result; + char wifiClientMac[18]; + unsigned char number_client; + struct station_info* stat_info; int i = 1; number_client = wifi_softap_get_station_num(); - stat_info = wifi_softap_get_station_info(); + stat_info = wifi_softap_get_station_info(); result = "<html><body><h1>Total Connected Clients : "; result += String(number_client); result += "</h1></br>"; while (stat_info != NULL) { - result += "Client "; result += String(i); result += " = "; @@ -52,18 +51,20 @@ void handleRoot() { void setup() { /* List of mac address for static lease */ uint8 mac_CAM[6] = { 0x00, 0x0C, 0x43, 0x01, 0x60, 0x15 }; - uint8 mac_PC[6] = { 0xb4, 0x52, 0x7e, 0x9a, 0x19, 0xa5 }; + uint8 mac_PC[6] = { 0xb4, 0x52, 0x7e, 0x9a, 0x19, 0xa5 }; Serial.begin(115200); Serial.println(); Serial.println("Configuring access point..."); - /* Disable the WiFi persistence to avoid any re-configuration that may erase static lease when starting softAP */ + /* Disable the WiFi persistence to avoid any re-configuration that may erase static lease when + * starting softAP */ WiFi.persistent(false); WiFi.mode(WIFI_AP); /* Configure AP with IP = 192.168.0.1 / Gateway = 192.168.0.1 / Subnet = 255.255.255.0 - if you specify the ESP8266's IP-address with 192.168.0.1, the function softAPConfig() sets the DHCP-range as 192.168.0.100 - 192.168.0.200 + if you specify the ESP8266's IP-address with 192.168.0.1, the function softAPConfig() sets the + DHCP-range as 192.168.0.100 - 192.168.0.200 */ WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0)); /* Setup your static leases. @@ -74,7 +75,8 @@ void setup() { first call to wifi_softap_add_dhcps_lease() will setup first IP address of the range second call to wifi_softap_add_dhcps_lease() will setup second IP address of the range ... - any client not listed will use next IP address available from the range (here 192.168.0.102 and more) + any client not listed will use next IP address available from the range (here 192.168.0.102 and + more) */ dhcpSoftAP.add_dhcps_lease(mac_CAM); // always 192.168.0.100 dhcpSoftAP.add_dhcps_lease(mac_PC); // always 192.168.0.101 @@ -88,6 +90,4 @@ void setup() { Serial.println("HTTP server started"); } -void loop() { - server.handleClient(); -} +void loop() { server.handleClient(); } diff --git a/libraries/ESP8266WiFi/examples/Udp/Udp.ino b/libraries/ESP8266WiFi/examples/Udp/Udp.ino index 7ec287b392..672e067c18 100644 --- a/libraries/ESP8266WiFi/examples/Udp/Udp.ino +++ b/libraries/ESP8266WiFi/examples/Udp/Udp.ino @@ -14,20 +14,19 @@ adapted from Ethernet library examples */ - #include <ESP8266WiFi.h> #include <WiFiUdp.h> #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; @@ -50,13 +49,11 @@ void loop() { int packetSize = Udp.parsePacket(); if (packetSize) { Serial.printf("Received packet of size %d from %s:%d\n (to %s:%d, free heap = %d B)\n", - packetSize, - Udp.remoteIP().toString().c_str(), Udp.remotePort(), - Udp.destinationIP().toString().c_str(), Udp.localPort(), - ESP.getFreeHeap()); + packetSize, Udp.remoteIP().toString().c_str(), Udp.remotePort(), + Udp.destinationIP().toString().c_str(), Udp.localPort(), ESP.getFreeHeap()); // read the packet into packetBufffer - int n = Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE); + int n = Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE); packetBuffer[n] = 0; Serial.println("Contents:"); Serial.println(packetBuffer); @@ -66,11 +63,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..f31830af11 100644 --- a/libraries/ESP8266WiFi/examples/WiFiAccessPoint/WiFiAccessPoint.ino +++ b/libraries/ESP8266WiFi/examples/WiFiAccessPoint/WiFiAccessPoint.ino @@ -36,21 +36,19 @@ #ifndef APSSID #define APSSID "ESPap" -#define APPSK "thereisnospoon" +#define APPSK "thereisnospoon" #endif /* Set these to your desired credentials. */ -const char *ssid = APSSID; -const char *password = APPSK; +const char* ssid = APSSID; +const char* password = APPSK; ESP8266WebServer server(80); /* Just a little test message. Go to http://192.168.4.1 in a web browser connected to this access point to see it. */ -void handleRoot() { - server.send(200, "text/html", "<h1>You are connected</h1>"); -} +void handleRoot() { server.send(200, "text/html", "<h1>You are connected</h1>"); } void setup() { delay(1000); @@ -68,6 +66,4 @@ void setup() { Serial.println("HTTP server started"); } -void loop() { - server.handleClient(); -} +void loop() { server.handleClient(); } diff --git a/libraries/ESP8266WiFi/examples/WiFiClient/WiFiClient.ino b/libraries/ESP8266WiFi/examples/WiFiClient/WiFiClient.ino index ef9016063b..9474d5e0b1 100644 --- a/libraries/ESP8266WiFi/examples/WiFiClient/WiFiClient.ino +++ b/libraries/ESP8266WiFi/examples/WiFiClient/WiFiClient.ino @@ -7,13 +7,13 @@ #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* host = "djxmmx.net"; +const char* host = "djxmmx.net"; const uint16_t port = 17; void setup() { @@ -90,7 +90,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..7ffdb3d033 100644 --- a/libraries/ESP8266WiFi/examples/WiFiClientBasic/WiFiClientBasic.ino +++ b/libraries/ESP8266WiFi/examples/WiFiClientBasic/WiFiClientBasic.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* password = STAPSK; -const char* host = "192.168.1.1"; +const char* host = "192.168.1.1"; const uint16_t port = 3000; ESP8266WiFiMulti WiFiMulti; @@ -44,7 +44,6 @@ void setup() { delay(500); } - void loop() { Serial.print("connecting to "); Serial.print(host); @@ -64,7 +63,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 +74,3 @@ void loop() { Serial.println("wait 5 sec..."); delay(5000); } - diff --git a/libraries/ESP8266WiFi/examples/WiFiEcho/WiFiEcho.ino b/libraries/ESP8266WiFi/examples/WiFiEcho/WiFiEcho.ino index f902e019a9..2206e04362 100644 --- a/libraries/ESP8266WiFi/examples/WiFiEcho/WiFiEcho.ino +++ b/libraries/ESP8266WiFi/examples/WiFiEcho/WiFiEcho.ino @@ -7,11 +7,11 @@ #include <ESP8266WiFi.h> #include <ESP8266mDNS.h> #include <PolledTimeout.h> -#include <algorithm> // std::min +#include <algorithm> // std::min #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif constexpr int port = 23; @@ -19,15 +19,14 @@ constexpr int port = 23; WiFiServer server(port); WiFiClient client; -constexpr size_t sizes [] = { 0, 512, 384, 256, 128, 64, 16, 8, 4 }; -constexpr uint32_t breathMs = 200; -esp8266::polledTimeout::oneShotFastMs enoughMs(breathMs); +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() { - Serial.begin(115200); Serial.println(ESP.getFullVersion()); @@ -54,9 +53,7 @@ void setup() { port); } - void loop() { - MDNS.update(); static uint32_t tot = 0; @@ -75,7 +72,7 @@ void loop() { 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 +81,29 @@ 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(); @@ -109,12 +125,13 @@ void loop() { // block by block through a local buffer (2 copies) while (client.available() && client.availableForWrite() && !enoughMs) { size_t maxTo = std::min(client.available(), client.availableForWrite()); - maxTo = std::min(maxTo, sizes[s]); + maxTo = std::min(maxTo, sizes[s]); uint8_t buf[maxTo]; - size_t tcp_got = client.read(buf, maxTo); - size_t tcp_sent = client.write(buf, tcp_got); + 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); + Serial.printf("len mismatch: available:%zd tcp-read:%zd serial-write:%zd\n", maxTo, tcp_got, + tcp_sent); } tot += tcp_sent; cnt++; @@ -131,26 +148,43 @@ void loop() { cnt++; switch (client.getLastSendReport()) { - case Stream::Report::Success: break; - case Stream::Report::TimedOut: Serial.println("Stream::send: timeout"); break; - case Stream::Report::ReadError: Serial.println("Stream::send: read error"); break; - case Stream::Report::WriteError: Serial.println("Stream::send: write error"); break; - case Stream::Report::ShortOperation: Serial.println("Stream::send: short transfer"); break; + case Stream::Report::Success: + break; + case Stream::Report::TimedOut: + Serial.println("Stream::send: timeout"); + break; + case Stream::Report::ReadError: + Serial.println("Stream::send: read error"); + break; + case Stream::Report::WriteError: + Serial.println("Stream::send: write error"); + break; + case Stream::Report::ShortOperation: + Serial.println("Stream::send: short transfer"); + break; } } 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()) { - case Stream::Report::Success: break; - case Stream::Report::TimedOut: Serial.println("Stream::send: timeout"); break; - case Stream::Report::ReadError: Serial.println("Stream::send: read error"); break; - case Stream::Report::WriteError: Serial.println("Stream::send: write error"); break; - case Stream::Report::ShortOperation: Serial.println("Stream::send: short transfer"); break; + case Stream::Report::Success: + break; + case Stream::Report::TimedOut: + Serial.println("Stream::send: timeout"); + break; + case Stream::Report::ReadError: + Serial.println("Stream::send: read error"); + break; + case Stream::Report::WriteError: + Serial.println("Stream::send: write error"); + break; + case Stream::Report::ShortOperation: + Serial.println("Stream::send: short transfer"); + break; } } - } diff --git a/libraries/ESP8266WiFi/examples/WiFiEvents/WiFiEvents.ino b/libraries/ESP8266WiFi/examples/WiFiEvents/WiFiEvents.ino index d72985a9c1..161bd01d8f 100644 --- a/libraries/ESP8266WiFi/examples/WiFiEvents/WiFiEvents.ino +++ b/libraries/ESP8266WiFi/examples/WiFiEvents/WiFiEvents.ino @@ -18,7 +18,7 @@ #ifndef APSSID #define APSSID "esp8266" -#define APPSK "esp8266" +#define APPSK "esp8266" #endif const char* ssid = APSSID; @@ -98,7 +98,7 @@ 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..cf826046a1 100644 --- a/libraries/ESP8266WiFi/examples/WiFiManualWebServer/WiFiManualWebServer.ino +++ b/libraries/ESP8266WiFi/examples/WiFiManualWebServer/WiFiManualWebServer.ino @@ -11,10 +11,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; // Create an instance of the server @@ -60,7 +60,7 @@ void loop() { } 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'); @@ -91,7 +91,8 @@ void loop() { // Send the response to the client // it is OK for multiple small client.print/write, // because nagle algorithm will group them into one single packet - client.print(F("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nGPIO is now ")); + client.print(F("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE " + "HTML>\r\n<html>\r\nGPIO is now ")); client.print((val) ? F("high") : F("low")); client.print(F("<br><br>Click <a href='http://")); client.print(WiFi.localIP()); diff --git a/libraries/ESP8266WiFi/examples/WiFiScan/WiFiScan.ino b/libraries/ESP8266WiFi/examples/WiFiScan/WiFiScan.ino index b546df4a7d..344c02f696 100644 --- a/libraries/ESP8266WiFi/examples/WiFiScan/WiFiScan.ino +++ b/libraries/ESP8266WiFi/examples/WiFiScan/WiFiScan.ino @@ -19,13 +19,13 @@ void setup() { } void loop() { - String ssid; - int32_t rssi; - uint8_t encryptionType; + String ssid; + int32_t rssi; + uint8_t encryptionType; uint8_t* bssid; - int32_t channel; - bool hidden; - int scanResult; + int32_t channel; + bool hidden; + int scanResult; Serial.println(F("Starting WiFi scan...")); @@ -40,14 +40,9 @@ 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', + 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(); } diff --git a/libraries/ESP8266WiFi/examples/WiFiShutdown/WiFiShutdown.ino b/libraries/ESP8266WiFi/examples/WiFiShutdown/WiFiShutdown.ino index b03357c143..c48e360f92 100644 --- a/libraries/ESP8266WiFi/examples/WiFiShutdown/WiFiShutdown.ino +++ b/libraries/ESP8266WiFi/examples/WiFiShutdown/WiFiShutdown.ino @@ -17,35 +17,35 @@ #endif #include <ESP8266WiFi.h> -#include <include/WiFiState.h> // WiFiState structure details +#include <include/WiFiState.h> // WiFiState structure details WiFiState state; -const char* ssid = STASSID; +const char* ssid = STASSID; 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 + // May be necessary after deepSleep. Otherwise you may get "error: pll_cal exceeds 2ms!!!" when + // trying to connect delay(1); // --- // 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<uint32_t *>(&state), sizeof(state)); + ESP.rtcUserMemoryRead(RTC_USER_DATA_SLOT_WIFI_STATE, reinterpret_cast<uint32_t*>(&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) + if (!WiFi.mode(WIFI_STA) || !WiFi.begin(ssid, password) || (WiFi.waitForConnectResult(10000) != WL_CONNECTED)) { WiFi.mode(WIFI_OFF); Serial.println("Cannot connect!"); @@ -64,7 +64,8 @@ void setup() { // --- WiFi.shutdown(state); - ESP.rtcUserMemoryWrite(RTC_USER_DATA_SLOT_WIFI_STATE, reinterpret_cast<uint32_t *>(&state), sizeof(state)); + ESP.rtcUserMemoryWrite(RTC_USER_DATA_SLOT_WIFI_STATE, reinterpret_cast<uint32_t*>(&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..97d160e309 100644 --- a/libraries/ESP8266WiFi/examples/WiFiTelnetToSerial/WiFiTelnetToSerial.ino +++ b/libraries/ESP8266WiFi/examples/WiFiTelnetToSerial/WiFiTelnetToSerial.ino @@ -20,11 +20,11 @@ */ #include <ESP8266WiFi.h> -#include <algorithm> // std::min +#include <algorithm> // std::min #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif /* @@ -64,11 +64,11 @@ 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* ssid = STASSID; const char* password = STAPSK; const int port = 23; @@ -77,7 +77,6 @@ WiFiServer server(port); WiFiClient serverClients[MAX_SRV_CLIENTS]; void setup() { - Serial.begin(BAUD_SERIAL); Serial.setRxBufferSize(RXBUFFERSIZE); @@ -98,7 +97,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 +113,7 @@ void setup() { logger->print("connected, address="); logger->println(WiFi.localIP()); - //start server + // start server server.begin(); server.setNoDelay(true); @@ -124,19 +123,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 +146,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 @@ -161,12 +160,13 @@ void loop() { for (int i = 0; i < MAX_SRV_CLIENTS; i++) while (serverClients[i].available() && Serial.availableForWrite() > 0) { size_t maxToSerial = std::min(serverClients[i].available(), Serial.availableForWrite()); - maxToSerial = std::min(maxToSerial, (size_t)STACK_PROTECTOR); + maxToSerial = std::min(maxToSerial, (size_t)STACK_PROTECTOR); uint8_t buf[maxToSerial]; - size_t tcp_got = serverClients[i].read(buf, maxToSerial); - size_t serial_sent = Serial.write(buf, tcp_got); + 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); + logger->printf("len mismatch: available:%zd tcp-read:%zd serial-write:%zd\n", maxToSerial, + tcp_got, serial_sent); } } #endif @@ -189,12 +189,12 @@ 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); + len = std::min(len, (size_t)STACK_PROTECTOR); if (len) { uint8_t sbuf[len]; - int serial_got = Serial.readBytes(sbuf, len); + int serial_got = Serial.readBytes(sbuf, len); // push UART data to all connected telnet clients for (int i = 0; i < MAX_SRV_CLIENTS; i++) // if client.availableForWrite() was 0 (congested) @@ -203,7 +203,8 @@ void loop() { 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); + 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..80ae6ad429 100644 --- a/libraries/ESP8266WiFiMesh/examples/HelloEspnow/HelloEspnow.ino +++ b/libraries/ESP8266WiFiMesh/examples/HelloEspnow/HelloEspnow.ino @@ -1,4 +1,7 @@ -#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 <ESP8266WiFi.h> #include <EspnowMeshBackend.h> @@ -10,67 +13,94 @@ namespace TypeCast = MeshTypeConversionFunctions; /** NOTE: Although we could define the strings below as normal String variables, - here we are using PROGMEM combined with the FPSTR() macro (and also just the F() macro further down in the file). - The reason is that this approach will place the strings in flash memory which will help save RAM during program execution. - Reading strings from flash will be slower than reading them from RAM, - but this will be a negligible difference when printing them to Serial. + here we are using PROGMEM combined with the FPSTR() macro (and also just the F() macro further + down in the file). The reason is that this approach will place the strings in flash memory which + will help save RAM during program execution. Reading strings from flash will be slower than + reading them from RAM, but this will be a negligible difference when printing them to Serial. More on F(), FPSTR() and PROGMEM: 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. - -// 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 - }; - -unsigned int requestNumber = 0; +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 +}; + +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); -void networkFilter(int numberOfNetworks, MeshBackendBase &meshInstance); -bool broadcastFilter(String &firstTransmission, EspnowMeshBackend &meshInstance); +String manageRequest(const String& request, MeshBackendBase& meshInstance); +TransmissionStatusType manageResponse(const String& response, MeshBackendBase& meshInstance); +void networkFilter(int numberOfNetworks, MeshBackendBase& meshInstance); +bool broadcastFilter(String& firstTransmission, EspnowMeshBackend& meshInstance); /* Create the mesh node object */ -EspnowMeshBackend espnowNode = EspnowMeshBackend(manageRequest, manageResponse, networkFilter, broadcastFilter, FPSTR(exampleWiFiPassword), espnowEncryptedConnectionKey, espnowHashKey, FPSTR(exampleMeshName), TypeCast::uint64ToString(ESP.getChipId()), true); +EspnowMeshBackend espnowNode + = EspnowMeshBackend(manageRequest, manageResponse, networkFilter, broadcastFilter, + FPSTR(exampleWiFiPassword), espnowEncryptedConnectionKey, espnowHashKey, + FPSTR(exampleMeshName), TypeCast::uint64ToString(ESP.getChipId()), true); /** Callback for when other nodes send you a request @param request The request string received from another node in the mesh @param meshInstance The MeshBackendBase instance that called the function. - @return The string to send back to the other node. For ESP-NOW, return an empty string ("") if no response should be sent. + @return The string to send back to the other node. For ESP-NOW, return an empty string ("") if no + response should be sent. */ -String manageRequest(const String &request, MeshBackendBase &meshInstance) { - // To get the actual class of the polymorphic meshInstance, do as follows (meshBackendCast replaces dynamic_cast since RTTI is disabled) - if (EspnowMeshBackend *espnowInstance = TypeCast::meshBackendCast<EspnowMeshBackend *>(&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<TcpIpMeshBackend *>(&meshInstance)) { - (void)tcpIpInstance; // This is useful to remove a "unused parameter" compiler warning. Does nothing else. +String manageRequest(const String& request, MeshBackendBase& meshInstance) { + // To get the actual class of the polymorphic meshInstance, do as follows (meshBackendCast + // replaces dynamic_cast since RTTI is disabled) + if (EspnowMeshBackend* espnowInstance + = TypeCast::meshBackendCast<EspnowMeshBackend*>(&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<TcpIpMeshBackend*>(&meshInstance)) { + (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!: ")); } /* Print out received message */ - // Only show first 100 characters because printing a large String takes a lot of time, which is a bad thing for a callback function. - // If you need to print the whole String it is better to store it and print it in the loop() later. - // Note that request.substring will not work as expected if the String contains null values as data. + // Only show first 100 characters because printing a large String takes a lot of time, which is a + // bad thing for a callback function. If you need to print the whole String it is better to store + // it and print it in the loop() later. Note that request.substring will not work as expected if + // the String contains null values as data. Serial.print(F("Request received: ")); if (request.charAt(0) == 0) { @@ -80,7 +110,9 @@ String manageRequest(const String &request, MeshBackendBase &meshInstance) { } /* return a string to send back */ - return (String(F("Hello world response #")) + String(responseNumber++) + F(" from ") + meshInstance.getMeshName() + meshInstance.getNodeID() + F(" with AP MAC ") + WiFi.softAPmacAddress() + String('.')); + return (String(F("Hello world response #")) + String(responseNumber++) + F(" from ") + + meshInstance.getMeshName() + meshInstance.getNodeID() + F(" with AP MAC ") + + WiFi.softAPmacAddress() + String('.')); } /** @@ -90,20 +122,27 @@ String manageRequest(const String &request, MeshBackendBase &meshInstance) { @param meshInstance The MeshBackendBase instance that called the function. @return The status code resulting from the response, as an int */ -TransmissionStatusType manageResponse(const String &response, MeshBackendBase &meshInstance) { +TransmissionStatusType manageResponse(const String& response, MeshBackendBase& meshInstance) { TransmissionStatusType statusCode = TransmissionStatusType::TRANSMISSION_COMPLETE; - // To get the actual class of the polymorphic meshInstance, do as follows (meshBackendCast replaces dynamic_cast since RTTI is disabled) - if (EspnowMeshBackend *espnowInstance = TypeCast::meshBackendCast<EspnowMeshBackend *>(&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<TcpIpMeshBackend *>(&meshInstance)) { + // To get the actual class of the polymorphic meshInstance, do as follows (meshBackendCast + // replaces dynamic_cast since RTTI is disabled) + if (EspnowMeshBackend* espnowInstance + = TypeCast::meshBackendCast<EspnowMeshBackend*>(&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<TcpIpMeshBackend*>(&meshInstance)) { Serial.print(F("TCP/IP: ")); // Getting the sent message like this will work as long as ONLY(!) TCP/IP is used. - // With TCP/IP the response will follow immediately after the request, so the stored message will not have changed. - // With ESP-NOW there is no guarantee when or if a response will show up, it can happen before or after the stored message is changed. - // So for ESP-NOW, adding unique identifiers in the response and request is required to associate a response with a request. + // With TCP/IP the response will follow immediately after the request, so the stored message + // will not have changed. With ESP-NOW there is no guarantee when or if a response will show up, + // it can happen before or after the stored message is changed. So for ESP-NOW, adding unique + // identifiers in the response and request is required to associate a response with a request. Serial.print(F("Request sent: ")); Serial.println(tcpIpInstance->getCurrentMessage().substring(0, 100)); } else { @@ -111,9 +150,10 @@ TransmissionStatusType manageResponse(const String &response, MeshBackendBase &m } /* Print out received message */ - // Only show first 100 characters because printing a large String takes a lot of time, which is a bad thing for a callback function. - // If you need to print the whole String it is better to store it and print it in the loop() later. - // Note that response.substring will not work as expected if the String contains null values as data. + // Only show first 100 characters because printing a large String takes a lot of time, which is a + // bad thing for a callback function. If you need to print the whole String it is better to store + // it and print it in the loop() later. Note that response.substring will not work as expected if + // the String contains null values as data. Serial.print(F("Response received: ")); Serial.println(response.substring(0, 100)); @@ -126,20 +166,23 @@ TransmissionStatusType manageResponse(const String &response, MeshBackendBase &m @param numberOfNetworks The number of networks found in the WiFi scan. @param meshInstance The MeshBackendBase instance that called the function. */ -void networkFilter(int numberOfNetworks, MeshBackendBase &meshInstance) { +void networkFilter(int numberOfNetworks, MeshBackendBase& meshInstance) { // Note that the network index of a given node may change whenever a new scan is done. for (int networkIndex = 0; networkIndex < numberOfNetworks; ++networkIndex) { - String currentSSID = WiFi.SSID(networkIndex); - int meshNameIndex = currentSSID.indexOf(meshInstance.getMeshName()); + String currentSSID = WiFi.SSID(networkIndex); + int meshNameIndex = currentSSID.indexOf(meshInstance.getMeshName()); /* Connect to any _suitable_ APs which contain meshInstance.getMeshName() */ if (meshNameIndex >= 0) { - uint64_t targetNodeID = TypeCast::stringToUint64(currentSSID.substring(meshNameIndex + meshInstance.getMeshName().length())); + uint64_t targetNodeID = TypeCast::stringToUint64( + currentSSID.substring(meshNameIndex + meshInstance.getMeshName().length())); if (targetNodeID < TypeCast::stringToUint64(meshInstance.getNodeID())) { - if (EspnowMeshBackend *espnowInstance = TypeCast::meshBackendCast<EspnowMeshBackend *>(&meshInstance)) { + if (EspnowMeshBackend* espnowInstance + = TypeCast::meshBackendCast<EspnowMeshBackend*>(&meshInstance)) { espnowInstance->connectionQueue().emplace_back(networkIndex); - } else if (TcpIpMeshBackend *tcpIpInstance = TypeCast::meshBackendCast<TcpIpMeshBackend *>(&meshInstance)) { + } else if (TcpIpMeshBackend* tcpIpInstance + = TypeCast::meshBackendCast<TcpIpMeshBackend*>(&meshInstance)) { tcpIpInstance->connectionQueue().emplace_back(networkIndex); } else { Serial.println(F("Invalid mesh backend!")); @@ -150,20 +193,24 @@ void networkFilter(int numberOfNetworks, MeshBackendBase &meshInstance) { } /** - Callback used to decide which broadcast messages to accept. Only called for the first transmission in each broadcast. - If true is returned from this callback, the first broadcast transmission is saved until the entire broadcast message has been received. - The complete broadcast message will then be sent to the requestHandler (manageRequest in this example). - If false is returned from this callback, the broadcast message is discarded. - Note that the BroadcastFilter may be called multiple times for messages that are discarded in this way, but is only called once for accepted messages. - - @param firstTransmission The first transmission of the broadcast. Modifications to this String are passed on to the broadcast message. + Callback used to decide which broadcast messages to accept. Only called for the first + transmission in each broadcast. If true is returned from this callback, the first broadcast + transmission is saved until the entire broadcast message has been received. The complete + broadcast message will then be sent to the requestHandler (manageRequest in this example). If + false is returned from this callback, the broadcast message is discarded. Note that the + BroadcastFilter may be called multiple times for messages that are discarded in this way, but is + only called once for accepted messages. + + @param firstTransmission The first transmission of the broadcast. Modifications to this String + are passed on to the broadcast message. @param meshInstance The EspnowMeshBackend instance that called the function. @return True if the broadcast should be accepted. False otherwise. */ -bool broadcastFilter(String &firstTransmission, EspnowMeshBackend &meshInstance) { - // This example broadcastFilter will accept a transmission if it contains the broadcastMetadataDelimiter - // and as metaData either no targetMeshName or a targetMeshName that matches the MeshName of meshInstance. +bool broadcastFilter(String& firstTransmission, EspnowMeshBackend& meshInstance) { + // This example broadcastFilter will accept a transmission if it contains the + // broadcastMetadataDelimiter and as metaData either no targetMeshName or a targetMeshName that + // matches the MeshName of meshInstance. int32_t metadataEndIndex = firstTransmission.indexOf(broadcastMetadataDelimiter); @@ -174,11 +221,12 @@ 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. - // Otherwise your broadcasts cannot include null values in the message bytes. + // 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. Otherwise your + // broadcasts cannot include null values in the message bytes. firstTransmission.remove(0, metadataEndIndex + 1); return true; } @@ -186,19 +234,23 @@ bool broadcastFilter(String &firstTransmission, EspnowMeshBackend &meshInstance) /** Once passed to the setTransmissionOutcomesUpdateHook method of the ESP-NOW backend, - this function will be called after each update of the latestTransmissionOutcomes vector during attemptTransmission. - (which happens after each individual transmission has finished) + this function will be called after each update of the latestTransmissionOutcomes vector during + attemptTransmission. (which happens after each individual transmission has finished) - Example use cases is modifying getMessage() between transmissions, or aborting attemptTransmission before all nodes in the connectionQueue have been contacted. + Example use cases is modifying getMessage() between transmissions, or aborting + attemptTransmission before all nodes in the connectionQueue have been contacted. @param meshInstance The MeshBackendBase instance that called the function. - @return True if attemptTransmission should continue with the next entry in the connectionQueue. False if attemptTransmission should stop. + @return True if attemptTransmission should continue with the next entry in the connectionQueue. + False if attemptTransmission should stop. */ -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. +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; } @@ -206,8 +258,9 @@ bool exampleTransmissionOutcomesUpdateHook(MeshBackendBase &meshInstance) { /** Once passed to the setResponseTransmittedHook method of the ESP-NOW backend, this function will be called after each attempted ESP-NOW response transmission. - In case of a successful response transmission, this happens just before the response is removed from the waiting list. - Only the hook of the EspnowMeshBackend instance that is getEspnowRequestManager() will be called. + In case of a successful response transmission, this happens just before the response is removed + from the waiting list. Only the hook of the EspnowMeshBackend instance that is + getEspnowRequestManager() will be called. @param transmissionSuccessful True if the response was transmitted successfully. False otherwise. @param response The sent response. @@ -215,13 +268,18 @@ bool exampleTransmissionOutcomesUpdateHook(MeshBackendBase &meshInstance) { @param responseIndex The index of the response in the waiting list. @param meshInstance The EspnowMeshBackend instance that called the function. - @return True if the response transmission process should continue with the next response in the waiting list. - False if the response transmission process should stop once processing of the just sent response is complete. + @return True if the response transmission process should continue with the next response in the + waiting list. False if the response transmission process should stop once processing of the just + sent response is complete. */ -bool exampleResponseTransmittedHook(bool transmissionSuccessful, const String &response, const uint8_t *recipientMac, uint32_t responseIndex, EspnowMeshBackend &meshInstance) { - // 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. +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)response; (void)recipientMac; (void)responseIndex; @@ -231,8 +289,10 @@ bool exampleResponseTransmittedHook(bool transmissionSuccessful, const String &r } void setup() { - // Prevents the flash memory from being worn out, see: https://github.com/esp8266/Arduino/issues/1054 . - // This will however delay node WiFi start-up by about 700 ms. The delay is 900 ms if we otherwise would have stored the WiFi network we want to connect to. + // Prevents the flash memory from being worn out, see: + // https://github.com/esp8266/Arduino/issues/1054 . This will however delay node WiFi start-up by + // about 700 ms. The delay is 900 ms if we otherwise would have stored the WiFi network we want to + // connect to. WiFi.persistent(false); Serial.begin(115200); @@ -240,10 +300,12 @@ void setup() { Serial.println(); Serial.println(); - Serial.println(F("Note that this library can use static IP:s for the nodes with the TCP/IP backend to speed up connection times.\n" - "Use the setStaticIP method to enable this.\n" - "Ensure that nodes connecting to the same AP have distinct static IP:s.\n" - "Also, remember to change the default mesh network password and ESP-NOW keys!\n\n")); + Serial.println( + F("Note that this library can use static IP:s for the nodes with the TCP/IP backend to speed " + "up connection times.\n" + "Use the setStaticIP method to enable this.\n" + "Ensure that nodes connecting to the same AP have distinct static IP:s.\n" + "Also, remember to change the default mesh network password and ESP-NOW keys!\n\n")); Serial.println(F("Setting up mesh node...")); @@ -252,61 +314,81 @@ void setup() { // Note: This changes the Kok for all EspnowMeshBackend instances on this ESP8266. // Encrypted connections added before the Kok change will retain their old Kok. - // Both Kok and encrypted connection key must match in an encrypted connection pair for encrypted communication to be possible. - // Otherwise the transmissions will never reach the recipient, even though acks are received by the sender. + // Both Kok and encrypted connection key must match in an encrypted connection pair for encrypted + // communication to be possible. Otherwise the transmissions will never reach the recipient, even + // though acks are received by the sender. EspnowMeshBackend::setEspnowEncryptionKok(espnowEncryptionKok); espnowNode.setEspnowEncryptedConnectionKey(espnowEncryptedConnectionKey); - // Makes it possible to find the node through scans, makes it possible to recover from an encrypted connection where only the other node is encrypted, and also makes it possible to receive broadcast transmissions. - // Note that only one AP can be active at a time in total, and this will always be the one which was last activated. - // Thus the AP is shared by all backends. + // Makes it possible to find the node through scans, makes it possible to recover from an + // encrypted connection where only the other node is encrypted, and also makes it possible to + // receive broadcast transmissions. Note that only one AP can be active at a time in total, and + // this will always be the one which was last activated. Thus the AP is shared by all backends. espnowNode.activateAP(); - // Storing our message in the EspnowMeshBackend instance is not required, but can be useful for organizing code, especially when using many EspnowMeshBackend instances. - // Note that calling the multi-recipient versions of espnowNode.attemptTransmission and espnowNode.attemptAutoEncryptingTransmission will replace the stored message with whatever message is transmitted. - // Also note that the maximum allowed number of ASCII characters in a ESP-NOW message is given by EspnowMeshBackend::getMaxMessageLength(). - espnowNode.setMessage(String(F("Hello world request #")) + String(requestNumber) + F(" from ") + espnowNode.getMeshName() + espnowNode.getNodeID() + String('.')); + // Storing our message in the EspnowMeshBackend instance is not required, but can be useful for + // organizing code, especially when using many EspnowMeshBackend instances. Note that calling the + // multi-recipient versions of espnowNode.attemptTransmission and + // espnowNode.attemptAutoEncryptingTransmission will replace the stored message with whatever + // message is transmitted. Also note that the maximum allowed number of ASCII characters in a + // ESP-NOW message is given by EspnowMeshBackend::getMaxMessageLength(). + espnowNode.setMessage(String(F("Hello world request #")) + String(requestNumber) + F(" from ") + + espnowNode.getMeshName() + espnowNode.getNodeID() + String('.')); espnowNode.setTransmissionOutcomesUpdateHook(exampleTransmissionOutcomesUpdateHook); espnowNode.setResponseTransmittedHook(exampleResponseTransmittedHook); - // In addition to using encrypted ESP-NOW connections the framework can also send automatically encrypted messages (AEAD) over both encrypted and unencrypted connections. - // Using AEAD will only encrypt the message content, not the transmission metadata. - // The AEAD encryption does not require any pairing, and is thus faster for single messages than establishing a new encrypted connection before transfer. - // AEAD encryption also works with ESP-NOW broadcasts and supports an unlimited number of nodes, which is not true for encrypted connections. - // Encrypted ESP-NOW connections do however come with built in replay attack protection, which is not provided by the framework when using AEAD encryption, - // and allow EspnowProtocolInterpreter::aeadMetadataSize extra message bytes per transmission. - // Transmissions via encrypted connections are also slightly faster than via AEAD once a connection has been established. + // In addition to using encrypted ESP-NOW connections the framework can also send automatically + // encrypted messages (AEAD) over both encrypted and unencrypted connections. Using AEAD will only + // encrypt the message content, not the transmission metadata. The AEAD encryption does not + // require any pairing, and is thus faster for single messages than establishing a new encrypted + // connection before transfer. AEAD encryption also works with ESP-NOW broadcasts and supports an + // unlimited number of nodes, which is not true for encrypted connections. Encrypted ESP-NOW + // connections do however come with built in replay attack protection, which is not provided by + // the framework when using AEAD encryption, and allow EspnowProtocolInterpreter::aeadMetadataSize + // extra message bytes per transmission. Transmissions via encrypted connections are also slightly + // faster than via AEAD once a connection has been established. // - // 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); + // 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); } int32_t timeOfLastScan = -10000; -void loop() { - // The performEspnowMaintenance() method performs all the background operations for the EspnowMeshBackend. - // It is recommended to place it in the beginning of the loop(), unless there is a need to put it elsewhere. - // Among other things, the method cleans up old Espnow log entries (freeing up RAM) and sends the responses you provide to Espnow requests. - // 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. +void loop() { + // The performEspnowMaintenance() method performs all the background operations for the + // EspnowMeshBackend. It is recommended to place it in the beginning of the loop(), unless there + // is a need to put it elsewhere. Among other things, the method cleans up old Espnow log entries + // (freeing up RAM) and sends the responses you provide to Espnow requests. 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. 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(); espnowNode.attemptTransmission(espnowNode.getMessage()); - Serial.println(String(F("Scan and ")) + String(espnowNode.latestTransmissionOutcomes().size()) + F(" transmissions done in ") + String(millis() - startTime) + F(" ms.")); + Serial.println(String(F("Scan and ")) + String(espnowNode.latestTransmissionOutcomes().size()) + + F(" transmissions done in ") + String(millis() - startTime) + F(" ms.")); timeOfLastScan = millis(); - // Wait for response. espnowDelay continuously calls performEspnowMaintenance() so we will respond to ESP-NOW request while waiting. - // Should not be used inside responseHandler, requestHandler, networkFilter or broadcastFilter callbacks since performEspnowMaintenance() can alter the ESP-NOW state. + // Wait for response. espnowDelay continuously calls performEspnowMaintenance() so we will + // respond to ESP-NOW request while waiting. Should not be used inside responseHandler, + // requestHandler, networkFilter or broadcastFilter callbacks since performEspnowMaintenance() + // can alter the ESP-NOW state. espnowDelay(100); // One way to check how attemptTransmission worked out @@ -318,15 +400,19 @@ void loop() { if (espnowNode.latestTransmissionOutcomes().empty()) { Serial.println(F("No mesh AP found.")); } else { - for (TransmissionOutcome &transmissionOutcome : espnowNode.latestTransmissionOutcomes()) { - if (transmissionOutcome.transmissionStatus() == TransmissionStatusType::TRANSMISSION_FAILED) { + for (TransmissionOutcome& transmissionOutcome : espnowNode.latestTransmissionOutcomes()) { + if (transmissionOutcome.transmissionStatus() + == TransmissionStatusType::TRANSMISSION_FAILED) { Serial.println(String(F("Transmission failed to mesh AP ")) + transmissionOutcome.SSID()); - } else if (transmissionOutcome.transmissionStatus() == TransmissionStatusType::CONNECTION_FAILED) { + } else if (transmissionOutcome.transmissionStatus() + == TransmissionStatusType::CONNECTION_FAILED) { Serial.println(String(F("Connection failed to mesh AP ")) + transmissionOutcome.SSID()); - } else if (transmissionOutcome.transmissionStatus() == TransmissionStatusType::TRANSMISSION_COMPLETE) { + } else if (transmissionOutcome.transmissionStatus() + == TransmissionStatusType::TRANSMISSION_COMPLETE) { // No need to do anything, transmission was successful. } else { - Serial.println(String(F("Invalid transmission status for ")) + transmissionOutcome.SSID() + String('!')); + Serial.println(String(F("Invalid transmission status for ")) + transmissionOutcome.SSID() + + String('!')); assert(F("Invalid transmission status returned from responseHandler!") && false); } } @@ -335,118 +421,153 @@ void loop() { startTime = millis(); - // Remove espnowNode.getMeshName() from the broadcastMetadata below to broadcast to all ESP-NOW nodes regardless of MeshName. - // Note that data that comes before broadcastMetadataDelimiter should not contain any broadcastMetadataDelimiter characters, + // Remove espnowNode.getMeshName() from the broadcastMetadata below to broadcast to all + // ESP-NOW nodes regardless of MeshName. Note that data that comes before + // broadcastMetadataDelimiter should not contain any broadcastMetadataDelimiter characters, // otherwise the broadcastFilter function used in this example file will not work. String broadcastMetadata = espnowNode.getMeshName() + String(broadcastMetadataDelimiter); - String broadcastMessage = String(F("Broadcast #")) + String(requestNumber) + F(" from ") + espnowNode.getMeshName() + espnowNode.getNodeID() + String('.'); + String broadcastMessage = String(F("Broadcast #")) + String(requestNumber) + F(" from ") + + espnowNode.getMeshName() + espnowNode.getNodeID() + String('.'); 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). - - // 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'}; - String espnowMessage = TypeCast::uint8ArrayToMultiString(dataArray, sizeof dataArray) + F(" from ") + espnowNode.getMeshName() + espnowNode.getNodeID() + String('.'); + 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). + + // 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' }; + 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) { - // The WiFi scan will detect the AP MAC, but this will automatically be converted to the encrypted STA MAC by the framework. + // 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) { + // The WiFi scan will detect the AP MAC, but this will automatically be converted to the + // encrypted STA MAC by the framework. String peerMac = TypeCast::macToString(targetBSSID); - Serial.println(String(F("Encrypted ESP-NOW connection with ")) + peerMac + F(" established!")); + Serial.println(String(F("Encrypted ESP-NOW connection with ")) + peerMac + + F(" established!")); // Making a transmission now will cause messages to targetBSSID to be encrypted. - String espnowMessage = String(F("This message is encrypted only when received by node ")) + peerMac; + 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. - String serializedEncryptedConnection = EspnowMeshBackend::serializeEncryptedConnection(targetBSSID); + // Note that this saves the current state only, so if encrypted communication between the + // nodes happen after this, the stored state is invalid. + String serializedEncryptedConnection + = EspnowMeshBackend::serializeEncryptedConnection(targetBSSID); Serial.println(); // We can remove an encrypted connection like so. espnowNode.removeEncryptedConnection(targetBSSID); - // Note that the peer will still be encrypted, so although we can send unencrypted messages to the peer, we cannot read the encrypted responses it sends back. - espnowMessage = String(F("This message is no longer encrypted when received by node ")) + peerMac; + // Note that the peer will still be encrypted, so although we can send unencrypted messages + // to the peer, we cannot read the encrypted responses it sends back. + 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! espnowNode.addEncryptedConnection(serializedEncryptedConnection); - espnowMessage = String(F("This message is once again encrypted when received by node ")) + peerMac; + 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. - EncryptedConnectionRemovalOutcome removalOutcome = espnowNode.requestEncryptedConnectionRemoval(targetBSSID); + EncryptedConnectionRemovalOutcome removalOutcome + = espnowNode.requestEncryptedConnectionRemoval(targetBSSID); if (removalOutcome == EncryptedConnectionRemovalOutcome::REMOVAL_SUCCEEDED) { Serial.println(peerMac + F(" is no longer encrypted!")); - 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."); + 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(); - // Of course, we can also just create a temporary encrypted connection that will remove itself once its duration has passed. - if (espnowNode.requestTemporaryEncryptedConnection(targetBSSID, 1000) == EncryptedConnectionStatus::CONNECTION_ESTABLISHED) { + // Of course, we can also just create a temporary encrypted connection that will remove + // itself once its duration has passed. + if (espnowNode.requestTemporaryEncryptedConnection(targetBSSID, 1000) + == EncryptedConnectionStatus::CONNECTION_ESTABLISHED) { espnowDelay(42); uint32_t remainingDuration = 0; EspnowMeshBackend::getConnectionInfo(targetBSSID, &remainingDuration); - espnowMessage = String(F("Messages this node sends to ")) + peerMac + F(" will be encrypted for ") + String(remainingDuration) + F(" ms more."); + espnowMessage = String(F("Messages this node sends to ")) + peerMac + + F(" will be encrypted for ") + String(remainingDuration) + + F(" ms more."); Serial.println(String(F("\nTransmitting: ")) + espnowMessage); espnowNode.attemptTransmission(espnowMessage, false); EspnowMeshBackend::getConnectionInfo(targetBSSID, &remainingDuration); espnowDelay(remainingDuration + 100); - espnowMessage = String(F("Due to encrypted connection expiration, this message is no longer encrypted when received by node ")) + peerMac; + 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. - // Note that encrypted responses will not be received, unless there already was an encrypted connection established with the peer before attemptAutoEncryptingTransmission was called. - // This can be remedied via the requestPermanentConnections argument, though it must be noted that the maximum number of encrypted connections supported at a time is 6. + // Or if we prefer we can just let the library automatically create brief encrypted + // connections which are long enough to transmit an encrypted message. Note that encrypted + // responses will not be received, unless there already was an encrypted connection + // established with the peer before attemptAutoEncryptingTransmission was called. This can + // be remedied via the requestPermanentConnections argument, though it must be noted that + // the maximum number of encrypted connections supported at a time is 6. 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<int>(removalOutcome))); + Serial.println(String(F("Ooops! Encrypted connection removal failed. Status: ")) + + String(static_cast<int>(removalOutcome))); } - // Finally, should you ever want to stop other parties from sending unencrypted messages to the node - // setAcceptsUnencryptedRequests(false); - // can be used for this. It applies to both encrypted connection requests and regular transmissions. + // Finally, should you ever want to stop other parties from sending unencrypted messages to + // the node setAcceptsUnencryptedRequests(false); can be used for this. It applies to both + // encrypted connection requests and regular transmissions. - Serial.println(F("\n##############################################################################################")); + Serial.println(F("\n#######################################################################" + "#######################")); } // 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..78bab243b2 100644 --- a/libraries/ESP8266WiFiMesh/examples/HelloMesh/HelloMesh.ino +++ b/libraries/ESP8266WiFiMesh/examples/HelloMesh/HelloMesh.ino @@ -1,14 +1,21 @@ /** - This example makes every node broadcast their AP MAC to the rest of the network during the first 28 seconds, as long as the node thinks it has the highest AP MAC in the network. - Once 28 seconds have passed, the node that has the highest AP MAC will start broadcasting benchmark messages, which will allow you to see how many messages are lost at the other nodes. - If you have an onboard LED on your ESP8266 it is recommended that you change the useLED variable below to true. - That way you will get instant confirmation of the mesh communication without checking the Serial Monitor. - - If you want to experiment with reducing error rates you can use the mesh method "void setBroadcastReceptionRedundancy(uint8_t redundancy);" (default 2) at the cost of more RAM. - Or "floodingMesh.getEspnowMeshBackend().setBroadcastTransmissionRedundancy(uint8_t redundancy)" (default 1) at the cost of longer transmission times. + This example makes every node broadcast their AP MAC to the rest of the network during the first + 28 seconds, as long as the node thinks it has the highest AP MAC in the network. Once 28 seconds + have passed, the node that has the highest AP MAC will start broadcasting benchmark messages, + which will allow you to see how many messages are lost at the other nodes. If you have an onboard + LED on your ESP8266 it is recommended that you change the useLED variable below to true. That way + you will get instant confirmation of the mesh communication without checking the Serial Monitor. + + If you want to experiment with reducing error rates you can use the mesh method "void + setBroadcastReceptionRedundancy(uint8_t redundancy);" (default 2) at the cost of more RAM. 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 <ESP8266WiFi.h> #include <TypeConversionFunctions.h> @@ -19,66 +26,81 @@ namespace TypeCast = MeshTypeConversionFunctions; /** NOTE: Although we could define the strings below as normal String variables, - here we are using PROGMEM combined with the FPSTR() macro (and also just the F() macro further down in the file). - The reason is that this approach will place the strings in flash memory which will help save RAM during program execution. - Reading strings from flash will be slower than reading them from RAM, - but this will be a negligible difference when printing them to Serial. + here we are using PROGMEM combined with the FPSTR() macro (and also just the F() macro further + down in the file). The reason is that this approach will place the strings in flash memory which + will help save RAM during program execution. Reading strings from flash will be slower than + reading them from RAM, but this will be a negligible difference when printing them to Serial. More on F(), FPSTR() and PROGMEM: 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. - -// 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 - }; - -bool meshMessageHandler(String &message, FloodingMesh &meshInstance); +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 +}; + +bool meshMessageHandler(String& message, FloodingMesh& meshInstance); /* Create the mesh node object */ -FloodingMesh floodingMesh = FloodingMesh(meshMessageHandler, FPSTR(exampleWiFiPassword), espnowEncryptedConnectionKey, espnowHashKey, FPSTR(exampleMeshName), TypeCast::uint64ToString(ESP.getChipId()), true); +FloodingMesh floodingMesh = FloodingMesh( + meshMessageHandler, FPSTR(exampleWiFiPassword), espnowEncryptedConnectionKey, espnowHashKey, + FPSTR(exampleMeshName), TypeCast::uint64ToString(ESP.getChipId()), true); -bool theOne = true; +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. @param message The message String received from the mesh. - Modifications to this String are passed on when the message is forwarded from this node to other nodes. - However, the forwarded message will still use the same messageID. - Thus it will not be sent to nodes that have already received this messageID. - If you want to send a new message to the whole network, use a new broadcast from within the loop() instead. + Modifications to this String are passed on when the message is forwarded from this + node to other nodes. However, the forwarded message will still use the same messageID. Thus it + will not be sent to nodes that have already received this messageID. If you want to send a new + message to the whole network, use a new broadcast from within the loop() instead. @param meshInstance The FloodingMesh instance that received the message. @return True if this node should forward the received message to other nodes. False otherwise. */ -bool meshMessageHandler(String &message, FloodingMesh &meshInstance) { +bool meshMessageHandler(String& message, FloodingMesh& meshInstance) { int32_t delimiterIndex = message.indexOf(meshInstance.metadataDelimiter()); if (delimiterIndex == 0) { - Serial.print(String(F("Message received from STA MAC ")) + meshInstance.getEspnowMeshBackend().getSenderMac() + F(": ")); + Serial.print(String(F("Message received from STA MAC ")) + + meshInstance.getEspnowMeshBackend().getSenderMac() + F(": ")); Serial.println(message.substring(2, 102)); String potentialMac = message.substring(2, 14); if (potentialMac >= theOneMac) { if (potentialMac > theOneMac) { - theOne = false; + theOne = false; theOneMac = potentialMac; } 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,22 +109,27 @@ 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)); + Serial.println(String(F("missed/total: ")) + String(missedBroadcasts) + '/' + + String(totalReceivedBroadcasts)); } if (totalReceivedBroadcasts % 500 == 0) { Serial.println(String(F("Benchmark message: ")) + message.substring(0, 100)); @@ -110,9 +137,11 @@ bool meshMessageHandler(String &message, FloodingMesh &meshInstance) { } } } else { - // Only show first 100 characters because printing a large String takes a lot of time, which is a bad thing for a callback function. - // If you need to print the whole String it is better to store it and print it in the loop() later. - Serial.print(String(F("Message with origin ")) + meshInstance.getOriginMac() + F(" received: ")); + // Only show first 100 characters because printing a large String takes a lot of time, which is + // a bad thing for a callback function. If you need to print the whole String it is better to + // store it and print it in the loop() later. + Serial.print(String(F("Message with origin ")) + meshInstance.getOriginMac() + + F(" received: ")); Serial.println(message.substring(0, 100)); } @@ -120,8 +149,10 @@ bool meshMessageHandler(String &message, FloodingMesh &meshInstance) { } void setup() { - // Prevents the flash memory from being worn out, see: https://github.com/esp8266/Arduino/issues/1054 . - // This will however delay node WiFi start-up by about 700 ms. The delay is 900 ms if we otherwise would have stored the WiFi network we want to connect to. + // Prevents the flash memory from being worn out, see: + // https://github.com/esp8266/Arduino/issues/1054 . This will however delay node WiFi start-up by + // about 700 ms. The delay is 900 ms if we otherwise would have stored the WiFi network we want to + // connect to. WiFi.persistent(false); Serial.begin(115200); @@ -129,68 +160,87 @@ void setup() { Serial.println(); Serial.println(); - Serial.println(F("If you have an onboard LED on your ESP8266 it is recommended that you change the useLED variable to true.\n" - "That way you will get instant confirmation of the mesh communication.\n" - "Also, remember to change the default mesh network password and ESP-NOW keys!\n")); + Serial.println( + F("If you have an onboard LED on your ESP8266 it is recommended that you change the useLED " + "variable to true.\n" + "That way you will get instant confirmation of the mesh communication.\n" + "Also, remember to change the default mesh network password and ESP-NOW keys!\n")); 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); - - floodingMeshDelay(5000); // Give some time for user to start the nodes + // 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); + + floodingMeshDelay(5000); // Give some time for user to start the nodes } int32_t timeOfLastProclamation = -10000; -void loop() { - static bool ledState = 1; +void loop() { + static bool ledState = 1; static uint32_t benchmarkCount = 0; - static uint32_t loopStart = millis(); - - // The floodingMeshDelay() method performs all the background operations for the FloodingMesh (via FloodingMesh::performMeshMaintenance()). - // It is recommended to place one of these methods in the beginning of the loop(), unless there is a need to put them elsewhere. - // Among other things, the method cleans up old ESP-NOW log entries (freeing up RAM) and forwards received mesh messages. - // Note that depending on the amount of messages to forward and their length, this method can take tens or even hundreds of milliseconds to complete. - // More intense transmission activity and less frequent calls to performMeshMaintenance will likely cause the method to take longer to complete, so plan accordingly. - // The maintenance methods should not be used inside the meshMessageHandler callback, since they can alter the mesh node state. The framework will alert you during runtime if you make this mistake. + static uint32_t loopStart = millis(); + + // The floodingMeshDelay() method performs all the background operations for the FloodingMesh (via + // FloodingMesh::performMeshMaintenance()). It is recommended to place one of these methods in the + // beginning of the loop(), unless there is a need to put them elsewhere. Among other things, the + // method cleans up old ESP-NOW log entries (freeing up RAM) and forwards received mesh messages. + // Note that depending on the amount of messages to forward and their length, this method can take + // tens or even hundreds of milliseconds to complete. More intense transmission activity and less + // frequent calls to performMeshMaintenance will likely cause the method to take longer to + // complete, so plan accordingly. The maintenance methods should not be used inside the + // meshMessageHandler callback, since they can alter the mesh node state. The framework will alert + // you during runtime if you make this mistake. floodingMeshDelay(1); - // If you wish to transmit only to a single node, try using one of the following methods (requires the node to be within range and know the MAC of the recipient): - // Unencrypted: TransmissionStatusType floodingMesh.getEspnowMeshBackend().attemptTransmission(message, EspnowNetworkInfo(recipientMac)); - // Encrypted (slow): floodingMesh.getEspnowMeshBackend().attemptAutoEncryptingTransmission(message, EspnowNetworkInfo(recipientMac)); + // If you wish to transmit only to a single node, try using one of the following methods (requires + // the node to be within range and know the MAC of the recipient): Unencrypted: + // TransmissionStatusType floodingMesh.getEspnowMeshBackend().attemptTransmission(message, + // EspnowNetworkInfo(recipientMac)); Encrypted (slow): + // floodingMesh.getEspnowMeshBackend().attemptAutoEncryptingTransmission(message, + // EspnowNetworkInfo(recipientMac)); 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.")); - Serial.println(String(F("Proclamation broadcast done in ")) + String(millis() - startTime) + F(" ms.")); + // 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.")); + Serial.println(String(F("Proclamation broadcast done in ")) + String(millis() - startTime) + + F(" ms.")); timeOfLastProclamation = millis(); 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.")); + 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.")); floodingMeshDelay(20); } } diff --git a/libraries/ESP8266WiFiMesh/examples/HelloTcpIp/HelloTcpIp.ino b/libraries/ESP8266WiFiMesh/examples/HelloTcpIp/HelloTcpIp.ino index f68b81f181..2ca5514341 100644 --- a/libraries/ESP8266WiFiMesh/examples/HelloTcpIp/HelloTcpIp.ino +++ b/libraries/ESP8266WiFiMesh/examples/HelloTcpIp/HelloTcpIp.ino @@ -1,4 +1,7 @@ -#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 <ESP8266WiFi.h> #include <TcpIpMeshBackend.h> @@ -10,56 +13,72 @@ namespace TypeCast = MeshTypeConversionFunctions; /** NOTE: Although we could define the strings below as normal String variables, - here we are using PROGMEM combined with the FPSTR() macro (and also just the F() macro further down in the file). - The reason is that this approach will place the strings in flash memory which will help save RAM during program execution. - Reading strings from flash will be slower than reading them from RAM, - but this will be a negligible difference when printing them to Serial. + here we are using PROGMEM combined with the FPSTR() macro (and also just the F() macro further + down in the file). The reason is that this approach will place the strings in flash memory which + will help save RAM during program execution. Reading strings from flash will be slower than + reading them from RAM, but this will be a negligible difference when printing them to Serial. More on F(), FPSTR() and PROGMEM: https://github.com/esp8266/Arduino/issues/1143 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 requestNumber = 0; unsigned int responseNumber = 0; -String manageRequest(const String &request, MeshBackendBase &meshInstance); -TransmissionStatusType manageResponse(const String &response, MeshBackendBase &meshInstance); -void networkFilter(int numberOfNetworks, MeshBackendBase &meshInstance); +String manageRequest(const String& request, MeshBackendBase& meshInstance); +TransmissionStatusType manageResponse(const String& response, MeshBackendBase& meshInstance); +void networkFilter(int numberOfNetworks, MeshBackendBase& meshInstance); /* Create the mesh node object */ -TcpIpMeshBackend tcpIpNode = TcpIpMeshBackend(manageRequest, manageResponse, networkFilter, FPSTR(exampleWiFiPassword), FPSTR(exampleMeshName), TypeCast::uint64ToString(ESP.getChipId()), true); +TcpIpMeshBackend tcpIpNode + = TcpIpMeshBackend(manageRequest, manageResponse, networkFilter, FPSTR(exampleWiFiPassword), + FPSTR(exampleMeshName), TypeCast::uint64ToString(ESP.getChipId()), true); /** Callback for when other nodes send you a request @param request The request string received from another node in the mesh @param meshInstance The MeshBackendBase instance that called the function. - @return The string to send back to the other node. For ESP-NOW, return an empty string ("") if no response should be sent. + @return The string to send back to the other node. For ESP-NOW, return an empty string ("") if no + response should be sent. */ -String manageRequest(const String &request, MeshBackendBase &meshInstance) { - // To get the actual class of the polymorphic meshInstance, do as follows (meshBackendCast replaces dynamic_cast since RTTI is disabled) - if (EspnowMeshBackend *espnowInstance = TypeCast::meshBackendCast<EspnowMeshBackend *>(&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<TcpIpMeshBackend *>(&meshInstance)) { - (void)tcpIpInstance; // This is useful to remove a "unused parameter" compiler warning. Does nothing else. +String manageRequest(const String& request, MeshBackendBase& meshInstance) { + // To get the actual class of the polymorphic meshInstance, do as follows (meshBackendCast + // replaces dynamic_cast since RTTI is disabled) + if (EspnowMeshBackend* espnowInstance + = TypeCast::meshBackendCast<EspnowMeshBackend*>(&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<TcpIpMeshBackend*>(&meshInstance)) { + (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!: ")); } /* Print out received message */ - // Only show first 100 characters because printing a large String takes a lot of time, which is a bad thing for a callback function. - // If you need to print the whole String it is better to store it and print it in the loop() later. - // Note that request.substring will not work as expected if the String contains null values as data. + // Only show first 100 characters because printing a large String takes a lot of time, which is a + // bad thing for a callback function. If you need to print the whole String it is better to store + // it and print it in the loop() later. Note that request.substring will not work as expected if + // the String contains null values as data. Serial.print(F("Request received: ")); Serial.println(request.substring(0, 100)); /* return a string to send back */ - return (String(F("Hello world response #")) + String(responseNumber++) + F(" from ") + meshInstance.getMeshName() + meshInstance.getNodeID() + F(" with AP MAC ") + WiFi.softAPmacAddress() + String('.')); + return (String(F("Hello world response #")) + String(responseNumber++) + F(" from ") + + meshInstance.getMeshName() + meshInstance.getNodeID() + F(" with AP MAC ") + + WiFi.softAPmacAddress() + String('.')); } /** @@ -69,20 +88,27 @@ String manageRequest(const String &request, MeshBackendBase &meshInstance) { @param meshInstance The MeshBackendBase instance that called the function. @return The status code resulting from the response, as an int */ -TransmissionStatusType manageResponse(const String &response, MeshBackendBase &meshInstance) { +TransmissionStatusType manageResponse(const String& response, MeshBackendBase& meshInstance) { TransmissionStatusType statusCode = TransmissionStatusType::TRANSMISSION_COMPLETE; - // To get the actual class of the polymorphic meshInstance, do as follows (meshBackendCast replaces dynamic_cast since RTTI is disabled) - if (EspnowMeshBackend *espnowInstance = TypeCast::meshBackendCast<EspnowMeshBackend *>(&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<TcpIpMeshBackend *>(&meshInstance)) { + // To get the actual class of the polymorphic meshInstance, do as follows (meshBackendCast + // replaces dynamic_cast since RTTI is disabled) + if (EspnowMeshBackend* espnowInstance + = TypeCast::meshBackendCast<EspnowMeshBackend*>(&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<TcpIpMeshBackend*>(&meshInstance)) { Serial.print(F("TCP/IP: ")); // Getting the sent message like this will work as long as ONLY(!) TCP/IP is used. - // With TCP/IP the response will follow immediately after the request, so the stored message will not have changed. - // With ESP-NOW there is no guarantee when or if a response will show up, it can happen before or after the stored message is changed. - // So for ESP-NOW, adding unique identifiers in the response and request is required to associate a response with a request. + // With TCP/IP the response will follow immediately after the request, so the stored message + // will not have changed. With ESP-NOW there is no guarantee when or if a response will show up, + // it can happen before or after the stored message is changed. So for ESP-NOW, adding unique + // identifiers in the response and request is required to associate a response with a request. Serial.print(F("Request sent: ")); Serial.println(tcpIpInstance->getCurrentMessage().substring(0, 100)); } else { @@ -90,9 +116,10 @@ TransmissionStatusType manageResponse(const String &response, MeshBackendBase &m } /* Print out received message */ - // Only show first 100 characters because printing a large String takes a lot of time, which is a bad thing for a callback function. - // If you need to print the whole String it is better to store it and print it in the loop() later. - // Note that response.substring will not work as expected if the String contains null values as data. + // Only show first 100 characters because printing a large String takes a lot of time, which is a + // bad thing for a callback function. If you need to print the whole String it is better to store + // it and print it in the loop() later. Note that response.substring will not work as expected if + // the String contains null values as data. Serial.print(F("Response received: ")); Serial.println(response.substring(0, 100)); @@ -105,20 +132,23 @@ TransmissionStatusType manageResponse(const String &response, MeshBackendBase &m @param numberOfNetworks The number of networks found in the WiFi scan. @param meshInstance The MeshBackendBase instance that called the function. */ -void networkFilter(int numberOfNetworks, MeshBackendBase &meshInstance) { +void networkFilter(int numberOfNetworks, MeshBackendBase& meshInstance) { // Note that the network index of a given node may change whenever a new scan is done. for (int networkIndex = 0; networkIndex < numberOfNetworks; ++networkIndex) { - String currentSSID = WiFi.SSID(networkIndex); - int meshNameIndex = currentSSID.indexOf(meshInstance.getMeshName()); + String currentSSID = WiFi.SSID(networkIndex); + int meshNameIndex = currentSSID.indexOf(meshInstance.getMeshName()); /* Connect to any _suitable_ APs which contain meshInstance.getMeshName() */ if (meshNameIndex >= 0) { - uint64_t targetNodeID = TypeCast::stringToUint64(currentSSID.substring(meshNameIndex + meshInstance.getMeshName().length())); + uint64_t targetNodeID = TypeCast::stringToUint64( + currentSSID.substring(meshNameIndex + meshInstance.getMeshName().length())); if (targetNodeID < TypeCast::stringToUint64(meshInstance.getNodeID())) { - if (EspnowMeshBackend *espnowInstance = TypeCast::meshBackendCast<EspnowMeshBackend *>(&meshInstance)) { + if (EspnowMeshBackend* espnowInstance + = TypeCast::meshBackendCast<EspnowMeshBackend*>(&meshInstance)) { espnowInstance->connectionQueue().emplace_back(networkIndex); - } else if (TcpIpMeshBackend *tcpIpInstance = TypeCast::meshBackendCast<TcpIpMeshBackend *>(&meshInstance)) { + } else if (TcpIpMeshBackend* tcpIpInstance + = TypeCast::meshBackendCast<TcpIpMeshBackend*>(&meshInstance)) { tcpIpInstance->connectionQueue().emplace_back(networkIndex); } else { Serial.println(F("Invalid mesh backend!")); @@ -130,23 +160,28 @@ void networkFilter(int numberOfNetworks, MeshBackendBase &meshInstance) { /** Once passed to the setTransmissionOutcomesUpdateHook method of the TCP/IP backend, - this function will be called after each update of the latestTransmissionOutcomes vector during attemptTransmission. - (which happens after each individual transmission has finished) + this function will be called after each update of the latestTransmissionOutcomes vector during + attemptTransmission. (which happens after each individual transmission has finished) - Example use cases is modifying getMessage() between transmissions, or aborting attemptTransmission before all nodes in the connectionQueue have been contacted. + Example use cases is modifying getMessage() between transmissions, or aborting + attemptTransmission before all nodes in the connectionQueue have been contacted. @param meshInstance The MeshBackendBase instance that called the function. - @return True if attemptTransmission should continue with the next entry in the connectionQueue. False if attemptTransmission should stop. + @return True if attemptTransmission should continue with the next entry in the connectionQueue. + False if attemptTransmission should stop. */ -bool exampleTransmissionOutcomesUpdateHook(MeshBackendBase &meshInstance) { +bool exampleTransmissionOutcomesUpdateHook(MeshBackendBase& meshInstance) { // The default hook only returns true and does nothing else. - if (TcpIpMeshBackend *tcpIpInstance = TypeCast::meshBackendCast<TcpIpMeshBackend *>(&meshInstance)) { - if (tcpIpInstance->latestTransmissionOutcomes().back().transmissionStatus() == TransmissionStatusType::TRANSMISSION_COMPLETE) { + if (TcpIpMeshBackend* tcpIpInstance + = TypeCast::meshBackendCast<TcpIpMeshBackend*>(&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!")); @@ -156,8 +191,10 @@ bool exampleTransmissionOutcomesUpdateHook(MeshBackendBase &meshInstance) { } void setup() { - // Prevents the flash memory from being worn out, see: https://github.com/esp8266/Arduino/issues/1054 . - // This will however delay node WiFi start-up by about 700 ms. The delay is 900 ms if we otherwise would have stored the WiFi network we want to connect to. + // Prevents the flash memory from being worn out, see: + // https://github.com/esp8266/Arduino/issues/1054 . This will however delay node WiFi start-up by + // about 700 ms. The delay is 900 ms if we otherwise would have stored the WiFi network we want to + // connect to. WiFi.persistent(false); Serial.begin(115200); @@ -165,31 +202,40 @@ void setup() { Serial.println(); Serial.println(); - Serial.println(F("Note that this library can use static IP:s for the nodes to speed up connection times.\n" - "Use the setStaticIP method as shown in this example to enable this.\n" - "Ensure that nodes connecting to the same AP have distinct static IP:s.\n" - "Also, remember to change the default mesh network password!\n\n")); + Serial.println( + F("Note that this library can use static IP:s for the nodes to speed up connection times.\n" + "Use the setStaticIP method as shown in this example to enable this.\n" + "Ensure that nodes connecting to the same AP have distinct static IP:s.\n" + "Also, remember to change the default mesh network password!\n\n")); Serial.println(F("Setting up mesh node...")); /* 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. - tcpIpNode.setMessage(String(F("Hello world request #")) + String(requestNumber) + F(" from ") + tcpIpNode.getMeshName() + tcpIpNode.getNodeID() + String('.')); + // 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. + tcpIpNode.setMessage(String(F("Hello world request #")) + String(requestNumber) + F(" from ") + + tcpIpNode.getMeshName() + tcpIpNode.getNodeID() + String('.')); tcpIpNode.setTransmissionOutcomesUpdateHook(exampleTransmissionOutcomesUpdateHook); } 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. - - // attemptTransmission(message, scan, scanAllWiFiChannels, concludingDisconnect, initialDisconnect = false) +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. + + // attemptTransmission(message, scan, scanAllWiFiChannels, concludingDisconnect, + // initialDisconnect = false) tcpIpNode.attemptTransmission(tcpIpNode.getMessage(), true, false, false); timeOfLastScan = millis(); @@ -202,15 +248,19 @@ void loop() { if (tcpIpNode.latestTransmissionOutcomes().empty()) { Serial.println(F("No mesh AP found.")); } else { - for (TransmissionOutcome &transmissionOutcome : tcpIpNode.latestTransmissionOutcomes()) { - if (transmissionOutcome.transmissionStatus() == TransmissionStatusType::TRANSMISSION_FAILED) { + for (TransmissionOutcome& transmissionOutcome : tcpIpNode.latestTransmissionOutcomes()) { + if (transmissionOutcome.transmissionStatus() + == TransmissionStatusType::TRANSMISSION_FAILED) { Serial.println(String(F("Transmission failed to mesh AP ")) + transmissionOutcome.SSID()); - } else if (transmissionOutcome.transmissionStatus() == TransmissionStatusType::CONNECTION_FAILED) { + } else if (transmissionOutcome.transmissionStatus() + == TransmissionStatusType::CONNECTION_FAILED) { Serial.println(String(F("Connection failed to mesh AP ")) + transmissionOutcome.SSID()); - } else if (transmissionOutcome.transmissionStatus() == TransmissionStatusType::TRANSMISSION_COMPLETE) { + } else if (transmissionOutcome.transmissionStatus() + == TransmissionStatusType::TRANSMISSION_COMPLETE) { // No need to do anything, transmission was successful. } else { - Serial.println(String(F("Invalid transmission status for ")) + transmissionOutcome.SSID() + String('!')); + Serial.println(String(F("Invalid transmission status for ")) + transmissionOutcome.SSID() + + String('!')); assert(F("Invalid transmission status returned from responseHandler!") && false); } } diff --git a/libraries/ESP8266httpUpdate/examples/httpUpdate/httpUpdate.ino b/libraries/ESP8266httpUpdate/examples/httpUpdate/httpUpdate.ino index 19c555a235..b2e5376f4e 100644 --- a/libraries/ESP8266httpUpdate/examples/httpUpdate/httpUpdate.ino +++ b/libraries/ESP8266httpUpdate/examples/httpUpdate/httpUpdate.ino @@ -15,13 +15,12 @@ #ifndef APSSID #define APSSID "APSSID" -#define APPSK "APPSK" +#define APPSK "APPSK" #endif ESP8266WiFiMulti WiFiMulti; void setup() { - Serial.begin(115200); // Serial.setDebugOutput(true); @@ -37,31 +36,21 @@ void setup() { WiFi.mode(WIFI_STA); WiFiMulti.addAP(APSSID, APPSK); - - } -void update_started() { - Serial.println("CALLBACK: HTTP update process started"); -} +void update_started() { Serial.println("CALLBACK: HTTP update process started"); } -void update_finished() { - Serial.println("CALLBACK: HTTP update process finished"); -} +void update_finished() { Serial.println("CALLBACK: HTTP update process finished"); } void update_progress(int cur, int total) { Serial.printf("CALLBACK: HTTP update process at %d of %d bytes...\n", cur, total); } -void update_error(int err) { - Serial.printf("CALLBACK: HTTP update fatal error code %d\n", err); -} - +void update_error(int err) { Serial.printf("CALLBACK: HTTP update fatal error code %d\n", err); } void loop() { // wait for WiFi connection if ((WiFiMulti.run() == WL_CONNECTED)) { - WiFiClient client; // The line below is optional. It can be used to blink the LED on the board during flashing @@ -80,11 +69,12 @@ 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()); + Serial.printf("HTTP_UPDATE_FAILD Error (%d): %s\n", ESPhttpUpdate.getLastError(), + ESPhttpUpdate.getLastErrorString().c_str()); break; case HTTP_UPDATE_NO_UPDATES: @@ -97,4 +87,3 @@ void loop() { } } } - diff --git a/libraries/ESP8266httpUpdate/examples/httpUpdateLittleFS/httpUpdateLittleFS.ino b/libraries/ESP8266httpUpdate/examples/httpUpdateLittleFS/httpUpdateLittleFS.ino index 6541d047fd..2e61e0735e 100644 --- a/libraries/ESP8266httpUpdate/examples/httpUpdateLittleFS/httpUpdateLittleFS.ino +++ b/libraries/ESP8266httpUpdate/examples/httpUpdateLittleFS/httpUpdateLittleFS.ino @@ -17,11 +17,10 @@ ESP8266WiFiMulti WiFiMulti; #ifndef APSSID #define APSSID "APSSID" -#define APPSK "APPSK" +#define APPSK "APPSK" #endif void setup() { - Serial.begin(115200); // Serial.setDebugOutput(true); @@ -37,13 +36,11 @@ void setup() { WiFi.mode(WIFI_STA); WiFiMulti.addAP(APSSID, APPSK); - } void loop() { // wait for WiFi connection if ((WiFiMulti.run() == WL_CONNECTED)) { - Serial.println("Update LittleFS..."); WiFiClient client; @@ -63,7 +60,8 @@ void loop() { switch (ret) { case HTTP_UPDATE_FAILED: - Serial.printf("HTTP_UPDATE_FAILED Error (%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str()); + Serial.printf("HTTP_UPDATE_FAILED Error (%d): %s", ESPhttpUpdate.getLastError(), + ESPhttpUpdate.getLastErrorString().c_str()); break; case HTTP_UPDATE_NO_UPDATES: @@ -77,4 +75,3 @@ void loop() { } } } - diff --git a/libraries/ESP8266httpUpdate/examples/httpUpdateSecure/httpUpdateSecure.ino b/libraries/ESP8266httpUpdate/examples/httpUpdateSecure/httpUpdateSecure.ino index beb613897c..2b06b54980 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; @@ -50,7 +50,6 @@ void setClock() { } void setup() { - Serial.begin(115200); // Serial.setDebugOutput(true); @@ -73,19 +72,20 @@ void setup() { Serial.print(F("Number of CA certs read: ")); 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! + 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! } } void loop() { // wait for WiFi connection if ((WiFiMulti.run() == WL_CONNECTED)) { - setClock(); BearSSL::WiFiClientSecure client; - bool mfln = client.probeMaxFragmentLength("server", 443, 1024); // server must be the same as in ESPhttpUpdate.update() + bool mfln = client.probeMaxFragmentLength( + "server", 443, 1024); // server must be the same as in ESPhttpUpdate.update() Serial.printf("MFLN supported: %s\n", mfln ? "yes" : "no"); if (mfln) { client.setBufferSizes(1024, 1024); @@ -102,12 +102,12 @@ 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()); + Serial.printf("HTTP_UPDATE_FAILED Error (%d): %s\n", ESPhttpUpdate.getLastError(), + ESPhttpUpdate.getLastErrorString().c_str()); break; case HTTP_UPDATE_NO_UPDATES: diff --git a/libraries/ESP8266httpUpdate/examples/httpUpdateSigned/httpUpdateSigned.ino b/libraries/ESP8266httpUpdate/examples/httpUpdateSigned/httpUpdateSigned.ino index e196ef6419..2ba0b483fa 100644 --- a/libraries/ESP8266httpUpdate/examples/httpUpdateSigned/httpUpdateSigned.ino +++ b/libraries/ESP8266httpUpdate/examples/httpUpdateSigned/httpUpdateSigned.ino @@ -23,7 +23,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif ESP8266WiFiMulti WiFiMulti; @@ -50,13 +50,12 @@ TQIDAQAB -----END PUBLIC KEY----- )EOF"; #if MANUAL_SIGNING -BearSSL::PublicKey *signPubKey = nullptr; -BearSSL::HashSHA256 *hash; -BearSSL::SigningVerifier *sign; +BearSSL::PublicKey* signPubKey = nullptr; +BearSSL::HashSHA256* hash; +BearSSL::SigningVerifier* sign; #endif void setup() { - Serial.begin(115200); // Serial.setDebugOutput(true); @@ -73,24 +72,22 @@ 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 + hash = new BearSSL::HashSHA256(); + sign = new BearSSL::SigningVerifier(signPubKey); +#endif } - void loop() { // wait for WiFi connection if ((WiFiMulti.run() == WL_CONNECTED)) { - WiFiClient client; - #if MANUAL_SIGNING +#if MANUAL_SIGNING // Ensure all updates are signed appropriately. W/o this call, all will be accepted. Update.installSignature(hash, sign); - #endif +#endif // If the key files are present in the build directory, signing will be // enabled using them automatically @@ -100,7 +97,8 @@ void loop() { switch (ret) { case HTTP_UPDATE_FAILED: - Serial.printf("HTTP_UPDATE_FAILED Error (%d): %s\n", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str()); + Serial.printf("HTTP_UPDATE_FAILED Error (%d): %s\n", ESPhttpUpdate.getLastError(), + ESPhttpUpdate.getLastErrorString().c_str()); break; case HTTP_UPDATE_NO_UPDATES: @@ -114,4 +112,3 @@ void loop() { } delay(10000); } - diff --git a/libraries/ESP8266mDNS/examples/LEAmDNS/mDNS_Clock/mDNS_Clock.ino b/libraries/ESP8266mDNS/examples/LEAmDNS/mDNS_Clock/mDNS_Clock.ino index f0a9de1225..d6cd3f9bd1 100644 --- a/libraries/ESP8266mDNS/examples/LEAmDNS/mDNS_Clock/mDNS_Clock.ino +++ b/libraries/ESP8266mDNS/examples/LEAmDNS/mDNS_Clock/mDNS_Clock.ino @@ -31,7 +31,6 @@ */ - #include <ESP8266WiFi.h> #include <WiFiClient.h> #include <ESP8266WebServer.h> @@ -43,54 +42,54 @@ 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]; - time_t now = time(nullptr); + 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; } - /* setClock Set time via NTP */ void setClock(void) { - configTime((TIMEZONE_OFFSET * 3600), (DST_OFFSET * 3600), "pool.ntp.org", "time.nist.gov", "time.windows.com"); + configTime((TIMEZONE_OFFSET * 3600), (DST_OFFSET * 3600), "pool.ntp.org", "time.nist.gov", + "time.windows.com"); Serial.print("Waiting for NTP time sync: "); - time_t now = time(nullptr); // Secs since 01.01.1970 (when uninitialized starts with (8 * 3600 = 28800) + time_t now + = time(nullptr); // Secs since 01.01.1970 (when uninitialized starts with (8 * 3600 = 28800) while (now < 8 * 3600 * 2) { // Wait for realistic value delay(500); Serial.print("."); @@ -100,12 +99,10 @@ void setClock(void) { Serial.printf("Current time: %s\n", getTimeString()); } - /* setStationHostname */ bool setStationHostname(const char* p_pcHostname) { - if (p_pcHostname) { WiFi.hostname(p_pcHostname); Serial.printf("setDeviceHostname: Station hostname is set to '%s'\n", p_pcHostname); @@ -113,7 +110,6 @@ bool setStationHostname(const char* p_pcHostname) { return true; } - /* MDNSDynamicServiceTxtCallback @@ -132,7 +128,6 @@ void MDNSDynamicServiceTxtCallback(const MDNSResponder::hMDNSService p_hService) } } - /* MDNSProbeResultCallback @@ -144,9 +139,9 @@ void MDNSDynamicServiceTxtCallback(const MDNSResponder::hMDNSService p_hService) */ void hostProbeResult(String p_pcDomainName, bool p_bProbeResult) { - Serial.println("MDNSProbeResultCallback"); - Serial.printf("MDNSProbeResultCallback: Host domain '%s.local' is %s\n", p_pcDomainName.c_str(), (p_bProbeResult ? "free" : "already USED!")); + Serial.printf("MDNSProbeResultCallback: Host domain '%s.local' is %s\n", p_pcDomainName.c_str(), + (p_bProbeResult ? "free" : "already USED!")); if (true == p_bProbeResult) { // Set station hostname setStationHostname(pcHostDomain); @@ -156,7 +151,8 @@ void hostProbeResult(String p_pcDomainName, bool p_bProbeResult) { bHostDomainConfirmed = true; if (!hMDNSService) { - // Add a 'clock.tcp' service to port 'SERVICE_PORT', using the host domain as instance domain + // Add a 'clock.tcp' service to port 'SERVICE_PORT', using the host domain as instance + // domain hMDNSService = MDNS.addService(0, "espclk", "tcp", SERVICE_PORT); if (hMDNSService) { // Add a simple static MDNS service TXT item @@ -176,7 +172,6 @@ void hostProbeResult(String p_pcDomainName, bool p_bProbeResult) { } } - /* handleHTTPClient */ @@ -186,7 +181,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 +227,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); } } @@ -250,7 +245,6 @@ void setup(void) { loop */ void loop(void) { - // Check if a request has come in server.handleClient(); // Allow MDNS processing @@ -258,7 +252,6 @@ void loop(void) { static esp8266::polledTimeout::periodicMs timeout(UPDATE_CYCLE); if (timeout.expired()) { - if (hMDNSService) { // Just trigger a new MDNS announcement, this will lead to a call to // 'MDNSDynamicServiceTxtCallback', which will update the time TXT item diff --git a/libraries/ESP8266mDNS/examples/LEAmDNS/mDNS_ServiceMonitor/mDNS_ServiceMonitor.ino b/libraries/ESP8266mDNS/examples/LEAmDNS/mDNS_ServiceMonitor/mDNS_ServiceMonitor.ino index 17b29ec57c..14c418013b 100644 --- a/libraries/ESP8266mDNS/examples/LEAmDNS/mDNS_ServiceMonitor/mDNS_ServiceMonitor.ino +++ b/libraries/ESP8266mDNS/examples/LEAmDNS/mDNS_ServiceMonitor/mDNS_ServiceMonitor.ino @@ -14,9 +14,9 @@ is already used in the local network, another host domain is negotiated. Keep an eye to the serial output to learn the final host domain for the HTTP service. The service itself is is announced as 'host domain'._http._tcp.local. - The HTTP server delivers a short greeting and the current list of other 'HTTP' services (not updated). - The web server code is taken nearly 1:1 from the 'mDNS_Web_Server.ino' example. - Point your browser to 'host domain'.local to see this web page. + The HTTP server delivers a short greeting and the current list of other 'HTTP' services (not + updated). The web server code is taken nearly 1:1 from the 'mDNS_Web_Server.ino' example. Point + your browser to 'host domain'.local to see this web page. Instructions: - Update WiFi SSID and password as necessary. @@ -29,7 +29,6 @@ */ - #include <ESP8266WiFi.h> #include <WiFiClient.h> #include <ESP8266WebServer.h> @@ -39,33 +38,33 @@ 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!<br/>"; -String strHTTPServices = cstrNoHTTPServices; +const String cstrNoHTTPServices = "Currently no 'http.tcp' services in the local network!<br/>"; +String strHTTPServices = cstrNoHTTPServices; // HTTP server at port 'SERVICE_PORT' will respond to HTTP requests -ESP8266WebServer server(SERVICE_PORT); - +ESP8266WebServer server(SERVICE_PORT); /* setStationHostname */ bool setStationHostname(const char* p_pcHostname) { - if (p_pcHostname) { WiFi.hostname(p_pcHostname); Serial.printf("setStationHostname: Station hostname is set to '%s'\n", p_pcHostname); @@ -77,28 +76,30 @@ bool setStationHostname(const char* p_pcHostname) { MDNSServiceQueryCallback */ -void MDNSServiceQueryCallback(MDNSResponder::MDNSServiceInfo serviceInfo, MDNSResponder::AnswerType answerType, bool p_bSetContent) { +void MDNSServiceQueryCallback(MDNSResponder::MDNSServiceInfo serviceInfo, + MDNSResponder::AnswerType answerType, bool p_bSetContent) { String answerInfo; switch (answerType) { - case MDNSResponder::AnswerType::ServiceDomain : + case MDNSResponder::AnswerType::ServiceDomain: answerInfo = "ServiceDomain " + String(serviceInfo.serviceDomain()); break; - case MDNSResponder::AnswerType::HostDomainAndPort : - answerInfo = "HostDomainAndPort " + String(serviceInfo.hostDomain()) + ":" + String(serviceInfo.hostPort()); + case MDNSResponder::AnswerType::HostDomainAndPort: + answerInfo = "HostDomainAndPort " + String(serviceInfo.hostDomain()) + ":" + + String(serviceInfo.hostPort()); break; - case MDNSResponder::AnswerType::IP4Address : + case MDNSResponder::AnswerType::IP4Address: answerInfo = "IP4Address "; for (IPAddress ip : serviceInfo.IP4Adresses()) { answerInfo += "- " + ip.toString(); }; break; - case MDNSResponder::AnswerType::Txt : + case MDNSResponder::AnswerType::Txt: answerInfo = "TXT " + String(serviceInfo.strKeyValue()); for (auto kv : serviceInfo.keyValues()) { answerInfo += "\nkv : " + String(kv.first) + " : " + String(kv.second); } break; - default : + default: answerInfo = "Unknown Answertype"; } Serial.printf("Answer %s %s\n", answerInfo.c_str(), p_bSetContent ? "Modified" : "Deleted"); @@ -109,11 +110,11 @@ void MDNSServiceQueryCallback(MDNSResponder::MDNSServiceInfo serviceInfo, MDNSRe Probe result callback for Services */ -void serviceProbeResult(String p_pcServiceName, - const MDNSResponder::hMDNSService 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!")); + (void)p_hMDNSService; + Serial.printf("MDNSServiceProbeResultCallback: Service %s probe %s\n", p_pcServiceName.c_str(), + (p_bProbeResult ? "succeeded." : "failed!")); } /* @@ -128,8 +129,8 @@ void serviceProbeResult(String p_pcServiceName, */ void hostProbeResult(String p_pcDomainName, bool p_bProbeResult) { - - Serial.printf("MDNSHostProbeResultCallback: Host domain '%s.local' is %s\n", p_pcDomainName.c_str(), (p_bProbeResult ? "free" : "already USED!")); + Serial.printf("MDNSHostProbeResultCallback: Host domain '%s.local' is %s\n", + p_pcDomainName.c_str(), (p_bProbeResult ? "free" : "already USED!")); if (true == p_bProbeResult) { // Set station hostname @@ -156,9 +157,11 @@ void hostProbeResult(String p_pcDomainName, bool p_bProbeResult) { if (!hMDNSServiceQuery) { hMDNSServiceQuery = MDNS.installServiceQuery("http", "tcp", MDNSServiceQueryCallback); if (hMDNSServiceQuery) { - Serial.printf("MDNSProbeResultCallback: Service query for 'http.tcp' services installed.\n"); + Serial.printf( + "MDNSProbeResultCallback: Service query for 'http.tcp' services installed.\n"); } else { - Serial.printf("MDNSProbeResultCallback: FAILED to install service query for 'http.tcp' services!\n"); + Serial.printf("MDNSProbeResultCallback: FAILED to install service query for 'http.tcp' " + "services!\n"); } } } @@ -180,13 +183,13 @@ void handleHTTPRequest() { Serial.println(""); Serial.println("HTTP Request"); - IPAddress ip = WiFi.localIP(); - String ipStr = ip.toString(); - String s = "<!DOCTYPE HTML>\r\n<html><h3><head>Hello from "; + IPAddress ip = WiFi.localIP(); + String ipStr = ip.toString(); + String s = "<!DOCTYPE HTML>\r\n<html><h3><head>Hello from "; s += WiFi.hostname() + ".local at " + WiFi.localIP().toString() + "</h3></head>"; s += "<br/><h4>Local HTTP services are :</h4>"; s += "<ol>"; - for (auto info : MDNS.answerInfo(hMDNSServiceQuery)) { + for (auto info : MDNS.answerInfo(hMDNSServiceQuery)) { s += "<li>"; s += info.serviceDomain(); if (info.hostDomainAvailable()) { @@ -245,10 +248,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 +267,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..0bd58c4ec1 100644 --- a/libraries/ESP8266mDNS/examples/OTA-mDNS-LittleFS/OTA-mDNS-LittleFS.ino +++ b/libraries/ESP8266mDNS/examples/OTA-mDNS-LittleFS/OTA-mDNS-LittleFS.ino @@ -14,12 +14,12 @@ #ifndef APSSID #define APSSID "your-apssid" -#define APPSK "your-password" +#define APPSK "your-password" #endif #ifndef STASSID #define STASSID "your-sta" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif // includes @@ -30,20 +30,19 @@ #include <ArduinoOTA.h> #include <ESP8266mDNS.h> - /** @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. @@ -59,7 +58,7 @@ const char* ap_default_psk = APPSK; ///< Default PSK. and the WiFi PSK in the second line. Line separator can be \r\n (CR LF) \r or \n. */ -bool loadConfig(String *ssid, String *pass) { +bool loadConfig(String* ssid, String* pass) { // open file for reading. File configFile = LittleFS.open("/cl_conf.txt", "r"); if (!configFile) { @@ -75,11 +74,11 @@ bool loadConfig(String *ssid, String *pass) { content.trim(); // Check if there is a second line available. - int8_t pos = content.indexOf("\r\n"); - uint8_t le = 2; + int8_t pos = content.indexOf("\r\n"); + uint8_t le = 2; // check for linux and mac line ending. if (pos == -1) { - le = 1; + le = 1; pos = content.indexOf("\n"); if (pos == -1) { pos = content.indexOf("\r"); @@ -110,8 +109,7 @@ bool loadConfig(String *ssid, String *pass) { #endif return true; -} // loadConfig - +} // loadConfig /** @brief Save WiFi SSID and PSK to configuration file. @@ -119,7 +117,7 @@ bool loadConfig(String *ssid, String *pass) { @param pass PSK as string pointer, @return True or False. */ -bool saveConfig(String *ssid, String *pass) { +bool saveConfig(String* ssid, String* pass) { // Open config file for writing. File configFile = LittleFS.open("/cl_conf.txt", "w"); if (!configFile) { @@ -135,15 +133,14 @@ bool saveConfig(String *ssid, String *pass) { configFile.close(); return true; -} // saveConfig - +} // saveConfig /** @brief Arduino setup function. */ void setup() { String station_ssid = ""; - String station_psk = ""; + String station_psk = ""; Serial.begin(115200); @@ -160,8 +157,7 @@ void setup() { // Print hostname. Serial.println("Hostname: " + hostname); - //Serial.println(WiFi.hostname()); - + // Serial.println(WiFi.hostname()); // Initialize file system. if (!LittleFS.begin()) { @@ -170,9 +166,9 @@ void setup() { } // Load wifi connection information. - if (! loadConfig(&station_ssid, &station_psk)) { + if (!loadConfig(&station_ssid, &station_psk)) { station_ssid = STASSID; - station_psk = STAPSK; + station_psk = STAPSK; Serial.println("No WiFi connection information available."); } @@ -196,7 +192,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 +204,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(); @@ -233,11 +229,10 @@ void setup() { } // Start OTA server. - ArduinoOTA.setHostname((const char *)hostname.c_str()); + ArduinoOTA.setHostname((const char*)hostname.c_str()); ArduinoOTA.begin(); } - /** @brief Arduino loop function. */ @@ -245,4 +240,3 @@ void loop() { // Handle OTA server. ArduinoOTA.handle(); } - diff --git a/libraries/ESP8266mDNS/examples/mDNS-SD_Extended/mDNS-SD_Extended.ino b/libraries/ESP8266mDNS/examples/mDNS-SD_Extended/mDNS-SD_Extended.ino index fda2fe6562..d07595db18 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* password = STAPSK; -char hostString[16] = {0}; +const char* ssid = STASSID; +const char* password = STAPSK; +char hostString[16] = { 0 }; void setup() { Serial.begin(115200); @@ -47,10 +47,10 @@ void setup() { 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..ccc745d62a 100644 --- a/libraries/ESP8266mDNS/examples/mDNS_Web_Server/mDNS_Web_Server.ino +++ b/libraries/ESP8266mDNS/examples/mDNS_Web_Server/mDNS_Web_Server.ino @@ -15,17 +15,16 @@ */ - #include <ESP8266WiFi.h> #include <ESP8266mDNS.h> #include <WiFiClient.h> #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; // TCP server at port 80 will respond to HTTP requests @@ -72,7 +71,6 @@ void setup(void) { } void loop(void) { - MDNS.update(); // Check if a client has connected @@ -94,7 +92,7 @@ void loop(void) { // First line of HTTP request looks like "GET /path HTTP/1.1" // Retrieve the "/path" part by finding the spaces int addr_start = req.indexOf(' '); - int addr_end = req.indexOf(' ', addr_start + 1); + int addr_end = req.indexOf(' ', addr_start + 1); if (addr_start == -1 || addr_end == -1) { Serial.print("Invalid request: "); Serial.println(req); @@ -109,7 +107,8 @@ void loop(void) { if (req == "/") { IPAddress ip = WiFi.localIP(); String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]); - s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>Hello from ESP8266 at "; + s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>Hello from " + "ESP8266 at "; s += ipStr; s += "</html>\r\n\r\n"; Serial.println("Sending 200"); @@ -121,4 +120,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..c400c63c09 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS.cpp +++ b/libraries/ESP8266mDNS/src/LEAmDNS.cpp @@ -27,19 +27,17 @@ #include "ESP8266mDNS.h" #include "LEAmDNS_Priv.h" -#include <LwipIntf.h> // LwipIntf::stateUpCB() +#include <LwipIntf.h> // LwipIntf::stateUpCB() #include <lwip/igmp.h> #include <lwip/prot/dns.h> namespace esp8266 { - /* LEAmDNS */ namespace MDNSImplementation { - /** STRINGIZE */ @@ -50,1335 +48,1301 @@ 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) - { - (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) + /* + MDNSResponder::~MDNSResponder + */ + MDNSResponder::~MDNSResponder(void) { - _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) -{ - return setHostname(p_strHostname.c_str()); -} + /* + MDNSResponder::end + 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 + + Add a static service TXT item ('Key'='Value') to a service. - hMDNSTxt hTxt = 0; - stcMDNSService* pService = _findService(p_hService); - if (pService) + */ + MDNSResponder::hMDNSTxt + MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSService p_hService, const char* p_pcKey, + const char* p_pcValue) { - hTxt = (hMDNSTxt)_addServiceTxt(pService, p_pcKey, p_pcValue, false); + hMDNSTxt hTxt = 0; + stcMDNSService* pService = _findService(p_hService); + if (pService) + { + hTxt = (hMDNSTxt)_addServiceTxt(pService, p_pcKey, p_pcValue, false); + } + DEBUG_EX_ERR(if (!hTxt) { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] addServiceTxt: FAILED for '%s=%s'!\n"), + (p_pcKey ?: "-"), (p_pcValue ?: "-")); + }); + return hTxt; } - DEBUG_EX_ERR(if (!hTxt) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] addServiceTxt: FAILED for '%s=%s'!\n"), (p_pcKey ? : "-"), (p_pcValue ? : "-")); - }); - return hTxt; -} - -/* - MDNSResponder::addServiceTxt (uint32_t) - - Formats: http://www.cplusplus.com/reference/cstdio/printf/ -*/ -MDNSResponder::hMDNSTxt MDNSResponder::addServiceTxt(const MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - uint32_t p_u32Value) -{ - char acBuffer[32]; *acBuffer = 0; - sprintf(acBuffer, "%u", p_u32Value); - 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::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::setDynamicServiceTxtCallback (global) + /* + 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)); + } - Set a global callback for dynamic service TXT items. The callback is called, whenever - service TXT items are needed. + /* + MDNSResponder::setDynamicServiceTxtCallback (global) -*/ -bool MDNSResponder::setDynamicServiceTxtCallback(MDNSResponder::MDNSDynamicServiceTxtCallbackFunc p_fnCallback) -{ + Set a global callback for dynamic service TXT items. The callback is called, whenever + service TXT items are needed. - m_fnServiceTxtCallback = p_fnCallback; + */ + bool MDNSResponder::setDynamicServiceTxtCallback( + MDNSResponder::MDNSDynamicServiceTxtCallbackFunc p_fnCallback) + { + m_fnServiceTxtCallback = p_fnCallback; - return true; -} + return true; + } -/* - MDNSResponder::setDynamicServiceTxtCallback (service specific) + /* + 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. + 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, + */ + bool MDNSResponder::setDynamicServiceTxtCallback( + MDNSResponder::hMDNSService p_hService, MDNSResponder::MDNSDynamicServiceTxtCallbackFunc p_fnCallback) -{ + { + bool bResult = false; + + stcMDNSService* pService = _findService(p_hService); + if (pService) + { + pService->m_fnTxtCallback = p_fnCallback; - bool bResult = false; + bResult = true; + } + DEBUG_EX_ERR(if (!bResult) { + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] setDynamicServiceTxtCallback: FAILED!\n")); + }); + return bResult; + } - stcMDNSService* pService = _findService(p_hService); - if (pService) + /* + MDNSResponder::addDynamicServiceTxt + */ + MDNSResponder::hMDNSTxt + MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, const char* p_pcKey, + const char* p_pcValue) { - pService->m_fnTxtCallback = p_fnCallback; + // DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] addDynamicServiceTxt + // (%s=%s)\n"), p_pcKey, p_pcValue);); + + hMDNSTxt hTxt = 0; - bResult = true; + stcMDNSService* pService = _findService(p_hService); + if (pService) + { + hTxt = _addServiceTxt(pService, p_pcKey, p_pcValue, true); + } + DEBUG_EX_ERR(if (!hTxt) { + DEBUG_OUTPUT.printf_P( + PSTR("[MDNSResponder] addDynamicServiceTxt: FAILED for '%s=%s'!\n"), + (p_pcKey ?: "-"), (p_pcValue ?: "-")); + }); + return hTxt; } - DEBUG_EX_ERR(if (!bResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] setDynamicServiceTxtCallback: FAILED!\n")); - }); - return bResult; -} -/* - MDNSResponder::addDynamicServiceTxt -*/ -MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - const char* p_pcValue) -{ - //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] addDynamicServiceTxt (%s=%s)\n"), p_pcKey, p_pcValue);); + /* + MDNSResponder::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); - hMDNSTxt hTxt = 0; + return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); + } - stcMDNSService* pService = _findService(p_hService); - if (pService) + /* + MDNSResponder::addDynamicServiceTxt (uint16_t) + */ + MDNSResponder::hMDNSTxt + MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, const char* p_pcKey, + uint16_t p_u16Value) { - 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; -} + char acBuffer[16]; + *acBuffer = 0; + sprintf(acBuffer, "%hu", p_u16Value); -/* - MDNSResponder::addDynamicServiceTxt (uint32_t) -*/ -MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - uint32_t p_u32Value) -{ + return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); + } - char acBuffer[32]; *acBuffer = 0; - sprintf(acBuffer, "%u", p_u32Value); + /* + 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); -} + 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) -{ + /* + 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); - char acBuffer[16]; *acBuffer = 0; - sprintf(acBuffer, "%hu", p_u16Value); + return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); + } - return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); -} + /* + MDNSResponder::addDynamicServiceTxt (int16_t) + */ + MDNSResponder::hMDNSTxt + MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, const char* p_pcKey, + int16_t p_i16Value) + { + char acBuffer[16]; + *acBuffer = 0; + sprintf(acBuffer, "%hi", p_i16Value); -/* - MDNSResponder::addDynamicServiceTxt (uint8_t) -*/ -MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - uint8_t p_u8Value) -{ + return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); + } - char acBuffer[8]; *acBuffer = 0; - sprintf(acBuffer, "%hhu", p_u8Value); + /* + 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); - return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); -} + return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); + } -/* - MDNSResponder::addDynamicServiceTxt (int32_t) -*/ -MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - int32_t p_i32Value) -{ + /** + STATIC SERVICE QUERY (LEGACY) + */ - char acBuffer[32]; *acBuffer = 0; - sprintf(acBuffer, "%i", p_i32Value); + /* + MDNSResponder::queryService - return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); -} + Perform a (blocking) static service query. + The arrived answers can be queried by calling: + - answerHostname (or 'hostname') + - answerIP (or 'IP') + - answerPort (or 'port') -/* - MDNSResponder::addDynamicServiceTxt (int16_t) -*/ -MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - int16_t p_i16Value) -{ + */ + 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; + } - char acBuffer[16]; *acBuffer = 0; - sprintf(acBuffer, "%hi", p_i16Value); + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] queryService '%s.%s'\n"), + p_pcService, p_pcProtocol);); - return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); -} + uint32_t u32Result = 0; -/* - MDNSResponder::addDynamicServiceTxt (int8_t) -*/ -MDNSResponder::hMDNSTxt MDNSResponder::addDynamicServiceTxt(MDNSResponder::hMDNSService p_hService, - const char* p_pcKey, - int8_t p_i8Value) -{ + stcMDNSServiceQuery* pServiceQuery = 0; + if ((p_pcService) && (os_strlen(p_pcService)) && (p_pcProtocol) && (os_strlen(p_pcProtocol)) + && (p_u16Timeout) && (_removeLegacyServiceQuery()) + && ((pServiceQuery = _allocServiceQuery())) + && (_buildDomainForService(p_pcService, p_pcProtocol, + pServiceQuery->m_ServiceTypeDomain))) + { + pServiceQuery->m_bLegacyQuery = true; - char acBuffer[8]; *acBuffer = 0; - sprintf(acBuffer, "%hhi", p_i8Value); + 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 + { + DEBUG_EX_ERR(DEBUG_OUTPUT.printf_P( + PSTR("[MDNSResponder] queryService: INVALID input data!\n"));); + } + return u32Result; + } - return addDynamicServiceTxt(p_hService, p_pcKey, acBuffer); -} + /* + MDNSResponder::removeQuery + Remove the last static service query (and all answers). -/** - STATIC SERVICE QUERY (LEGACY) -*/ + */ + bool MDNSResponder::removeQuery(void) { return _removeLegacyServiceQuery(); } -/* - MDNSResponder::queryService + /* + 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()); + } - Perform a (blocking) static service query. - The arrived answers can be queried by calling: - - answerHostname (or 'hostname') - - answerIP (or 'IP') - - answerPort (or 'port') + /* + MDNSResponder::answerHostname + */ + const char* MDNSResponder::answerHostname(const uint32_t p_u32AnswerIndex) + { + stcMDNSServiceQuery* pServiceQuery = _findLegacyServiceQuery(); + stcMDNSServiceQuery::stcAnswer* pSQAnswer + = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); -*/ -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);); - - uint32_t u32Result = 0; - - stcMDNSServiceQuery* pServiceQuery = 0; - if ((p_pcService) && - (os_strlen(p_pcService)) && - (p_pcProtocol) && - (os_strlen(p_pcProtocol)) && - (p_u16Timeout) && - (_removeLegacyServiceQuery()) && - ((pServiceQuery = _allocServiceQuery())) && - (_buildDomainForService(p_pcService, p_pcProtocol, pServiceQuery->m_ServiceTypeDomain))) - { - - pServiceQuery->m_bLegacyQuery = true; - - if (_sendMDNSServiceQuery(*pServiceQuery)) + if ((pSQAnswer) && (pSQAnswer->m_HostDomain.m_u16NameLength) + && (!pSQAnswer->m_pcHostDomain)) { - // 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); + char* pcHostDomain = pSQAnswer->allocHostDomain(pSQAnswer->m_HostDomain.c_strLength()); + if (pcHostDomain) + { + pSQAnswer->m_HostDomain.c_str(pcHostDomain); + } } + return (pSQAnswer ? pSQAnswer->m_pcHostDomain : 0); } - 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)) +#ifdef MDNS_IP4_SUPPORT + /* + MDNSResponder::answerIP + */ + IPAddress MDNSResponder::answerIP(const uint32_t p_u32AnswerIndex) { - - char* pcHostDomain = pSQAnswer->allocHostDomain(pSQAnswer->m_HostDomain.c_strLength()); - if (pcHostDomain) - { - pSQAnswer->m_HostDomain.c_str(pcHostDomain); - } + 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 (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()); -} + /* + 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::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); -} - -/* - MDNSResponder::hostname (LEGACY) -*/ -String MDNSResponder::hostname(const uint32_t p_u32AnswerIndex) -{ - - return String(answerHostname(p_u32AnswerIndex)); -} - -/* - MDNSResponder::IP (LEGACY) -*/ -IPAddress MDNSResponder::IP(const uint32_t p_u32AnswerIndex) -{ - - return answerIP(p_u32AnswerIndex); -} - -/* - MDNSResponder::port (LEGACY) -*/ -uint16_t MDNSResponder::port(const uint32_t p_u32AnswerIndex) -{ - - return answerPort(p_u32AnswerIndex); -} - - -/** - DYNAMIC SERVICE QUERY -*/ - -/* - MDNSResponder::installServiceQuery + /* + 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); + } - 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::hostname (LEGACY) + */ + String MDNSResponder::hostname(const uint32_t p_u32AnswerIndex) + { + return String(answerHostname(p_u32AnswerIndex)); + } -*/ -MDNSResponder::hMDNSServiceQuery MDNSResponder::installServiceQuery(const char* p_pcService, - const char* p_pcProtocol, - MDNSResponder::MDNSServiceQueryCallbackFunc p_fnCallback) -{ - hMDNSServiceQuery hResult = 0; + /* + MDNSResponder::IP (LEGACY) + */ + IPAddress MDNSResponder::IP(const uint32_t p_u32AnswerIndex) + { + return answerIP(p_u32AnswerIndex); + } - stcMDNSServiceQuery* pServiceQuery = 0; - if ((p_pcService) && - (os_strlen(p_pcService)) && - (p_pcProtocol) && - (os_strlen(p_pcProtocol)) && - (p_fnCallback) && - ((pServiceQuery = _allocServiceQuery())) && - (_buildDomainForService(p_pcService, p_pcProtocol, pServiceQuery->m_ServiceTypeDomain))) + /* + MDNSResponder::port (LEGACY) + */ + uint16_t MDNSResponder::port(const uint32_t p_u32AnswerIndex) { + return answerPort(p_u32AnswerIndex); + } - pServiceQuery->m_fnCallback = p_fnCallback; - pServiceQuery->m_bLegacyQuery = false; + /** + 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; - if (_sendMDNSServiceQuery(*pServiceQuery)) + stcMDNSServiceQuery* pServiceQuery = 0; + if ((p_pcService) && (os_strlen(p_pcService)) && (p_pcProtocol) && (os_strlen(p_pcProtocol)) + && (p_fnCallback) && ((pServiceQuery = _allocServiceQuery())) + && (_buildDomainForService(p_pcService, p_pcProtocol, + pServiceQuery->m_ServiceTypeDomain))) { - pServiceQuery->m_u8SentCount = 1; - pServiceQuery->m_ResendTimeout.reset(MDNS_DYNAMIC_QUERY_RESEND_DELAY); + pServiceQuery->m_fnCallback = p_fnCallback; + pServiceQuery->m_bLegacyQuery = false; - hResult = (hMDNSServiceQuery)pServiceQuery; - } - else - { - _removeServiceQuery(pServiceQuery); + if (_sendMDNSServiceQuery(*pServiceQuery)) + { + pServiceQuery->m_u8SentCount = 1; + pServiceQuery->m_ResendTimeout.reset(MDNS_DYNAMIC_QUERY_RESEND_DELAY); + + hResult = (hMDNSServiceQuery)pServiceQuery; + } + else + { + _removeServiceQuery(pServiceQuery); + } } + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P( + PSTR("[MDNSResponder] installServiceQuery: %s for '%s.%s'!\n\n"), + (hResult ? "Succeeded" : "FAILED"), (p_pcService ?: "-"), (p_pcProtocol ?: "-"));); + DEBUG_EX_ERR(if (!hResult) { + DEBUG_OUTPUT.printf_P( + PSTR("[MDNSResponder] installServiceQuery: FAILED for '%s.%s'!\n\n"), + (p_pcService ?: "-"), (p_pcProtocol ?: "-")); + }); + return hResult; } - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] installServiceQuery: %s for '%s.%s'!\n\n"), (hResult ? "Succeeded" : "FAILED"), (p_pcService ? : "-"), (p_pcProtocol ? : "-"));); - DEBUG_EX_ERR(if (!hResult) -{ - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] installServiceQuery: FAILED for '%s.%s'!\n\n"), (p_pcService ? : "-"), (p_pcProtocol ? : "-")); - }); - return hResult; -} - -/* - MDNSResponder::removeServiceQuery - Remove a dynamic service query (and all collected answers) from the MDNS responder + /* + MDNSResponder::removeServiceQuery -*/ -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) -{ + Remove a dynamic service query (and all collected answers) from the MDNS responder - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); - return (pServiceQuery ? pServiceQuery->answerCount() : 0); -} + */ + 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; + } -std::vector<MDNSResponder::MDNSServiceInfo> MDNSResponder::answerInfo(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery) -{ - std::vector<MDNSResponder::MDNSServiceInfo> tempVector; - for (uint32_t i = 0; i < answerCount(p_hServiceQuery); i++) + /* + MDNSResponder::answerCount + */ + uint32_t MDNSResponder::answerCount(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery) { - tempVector.emplace_back(*this, p_hServiceQuery, i); + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + return (pServiceQuery ? pServiceQuery->answerCount() : 0); } - return tempVector; -} -/* - MDNSResponder::answerServiceDomain + std::vector<MDNSResponder::MDNSServiceInfo> + MDNSResponder::answerInfo(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery) + { + std::vector<MDNSResponder::MDNSServiceInfo> tempVector; + for (uint32_t i = 0; i < answerCount(p_hServiceQuery); i++) + { + tempVector.emplace_back(*this, p_hServiceQuery, i); + } + return tempVector; + } - Returns the domain for the given service. - If not already existing, the string is allocated, filled and attached to the answer. + /* + MDNSResponder::answerServiceDomain -*/ -const char* MDNSResponder::answerServiceDomain(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) -{ + Returns the domain for the given service. + 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_pcServiceDomain (if not already done) - if ((pSQAnswer) && - (pSQAnswer->m_ServiceDomain.m_u16NameLength) && - (!pSQAnswer->m_pcServiceDomain)) + */ + const char* + MDNSResponder::answerServiceDomain(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex) { - - pSQAnswer->m_pcServiceDomain = pSQAnswer->allocServiceDomain(pSQAnswer->m_ServiceDomain.c_strLength()); - if (pSQAnswer->m_pcServiceDomain) + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery::stcAnswer* pSQAnswer + = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); + // Fill m_pcServiceDomain (if not already done) + if ((pSQAnswer) && (pSQAnswer->m_ServiceDomain.m_u16NameLength) + && (!pSQAnswer->m_pcServiceDomain)) { - pSQAnswer->m_ServiceDomain.c_str(pSQAnswer->m_pcServiceDomain); + pSQAnswer->m_pcServiceDomain + = pSQAnswer->allocServiceDomain(pSQAnswer->m_ServiceDomain.c_strLength()); + if (pSQAnswer->m_pcServiceDomain) + { + pSQAnswer->m_ServiceDomain.c_str(pSQAnswer->m_pcServiceDomain); + } } + return (pSQAnswer ? pSQAnswer->m_pcServiceDomain : 0); } - return (pSQAnswer ? pSQAnswer->m_pcServiceDomain : 0); -} - -/* - MDNSResponder::hasAnswerHostDomain -*/ -bool MDNSResponder::hasAnswerHostDomain(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) -{ - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); - stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - return ((pSQAnswer) && - (pSQAnswer->m_u32ContentFlags & ServiceQueryAnswerType_HostDomainAndPort)); -} + /* + 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)); + } -/* - MDNSResponder::answerHostDomain + /* + MDNSResponder::answerHostDomain - Returns the host domain for the given service. - If not already existing, the string is allocated, filled and attached to the answer. + Returns the host domain for the given service. + If not already existing, the string is allocated, filled and attached to the answer. -*/ -const char* MDNSResponder::answerHostDomain(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) -{ - - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); - stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - // Fill m_pcHostDomain (if not already done) - if ((pSQAnswer) && - (pSQAnswer->m_HostDomain.m_u16NameLength) && - (!pSQAnswer->m_pcHostDomain)) + */ + const char* + MDNSResponder::answerHostDomain(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, + const uint32_t p_u32AnswerIndex) { - - pSQAnswer->m_pcHostDomain = pSQAnswer->allocHostDomain(pSQAnswer->m_HostDomain.c_strLength()); - if (pSQAnswer->m_pcHostDomain) + stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); + stcMDNSServiceQuery::stcAnswer* pSQAnswer + = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); + // Fill m_pcHostDomain (if not already done) + if ((pSQAnswer) && (pSQAnswer->m_HostDomain.m_u16NameLength) + && (!pSQAnswer->m_pcHostDomain)) { - pSQAnswer->m_HostDomain.c_str(pSQAnswer->m_pcHostDomain); + pSQAnswer->m_pcHostDomain + = pSQAnswer->allocHostDomain(pSQAnswer->m_HostDomain.c_strLength()); + if (pSQAnswer->m_pcHostDomain) + { + pSQAnswer->m_HostDomain.c_str(pSQAnswer->m_pcHostDomain); + } } + return (pSQAnswer ? pSQAnswer->m_pcHostDomain : 0); } - return (pSQAnswer ? pSQAnswer->m_pcHostDomain : 0); -} #ifdef MDNS_IP4_SUPPORT -/* - MDNSResponder::hasAnswerIP4Address -*/ -bool MDNSResponder::hasAnswerIP4Address(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex) -{ - - stcMDNSServiceQuery* pServiceQuery = _findServiceQuery(p_hServiceQuery); - stcMDNSServiceQuery::stcAnswer* pSQAnswer = (pServiceQuery ? pServiceQuery->answerAtIndex(p_u32AnswerIndex) : 0); - return ((pSQAnswer) && - (pSQAnswer->m_u32ContentFlags & ServiceQueryAnswerType_IP4Address)); -} - -/* - 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); -} + /* + 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::answerIP4Address -*/ -IPAddress MDNSResponder::answerIP4Address(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::stcIP4Address* pIP4Address = (pSQAnswer ? pSQAnswer->IP4AddressAtIndex(p_u32AddressIndex) : 0); - return (pIP4Address ? pIP4Address->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 #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::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); -} + /* + 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::answerIP6Address -*/ -IPAddress MDNSResponder::answerIP6Address(const MDNSResponder::hMDNSServiceQuery p_hServiceQuery, - const uint32_t p_u32AnswerIndex, - const uint32_t p_u32AddressIndex) -{ + /* + 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); - stcMDNSServiceQuery::stcAnswer::stcIP6Address* pIP6Address = (pSQAnswer ? pSQAnswer->IP6AddressAtIndex(p_u32AddressIndex) : 0); - return (pIP6Address ? pIP6Address->m_IPAddress : IPAddress()); -} + /* + 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::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)); -} - -/* - 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::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. - -*/ -bool MDNSResponder::setHostProbeResultCallback(MDNSResponder::MDNSHostProbeFn p_fnCallback) -{ + /* + PROBING + */ - m_HostProbeInformation.m_fnHostProbeResultCallback = p_fnCallback; + /* + MDNSResponder::setProbeResultCallback - return true; -} + 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. -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); - }); -} - + using namespace std::placeholders; + return setServiceProbeResultCallback( + p_hService, [this, p_fnCallback](const char* p_pcServiceName, + const hMDNSService p_hMDNSService, bool p_bProbeResult) + { p_fnCallback(*this, p_pcServiceName, p_hMDNSService, p_bProbeResult); }); + } -/* - MISC -*/ + /* + MISC + */ -/* - MDNSResponder::notifyAPChange + /* + 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. + Should be called, whenever the AP for the MDNS responder changes. + A bit of this is caught by the event callbacks installed in the constructor. -*/ -bool MDNSResponder::notifyAPChange(void) -{ + */ + bool MDNSResponder::notifyAPChange(void) { return _restart(); } - return _restart(); -} + /* + MDNSResponder::update -/* - MDNSResponder::update + Should be called in every 'loop'. - Should be called in every 'loop'. + */ + bool MDNSResponder::update(void) { return _process(true); } -*/ -bool MDNSResponder::update(void) -{ - return _process(true); -} + /* + MDNSResponder::announce -/* - MDNSResponder::announce + Should be called, if the 'configuration' changes. Mainly this will be changes in the TXT + items... + */ + bool MDNSResponder::announce(void) { return (_announce(true, true)); } - Should be called, if the 'configuration' changes. Mainly this will be changes in the TXT items... -*/ -bool MDNSResponder::announce(void) -{ + /* + MDNSResponder::enableArduino - return (_announce(true, true)); -} + Enable the OTA update service. -/* - MDNSResponder::enableArduino - - Enable the OTA update service. - -*/ -MDNSResponder::hMDNSService MDNSResponder::enableArduino(uint16_t p_u16Port, - bool p_bAuthUpload /*= false*/) -{ - - hMDNSService hService = addService(0, "arduino", "tcp", p_u16Port); - if (hService) + */ + MDNSResponder::hMDNSService MDNSResponder::enableArduino(uint16_t p_u16Port, + bool p_bAuthUpload /*= false*/) { - if ((!addServiceTxt(hService, "tcp_check", "no")) || - (!addServiceTxt(hService, "ssh_upload", "no")) || - (!addServiceTxt(hService, "board", STRINGIZE_VALUE_OF(ARDUINO_BOARD))) || - (!addServiceTxt(hService, "auth_upload", (p_bAuthUpload) ? "yes" : "no"))) + hMDNSService hService = addService(0, "arduino", "tcp", p_u16Port); + if (hService) { - - removeService(hService); - hService = 0; + if ((!addServiceTxt(hService, "tcp_check", "no")) + || (!addServiceTxt(hService, "ssh_upload", "no")) + || (!addServiceTxt(hService, "board", STRINGIZE_VALUE_OF(ARDUINO_BOARD))) + || (!addServiceTxt(hService, "auth_upload", (p_bAuthUpload) ? "yes" : "no"))) + { + removeService(hService); + hService = 0; + } } + return hService; } - return hService; -} -/* + /* - MULTICAST GROUPS + 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..0b02f69bc8 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<u32AnswerCount; ++u) { const char* pHostname = MDNS.answerHostname(u); }' - You should call MDNS.removeQuery() sometimes later (when the answers are not needed anymore) + Iterate answers by: 'for (uint32_t u=0; u<u32AnswerCount; ++u) { const char* pHostname = + MDNS.answerHostname(u); }' You should call MDNS.removeQuery() sometimes later (when the answers + are not needed anymore) Dynamic: - Install a dynamic query by calling 'DNSResponder::hMDNSServiceQuery hServiceQuery = MDNS.installServiceQuery("http", "tcp", serviceQueryCallback, &userData);' - The callback 'serviceQueryCallback(MDNSResponder* p_MDNSResponder, const hMDNSServiceQuery p_hServiceQuery, uint32_t p_u32AnswerIndex, - enuServiceQueryAnswerType p_ServiceQueryAnswerType, bool p_bSetContent, void* p_pUserdata)' - is called for any change in the answer set. - Call 'MDNS.removeServiceQuery(hServiceQuery);' when the answers are not needed anymore + Install a dynamic query by calling 'DNSResponder::hMDNSServiceQuery hServiceQuery = + MDNS.installServiceQuery("http", "tcp", serviceQueryCallback, &userData);' The callback + 'serviceQueryCallback(MDNSResponder* p_MDNSResponder, const hMDNSServiceQuery p_hServiceQuery, + uint32_t p_u32AnswerIndex, enuServiceQueryAnswerType p_ServiceQueryAnswerType, bool + p_bSetContent, void* p_pUserdata)' is called for any change in the answer set. Call + 'MDNS.removeServiceQuery(hServiceQuery);' when the answers are not needed anymore Reference: @@ -69,9 +79,9 @@ 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 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 - 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 + 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 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 Some NOT used message types: OPT (0x29): eDNS @@ -102,7 +112,7 @@ #ifndef MDNS_H #define MDNS_H -#include <functional> // for UdpContext.h +#include <functional> // for UdpContext.h #include "WiFiUdp.h" #include "lwip/udp.h" #include "debug.h" @@ -111,20 +121,16 @@ #include <PolledTimeout.h> #include <map> - #include "ESP8266WiFi.h" - namespace esp8266 { - /** LEAmDNS */ 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 +141,1242 @@ 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); - /** - hMDNSTxt (opaque handle to access the TXT items) - */ - typedef void* hMDNSTxt; + // 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); } - // Add a (static) MDNS TXT item ('key' = 'value') to the service - hMDNSTxt addServiceTxt(const hMDNSService p_hService, - const char* p_pcKey, + /** + 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()); } + + /** + 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<void(const hMDNSService p_hService)> 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<void(const hMDNSService p_hService)> + 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<void(const MDNSServiceInfo& mdnsServiceInfo, - AnswerType answerType, // flag for the updated answer item - bool p_bSetContent // true: Answer component set, false: component deleted - )> MDNSServiceQueryCallbackFunc; - - // Install a dynamic service query. For every received answer (part) the given callback - // function is called. The query will be updated every time, the TTL for an answer - // 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<MDNSResponder::MDNSServiceInfo> 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<void( + const MDNSServiceInfo& mdnsServiceInfo, + AnswerType answerType, // flag for the updated answer item + bool p_bSetContent // true: Answer component set, false: component deleted + )> + MDNSServiceQueryCallbackFunc; + + // Install a dynamic service query. For every received answer (part) the given callback + // function is called. The query will be updated every time, the TTL for an answer + // 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<MDNSResponder::MDNSServiceInfo> + 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<void(const char* p_pcDomainName, - bool p_bProbeResult)> MDNSHostProbeFn; - - typedef std::function<void(MDNSResponder& resp, - const char* p_pcDomainName, - bool p_bProbeResult)> MDNSHostProbeFn1; - - typedef std::function<void(const char* p_pcServiceName, - const hMDNSService p_hMDNSService, - bool p_bProbeResult)> MDNSServiceProbeFn; - - typedef std::function<void(MDNSResponder& resp, - const char* p_pcServiceName, - const hMDNSService p_hMDNSService, - bool p_bProbeResult)> MDNSServiceProbeFn1; - - // Set a global callback function for host and service probe results - // The callback function is called, when the probing for the host domain - // (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<void(const char* p_pcDomainName, bool p_bProbeResult)> + MDNSHostProbeFn; + + typedef std::function<void(MDNSResponder& resp, const char* p_pcDomainName, + bool p_bProbeResult)> + MDNSHostProbeFn1; + + typedef std::function<void(const char* p_pcServiceName, const hMDNSService p_hMDNSService, + bool p_bProbeResult)> + MDNSServiceProbeFn; + + typedef std::function<void(MDNSResponder& resp, const char* p_pcServiceName, + const hMDNSService p_hMDNSService, bool p_bProbeResult)> + MDNSServiceProbeFn1; + + // Set a global callback function for host and service probe results + // The callback function is called, when the probing for the host domain + // (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<const char*, const char*, CompareKey>; + + protected: + MDNSResponder& p_pMDNSResponder; + MDNSResponder::hMDNSServiceQuery p_hServiceQuery; + uint32_t p_u32AnswerIndex; + KeyValueMap keyValueMap; + + public: + const char* serviceDomain() { - return strcmp(a, b) < 0; + return p_pMDNSResponder.answerServiceDomain(p_hServiceQuery, p_u32AnswerIndex); + }; + bool hostDomainAvailable() + { + return (p_pMDNSResponder.hasAnswerHostDomain(p_hServiceQuery, p_u32AnswerIndex)); } - }; - using KeyValueMap = std::map<const char*, const char*, CompareKey>; - 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<IPAddress> IP4Adresses() - { - std::vector<IPAddress> 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<IPAddress> IP4Adresses() { - uint16_t cntIP4Adress = p_pMDNSResponder.answerIP4AddressCount(p_hServiceQuery, p_u32AnswerIndex); - for (uint32_t u2 = 0; u2 < cntIP4Adress; ++u2) + std::vector<IPAddress> internalIP; + if (IP4AddressAvailable()) { - internalIP.emplace_back(p_pMDNSResponder.answerIP4Address(p_hServiceQuery, p_u32AnswerIndex, u2)); + uint16_t cntIP4Adress + = p_pMDNSResponder.answerIP4AddressCount(p_hServiceQuery, p_u32AnswerIndex); + for (uint32_t u2 = 0; u2 < cntIP4Adress; ++u2) + { + internalIP.emplace_back(p_pMDNSResponder.answerIP4Address( + p_hServiceQuery, p_u32AnswerIndex, u2)); + } } + return internalIP; + }; + bool txtAvailable() + { + return (p_pMDNSResponder.hasAnswerTxts(p_hServiceQuery, p_u32AnswerIndex)); } - return internalIP; - }; - bool txtAvailable() - { - return (p_pMDNSResponder.hasAnswerTxts(p_hServiceQuery, p_u32AnswerIndex)); - } - const char* strKeyValue() - { - return (txtAvailable()) ? - p_pMDNSResponder.answerTxts(p_hServiceQuery, p_u32AnswerIndex) : nullptr; - }; - const KeyValueMap& keyValues() - { - if (txtAvailable() && keyValueMap.size() == 0) + const char* strKeyValue() + { + return (txtAvailable()) ? + p_pMDNSResponder.answerTxts(p_hServiceQuery, p_u32AnswerIndex) : + nullptr; + }; + const KeyValueMap& keyValues() { - for (auto kv = p_pMDNSResponder._answerKeyValue(p_hServiceQuery, p_u32AnswerIndex); kv != nullptr; kv = kv->m_pNext) + if (txtAvailable() && keyValueMap.size() == 0) { - keyValueMap.emplace(std::pair<const char*, const char*>(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<const char*, const char*>(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; + + stcMDNS_RRHeader(void); + stcMDNS_RRHeader(const stcMDNS_RRHeader& p_Other); - virtual ~stcMDNS_RRAnswer(void); + stcMDNS_RRHeader& operator=(const stcMDNS_RRHeader& p_Other); - enuAnswerType answerType(void) const; + bool clear(void); + }; - bool clear(void); + /** + stcMDNS_RRQuestion + */ + struct stcMDNS_RRQuestion + { + stcMDNS_RRQuestion* m_pNext; + stcMDNS_RRHeader m_Header; + bool m_bUnicast; // Unicast reply requested - protected: - stcMDNS_RRAnswer(enuAnswerType p_AnswerType, - const stcMDNS_RRHeader& p_Header, - uint32_t p_u32TTL); - }; + 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..b1cc05faaf 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" } @@ -48,2085 +49,2301 @@ namespace esp8266 */ namespace MDNSImplementation { + /** + CONTROL + */ -/** - CONTROL -*/ - - -/** - MAINTENANCE -*/ - -/* - MDNSResponder::_process - - 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 - 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, ... + /* + MDNSResponder::_parseQuery - 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). + 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 - 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) - { - // 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) + stcMDNS_RRQuestion questionRR; + if ((bResult = _readRRQuestion(questionRR))) { - 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)) - { - 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)) + if (AnswerType_PTR == pKnownRRAnswer->answerType()) { - 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 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(DEBUG_OUTPUT.printf_P( + PSTR("[MDNSResponder] _parseQuery: UNSOLVED tiebreak-need for host domain!\n"));); + m_HostProbeInformation.m_bTiebreakNeeded = false; } + for (stcMDNSService* pService = m_pServices; pService; pService = pService->m_pNext) + { + if (pService->m_ProbeInformation.m_bTiebreakNeeded) + { + DEBUG_EX_ERR( + DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: UNSOLVED " + "tiebreak-need for service domain (%s.%s.%s)\n"), + (pService->m_pcName ?: m_pcHostname), + pService->m_pcService, pService->m_pcProtocol);); + pService->m_ProbeInformation.m_bTiebreakNeeded = false; + } + } + DEBUG_EX_ERR(if (!bResult) + { DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseQuery: FAILED!\n")); }); + return bResult; } - 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)) { - delete pRRAnswer; - pRRAnswer = 0; + // DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse: + // ADDING answer!\n"));); + pRRAnswer->m_pNext = pCollectedRRAnswers; + pCollectedRRAnswers = pRRAnswer; + } + else + { + 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) && (qd<p_MsgHeader.m_u16QDCount)); ++qd) { + stcMDNS_RRQuestion questionRR; + bDumpResult = _readRRQuestion(questionRR); + esp_suspend(); + } // for questions + // Handle known answers + uint32_t u32Answers = (p_MsgHeader.m_u16ANCount + p_MsgHeader.m_u16NSCount + + p_MsgHeader.m_u16ARCount); for (uint32_t an=0; ((bDumpResult) && (an<u32Answers)); + ++an) { stcMDNS_RRAnswer* pRRAnswer = 0; bDumpResult = _readRRAnswer(pRRAnswer); if + (pRRAnswer) { delete pRRAnswer; pRRAnswer = 0; + } + esp_suspend(); + } + );*/ m_pUDPContext->flush(); + 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; - } + DEBUG_EX_ERR(if (!bResult) + { DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _parseResponse: FAILED!\n")); }); + return bResult; } - else // Received an unexpected response -> ignore + + /* + 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) { - /* 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) && (qd<p_MsgHeader.m_u16QDCount)); ++qd) { - stcMDNS_RRQuestion questionRR; - bDumpResult = _readRRQuestion(questionRR); - esp_suspend(); - } // for questions - // Handle known answers - uint32_t u32Answers = (p_MsgHeader.m_u16ANCount + p_MsgHeader.m_u16NSCount + p_MsgHeader.m_u16ARCount); - for (uint32_t an=0; ((bDumpResult) && (an<u32Answers)); ++an) { - stcMDNS_RRAnswer* pRRAnswer = 0; - bDumpResult = _readRRAnswer(pRRAnswer); - if (pRRAnswer) { - delete pRRAnswer; - pRRAnswer = 0; - } - esp_suspend(); - } - );*/ - m_pUDPContext->flush(); - bResult = true; - } - 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 - -*/ -bool MDNSResponder::_processAnswers(const MDNSResponder::stcMDNS_RRAnswer* p_pAnswers) -{ - - bool bResult = false; + 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 - { - pSQAnswer->m_TTLServiceDomain.set(p_pPTRAnswer->m_u32TTL); // Update TTL tag - DEBUG_EX_INFO( - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processPTRAnswer: Updated TTL(%d) for "), (int)p_pPTRAnswer->m_u32TTL); - _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR("\n")); - ); - } - else // received goodbye-message + // Find answer for service domain (eg. MyESP._http._tcp.local) + stcMDNSServiceQuery::stcAnswer* pSQAnswer + = pServiceQuery->findAnswerForServiceDomain(p_pPTRAnswer->m_PTRDomain); + if (pSQAnswer) // existing answer { - pSQAnswer->m_TTLServiceDomain.prepareDeletion(); // Prepare answer deletion according to RFC 6762, 10.1 - DEBUG_EX_INFO( - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processPTRAnswer: 'Goodbye' received for ")); - _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR("\n")); - ); + if (p_pPTRAnswer->m_u32TTL) // Received update message + { + pSQAnswer->m_TTLServiceDomain.set( + p_pPTRAnswer->m_u32TTL); // Update TTL tag + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P( + PSTR("[MDNSResponder] _processPTRAnswer: Updated TTL(%d) for "), + (int)p_pPTRAnswer->m_u32TTL); + _printRRDomain(pSQAnswer->m_ServiceDomain); + DEBUG_OUTPUT.printf_P(PSTR("\n"));); + } + else // received goodbye-message + { + pSQAnswer->m_TTLServiceDomain + .prepareDeletion(); // Prepare answer deletion according to RFC + // 6762, 10.1 + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P( + PSTR("[MDNSResponder] _processPTRAnswer: 'Goodbye' received for ")); + _printRRDomain(pSQAnswer->m_ServiceDomain); + DEBUG_OUTPUT.printf_P(PSTR("\n"));); + } } - } - else if ((p_pPTRAnswer->m_u32TTL) && // Not just a goodbye-message - ((pSQAnswer = new stcMDNSServiceQuery::stcAnswer))) // Not yet included -> add answer - { - pSQAnswer->m_ServiceDomain = p_pPTRAnswer->m_PTRDomain; - pSQAnswer->m_u32ContentFlags |= ServiceQueryAnswerType_ServiceDomain; - pSQAnswer->m_TTLServiceDomain.set(p_pPTRAnswer->m_u32TTL); - pSQAnswer->releaseServiceDomain(); - - bResult = pServiceQuery->addAnswer(pSQAnswer); - p_rbFoundNewKeyAnswer = true; - if (pServiceQuery->m_fnCallback) + else if ((p_pPTRAnswer->m_u32TTL) && // Not just a goodbye-message + ((pSQAnswer + = new stcMDNSServiceQuery::stcAnswer))) // Not yet included -> add + // answer { - MDNSServiceInfo serviceInfo(*this, (hMDNSServiceQuery)pServiceQuery, pServiceQuery->indexOfAnswer(pSQAnswer)); - pServiceQuery->m_fnCallback(serviceInfo, static_cast<AnswerType>(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<AnswerType>(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<AnswerType>(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<AnswerType>( + 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<AnswerType>(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<AnswerType>(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 + stcMDNSServiceQuery::stcAnswer::stcIP4Address* pIP4Address + = pSQAnswer->findIP4Address(p_pAAnswer->m_IPAddress); + if (pIP4Address) { - pIP4Address->m_TTL.set(p_pAAnswer->m_u32TTL); - DEBUG_EX_INFO( - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAAnswer: Updated TTL(%d) for "), (int)p_pAAnswer->m_u32TTL); - _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR(" IP4Address (%s)\n"), pIP4Address->m_IPAddress.toString().c_str()); - ); - } - else // 'Goodbye' message for known IP4 address - { - pIP4Address->m_TTL.prepareDeletion(); // Prepare answer deletion according to RFC 6762, 10.1 - DEBUG_EX_INFO( - DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _processAAnswer: 'Goodbye' received for ")); - _printRRDomain(pSQAnswer->m_ServiceDomain); - DEBUG_OUTPUT.printf_P(PSTR(" IP4 address (%s)\n"), pIP4Address->m_IPAddress.toString().c_str()); - ); + // Already known IP4 address + if (p_pAAnswer->m_u32TTL) // Valid TTL -> Update answers TTL + { + pIP4Address->m_TTL.set(p_pAAnswer->m_u32TTL); + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P( + PSTR("[MDNSResponder] _processAAnswer: Updated TTL(%d) for "), + (int)p_pAAnswer->m_u32TTL); + _printRRDomain(pSQAnswer->m_ServiceDomain); + DEBUG_OUTPUT.printf_P( + PSTR(" IP4Address (%s)\n"), + pIP4Address->m_IPAddress.toString().c_str());); + } + else // 'Goodbye' message for known IP4 address + { + pIP4Address->m_TTL.prepareDeletion(); // Prepare answer deletion + // according to RFC 6762, 10.1 + DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P( + PSTR("[MDNSResponder] _processAAnswer: 'Goodbye' received for ")); + _printRRDomain(pSQAnswer->m_ServiceDomain); + DEBUG_OUTPUT.printf_P( + PSTR(" IP4 address (%s)\n"), + pIP4Address->m_IPAddress.toString().c_str());); + } } - } - else - { - // Until now unknown IP4 address -> Add (if the message isn't just a 'Goodbye' note) - if (p_pAAnswer->m_u32TTL) // NOT just a 'Goodbye' message + else { - pIP4Address = new stcMDNSServiceQuery::stcAnswer::stcIP4Address(p_pAAnswer->m_IPAddress, p_pAAnswer->m_u32TTL); - if ((pIP4Address) && - (pSQAnswer->addIP4Address(pIP4Address))) + // Until now unknown IP4 address -> Add (if the message isn't just a + // 'Goodbye' note) + if (p_pAAnswer->m_u32TTL) // NOT just a 'Goodbye' message { - - pSQAnswer->m_u32ContentFlags |= ServiceQueryAnswerType_IP4Address; - if (pServiceQuery->m_fnCallback) + pIP4Address = new stcMDNSServiceQuery::stcAnswer::stcIP4Address( + p_pAAnswer->m_IPAddress, p_pAAnswer->m_u32TTL); + if ((pIP4Address) && (pSQAnswer->addIP4Address(pIP4Address))) { - MDNSServiceInfo serviceInfo(*this, (hMDNSServiceQuery)pServiceQuery, pServiceQuery->indexOfAnswer(pSQAnswer)); - pServiceQuery->m_fnCallback(serviceInfo, static_cast<AnswerType>(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<AnswerType>(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) + Conflict management is handled in '_parseResponse ff.' + Tiebraking is handled in 'parseQuery ff.' + */ + bool MDNSResponder::_updateProbeStatus(void) { - DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _updateProbeStatus: Starting host probing...\n"));); + bool bResult = true; - // 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 - { - - 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 - - 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); + /* + MDNSResponder::_resetProbeStatus - 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; -} + m_HostProbeInformation.clear(false); + m_HostProbeInformation.m_ProbingStatus + = (p_bRestart ? ProbingStatus_ReadyToStart : ProbingStatus_Done); -/* - MDNSResponder::_hasProbesWaitingForAnswers -*/ -bool MDNSResponder::_hasProbesWaitingForAnswers(void) const -{ - - bool bResult = ((ProbingStatus_InProgress == m_HostProbeInformation.m_ProbingStatus) && // Probing - (0 < m_HostProbeInformation.m_u8SentCount)); // And really probing + for (stcMDNSService* pService = m_pServices; 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 - } - return bResult; -} + bool bResult + = ((ProbingStatus_InProgress == m_HostProbeInformation.m_ProbingStatus) && // Probing + (0 < m_HostProbeInformation.m_u8SentCount)); // And really probing -/* - MDNSResponder::_sendHostProbe + 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; + } - Asks (probes) in the local network for the planned host domain - - (eg. esp8266.local) + /* + MDNSResponder::_sendHostProbe - 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());); + Asks (probes) in the local network for the planned host domain + - (eg. esp8266.local) - bool bResult = true; + 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());); - // Requests for host domain - stcMDNSSendParameter sendParameter; - sendParameter.m_bCacheFlush = false; // RFC 6762 10.2 + bool bResult = true; - sendParameter.m_pQuestions = new stcMDNS_RRQuestion; - if (((bResult = (0 != sendParameter.m_pQuestions))) && - ((bResult = _buildDomainForHost(m_pcHostname, sendParameter.m_pQuestions->m_Header.m_Domain)))) - { + // Requests for host domain + stcMDNSSendParameter sendParameter; + sendParameter.m_bCacheFlush = false; // RFC 6762 10.2 - //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<AnswerType>(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<AnswerType>(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<AnswerType>(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<AnswerType>(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<AnswerType>(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<AnswerType>(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<AnswerType>(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<AnswerType>(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..07c3b27dd8 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS_Helpers.cpp +++ b/libraries/ESP8266mDNS/src/LEAmDNS_Helpers.cpp @@ -23,7 +23,7 @@ */ #include <lwip/igmp.h> -#include <stdlib_noniso.h> // strrstr() +#include <stdlib_noniso.h> // strrstr() #include "ESP8266mDNS.h" #include "LEAmDNS_lwIPdefs.h" @@ -31,60 +31,84 @@ namespace esp8266 { - /* LEAmDNS */ namespace MDNSImplementation { + /** + HELPERS + */ -/** - HELPERS -*/ - -/* - MDNSResponder::indexDomain (static) - - 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 +117,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)); - } - else - { - return false; + return true; } - 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)) + { + pPred = pPred->m_pNext; + } + if (pPred) { - m_pServices = p_pService->m_pNext; + pPred->m_pNext = p_pService->m_pNext; delete p_pService; bResult = true; } - else + else // No predecessor { - DEBUG_EX_ERR(DEBUG_OUTPUT.println("[MDNSResponder] _releaseService: INVALID service!");); + if (m_pServices == p_pService) + { + m_pServices = p_pService->m_pNext; + delete p_pService; + bResult = true; + } + else + { + DEBUG_EX_ERR( + DEBUG_OUTPUT.println("[MDNSResponder] _releaseService: INVALID service!");); + } } } + return bResult; } - return bResult; -} - -/* - MDNSResponder::_releaseServices -*/ -bool MDNSResponder::_releaseServices(void) -{ - stcMDNSService* pService = m_pServices; - while (pService) + /* + 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) -{ + /* + SERVICE TXT + */ - stcMDNSServiceTxt* pTxt = 0; - - if ((p_pService) && - (p_pcKey) && - (MDNS_SERVICE_TXT_MAXLENGTH > (p_pService->m_Txts.length() + - 1 + // Length byte - (p_pcKey ? strlen(p_pcKey) : 0) + - 1 + // '=' - (p_pcValue ? strlen(p_pcValue) : 0)))) + /* + MDNSResponder::_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) - { - m_fnServiceTxtCallback((hMDNSService)&p_rService); - } - if (p_rService.m_fnTxtCallback) + /* + MDNSResponder::_releaseTempServiceTxts + */ + bool MDNSResponder::_releaseTempServiceTxts(MDNSResponder::stcMDNSService& p_rService) { - p_rService.m_fnTxtCallback((hMDNSService)&p_rService); + return (p_rService.m_Txts.removeTempTxts()); } - 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..7b7345e62b 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS_Priv.h +++ b/libraries/ESP8266mDNS/src/LEAmDNS_Priv.h @@ -27,17 +27,15 @@ namespace esp8266 { - /* LEAmDNS */ 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 +46,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 +61,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 +71,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 +87,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 +125,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 +181,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..b0499abde6 100644 --- a/libraries/ESP8266mDNS/src/LEAmDNS_Structs.cpp +++ b/libraries/ESP8266mDNS/src/LEAmDNS_Structs.cpp @@ -28,2460 +28,2224 @@ namespace esp8266 { - /* LEAmDNS */ namespace MDNSImplementation { + /** + STRUCTS + */ -/** - 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) -{ - - setKey(p_pcKey); - setValue(p_pcValue); -} - -/* - MDNSResponder::stcMDNSServiceTxt::stcMDNSServiceTxt copy-constructor -*/ -MDNSResponder::stcMDNSServiceTxt::stcMDNSServiceTxt(const MDNSResponder::stcMDNSServiceTxt& p_Other) - : m_pNext(0), - m_pcKey(0), - m_pcValue(0), - m_bTemp(false) -{ - - operator=(p_Other); -} - -/* - MDNSResponder::stcMDNSServiceTxt::~stcMDNSServiceTxt destructor -*/ -MDNSResponder::stcMDNSServiceTxt::~stcMDNSServiceTxt(void) -{ - - clear(); -} + /** + MDNSResponder::stcMDNSServiceTxt -/* - MDNSResponder::stcMDNSServiceTxt::operator= -*/ -MDNSResponder::stcMDNSServiceTxt& MDNSResponder::stcMDNSServiceTxt::operator=(const MDNSResponder::stcMDNSServiceTxt& p_Other) -{ + 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. + */ - if (&p_Other != this) + /* + 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) { - clear(); - set(p_Other.m_pcKey, p_Other.m_pcValue, p_Other.m_bTemp); + setKey(p_pcKey); + setValue(p_pcValue); } - return *this; -} -/* - MDNSResponder::stcMDNSServiceTxt::clear -*/ -bool MDNSResponder::stcMDNSServiceTxt::clear(void) -{ - - releaseKey(); - releaseValue(); - return true; -} + /* + 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::allocKey -*/ -char* MDNSResponder::stcMDNSServiceTxt::allocKey(size_t p_stLength) -{ + /* + MDNSResponder::stcMDNSServiceTxt::~stcMDNSServiceTxt destructor + */ + MDNSResponder::stcMDNSServiceTxt::~stcMDNSServiceTxt(void) { clear(); } - 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) - { - pPred->m_pNext = p_pTxt->m_pNext; - delete p_pTxt; - bResult = true; - } - else if (m_pTxts == p_pTxt) // No predecessor, but first item + if (this != &p_Other) { - m_pTxts = 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)); + } } + return *this; } - return bResult; -} - -/* - MDNSResponder::stcMDNSServiceTxts::removeTempTxts -*/ -bool MDNSResponder::stcMDNSServiceTxts::removeTempTxts(void) -{ - bool bResult = true; - - stcMDNSServiceTxt* pTxt = m_pTxts; - while ((bResult) && - (pTxt)) + /* + MDNSResponder::stcMDNSServiceTxts::clear + */ + bool MDNSResponder::stcMDNSServiceTxts::clear(void) { - stcMDNSServiceTxt* pNext = pTxt->m_pNext; - if (pTxt->m_bTemp) + while (m_pTxts) { - bResult = remove(pTxt); + stcMDNSServiceTxt* pNext = m_pTxts->m_pNext; + delete m_pTxts; + m_pTxts = pNext; } - pTxt = pNext; + return true; } - return bResult; -} - -/* - MDNSResponder::stcMDNSServiceTxts::find -*/ -MDNSResponder::stcMDNSServiceTxt* MDNSResponder::stcMDNSServiceTxts::find(const char* p_pcKey) -{ - - stcMDNSServiceTxt* pResult = 0; - for (stcMDNSServiceTxt* pTxt = m_pTxts; pTxt; pTxt = pTxt->m_pNext) + /* + MDNSResponder::stcMDNSServiceTxts::add + */ + bool MDNSResponder::stcMDNSServiceTxts::add(MDNSResponder::stcMDNSServiceTxt* p_pTxt) { - if ((p_pcKey) && - (0 == strcmp(pTxt->m_pcKey, p_pcKey))) + bool bResult = false; + + if (p_pTxt) { - pResult = pTxt; - break; + p_pTxt->m_pNext = m_pTxts; + m_pTxts = p_pTxt; + bResult = true; } + return bResult; } - return pResult; -} - -/* - MDNSResponder::stcMDNSServiceTxts::find -*/ -const MDNSResponder::stcMDNSServiceTxt* MDNSResponder::stcMDNSServiceTxts::find(const char* p_pcKey) const -{ - - const stcMDNSServiceTxt* pResult = 0; - for (const stcMDNSServiceTxt* pTxt = m_pTxts; pTxt; pTxt = pTxt->m_pNext) + /* + MDNSResponder::stcMDNSServiceTxts::remove + */ + bool MDNSResponder::stcMDNSServiceTxts::remove(stcMDNSServiceTxt* p_pTxt) { - if ((p_pcKey) && - (0 == strcmp(pTxt->m_pcKey, p_pcKey))) - { + bool bResult = false; - pResult = pTxt; - break; + 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; } - return pResult; -} -/* - MDNSResponder::stcMDNSServiceTxts::find -*/ -MDNSResponder::stcMDNSServiceTxt* MDNSResponder::stcMDNSServiceTxts::find(const stcMDNSServiceTxt* p_pTxt) -{ + /* + MDNSResponder::stcMDNSServiceTxts::removeTempTxts + */ + bool MDNSResponder::stcMDNSServiceTxts::removeTempTxts(void) + { + bool bResult = true; - stcMDNSServiceTxt* pResult = 0; + stcMDNSServiceTxt* pTxt = m_pTxts; + while ((bResult) && (pTxt)) + { + stcMDNSServiceTxt* pNext = pTxt->m_pNext; + if (pTxt->m_bTemp) + { + bResult = remove(pTxt); + } + pTxt = pNext; + } + return bResult; + } - for (stcMDNSServiceTxt* pTxt = m_pTxts; pTxt; pTxt = pTxt->m_pNext) + /* + MDNSResponder::stcMDNSServiceTxts::find + */ + MDNSResponder::stcMDNSServiceTxt* MDNSResponder::stcMDNSServiceTxts::find(const char* p_pcKey) { - if (p_pTxt == pTxt) + stcMDNSServiceTxt* pResult = 0; + + for (stcMDNSServiceTxt* pTxt = m_pTxts; pTxt; pTxt = pTxt->m_pNext) { - pResult = pTxt; - break; + if ((p_pcKey) && (0 == strcmp(pTxt->m_pcKey, p_pcKey))) + { + pResult = pTxt; + break; + } } + return pResult; } - return pResult; -} -/* - MDNSResponder::stcMDNSServiceTxts::length -*/ -uint16_t MDNSResponder::stcMDNSServiceTxts::length(void) const -{ + /* + MDNSResponder::stcMDNSServiceTxts::find + */ + const MDNSResponder::stcMDNSServiceTxt* + MDNSResponder::stcMDNSServiceTxts::find(const char* p_pcKey) const + { + const stcMDNSServiceTxt* pResult = 0; - uint16_t u16Length = 0; + 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; + } - stcMDNSServiceTxt* pTxt = m_pTxts; - while (pTxt) + /* + MDNSResponder::stcMDNSServiceTxts::find + */ + MDNSResponder::stcMDNSServiceTxt* + MDNSResponder::stcMDNSServiceTxts::find(const stcMDNSServiceTxt* p_pTxt) { - u16Length += 1; // Length byte - u16Length += pTxt->length(); // Text - pTxt = pTxt->m_pNext; - } - return u16Length; -} + stcMDNSServiceTxt* pResult = 0; -/* - MDNSResponder::stcMDNSServiceTxts::c_strLength + for (stcMDNSServiceTxt* pTxt = m_pTxts; pTxt; pTxt = pTxt->m_pNext) + { + if (p_pTxt == pTxt) + { + pResult = pTxt; + break; + } + } + return pResult; + } - (incl. closing '\0'). Length bytes place is used for delimiting ';' and closing '\0' -*/ -size_t MDNSResponder::stcMDNSServiceTxts::c_strLength(void) const -{ + /* + MDNSResponder::stcMDNSServiceTxts::length + */ + uint16_t MDNSResponder::stcMDNSServiceTxts::length(void) const + { + uint16_t u16Length = 0; - return length(); -} + stcMDNSServiceTxt* pTxt = m_pTxts; + while (pTxt) + { + u16Length += 1; // Length byte + u16Length += pTxt->length(); // Text + pTxt = pTxt->m_pNext; + } + return u16Length; + } -/* - MDNSResponder::stcMDNSServiceTxts::c_str -*/ -bool MDNSResponder::stcMDNSServiceTxts::c_str(char* p_pcBuffer) -{ + /* + MDNSResponder::stcMDNSServiceTxts::c_strLength - bool bResult = false; + (incl. closing '\0'). Length bytes place is used for delimiting ';' and closing '\0' + */ + size_t MDNSResponder::stcMDNSServiceTxts::c_strLength(void) const { return length(); } - 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) + size_t stLength; + if ((bResult = (0 != (stLength = (pTxt->m_pcKey ? strlen(pTxt->m_pcKey) : 0))))) { - *p_pcBuffer++ = ';'; - } - strncpy(p_pcBuffer, pTxt->m_pcKey, stLength); p_pcBuffer[stLength] = 0; - p_pcBuffer += stLength; - *p_pcBuffer++ = '='; - if ((stLength = (pTxt->m_pcValue ? strlen(pTxt->m_pcValue) : 0))) - { - strncpy(p_pcBuffer, pTxt->m_pcValue, stLength); 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 -{ + /* + MDNSResponder::stcMDNSServiceTxts::operator== + */ + bool MDNSResponder::stcMDNSServiceTxts::operator==(const stcMDNSServiceTxts& p_Other) const + { + return compare(p_Other); + } - 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::stcMDNS_MsgHeader - return !compare(p_Other); -} + A MDNS message header. + */ -/** - MDNSResponder::stcMDNS_MsgHeader + /* + 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) + { + } - A MDNS message header. + /** + 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_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(); -} - -/* - 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::operator = -*/ -MDNSResponder::stcMDNS_RRDomain& MDNSResponder::stcMDNS_RRDomain::operator=(const stcMDNS_RRDomain& p_Other) -{ + /* + MDNSResponder::stcMDNS_RRDomain::stcMDNS_RRDomain constructor + */ + MDNSResponder::stcMDNS_RRDomain::stcMDNS_RRDomain(void) : m_u16NameLength(0) { clear(); } - if (&p_Other != this) + /* + MDNSResponder::stcMDNS_RRDomain::stcMDNS_RRDomain copy-constructor + */ + MDNSResponder::stcMDNS_RRDomain::stcMDNS_RRDomain(const stcMDNS_RRDomain& p_Other) : + m_u16NameLength(0) { - memcpy(m_acName, p_Other.m_acName, sizeof(m_acName)); - m_u16NameLength = p_Other.m_u16NameLength; + operator=(p_Other); } - 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::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 + /* + MDNSResponder::stcMDNS_RRDomain::c_str + */ + bool MDNSResponder::stcMDNS_RRDomain::c_str(char* p_pcBuffer) + { + bool bResult = false; - A MDNS attributes object. + 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 -/* - 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) -{ + A MDNS attributes object. -} + */ -/* - MDNSResponder::stcMDNS_RRAttributes::stcMDNS_RRAttributes copy-constructor -*/ -MDNSResponder::stcMDNS_RRAttributes::stcMDNS_RRAttributes(const MDNSResponder::stcMDNS_RRAttributes& p_Other) -{ - - operator=(p_Other); -} - -/* - MDNSResponder::stcMDNS_RRAttributes::operator = -*/ -MDNSResponder::stcMDNS_RRAttributes& MDNSResponder::stcMDNS_RRAttributes::operator=(const MDNSResponder::stcMDNS_RRAttributes& p_Other) -{ - - if (&p_Other != this) + /* + MDNSResponder::stcMDNS_RRAttributes::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_RRAnswerGeneric - - An unknown (generic) MDNS answer object. - Extends the base class by a RDATA buffer member. - -*/ - -/* - 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_RRAnswerGeneric::clear -*/ -bool MDNSResponder::stcMDNS_RRAnswerGeneric::clear(void) -{ - - if (m_pu8RDData) + /* + MDNSResponder::stcMDNS_RRAttributes::operator = + */ + MDNSResponder::stcMDNS_RRAttributes& MDNSResponder::stcMDNS_RRAttributes::operator=( + const MDNSResponder::stcMDNS_RRAttributes& p_Other) { - delete[] m_pu8RDData; - m_pu8RDData = 0; + if (&p_Other != this) + { + m_u16Type = p_Other.m_u16Type; + m_u16Class = p_Other.m_u16Class; + } + return *this; } - m_u16RDLength = 0; - - return true; -} + /** + MDNSResponder::stcMDNS_RRHeader -/** - MDNSResponder::stcProbeInformation + A MDNS record header (domain and attributes) object. - Probing status information for a host or service domain + */ -*/ + /* + MDNSResponder::stcMDNS_RRHeader::stcMDNS_RRHeader constructor + */ + MDNSResponder::stcMDNS_RRHeader::stcMDNS_RRHeader(void) { } -/* - MDNSResponder::stcProbeInformation::stcProbeInformation constructor -*/ -MDNSResponder::stcProbeInformation::stcProbeInformation(void) - : m_ProbingStatus(ProbingStatus_WaitingForData), - m_u8SentCount(0), - m_Timeout(esp8266::polledTimeout::oneShotMs::neverExpires), - m_bConflict(false), - m_bTiebreakNeeded(false), - m_fnHostProbeResultCallback(0), - m_fnServiceProbeResultCallback(0) -{ -} - -/* - 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_RRHeader::stcMDNS_RRHeader copy-constructor + */ + MDNSResponder::stcMDNS_RRHeader::stcMDNS_RRHeader(const stcMDNS_RRHeader& p_Other) { - m_fnHostProbeResultCallback = 0; - m_fnServiceProbeResultCallback = 0; + operator=(p_Other); } - return true; -} -/** - MDNSResponder::stcMDNSService + /* + 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; + } - 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::stcMDNS_RRHeader::clear + */ + bool MDNSResponder::stcMDNS_RRHeader::clear(void) + { + m_Domain.clear(); + return true; + } -/* - 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_RRQuestion - setName(p_pcName); - setService(p_pcService); - setProtocol(p_pcProtocol); -} + A MDNS question record object (header + question flags) -/* - MDNSResponder::stcMDNSService::~stcMDNSService destructor -*/ -MDNSResponder::stcMDNSService::~stcMDNSService(void) -{ + */ - releaseName(); - releaseService(); - releaseProtocol(); -} + /* + MDNSResponder::stcMDNS_RRQuestion::stcMDNS_RRQuestion constructor + */ + MDNSResponder::stcMDNS_RRQuestion::stcMDNS_RRQuestion(void) : m_pNext(0), m_bUnicast(false) { } -/* - MDNSResponder::stcMDNSService::setName -*/ -bool MDNSResponder::stcMDNSService::setName(const char* p_pcName) -{ + /** + MDNSResponder::stcMDNS_RRAnswer + + A MDNS answer record object (header + answer content). + This is a 'virtual' base class for all other MDNS answer classes. - bool bResult = false; + */ - releaseName(); - size_t stLength = (p_pcName ? strlen(p_pcName) : 0); - if (stLength) + /* + 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) { - if ((bResult = (0 != (m_pcName = new char[stLength + 1])))) - { - strncpy(m_pcName, p_pcName, stLength); - m_pcName[stLength] = 0; - } + // Extract 'cache flush'-bit + m_bCacheFlush = (m_Header.m_Attributes.m_u16Class & 0x8000); + m_Header.m_Attributes.m_u16Class &= (~0x8000); } - else + + /* + MDNSResponder::stcMDNS_RRAnswer::~stcMDNS_RRAnswer destructor + */ + MDNSResponder::stcMDNS_RRAnswer::~stcMDNS_RRAnswer(void) { } + + /* + MDNSResponder::stcMDNS_RRAnswer::answerType + */ + MDNSResponder::enuAnswerType MDNSResponder::stcMDNS_RRAnswer::answerType(void) const { - bResult = true; + return m_AnswerType; } - return bResult; -} -/* - MDNSResponder::stcMDNSService::releaseName -*/ -bool MDNSResponder::stcMDNSService::releaseName(void) -{ - - if (m_pcName) + /* + MDNSResponder::stcMDNS_RRAnswer::clear + */ + bool MDNSResponder::stcMDNS_RRAnswer::clear(void) { - delete[] m_pcName; - m_pcName = 0; + m_pNext = 0; + m_Header.clear(); + return true; } - return true; -} -/* - MDNSResponder::stcMDNSService::setService -*/ -bool MDNSResponder::stcMDNSService::setService(const char* p_pcService) -{ + /** + MDNSResponder::stcMDNS_RRAnswerA - bool bResult = false; + A MDNS A answer object. + Extends the base class by an IP4 address member. - 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 + */ + +#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) { - bResult = true; } - return bResult; -} -/* - MDNSResponder::stcMDNSService::releaseService -*/ -bool MDNSResponder::stcMDNSService::releaseService(void) -{ + /* + MDNSResponder::stcMDNS_RRAnswerA::stcMDNS_RRAnswerA destructor + */ + MDNSResponder::stcMDNS_RRAnswerA::~stcMDNS_RRAnswerA(void) { clear(); } - if (m_pcService) + /* + MDNSResponder::stcMDNS_RRAnswerA::clear + */ + bool MDNSResponder::stcMDNS_RRAnswerA::clear(void) { - delete[] m_pcService; - m_pcService = 0; + m_IPAddress = IPAddress(0, 0, 0, 0); + return true; } - return true; -} +#endif -/* - MDNSResponder::stcMDNSService::setProtocol -*/ -bool MDNSResponder::stcMDNSService::setProtocol(const char* p_pcProtocol) -{ + /** + MDNSResponder::stcMDNS_RRAnswerPTR - bool bResult = false; + A MDNS PTR answer object. + Extends the base class by a MDNS domain member. - 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 + */ + + /* + 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) { - bResult = true; } - return bResult; -} -/* - MDNSResponder::stcMDNSService::releaseProtocol -*/ -bool MDNSResponder::stcMDNSService::releaseProtocol(void) -{ + /* + MDNSResponder::stcMDNS_RRAnswerPTR::~stcMDNS_RRAnswerPTR destructor + */ + MDNSResponder::stcMDNS_RRAnswerPTR::~stcMDNS_RRAnswerPTR(void) { clear(); } - if (m_pcProtocol) + /* + MDNSResponder::stcMDNS_RRAnswerPTR::clear + */ + bool MDNSResponder::stcMDNS_RRAnswerPTR::clear(void) { - delete[] m_pcProtocol; - m_pcProtocol = 0; + m_PTRDomain.clear(); + return true; } - return true; -} - -/** - MDNSResponder::stcMDNSServiceQuery + /** + MDNSResponder::stcMDNS_RRAnswerTXT - 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 TXT answer object. + Extends the base class by a MDNS TXT items list 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). + /* + 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::stcMDNSServiceQuery::stcAnswer::stcTTL + /* + MDNSResponder::stcMDNS_RRAnswerTXT::clear + */ + bool MDNSResponder::stcMDNS_RRAnswerTXT::clear(void) + { + m_Txts.clear(); + return true; + } - 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_RRAnswerAAAA - / + A MDNS AAAA answer object. + (Should) extend the base class by an IP6 address member. - / * - MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::stcTTL constructor - / - MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::stcTTL(uint32_t p_u32TTL / *= 0* /) - : m_bUpdateScheduled(false) { + */ - set(p_u32TTL * 1000); +#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::stcMDNSServiceQuery::stcAnswer::stcTTL::set - / - bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::set(uint32_t 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. - m_TTLTimeFlag.restart(p_u32TTL * 1000); - m_bUpdateScheduled = false; + */ - return true; + /* + 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::has80Percent - / - bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcTTL::has80Percent(void) const { + /* + MDNSResponder::stcMDNS_RRAnswerSRV::~stcMDNS_RRAnswerSRV destructor + */ + MDNSResponder::stcMDNS_RRAnswerSRV::~stcMDNS_RRAnswerSRV(void) { clear(); } - 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; -} - -#ifdef MDNS_IP4_SUPPORT -/* - MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseIP4Addresses -*/ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseIP4Addresses(void) -{ + bool bResult = true; - 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)) - { - pPred = pPred->m_pNext; - } - if (pPred) + if (TIMEOUTLEVEL_BASE == m_timeoutLevel) // 80% { - pPred->m_pNext = p_pIP4Address->m_pNext; - delete p_pIP4Address; - bResult = true; + return (m_u32TTL * 800L); // to milliseconds } - else if (m_pIP4Addresses == p_pIP4Address) // No predecessor, but first item + else if ((TIMEOUTLEVEL_BASE < m_timeoutLevel) && // >80% AND + (TIMEOUTLEVEL_FINAL >= m_timeoutLevel)) // <= 100% { - 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(); } + + /* + 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())); + } - return (stcIP4Address*)(((const stcAnswer*)this)->IP4AddressAtIndex(p_u32Index)); -} + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocServiceDomain -/* - MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP4AddressAtIndex (const) -*/ -const MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP4Address* MDNSResponder::stcMDNSServiceQuery::stcAnswer::IP4AddressAtIndex(uint32_t p_u32Index) const -{ + Alloc memory for the char array representation of the service domain. - const stcIP4Address* pIP4Address = 0; + */ + char* MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocServiceDomain(size_t p_stLength) + { + releaseServiceDomain(); + if (p_stLength) + { + m_pcServiceDomain = new char[p_stLength]; + } + return m_pcServiceDomain; + } - if (((uint32_t)(-1) != p_u32Index) && - (m_pIP4Addresses)) + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseServiceDomain + */ + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseServiceDomain(void) { - - uint32_t u32Index; - for (pIP4Address = m_pIP4Addresses, u32Index = 0; ((pIP4Address) && (u32Index < p_u32Index)); pIP4Address = pIP4Address->m_pNext, ++u32Index); + if (m_pcServiceDomain) + { + delete[] m_pcServiceDomain; + m_pcServiceDomain = 0; + } + return true; } - return pIP4Address; -} -#endif -#ifdef MDNS_IP6_SUPPORT -/* - MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseIP6Addresses -*/ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseIP6Addresses(void) -{ + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocHostDomain - while (m_pIP6Addresses) + Alloc memory for the char array representation of the host domain. + + */ + char* MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocHostDomain(size_t p_stLength) { - stcIP6Address* pNext = m_pIP6Addresses->m_pNext; - delete m_pIP6Addresses; - m_pIP6Addresses = pNext; + releaseHostDomain(); + if (p_stLength) + { + m_pcHostDomain = new char[p_stLength]; + } + return m_pcHostDomain; } - return true; -} - -/* - MDNSResponder::stcMDNSServiceQuery::stcAnswer::addIP6Address -*/ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::addIP6Address(MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* p_pIP6Address) -{ - - bool bResult = false; - if (p_pIP6Address) + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseHostDomain + */ + bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::releaseHostDomain(void) { - p_pIP6Address->m_pNext = m_pIP6Addresses; - m_pIP6Addresses = p_pIP6Address; - bResult = true; + if (m_pcHostDomain) + { + delete[] m_pcHostDomain; + m_pcHostDomain = 0; + } + return true; } - return bResult; -} -/* - MDNSResponder::stcMDNSServiceQuery::stcAnswer::removeIP6Address -*/ -bool MDNSResponder::stcMDNSServiceQuery::stcAnswer::removeIP6Address(MDNSResponder::stcMDNSServiceQuery::stcAnswer::stcIP6Address* p_pIP6Address) -{ + /* + MDNSResponder::stcMDNSServiceQuery::stcAnswer::allocTxts - bool bResult = false; + Alloc memory for the char array representation of the TXT items. - if (p_pIP6Address) + */ + 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..e755222a7f 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,1759 +31,1860 @@ extern "C" { #include "LEAmDNS_lwIPdefs.h" #include "LEAmDNS_Priv.h" - namespace esp8266 { - /* LEAmDNS */ namespace MDNSImplementation { - -/** - CONST STRINGS -*/ -static const char* scpcLocal = "local"; -static const char* scpcServices = "services"; -static const char* scpcDNSSD = "dns-sd"; -static const char* scpcUDP = "udp"; -//static const char* 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"));); + ((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"));); } - 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"));); + ((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) && - (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"));); + ((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"));); } - } // 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"));); + ((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) && - (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"));); + ((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"));); } - if ((pService->m_u8ReplyMask & (ContentFlag_PTR_NAME | ContentFlag_SRV)) || // If service instance name or SRV OR - (p_rSendParameter.m_u8HostReplyMask & (ContentFlag_A | ContentFlag_AAAA))) // any host IP address is requested +#endif + + for (stcMDNSService* pService = m_pServices; ((bResult) && (pService)); + pService = pService->m_pNext) { -#ifdef MDNS_IP4_SUPPORT - if ((bResult) && - (!(p_rSendParameter.m_u8HostReplyMask & ContentFlag_A))) // Add IP4 address + if ((bResult) && (pService->m_u8ReplyMask & ContentFlag_PTR_TYPE)) + { + ((Sequence_Count == sequence) ? + ++ru16Answers : + (bResult = _writeMDNSAnswer_PTR_TYPE(*pService, p_rSendParameter))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P( + PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_PTR_TYPE " + "FAILED!\n"));); + } + if ((bResult) && (pService->m_u8ReplyMask & ContentFlag_PTR_NAME)) + { + ((Sequence_Count == sequence) ? + ++ru16Answers : + (bResult = _writeMDNSAnswer_PTR_NAME(*pService, p_rSendParameter))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P( + PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_PTR_NAME " + "FAILED!\n"));); + } + if ((bResult) && (pService->m_u8ReplyMask & ContentFlag_SRV)) + { + ((Sequence_Count == sequence) ? + ++ru16Answers : + (bResult = _writeMDNSAnswer_SRV(*pService, p_rSendParameter))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P( + PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_SRV(A) " + "FAILED!\n"));); + } + if ((bResult) && (pService->m_u8ReplyMask & ContentFlag_TXT)) { - bNeedsAdditionalAnswerA = true; + ((Sequence_Count == sequence) ? + ++ru16Answers : + (bResult = _writeMDNSAnswer_TXT(*pService, p_rSendParameter))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P( + PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_TXT(A) " + "FAILED!\n"));); } + } // for services + + // Additional answers +#ifdef MDNS_IP4_SUPPORT + bool bNeedsAdditionalAnswerA = false; #endif #ifdef MDNS_IP6_SUPPORT - if ((bResult) && - (!(p_rSendParameter.m_u8HostReplyMask & ContentFlag_AAAA))) // Add IP6 address + bool bNeedsAdditionalAnswerAAAA = false; +#endif + for (stcMDNSService* pService = m_pServices; ((bResult) && (pService)); + pService = pService->m_pNext) + { + if ((bResult) && (pService->m_u8ReplyMask & ContentFlag_PTR_NAME) + && // If PTR_NAME is requested, AND + (!(pService->m_u8ReplyMask + & ContentFlag_SRV))) // NOT SRV -> add SRV as additional answer + { + ((Sequence_Count == sequence) ? + ++msgHeader.m_u16ARCount : + (bResult = _writeMDNSAnswer_SRV(*pService, p_rSendParameter))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P( + PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_SRV(B) " + "FAILED!\n"));); + } + if ((bResult) && (pService->m_u8ReplyMask & ContentFlag_PTR_NAME) + && // If PTR_NAME is requested, AND + (!(pService->m_u8ReplyMask + & ContentFlag_TXT))) // NOT TXT -> add TXT as additional answer { - bNeedsAdditionalAnswerAAAA = true; + ((Sequence_Count == sequence) ? + ++msgHeader.m_u16ARCount : + (bResult = _writeMDNSAnswer_TXT(*pService, p_rSendParameter))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P( + PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_TXT(B) " + "FAILED!\n"));); } + if ((pService->m_u8ReplyMask & (ContentFlag_PTR_NAME | ContentFlag_SRV)) + || // If service instance name or SRV OR + (p_rSendParameter.m_u8HostReplyMask + & (ContentFlag_A | ContentFlag_AAAA))) // any host IP address is requested + { +#ifdef MDNS_IP4_SUPPORT + if ((bResult) + && (!(p_rSendParameter.m_u8HostReplyMask + & ContentFlag_A))) // Add IP4 address + { + bNeedsAdditionalAnswerA = true; + } #endif - } - } // for services +#ifdef MDNS_IP6_SUPPORT + if ((bResult) + && (!(p_rSendParameter.m_u8HostReplyMask + & ContentFlag_AAAA))) // Add IP6 address + { + bNeedsAdditionalAnswerAAAA = true; + } +#endif + } + } // for services - // Answer A needed? + // Answer A needed? #ifdef MDNS_IP4_SUPPORT - if ((bResult) && - (bNeedsAdditionalAnswerA)) - { - ((Sequence_Count == sequence) - ? ++msgHeader.m_u16ARCount - : (bResult = _writeMDNSAnswer_A(p_IPAddress, p_rSendParameter))); - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_A(B) FAILED!\n"));); - } + if ((bResult) && (bNeedsAdditionalAnswerA)) + { + ((Sequence_Count == sequence) ? + ++msgHeader.m_u16ARCount : + (bResult = _writeMDNSAnswer_A(p_IPAddress, p_rSendParameter))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P( + PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_A(B) FAILED!\n"));); + } #endif #ifdef MDNS_IP6_SUPPORT - // Answer AAAA needed? - if ((bResult) && - (bNeedsAdditionalAnswerAAAA)) - { - ((Sequence_Count == sequence) - ? ++msgHeader.m_u16ARCount - : (bResult = _writeMDNSAnswer_AAAA(p_IPAddress, p_rSendParameter))); - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_AAAA(B) FAILED!\n"));); - } + // Answer AAAA needed? + if ((bResult) && (bNeedsAdditionalAnswerAAAA)) + { + ((Sequence_Count == sequence) ? + ++msgHeader.m_u16ARCount : + (bResult = _writeMDNSAnswer_AAAA(p_IPAddress, p_rSendParameter))); + DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR( + "[MDNSResponder] _prepareMDNSMessage: _writeMDNSAnswer_AAAA(B) FAILED!\n"));); + } #endif - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: Loop %i FAILED!\n"), sequence);); - } // for sequence - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _prepareMDNSMessage: FAILED!\n"));); - return bResult; -} - -/* - 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 MDNSResponder::_readRRDomain(MDNSResponder::stcMDNS_RRDomain& p_rRRDomain) -{ - //DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain\n"));); - - bool bResult = ((p_rRRDomain.clear()) && - (_readRRDomain_Loop(p_rRRDomain, 0))); - DEBUG_EX_ERR(if (!bResult) DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRDomain: FAILED!\n"));); - return bResult; -} - -/* - 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 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_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);); + /* + MDNSResponder::_readRRDomain_Loop - bool bResult = false; + 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. - 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; -} - -/* - DOMAIN NAMES -*/ - -/* - MDNSResponder::_buildDomainForHost - - Builds a MDNS host domain (eg. esp8266.local) for the given hostname. + /* + MDNSResponder::_readRRAttributes + */ + bool MDNSResponder::_readRRAttributes(MDNSResponder::stcMDNS_RRAttributes& p_rRRAttributes) + { + // DEBUG_EX_INFO(DEBUG_OUTPUT.printf_P(PSTR("[MDNSResponder] _readRRAttributes\n"));); -*/ -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 - - -/* - 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::_buildDomainForReverseIP6 -/* - 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 <lwip/prot/dns.h> // 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..39beac03e2 100644 --- a/libraries/Hash/examples/sha1/sha1.ino +++ b/libraries/Hash/examples/sha1/sha1.ino @@ -4,12 +4,9 @@ #include <Arduino.h> #include <Hash.h> -void setup() { - Serial.begin(115200); -} +void setup() { Serial.begin(115200); } void loop() { - // usage as String // SHA1:a9993e364706816aba3e25717850c26c9cd0d89d 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..535cbf5c0b 100644 --- a/libraries/I2S/examples/SimpleTone/SimpleTone.ino +++ b/libraries/I2S/examples/SimpleTone/SimpleTone.ino @@ -10,14 +10,14 @@ #include <I2S.h> -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 -int count = 0; +short sample = amplitude; // current sample value +int count = 0; void setup() { Serial.begin(115200); @@ -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..b78893103d 100644 --- a/libraries/LittleFS/examples/LittleFS_Timestamp/LittleFS_Timestamp.ino +++ b/libraries/LittleFS/examples/LittleFS_Timestamp/LittleFS_Timestamp.ino @@ -9,17 +9,16 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char *ssid = STASSID; -const char *pass = STAPSK; +const char* ssid = STASSID; +const char* pass = STAPSK; -long timezone = 2; +long timezone = 2; byte daysavetime = 1; - -void listDir(const char * dirname) { +void listDir(const char* dirname) { Serial.printf("Listing directory: %s\n", dirname); Dir root = LittleFS.openDir(dirname); @@ -33,15 +32,18 @@ void listDir(const char * dirname) { time_t cr = file.getCreationTime(); time_t lw = file.getLastWrite(); file.close(); - 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); + 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); + Serial.printf(" LAST WRITE: %d-%02d-%02d %02d:%02d:%02d\n", (tmstruct->tm_year) + 1900, + (tmstruct->tm_mon) + 1, tmstruct->tm_mday, tmstruct->tm_hour, tmstruct->tm_min, + tmstruct->tm_sec); } } - -void readFile(const char * path) { +void readFile(const char* path) { Serial.printf("Reading file: %s\n", path); File file = LittleFS.open(path, "r"); @@ -57,7 +59,7 @@ void readFile(const char * path) { file.close(); } -void writeFile(const char * path, const char * message) { +void writeFile(const char* path, const char* message) { Serial.printf("Writing file: %s\n", path); File file = LittleFS.open(path, "w"); @@ -70,11 +72,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 +92,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 +101,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"); @@ -126,12 +128,15 @@ void setup() { Serial.println("IP address: "); 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 ; + configTime(3600 * timezone, daysavetime * 3600, "time.nist.gov", "0.pool.ntp.org", + "1.pool.ntp.org"); + struct tm tmstruct; delay(2000); tmstruct.tm_year = 0; getLocalTime(&tmstruct, 5000); - Serial.printf("\nNow is : %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); + Serial.printf("\nNow is : %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); Serial.println(""); Serial.println("Formatting LittleFS filesystem"); LittleFS.format(); @@ -158,9 +163,6 @@ void setup() { } readFile("/hello.txt"); listDir("/"); - - } void loop() { } - diff --git a/libraries/LittleFS/examples/SpeedTest/SpeedTest.ino b/libraries/LittleFS/examples/SpeedTest/SpeedTest.ino index 35e0ac66e6..0d0425de68 100644 --- a/libraries/LittleFS/examples/SpeedTest/SpeedTest.ino +++ b/libraries/LittleFS/examples/SpeedTest/SpeedTest.ino @@ -15,13 +15,13 @@ #define TESTSIZEKB 512 // Format speed in bytes/second. Static buffer so not re-entrant safe -const char *rate(unsigned long start, unsigned long stop, unsigned long bytes) { +const char* rate(unsigned long start, unsigned long stop, unsigned long bytes) { static char buff[64]; if (stop == start) { strcpy_P(buff, PSTR("Inf b/s")); } else { unsigned long delta = stop - start; - float r = 1000.0 * (float)bytes / (float)delta; + float r = 1000.0 * (float)bytes / (float)delta; if (r >= 1000000.0) { sprintf_P(buff, PSTR("%0.2f MB/s"), r / 1000000.0); } else if (r >= 1000.0) { @@ -33,7 +33,7 @@ const char *rate(unsigned long start, unsigned long stop, unsigned long bytes) { return buff; } -void DoTest(FS *fs) { +void DoTest(FS* fs) { if (!fs->format()) { Serial.printf("Unable to format(), aborting\n"); return; @@ -45,12 +45,12 @@ void DoTest(FS *fs) { uint8_t data[256]; for (int i = 0; i < 256; i++) { - data[i] = (uint8_t) i; + data[i] = (uint8_t)i; } Serial.printf("Creating %dKB file, may take a while...\n", TESTSIZEKB); unsigned long start = millis(); - File f = fs->open("/testwrite.bin", "w"); + File f = fs->open("/testwrite.bin", "w"); if (!f) { Serial.printf("Unable to open file for writing, aborting\n"); return; @@ -62,7 +62,8 @@ void DoTest(FS *fs) { } f.close(); unsigned long stop = millis(); - Serial.printf("==> Time to write %dKB in 256b chunks = %lu milliseconds\n", TESTSIZEKB, stop - start); + Serial.printf("==> Time to write %dKB in 256b chunks = %lu milliseconds\n", TESTSIZEKB, + stop - start); f = fs->open("/testwrite.bin", "r"); Serial.printf("==> Created file size = %zu\n", f.size()); @@ -70,7 +71,7 @@ void DoTest(FS *fs) { Serial.printf("Reading %dKB file sequentially in 256b chunks\n", TESTSIZEKB); start = millis(); - f = fs->open("/testwrite.bin", "r"); + f = fs->open("/testwrite.bin", "r"); for (int i = 0; i < TESTSIZEKB; i++) { for (int j = 0; j < 4; j++) { f.read(data, 256); @@ -78,11 +79,13 @@ void DoTest(FS *fs) { } f.close(); stop = millis(); - Serial.printf("==> Time to read %dKB sequentially in 256b chunks = %lu milliseconds = %s\n", TESTSIZEKB, stop - start, rate(start, stop, TESTSIZEKB * 1024)); + Serial.printf("==> Time to read %dKB sequentially in 256b chunks = %lu milliseconds = %s\n", + TESTSIZEKB, stop - start, rate(start, stop, TESTSIZEKB * 1024)); - Serial.printf("Reading %dKB file MISALIGNED in flash and RAM sequentially in 256b chunks\n", TESTSIZEKB); + Serial.printf("Reading %dKB file MISALIGNED in flash and RAM sequentially in 256b chunks\n", + TESTSIZEKB); start = millis(); - f = fs->open("/testwrite.bin", "r"); + f = fs->open("/testwrite.bin", "r"); f.read(); for (int i = 0; i < TESTSIZEKB; i++) { for (int j = 0; j < 4; j++) { @@ -91,11 +94,13 @@ void DoTest(FS *fs) { } f.close(); stop = millis(); - Serial.printf("==> Time to read %dKB sequentially MISALIGNED in flash and RAM in 256b chunks = %lu milliseconds = %s\n", TESTSIZEKB, stop - start, rate(start, stop, TESTSIZEKB * 1024)); + Serial.printf("==> Time to read %dKB sequentially MISALIGNED in flash and RAM in 256b chunks = " + "%lu milliseconds = %s\n", + TESTSIZEKB, stop - start, rate(start, stop, TESTSIZEKB * 1024)); Serial.printf("Reading %dKB file in reverse by 256b chunks\n", TESTSIZEKB); start = millis(); - f = fs->open("/testwrite.bin", "r"); + f = fs->open("/testwrite.bin", "r"); for (int i = 0; i < TESTSIZEKB; i++) { for (int j = 0; j < 4; j++) { if (!f.seek(256 + 256 * j * i, SeekEnd)) { @@ -110,37 +115,40 @@ void DoTest(FS *fs) { } f.close(); stop = millis(); - Serial.printf("==> Time to read %dKB in reverse in 256b chunks = %lu milliseconds = %s\n", TESTSIZEKB, stop - start, rate(start, stop, TESTSIZEKB * 1024)); + Serial.printf("==> Time to read %dKB in reverse in 256b chunks = %lu milliseconds = %s\n", + TESTSIZEKB, stop - start, rate(start, stop, TESTSIZEKB * 1024)); Serial.printf("Writing 64K file in 1-byte chunks\n"); start = millis(); - f = fs->open("/test1b.bin", "w"); + f = fs->open("/test1b.bin", "w"); 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)); + Serial.printf("==> Time to write 64KB in 1b chunks = %lu milliseconds = %s\n", stop - start, + rate(start, stop, 65536)); Serial.printf("Reading 64K file in 1-byte chunks\n"); start = millis(); - f = fs->open("/test1b.bin", "r"); + f = fs->open("/test1b.bin", "r"); for (int i = 0; i < 65536; i++) { char c; f.read((uint8_t*)&c, 1); } f.close(); stop = millis(); - Serial.printf("==> Time to read 64KB in 1b chunks = %lu milliseconds = %s\n", stop - start, rate(start, stop, 65536)); + Serial.printf("==> Time to read 64KB in 1b chunks = %lu milliseconds = %s\n", stop - start, + rate(start, stop, 65536)); - - start = millis(); - auto dest = fs->open("/test1bw.bin", "w"); - f = fs->open("/test1b.bin", "r"); + start = millis(); + auto dest = fs->open("/test1bw.bin", "w"); + f = fs->open("/test1b.bin", "r"); auto copysize = f.sendAll(dest); dest.close(); stop = millis(); - Serial.printf("==> Time to copy %d = %zd bytes = %lu milliseconds = %s\n", f.size(), copysize, stop - start, rate(start, stop, f.size())); + Serial.printf("==> Time to copy %d = %zd bytes = %lu milliseconds = %s\n", f.size(), copysize, + stop - start, rate(start, stop, f.size())); f.close(); } @@ -152,6 +160,4 @@ void setup() { Serial.println("done"); } -void loop() { - delay(10000); -} +void loop() { delay(10000); } diff --git a/libraries/Netdump/examples/Netdump/Netdump.ino b/libraries/Netdump/examples/Netdump/Netdump.ino index dbba63869b..5317a6768d 100644 --- a/libraries/Netdump/examples/Netdump/Netdump.ino +++ b/libraries/Netdump/examples/Netdump/Netdump.ino @@ -12,15 +12,15 @@ using namespace NetCapture; #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; Netdump nd; -//FS* filesystem = &SPIFFS; +// FS* filesystem = &SPIFFS; FS* filesystem = &LittleFS; ESP8266WebServer webServer(80); // Used for sending commands @@ -29,33 +29,22 @@ File tracefile; std::map<PacketType, int> 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 + case SerialOption::LocalNone: // Only local IP traffic, full details nd.printDump(Serial, Packet::PacketDetail::NONE, - [](Packet n) { - return (n.hasIP(WiFi.localIP())); - } - ); + [](Packet n) { return (n.hasIP(WiFi.localIP())); }); break; - case SerialOption::HTTPChar : // Only HTTP traffic, show packet content as chars - nd.printDump(Serial, Packet::PacketDetail::CHAR, - [](Packet n) { - return (n.isHTTP()); - } - ); + case SerialOption::HTTPChar: // Only HTTP traffic, show packet content as chars + nd.printDump(Serial, Packet::PacketDetail::CHAR, [](Packet n) { return (n.isHTTP()); }); break; - default : + default: Serial.printf("No valid SerialOption provided\r\n"); }; } @@ -91,38 +80,33 @@ void setup(void) { filesystem->begin(); - webServer.on("/list", - []() { - Dir dir = filesystem->openDir("/"); - String d = "<h1>File list</h1>"; + webServer.on("/list", []() { + Dir dir = filesystem->openDir("/"); + String d = "<h1>File list</h1>"; while (dir.next()) { d.concat("<li>" + dir.fileName() + "</li>"); } webServer.send(200, "text.html", d); - } - ); + }); - webServer.on("/req", - []() { + webServer.on("/req", []() { static int rq = 0; - String a = "<h1>You are connected, Number of requests = " + String(rq++) + "</h1>"; + String a = "<h1>You are connected, Number of requests = " + String(rq++) + "</h1>"; webServer.send(200, "text/html", a); - } - ); + }); - webServer.on("/reset", - []() { + webServer.on("/reset", []() { nd.reset(); tracefile.close(); tcpServer.close(); webServer.send(200, "text.html", "<h1>Netdump session reset</h1>"); - } - ); + }); 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 +116,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 +137,3 @@ void loop(void) { webServer.handleClient(); MDNS.update(); } - diff --git a/libraries/Netdump/src/Netdump.cpp b/libraries/Netdump/src/Netdump.cpp index 4d4deb05b2..07a77598f2 100644 --- a/libraries/Netdump/src/Netdump.cpp +++ b/libraries/Netdump/src/Netdump.cpp @@ -23,10 +23,8 @@ #include <lwip/init.h> #include "Schedule.h" - namespace NetCapture { - CallBackList<Netdump::LwipCallback> Netdump::lwipCallback; Netdump::Netdump() @@ -45,10 +43,7 @@ Netdump::~Netdump() } }; -void Netdump::setCallback(const Callback nc) -{ - netDumpCallback = nc; -} +void Netdump::setCallback(const Callback nc) { netDumpCallback = nc; } void Netdump::setCallback(const Callback nc, const Filter nf) { @@ -56,37 +51,23 @@ void Netdump::setCallback(const Callback nc, const Filter nf) netDumpCallback = nc; } -void Netdump::setFilter(const Filter nf) -{ - netDumpFilter = nf; -} +void Netdump::setFilter(const Filter nf) { netDumpFilter = nf; } -void Netdump::reset() -{ - setCallback(nullptr, nullptr); -} +void Netdump::reset() { setCallback(nullptr, nullptr); } 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 +79,7 @@ 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 +87,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 +97,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 +110,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<char*>(pcapHeader), 24); @@ -145,7 +124,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 +133,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<char*>(pcapHeader), 16); // pcap record header + outfile.write(reinterpret_cast<char*>(pcapHeader), 16); // pcap record header outfile.write(np.rawData(), incl_len); } @@ -168,16 +147,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<uint32_t*>(&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 +168,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 +178,7 @@ 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 +192,8 @@ 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..e9f23425f5 100644 --- a/libraries/Netdump/src/Netdump.h +++ b/libraries/Netdump/src/Netdump.h @@ -32,15 +32,13 @@ namespace NetCapture { - using namespace experimental::CBListImplentation; class Netdump { public: - - using Filter = std::function<bool(const Packet&)>; - using Callback = std::function<void(const Packet&)>; + using Filter = std::function<bool(const Packet&)>; + using Callback = std::function<void(const Packet&)>; using LwipCallback = std::function<void(int, const char*, int, int, int)>; Netdump(); @@ -53,15 +51,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> lwipCallback; + static CallBackList<LwipCallback> lwipCallback; CallBackList<LwipCallback>::CallBackHandler lwipHandler; void netdumpCapture(int netif_idx, const char* data, size_t len, int out, int success); @@ -69,19 +66,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..f814687515 100644 --- a/libraries/Netdump/src/NetdumpIP.cpp +++ b/libraries/Netdump/src/NetdumpIP.cpp @@ -23,12 +23,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 +35,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 +86,7 @@ NetdumpIP::NetdumpIP(const String& ip) } } -bool NetdumpIP::fromString(const char *address) +bool NetdumpIP::fromString(const char* address) { if (!fromString4(address)) { @@ -97,12 +95,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 +122,7 @@ bool NetdumpIP::fromString4(const char *address) return false; } (*this)[dots++] = acc; - acc = 0; + acc = 0; } else { @@ -144,12 +142,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 +160,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 +170,7 @@ bool NetdumpIP::fromString6(const char *address) if (*address == ':') { if (doubledots >= 0) - // :: allowed once + // :: allowed once { return false; } @@ -181,22 +179,22 @@ bool NetdumpIP::fromString6(const char *address) address++; } if (dots == 7) - // too many separators + // too many separators { return false; } reinterpret_cast<uint16_t*>(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 +204,8 @@ bool NetdumpIP::fromString6(const char *address) { for (int i = dots - doubledots - 1; i >= 0; i--) { - reinterpret_cast<uint16_t*>(rawip)[8 - dots + doubledots + i] = reinterpret_cast<uint16_t*>(rawip)[doubledots + i]; + reinterpret_cast<uint16_t*>(rawip)[8 - dots + doubledots + i] + = reinterpret_cast<uint16_t*>(rawip)[doubledots + i]; } for (int i = doubledots; i < 8 - dots + doubledots; i++) { @@ -223,12 +222,11 @@ String NetdumpIP::toString() StreamString sstr; if (isV6()) { - sstr.reserve(40); // 8 shorts x 4 chars each + 7 colons + nullterm - + sstr.reserve(40); // 8 shorts x 4 chars each + 7 colons + nullterm } else { - sstr.reserve(16); // 4 bytes with 3 chars max + 3 dots + nullterm, or '(IP unset)' + sstr.reserve(16); // 4 bytes with 3 chars max + 3 dots + nullterm, or '(IP unset)' } printTo(sstr); return sstr; @@ -253,7 +251,7 @@ size_t NetdumpIP::printTo(Print& p) { n += p.printf_P(PSTR("%x"), bit); if (count0 > 0) - // no more hiding 0 + // no more hiding 0 { count0 = -8; } @@ -280,7 +278,7 @@ size_t NetdumpIP::printTo(Print& p) return n; } -bool NetdumpIP::compareRaw(IPversion v, const uint8_t* a, const uint8_t* b) const +bool NetdumpIP::compareRaw(IPversion v, const uint8_t* a, const uint8_t* b) const { for (int i = 0; i < (v == IPversion::IPV4 ? 4 : 16); i++) { @@ -296,7 +294,7 @@ bool NetdumpIP::compareIP(const IPAddress& ip) const { switch (ipv) { - case IPversion::UNSET : + case IPversion::UNSET: if (ip.isSet()) { return false; @@ -306,7 +304,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 +314,7 @@ bool NetdumpIP::compareIP(const IPAddress& ip) const return compareRaw(IPversion::IPV4, rawip, reinterpret_cast<const uint8_t*>(&ip.v4())); } break; - case IPversion::IPV6 : + case IPversion::IPV6: if (ip.isV4() || !ip.isSet()) { return false; @@ -326,7 +324,7 @@ bool NetdumpIP::compareIP(const IPAddress& ip) const return compareRaw(IPversion::IPV6, rawip, reinterpret_cast<const uint8_t*>(ip.raw6())); } break; - default : + default: return false; break; } @@ -336,7 +334,7 @@ bool NetdumpIP::compareIP(const NetdumpIP& nip) const { switch (ipv) { - case IPversion::UNSET : + case IPversion::UNSET: if (nip.isSet()) { return false; @@ -346,7 +344,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 +354,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 +364,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..5be98ae701 100644 --- a/libraries/Netdump/src/NetdumpIP.h +++ b/libraries/Netdump/src/NetdumpIP.h @@ -15,89 +15,57 @@ namespace NetCapture { - class NetdumpIP { public: NetdumpIP(); NetdumpIP(uint8_t first_octet, uint8_t second_octet, uint8_t third_octet, uint8_t fourth_octet); - NetdumpIP(const uint8_t *address, bool V4 = true); + NetdumpIP(const uint8_t* address, bool V4 = true); NetdumpIP(const IPAddress& ip); NetdumpIP(const String& ip); - uint8_t& operator[](int index) - { - return rawip[index]; - } + uint8_t& operator[](int index) { 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() - { - ipv = IPversion::IPV4; - }; - void setV6() - { - ipv = IPversion::IPV6; - }; - void setUnset() - { - ipv = IPversion::UNSET; - }; - bool isV4() const - { - return (ipv == IPversion::IPV4); - }; - bool isV6() const - { - return (ipv == IPversion::IPV6); - }; - bool isUnset() const - { - return (ipv == IPversion::UNSET); - }; - bool isSet() const - { - return (ipv != IPversion::UNSET); - }; + void setV4() { ipv = IPversion::IPV4; }; + void setV6() { ipv = IPversion::IPV6; }; + void setUnset() { ipv = IPversion::UNSET; }; + bool isV4() const { return (ipv == IPversion::IPV4); }; + bool isV6() const { return (ipv == IPversion::IPV6); }; + bool isUnset() const { return (ipv == IPversion::UNSET); }; + bool isSet() const { 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 - { - return compareIP(addr); - }; - bool operator!=(const IPAddress& addr) - { - return compareIP(addr); - }; - bool operator==(const NetdumpIP& addr) - { - return compareIP(addr); - }; - bool operator!=(const NetdumpIP& addr) - { - return !compareIP(addr); - }; +public: + bool operator==(const IPAddress& addr) const { return compareIP(addr); }; + bool operator!=(const IPAddress& addr) { return compareIP(addr); }; + bool operator==(const NetdumpIP& addr) { return compareIP(addr); }; + bool operator!=(const NetdumpIP& addr) { 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..443c36c439 100644 --- a/libraries/Netdump/src/NetdumpPacket.cpp +++ b/libraries/Netdump/src/NetdumpPacket.cpp @@ -24,8 +24,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) { @@ -139,15 +139,9 @@ void Packet::setPacketTypes() } } -const PacketType Packet::packetType() const -{ - return thisPacketType; -} +const PacketType Packet::packetType() const { return thisPacketType; } -const std::vector<PacketType>& Packet::allPacketTypes() const -{ - return thisAllPacketTypes; -} +const std::vector<PacketType>& Packet::allPacketTypes() const { return thisAllPacketTypes; } void Packet::MACtoString(int dataIdx, StreamString& sstr) const { @@ -159,21 +153,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 +195,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 +206,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 +218,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 +241,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 +280,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 +325,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 @@ -293,18 +338,15 @@ void Packet::UKNWtoString(PacketDetail, StreamString& sstr) const sstr.printf_P(PSTR("\r\n")); } -const String Packet::toString() const -{ - return toString(PacketDetail::NONE); -} - +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 +362,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 +420,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..1b0ad1eb22 100644 --- a/libraries/Netdump/src/NetdumpPacket.h +++ b/libraries/Netdump/src/NetdumpPacket.h @@ -31,14 +31,13 @@ namespace NetCapture { - 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(); }; @@ -51,185 +50,78 @@ class Packet RAW }; - const char* rawData() const - { - return data; - } - int getInOut() const - { - return out; - } - time_t getTime() const - { - return packetTime; - } - uint32_t getPacketSize() const - { - return packetLength; - } - uint16_t ntoh16(uint16_t idx) const - { - return data[idx + 1] | (((uint16_t)data[idx]) << 8); - }; - uint32_t ntoh32(uint16_t idx) const + const char* rawData() const { return data; } + int getInOut() const { return out; } + time_t getTime() const { return packetTime; } + uint32_t getPacketSize() const { return packetLength; } + uint16_t ntoh16(uint16_t idx) const { return data[idx + 1] | (((uint16_t)data[idx]) << 8); }; + uint32_t ntoh32(uint16_t idx) const { return ntoh16(idx + 2) | (((uint32_t)ntoh16(idx)) << 16); }; - uint8_t byteData(uint16_t idx) const - { - return data[idx]; - } - const char* byteIdx(uint16_t idx) const - { - return &data[idx]; - }; - uint16_t ethType() const - { - return ntoh16(12); - }; - uint8_t ipType() const + uint8_t byteData(uint16_t idx) const { return data[idx]; } + const char* byteIdx(uint16_t idx) const { return &data[idx]; }; + uint16_t ethType() const { return ntoh16(12); }; + 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; - } - uint32_t getTcpSeq() const - { - return isTCP() ? ntoh32(ETH_HDR_LEN + getIpHdrLen() + 4) : 0; - } - uint32_t getTcpAck() const - { - return isTCP() ? ntoh32(ETH_HDR_LEN + getIpHdrLen() + 8) : 0; - } - uint16_t getTcpFlags() const - { - return isTCP() ? ntoh16(ETH_HDR_LEN + getIpHdrLen() + 12) : 0; - } - uint16_t getTcpWindow() const - { - return isTCP() ? ntoh16(ETH_HDR_LEN + getIpHdrLen() + 14) : 0; + return isIP() ? isIPv4() ? ntoh16(ETH_HDR_LEN + 2) : (packetLength - ETH_HDR_LEN) : 0; } + uint32_t getTcpSeq() const { return isTCP() ? ntoh32(ETH_HDR_LEN + getIpHdrLen() + 4) : 0; } + uint32_t getTcpAck() const { return isTCP() ? ntoh32(ETH_HDR_LEN + getIpHdrLen() + 8) : 0; } + uint16_t getTcpFlags() const { return isTCP() ? ntoh16(ETH_HDR_LEN + getIpHdrLen() + 12) : 0; } + uint16_t getTcpWindow() const { return isTCP() ? ntoh16(ETH_HDR_LEN + getIpHdrLen() + 14) : 0; } 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 ; - }; - - uint8_t getIcmpType() const - { - return isICMP() ? data[ETH_HDR_LEN + getIpHdrLen() + 0] : 0; - } - uint8_t getIgmpType() const - { - return isIGMP() ? data[ETH_HDR_LEN + getIpHdrLen() + 0] : 0; - } - uint8_t getARPType() const - { - return isARP() ? data[ETH_HDR_LEN + 7] : 0; - } - bool is_ARP_who() const - { - return (getARPType() == 1); - } - bool is_ARP_is() const - { - return (getARPType() == 2); - } - - uint8_t getUdpHdrLen() const - { - return isUDP() ? 8 : 0; - }; - uint16_t getUdpLen() const - { - return isUDP() ? ntoh16(ETH_HDR_LEN + getIpHdrLen() + 4) : 0; - }; - bool isARP() const - { - return (ethType() == 0x0806); - }; - bool isIPv4() const - { - return (ethType() == 0x0800); - }; - bool isIPv6() const - { - return (ethType() == 0x86dd); - }; - bool isIP() const - { - return (isIPv4() || isIPv6()); - }; - bool isICMP() const - { - return (isIP() && ((ipType() == 1) || (ipType() == 58))); - }; - bool isIGMP() const - { - return (isIP() && (ipType() == 2)); - }; - bool isTCP() const - { - return (isIP() && (ipType() == 6)); - }; - bool isUDP() const - { - return (isIP() && ipType() == 17); - }; - bool isMDNS() const - { - return (isUDP() && hasPort(5353)); - }; - bool isDNS() const - { - return (isUDP() && hasPort(53)); - }; - bool isSSDP() const - { - return (isUDP() && hasPort(1900)); - }; - bool isDHCP() const + return isTCP() ? getIpTotalLen() - getIpHdrLen() - getTcpHdrLen() : 0; + }; + + uint8_t getIcmpType() const { return isICMP() ? data[ETH_HDR_LEN + getIpHdrLen() + 0] : 0; } + uint8_t getIgmpType() const { return isIGMP() ? data[ETH_HDR_LEN + getIpHdrLen() + 0] : 0; } + uint8_t getARPType() const { return isARP() ? data[ETH_HDR_LEN + 7] : 0; } + bool is_ARP_who() const { return (getARPType() == 1); } + bool is_ARP_is() const { return (getARPType() == 2); } + + uint8_t getUdpHdrLen() const { return isUDP() ? 8 : 0; }; + uint16_t getUdpLen() const { return isUDP() ? ntoh16(ETH_HDR_LEN + getIpHdrLen() + 4) : 0; }; + bool isARP() const { return (ethType() == 0x0806); }; + bool isIPv4() const { return (ethType() == 0x0800); }; + bool isIPv6() const { return (ethType() == 0x86dd); }; + bool isIP() const { return (isIPv4() || isIPv6()); }; + bool isICMP() const { return (isIP() && ((ipType() == 1) || (ipType() == 58))); }; + bool isIGMP() const { return (isIP() && (ipType() == 2)); }; + bool isTCP() const { return (isIP() && (ipType() == 6)); }; + bool isUDP() const { return (isIP() && ipType() == 17); }; + bool isMDNS() const { return (isUDP() && hasPort(5353)); }; + bool isDNS() const { return (isUDP() && hasPort(53)); }; + bool isSSDP() const { return (isUDP() && hasPort(1900)); }; + bool isDHCP() const { return (isUDP() && ((hasPort(546) || hasPort(547) || hasPort(67) || hasPort(68)))); }; - bool isWSDD() const - { - return (isUDP() && hasPort(3702)); - }; - bool isHTTP() const - { - return (isTCP() && hasPort(80)); - }; - bool isOTA() const - { - return (isUDP() && hasPort(8266)); - } - bool isNETBIOS() const - { - return (isUDP() && (hasPort(137) || hasPort(138) || hasPort(139))); - } - bool isSMB() const - { - return (isUDP() && hasPort(445)); - } + bool isWSDD() const { return (isUDP() && hasPort(3702)); }; + bool isHTTP() const { return (isTCP() && hasPort(80)); }; + bool isOTA() const { return (isUDP() && hasPort(8266)); } + bool isNETBIOS() const { return (isUDP() && (hasPort(137) || hasPort(138) || hasPort(139))); } + bool isSMB() const { return (isUDP() && hasPort(445)); } NetdumpIP getIP(uint16_t idx) const { return NetdumpIP(data[idx], data[idx + 1], data[idx + 2], data[idx + 3]); }; - NetdumpIP getIP6(uint16_t idx) const - { - return NetdumpIP((const uint8_t*)&data[idx], false); - }; + NetdumpIP getIP6(uint16_t idx) const { return NetdumpIP((const uint8_t*)&data[idx], false); }; NetdumpIP sourceIP() const { NetdumpIP ip; @@ -244,10 +136,7 @@ class Packet return ip; }; - bool hasIP(NetdumpIP ip) const - { - return (isIP() && ((ip == sourceIP()) || (ip == destIP()))); - } + bool hasIP(NetdumpIP ip) const { return (isIP() && ((ip == sourceIP()) || (ip == destIP()))); } NetdumpIP destIP() const { @@ -262,14 +151,8 @@ class Packet } return ip; }; - uint16_t getSrcPort() const - { - return isIP() ? ntoh16(ETH_HDR_LEN + getIpHdrLen() + 0) : 0; - } - uint16_t getDstPort() const - { - return isIP() ? ntoh16(ETH_HDR_LEN + getIpHdrLen() + 2) : 0; - } + uint16_t getSrcPort() const { return isIP() ? ntoh16(ETH_HDR_LEN + getIpHdrLen() + 0) : 0; } + uint16_t getDstPort() const { return isIP() ? ntoh16(ETH_HDR_LEN + getIpHdrLen() + 2) : 0; } bool hasPort(uint16_t p) const { return (isIP() && ((getSrcPort() == p) || (getDstPort() == p))); @@ -277,14 +160,13 @@ class Packet 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<PacketType>& allPacketTypes() const; - private: - void setPacketType(PacketType); void setPacketTypes(); @@ -298,17 +180,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<PacketType> 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..1eb458376b 100644 --- a/libraries/Netdump/src/PacketType.cpp +++ b/libraries/Netdump/src/PacketType.cpp @@ -9,34 +9,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..cff6a84813 100644 --- a/libraries/Netdump/src/PacketType.h +++ b/libraries/Netdump/src/PacketType.h @@ -11,11 +11,9 @@ namespace NetCapture { - class PacketType { public: - enum PType : int { ARP, @@ -41,14 +39,8 @@ class PacketType PacketType(); PacketType(PType pt) : ptype(pt) {}; - operator PType() const - { - return ptype; - }; - bool operator==(const PacketType& p) - { - return ptype == p.ptype; - }; + operator PType() const { return ptype; }; + bool operator==(const PacketType& p) { return ptype == p.ptype; }; String toString() const; diff --git a/libraries/SD/examples/Datalogger/Datalogger.ino b/libraries/SD/examples/Datalogger/Datalogger.ino index a023b63821..d75a2e1c8e 100644 --- a/libraries/SD/examples/Datalogger/Datalogger.ino +++ b/libraries/SD/examples/Datalogger/Datalogger.ino @@ -69,12 +69,3 @@ void loop() { Serial.println("error opening datalog.txt"); } } - - - - - - - - - diff --git a/libraries/SD/examples/DumpFile/DumpFile.ino b/libraries/SD/examples/DumpFile/DumpFile.ino index 3574652890..865d0bf5f7 100644 --- a/libraries/SD/examples/DumpFile/DumpFile.ino +++ b/libraries/SD/examples/DumpFile/DumpFile.ino @@ -56,6 +56,4 @@ void setup() { } } -void loop() { -} - +void loop() { } diff --git a/libraries/SD/examples/Files/Files.ino b/libraries/SD/examples/Files/Files.ino index 1c1b83ec20..f162837dcf 100644 --- a/libraries/SD/examples/Files/Files.ino +++ b/libraries/SD/examples/Files/Files.ino @@ -66,6 +66,3 @@ void setup() { void loop() { // nothing happens after setup finishes. } - - - diff --git a/libraries/SD/examples/ReadWrite/ReadWrite.ino b/libraries/SD/examples/ReadWrite/ReadWrite.ino index 7aa9a40c4b..680bb33296 100644 --- a/libraries/SD/examples/ReadWrite/ReadWrite.ino +++ b/libraries/SD/examples/ReadWrite/ReadWrite.ino @@ -71,5 +71,3 @@ void setup() { void loop() { // nothing happens after setup } - - diff --git a/libraries/SD/examples/listfiles/listfiles.ino b/libraries/SD/examples/listfiles/listfiles.ino index 55478d7080..06d31c0926 100644 --- a/libraries/SD/examples/listfiles/listfiles.ino +++ b/libraries/SD/examples/listfiles/listfiles.ino @@ -51,9 +51,8 @@ void loop() { void printDirectory(File dir, int numTabs) { while (true) { - - File entry = dir.openNextFile(); - if (! entry) { + File entry = dir.openNextFile(); + if (!entry) { // no more files break; } @@ -68,12 +67,16 @@ void printDirectory(File dir, int numTabs) { // files have sizes, directories do not Serial.print("\t\t"); Serial.print(entry.size(), DEC); - time_t cr = entry.getCreationTime(); - time_t lw = entry.getLastWrite(); - 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); + time_t cr = entry.getCreationTime(); + time_t lw = entry.getLastWrite(); + 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); + 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); } entry.close(); } diff --git a/libraries/SPISlave/examples/SPISlave_Master/SPISlave_Master.ino b/libraries/SPISlave/examples/SPISlave_Master/SPISlave_Master.ino index 528e52ed81..7b4515d6e1 100644 --- a/libraries/SPISlave/examples/SPISlave_Master/SPISlave_Master.ino +++ b/libraries/SPISlave/examples/SPISlave_Master/SPISlave_Master.ino @@ -9,81 +9,80 @@ 12 D6 MISO | D12 14 D5 SCK | D13 - Note: If the ESP is booting at a moment when the SPI Master has the Select line HIGH (deselected) - the ESP8266 WILL FAIL to boot! - See SPISlave_SafeMaster example for possible workaround + Note: If the ESP is booting at a moment when the SPI Master has the Select line HIGH + (deselected) the ESP8266 WILL FAIL to boot! See SPISlave_SafeMaster example for possible + workaround */ #include <SPI.h> class ESPMaster { private: - uint8_t _ss_pin; + uint8_t _ss_pin; public: - ESPMaster(uint8_t pin): _ss_pin(pin) {} - void begin() { - pinMode(_ss_pin, OUTPUT); - digitalWrite(_ss_pin, HIGH); - } + ESPMaster(uint8_t pin) : _ss_pin(pin) { } + void begin() { + pinMode(_ss_pin, OUTPUT); + digitalWrite(_ss_pin, HIGH); + } - uint32_t readStatus() { - digitalWrite(_ss_pin, LOW); - SPI.transfer(0x04); - uint32_t status = (SPI.transfer(0) | ((uint32_t)(SPI.transfer(0)) << 8) | ((uint32_t)(SPI.transfer(0)) << 16) | ((uint32_t)(SPI.transfer(0)) << 24)); - digitalWrite(_ss_pin, HIGH); - return status; - } + uint32_t readStatus() { + digitalWrite(_ss_pin, LOW); + SPI.transfer(0x04); + uint32_t status = (SPI.transfer(0) | ((uint32_t)(SPI.transfer(0)) << 8) + | ((uint32_t)(SPI.transfer(0)) << 16) | ((uint32_t)(SPI.transfer(0)) << 24)); + digitalWrite(_ss_pin, HIGH); + return status; + } - void writeStatus(uint32_t status) { - digitalWrite(_ss_pin, LOW); - SPI.transfer(0x01); - SPI.transfer(status & 0xFF); - SPI.transfer((status >> 8) & 0xFF); - SPI.transfer((status >> 16) & 0xFF); - SPI.transfer((status >> 24) & 0xFF); - digitalWrite(_ss_pin, HIGH); - } + void writeStatus(uint32_t status) { + digitalWrite(_ss_pin, LOW); + SPI.transfer(0x01); + SPI.transfer(status & 0xFF); + SPI.transfer((status >> 8) & 0xFF); + SPI.transfer((status >> 16) & 0xFF); + SPI.transfer((status >> 24) & 0xFF); + digitalWrite(_ss_pin, HIGH); + } - void readData(uint8_t * data) { - digitalWrite(_ss_pin, LOW); - SPI.transfer(0x03); - SPI.transfer(0x00); - for (uint8_t i = 0; i < 32; i++) { - data[i] = SPI.transfer(0); - } - digitalWrite(_ss_pin, HIGH); + void readData(uint8_t* data) { + digitalWrite(_ss_pin, LOW); + SPI.transfer(0x03); + SPI.transfer(0x00); + for (uint8_t i = 0; i < 32; i++) { + data[i] = SPI.transfer(0); } + digitalWrite(_ss_pin, HIGH); + } - void writeData(uint8_t * data, size_t len) { - uint8_t i = 0; - digitalWrite(_ss_pin, LOW); - SPI.transfer(0x02); - SPI.transfer(0x00); - while (len-- && i < 32) { - SPI.transfer(data[i++]); - } - while (i++ < 32) { - SPI.transfer(0); - } - digitalWrite(_ss_pin, HIGH); + void writeData(uint8_t* data, size_t len) { + uint8_t i = 0; + digitalWrite(_ss_pin, LOW); + SPI.transfer(0x02); + SPI.transfer(0x00); + while (len-- && i < 32) { + SPI.transfer(data[i++]); } - - String readData() { - char data[33]; - data[32] = 0; - readData((uint8_t *)data); - return String(data); + while (i++ < 32) { + SPI.transfer(0); } + digitalWrite(_ss_pin, HIGH); + } - void writeData(const char * data) { - writeData((uint8_t *)data, strlen(data)); - } + String readData() { + char data[33]; + data[32] = 0; + readData((uint8_t*)data); + return String(data); + } + + void writeData(const char* data) { writeData((uint8_t*)data, strlen(data)); } }; ESPMaster esp(SS); -void send(const char * message) { +void send(const char* message) { Serial.print("Master: "); Serial.println(message); esp.writeData(message); diff --git a/libraries/SPISlave/examples/SPISlave_SafeMaster/SPISlave_SafeMaster.ino b/libraries/SPISlave/examples/SPISlave_SafeMaster/SPISlave_SafeMaster.ino index 04c23c4502..fbc250a414 100644 --- a/libraries/SPISlave/examples/SPISlave_SafeMaster/SPISlave_SafeMaster.ino +++ b/libraries/SPISlave/examples/SPISlave_SafeMaster/SPISlave_SafeMaster.ino @@ -9,86 +9,85 @@ 12 D6 MISO | D12 14 D5 SCK | D13 - Note: If the ESP is booting at a moment when the SPI Master has the Select line HIGH (deselected) - the ESP8266 WILL FAIL to boot! - This sketch tries to go around this issue by only pulsing the Slave Select line to reset the command - and keeping the line LOW all other time. + Note: If the ESP is booting at a moment when the SPI Master has the Select line HIGH + (deselected) the ESP8266 WILL FAIL to boot! This sketch tries to go around this issue by only + pulsing the Slave Select line to reset the command and keeping the line LOW all other time. */ #include <SPI.h> class ESPSafeMaster { private: - uint8_t _ss_pin; - void _pulseSS() { - digitalWrite(_ss_pin, HIGH); - delayMicroseconds(5); - digitalWrite(_ss_pin, LOW); - } + uint8_t _ss_pin; + void _pulseSS() { + digitalWrite(_ss_pin, HIGH); + delayMicroseconds(5); + digitalWrite(_ss_pin, LOW); + } + public: - ESPSafeMaster(uint8_t pin): _ss_pin(pin) {} - void begin() { - pinMode(_ss_pin, OUTPUT); - _pulseSS(); - } + ESPSafeMaster(uint8_t pin) : _ss_pin(pin) { } + void begin() { + pinMode(_ss_pin, OUTPUT); + _pulseSS(); + } - uint32_t readStatus() { - _pulseSS(); - SPI.transfer(0x04); - uint32_t status = (SPI.transfer(0) | ((uint32_t)(SPI.transfer(0)) << 8) | ((uint32_t)(SPI.transfer(0)) << 16) | ((uint32_t)(SPI.transfer(0)) << 24)); - _pulseSS(); - return status; - } + uint32_t readStatus() { + _pulseSS(); + SPI.transfer(0x04); + uint32_t status = (SPI.transfer(0) | ((uint32_t)(SPI.transfer(0)) << 8) + | ((uint32_t)(SPI.transfer(0)) << 16) | ((uint32_t)(SPI.transfer(0)) << 24)); + _pulseSS(); + return status; + } - void writeStatus(uint32_t status) { - _pulseSS(); - SPI.transfer(0x01); - SPI.transfer(status & 0xFF); - SPI.transfer((status >> 8) & 0xFF); - SPI.transfer((status >> 16) & 0xFF); - SPI.transfer((status >> 24) & 0xFF); - _pulseSS(); - } + void writeStatus(uint32_t status) { + _pulseSS(); + SPI.transfer(0x01); + SPI.transfer(status & 0xFF); + SPI.transfer((status >> 8) & 0xFF); + SPI.transfer((status >> 16) & 0xFF); + SPI.transfer((status >> 24) & 0xFF); + _pulseSS(); + } - void readData(uint8_t * data) { - _pulseSS(); - SPI.transfer(0x03); - SPI.transfer(0x00); - for (uint8_t i = 0; i < 32; i++) { - data[i] = SPI.transfer(0); - } - _pulseSS(); + void readData(uint8_t* data) { + _pulseSS(); + SPI.transfer(0x03); + SPI.transfer(0x00); + for (uint8_t i = 0; i < 32; i++) { + data[i] = SPI.transfer(0); } + _pulseSS(); + } - void writeData(uint8_t * data, size_t len) { - uint8_t i = 0; - _pulseSS(); - SPI.transfer(0x02); - SPI.transfer(0x00); - while (len-- && i < 32) { - SPI.transfer(data[i++]); - } - while (i++ < 32) { - SPI.transfer(0); - } - _pulseSS(); + void writeData(uint8_t* data, size_t len) { + uint8_t i = 0; + _pulseSS(); + SPI.transfer(0x02); + SPI.transfer(0x00); + while (len-- && i < 32) { + SPI.transfer(data[i++]); } - - String readData() { - char data[33]; - data[32] = 0; - readData((uint8_t *)data); - return String(data); + while (i++ < 32) { + SPI.transfer(0); } + _pulseSS(); + } - void writeData(const char * data) { - writeData((uint8_t *)data, strlen(data)); - } + String readData() { + char data[33]; + data[32] = 0; + readData((uint8_t*)data); + return String(data); + } + + void writeData(const char* data) { writeData((uint8_t*)data, strlen(data)); } }; ESPSafeMaster esp(SS); -void send(const char * message) { +void send(const char* message) { Serial.print("Master: "); Serial.println(message); esp.writeData(message); diff --git a/libraries/SPISlave/examples/SPISlave_Test/SPISlave_Test.ino b/libraries/SPISlave/examples/SPISlave_Test/SPISlave_Test.ino index 0be83fd298..a04c295075 100644 --- a/libraries/SPISlave/examples/SPISlave_Test/SPISlave_Test.ino +++ b/libraries/SPISlave/examples/SPISlave_Test/SPISlave_Test.ino @@ -9,9 +9,9 @@ 12 D6 MISO | D12 14 D5 SCK | D13 - Note: If the ESP is booting at a moment when the SPI Master has the Select line HIGH (deselected) - the ESP8266 WILL FAIL to boot! - See SPISlave_SafeMaster example for possible workaround + Note: If the ESP is booting at a moment when the SPI Master has the Select line HIGH + (deselected) the ESP8266 WILL FAIL to boot! See SPISlave_SafeMaster example for possible + workaround */ @@ -24,9 +24,9 @@ void setup() { // data has been received from the master. Beware that len is always 32 // and the buffer is autofilled with zeroes if data is less than 32 bytes long // It's up to the user to implement protocol for handling data length - SPISlave.onData([](uint8_t * data, size_t len) { - String message = String((char *)data); - (void) len; + SPISlave.onData([](uint8_t* data, size_t len) { + String message = String((char*)data); + (void)len; if (message.equals("Hello Slave!")) { SPISlave.setData("Hello Master!"); } else if (message.equals("Are you alive?")) { @@ -36,27 +36,23 @@ void setup() { } else { SPISlave.setData("Say what?"); } - Serial.printf("Question: %s\n", (char *)data); + Serial.printf("Question: %s\n", (char*)data); }); // The master has read out outgoing data buffer // that buffer can be set with SPISlave.setData - SPISlave.onDataSent([]() { - Serial.println("Answer Sent"); - }); + SPISlave.onDataSent([]() { Serial.println("Answer Sent"); }); // status has been received from the master. - // The status register is a special register that bot the slave and the master can write to and read from. - // Can be used to exchange small data or status information + // The status register is a special register that bot the slave and the master can write to and + // read from. 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 - SPISlave.onStatusSent([]() { - Serial.println("Status Sent"); - }); + SPISlave.onStatusSent([]() { Serial.println("Status Sent"); }); // Setup SPI Slave registers and pins SPISlave.begin(); @@ -69,4 +65,4 @@ void setup() { SPISlave.setData("Ask me a question!"); } -void loop() {} +void loop() { } diff --git a/libraries/Servo/examples/Sweep/Sweep.ino b/libraries/Servo/examples/Sweep/Sweep.ino index 5a6bd6ef40..914709a4cf 100644 --- a/libraries/Servo/examples/Sweep/Sweep.ino +++ b/libraries/Servo/examples/Sweep/Sweep.ino @@ -15,7 +15,6 @@ Servo myservo; // create servo object to control a servo // twelve servo objects can be created on most boards - void setup() { myservo.attach(2); // attaches the servo on GIO2 to the servo object } @@ -23,14 +22,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..0cecffff62 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 <SPI.h> 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..244862cd43 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 <TFTv2.h> #include <SPI.h> 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..009258dee3 100644 --- a/libraries/TFT_Touch_Shield_V2/examples/drawNumber/drawNumber.ino +++ b/libraries/TFT_Touch_Shield_V2/examples/drawNumber/drawNumber.ino @@ -9,29 +9,35 @@ #include <SPI.h> 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..ba3e227ea9 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..020e7490d0 100644 --- a/libraries/TFT_Touch_Shield_V2/examples/paint/paint.ino +++ b/libraries/TFT_Touch_Shield_V2/examples/paint/paint.ino @@ -4,20 +4,20 @@ #include <TFTv2.h> #include <SPI.h> -int ColorPaletteHigh = 30; -int color = WHITE; //Paint brush color -unsigned int colors[8] = {BLACK, RED, GREEN, BLUE, CYAN, YELLOW, WHITE, GRAY1}; +int ColorPaletteHigh = 30; +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 + // Draw the pallet for (int i = 0; i < 8; i++) { Tft.fillRectangle(i * 30, 0, 30, ColorPaletteHigh, colors[i]); } @@ -27,7 +27,7 @@ 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 <SPI.h> 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..6dc49cc950 100644 --- a/libraries/TFT_Touch_Shield_V2/examples/text/text.ino +++ b/libraries/TFT_Touch_Shield_V2/examples/text/text.ino @@ -11,23 +11,20 @@ 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..e556aa8b08 100644 --- a/libraries/TFT_Touch_Shield_V2/examples/tftbmp/tftbmp.ino +++ b/libraries/TFT_Touch_Shield_V2/examples/tftbmp/tftbmp.ino @@ -16,32 +16,28 @@ #include "TFTv2.h" -#define MAX_BMP 10 // bmp file num -#define FILENAME_LEN 20 // max file name length +#define MAX_BMP 10 // bmp file num +#define FILENAME_LEN 20 // max file name length +const int PIN_SD_CS = 4; // pin of sd card -const int PIN_SD_CS = 4; // pin of sd card +const int __Gnbmp_height = 320; // bmp height +const int __Gnbmp_width = 240; // bmp width -const int __Gnbmp_height = 320; // bmp height -const int __Gnbmp_width = 240; // bmp width +unsigned char __Gnbmp_image_offset = 0; // offset -unsigned char __Gnbmp_image_offset = 0; // offset +int __Gnfile_num = 3; // num of file - -int __Gnfile_num = 3; // num of file - -char __Gsbmp_files[3][FILENAME_LEN] = { // add file name here +char __Gsbmp_files[3][FILENAME_LEN] = { + // add file name here "flower.BMP", "hibiscus.bmp", "test.bmp", }; - File bmpFile; - void setup() { - Serial.begin(115200); pinMode(PIN_SD_CS, OUTPUT); @@ -54,7 +50,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 +62,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 +78,6 @@ void loop() { delay(1000); } - } /*********************************************/ @@ -90,29 +87,28 @@ 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++) { - for (int j = 0; j < (240 / BUFFPIXEL); j++) { bmpFile.read(sdbuffer, BUFFPIXEL_X3); - uint8_t buffidx = 0; - int offset_x = j * BUFFPIXEL; + uint8_t buffidx = 0; + int offset_x = j * BUFFPIXEL; 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 +127,6 @@ void bmpdraw(File f, int x, int y) { TFT_CS_HIGH; } - } Serial.print(millis() - time, DEC); @@ -141,7 +136,7 @@ void bmpdraw(File f, int x, int y) { boolean bmpReadHeader(File f) { // read header uint32_t tmp; - uint8_t bmpDepth; + uint8_t bmpDepth; if (read16(f) != 0x4D42) { // magic bytes missing @@ -165,11 +160,11 @@ boolean bmpReadHeader(File f) { Serial.print("header size "); Serial.println(tmp, DEC); - - int bmp_width = read32(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; } @@ -199,7 +194,7 @@ boolean bmpReadHeader(File f) { // LITTLE ENDIAN! uint16_t read16(File f) { uint16_t d; - uint8_t b; + uint8_t b; b = f.read(); d = f.read(); d <<= 8; diff --git a/libraries/TFT_Touch_Shield_V2/examples/tftbmp2/tftbmp2.ino b/libraries/TFT_Touch_Shield_V2/examples/tftbmp2/tftbmp2.ino index 03423a4ef5..4f185999d0 100644 --- a/libraries/TFT_Touch_Shield_V2/examples/tftbmp2/tftbmp2.ino +++ b/libraries/TFT_Touch_Shield_V2/examples/tftbmp2/tftbmp2.ino @@ -18,23 +18,24 @@ #include "TFTv2.h" -#define MAX_BMP 10 // bmp file num -#define FILENAME_LEN 20 // max file name length +#define MAX_BMP 10 // bmp file num +#define FILENAME_LEN 20 // max file name length -const int PIN_SD_CS = 4; // pin of sd card +const int PIN_SD_CS = 4; // pin of sd card -const long __Gnbmp_height = 320; // bmp height -const long __Gnbmp_width = 240; // bmp width +const long __Gnbmp_height = 320; // bmp height +const long __Gnbmp_width = 240; // bmp width -long __Gnbmp_image_offset = 0;; +long __Gnbmp_image_offset = 0; +; -int __Gnfile_num = 0; // num of file -char __Gsbmp_files[MAX_BMP][FILENAME_LEN]; // file name +int __Gnfile_num = 0; // num of file +char __Gsbmp_files[MAX_BMP][FILENAME_LEN]; // file name File bmpFile; // if bmp file return 1, else return 0 -bool checkBMP(char *_name, char r_name[]) { +bool checkBMP(char* _name, char r_name[]) { int len = 0; if (NULL == _name) { @@ -55,29 +56,27 @@ bool checkBMP(char *_name, char r_name[]) { } // if xxx.bmp or xxx.BMP - if (r_name[len - 4] == '.' \ - && (r_name[len - 3] == 'b' || (r_name[len - 3] == 'B')) \ - && (r_name[len - 2] == 'm' || (r_name[len - 2] == 'M')) \ + if (r_name[len - 4] == '.' && (r_name[len - 3] == 'b' || (r_name[len - 3] == 'B')) + && (r_name[len - 2] == 'm' || (r_name[len - 2] == 'M')) && (r_name[len - 1] == 'p' || (r_name[len - 1] == 'P'))) { return true; } return false; - } // search root to find bmp file void searchDirectory() { - File root = SD.open("/"); // root + File root = SD.open("/"); // root while (true) { - File entry = root.openNextFile(); + File entry = root.openNextFile(); - if (! entry) { + if (!entry) { break; } if (!entry.isDirectory()) { - char *ptmp = entry.name(); + char* ptmp = entry.name(); char __Name[20]; @@ -99,9 +98,7 @@ void searchDirectory() { } } - void setup() { - Serial.begin(115200); pinMode(PIN_SD_CS, OUTPUT); @@ -114,7 +111,8 @@ void setup() { if (!SD.begin(PIN_SD_CS)) { Serial.println("failed!"); - while (1); // init fail, die here + while (1) + ; // init fail, die here } Serial.println("SD OK!"); @@ -150,15 +148,15 @@ void loop() { } */ - bmpFile = SD.open("pfvm_1.bmp"); - if (! bmpFile) { + if (!bmpFile) { Serial.println("didn't find image"); - while (1); + while (1) + ; } - if (! bmpReadHeader(bmpFile)) { + if (!bmpReadHeader(bmpFile)) { Serial.println("bad bmp"); return; } @@ -166,7 +164,8 @@ void loop() { bmpdraw(bmpFile, 0, 0, 1); bmpFile.close(); - while (1); + while (1) + ; } /*********************************************/ @@ -176,17 +175,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 - -#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 void bmpdraw(File f, int x, int y, int dir) { - if (bmpFile.seek(__Gnbmp_image_offset)) { Serial.print("pos = "); Serial.println(bmpFile.position()); @@ -194,7 +191,7 @@ void bmpdraw(File f, int x, int y, int dir) { uint32_t time = millis(); - uint8_t sdbuffer[BUFFPIXEL_X3]; // 3 * pixels to buffer + uint8_t sdbuffer[BUFFPIXEL_X3]; // 3 * pixels to buffer for (int i = 0; i < __Gnbmp_height; i++) { if (dir) { @@ -202,17 +199,16 @@ void bmpdraw(File f, int x, int y, int dir) { } for (int j = 0; j < (240 / BUFFPIXEL); j++) { - bmpFile.read(sdbuffer, BUFFPIXEL_X3); - uint8_t buffidx = 0; - int offset_x = j * BUFFPIXEL; + uint8_t buffidx = 0; + int offset_x = j * BUFFPIXEL; 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 +235,6 @@ void bmpdraw(File f, int x, int y, int dir) { TFT_CS_HIGH; } - } Serial.print(millis() - time, DEC); @@ -249,7 +244,7 @@ void bmpdraw(File f, int x, int y, int dir) { boolean bmpReadHeader(File f) { // read header uint32_t tmp; - uint8_t bmpDepth; + uint8_t bmpDepth; if (read16(f) != 0x4D42) { // magic bytes missing @@ -273,10 +268,11 @@ boolean bmpReadHeader(File f) { Serial.print("header size "); Serial.println(tmp, DEC); - int bmp_width = read32(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; } @@ -306,7 +302,7 @@ boolean bmpReadHeader(File f) { // LITTLE ENDIAN! uint16_t read16(File f) { uint16_t d; - uint8_t b; + uint8_t b; b = f.read(); d = f.read(); d <<= 8; diff --git a/libraries/Ticker/examples/TickerBasic/TickerBasic.ino b/libraries/Ticker/examples/TickerBasic/TickerBasic.ino index 2fabd98315..b49cf93a5c 100644 --- a/libraries/Ticker/examples/TickerBasic/TickerBasic.ino +++ b/libraries/Ticker/examples/TickerBasic/TickerBasic.ino @@ -41,5 +41,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..41c8bb6d5a 100644 --- a/libraries/Ticker/examples/TickerFunctional/TickerFunctional.ino +++ b/libraries/Ticker/examples/TickerFunctional/TickerFunctional.ino @@ -1,40 +1,31 @@ #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() {}; + 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; + int _pin, _duration; + Ticker _myTicker; - void classBlink() { - digitalWrite(_pin, !digitalRead(_pin)); - } + void classBlink() { digitalWrite(_pin, !digitalRead(_pin)); } }; -void staticBlink() { - digitalWrite(LED2, !digitalRead(LED2)); -} +void staticBlink() { digitalWrite(LED2, !digitalRead(LED2)); } -void scheduledBlink() { - digitalWrite(LED3, !digitalRead(LED2)); -} +void scheduledBlink() { digitalWrite(LED3, !digitalRead(LED2)); } -void parameterBlink(int p) { - digitalWrite(p, !digitalRead(p)); -} +void parameterBlink(int p) { digitalWrite(p, !digitalRead(p)); } Ticker staticTicker; Ticker scheduledTicker; @@ -43,7 +34,6 @@ Ticker lambdaTicker; ExampleClass example(LED1, 100); - void setup() { pinMode(LED2, OUTPUT); staticTicker.attach_ms(100, staticBlink); @@ -55,10 +45,7 @@ void setup() { parameterTicker.attach_ms(100, std::bind(parameterBlink, LED4)); pinMode(LED5, OUTPUT); - lambdaTicker.attach_ms(100, []() { - digitalWrite(LED5, !digitalRead(LED5)); - }); + lambdaTicker.attach_ms(100, []() { digitalWrite(LED5, !digitalRead(LED5)); }); } -void loop() { -} +void loop() { } diff --git a/libraries/Ticker/examples/TickerParameter/TickerParameter.ino b/libraries/Ticker/examples/TickerParameter/TickerParameter.ino index 8263c0bb56..6d4a129717 100644 --- a/libraries/Ticker/examples/TickerParameter/TickerParameter.ino +++ b/libraries/Ticker/examples/TickerParameter/TickerParameter.ino @@ -17,21 +17,13 @@ Ticker tickerSetLow; Ticker tickerSetHigh; Ticker tickerSetChar; -void setPinLow() { - digitalWrite(LED_BUILTIN, 0); -} +void setPinLow() { digitalWrite(LED_BUILTIN, 0); } -void setPinHigh() { - digitalWrite(LED_BUILTIN, 1); -} +void setPinHigh() { digitalWrite(LED_BUILTIN, 1); } -void setPin(int state) { - digitalWrite(LED_BUILTIN, state); -} +void setPin(int state) { digitalWrite(LED_BUILTIN, state); } -void setPinChar(char state) { - digitalWrite(LED_BUILTIN, state); -} +void setPinChar(char state) { digitalWrite(LED_BUILTIN, state); } void setup() { pinMode(LED_BUILTIN, OUTPUT); @@ -46,5 +38,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..44d07c8bb4 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 <stdlib.h> #include <string.h> #include <inttypes.h> @@ -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 ////////////////////////////////////////////////////////////// @@ -87,10 +87,7 @@ void TwoWire::pins(int sda, int scl) default_scl_pin = scl; } -void TwoWire::begin(void) -{ - begin(default_sda_pin, default_scl_pin); -} +void TwoWire::begin(void) { begin(default_sda_pin, default_scl_pin); } void TwoWire::begin(uint8_t address) { @@ -100,25 +97,13 @@ void TwoWire::begin(uint8_t address) begin(); } -uint8_t TwoWire::status() -{ - return twi_status(); -} +uint8_t TwoWire::status() { return twi_status(); } -void TwoWire::begin(int address) -{ - begin((uint8_t)address); -} +void TwoWire::begin(int address) { begin((uint8_t)address); } -void TwoWire::setClock(uint32_t frequency) -{ - twi_setClock(frequency); -} +void TwoWire::setClock(uint32_t frequency) { twi_setClock(frequency); } -void TwoWire::setClockStretchLimit(uint32_t limit) -{ - twi_setClockStretchLimit(limit); -} +void TwoWire::setClockStretchLimit(uint32_t limit) { twi_setClockStretchLimit(limit); } size_t TwoWire::requestFrom(uint8_t address, size_t size, bool sendStop) { @@ -126,8 +111,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,35 +134,30 @@ uint8_t TwoWire::requestFrom(int address, int quantity) uint8_t TwoWire::requestFrom(int address, int quantity, int sendStop) { - return requestFrom(static_cast<uint8_t>(address), static_cast<size_t>(quantity), static_cast<bool>(sendStop)); + return requestFrom(static_cast<uint8_t>(address), static_cast<size_t>(quantity), + static_cast<bool>(sendStop)); } void TwoWire::beginTransmission(uint8_t address) { - transmitting = 1; - txAddress = address; - txBufferIndex = 0; + transmitting = 1; + txAddress = address; + txBufferIndex = 0; txBufferLength = 0; } -void TwoWire::beginTransmission(int address) -{ - beginTransmission((uint8_t)address); -} +void TwoWire::beginTransmission(int address) { beginTransmission((uint8_t)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; } -uint8_t TwoWire::endTransmission(void) -{ - return endTransmission(true); -} +uint8_t TwoWire::endTransmission(void) { return endTransmission(true); } size_t TwoWire::write(uint8_t data) { @@ -199,7 +179,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 +235,9 @@ int TwoWire::peek(void) void TwoWire::flush(void) { - rxBufferIndex = 0; + rxBufferIndex = 0; rxBufferLength = 0; - txBufferIndex = 0; + txBufferIndex = 0; txBufferLength = 0; } @@ -283,7 +263,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 +280,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 +292,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<void(*)(size_t)>(function); + user_onReceive = reinterpret_cast<void (*)(size_t)>(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 <inttypes.h> #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..73f45e0ae0 100644 --- a/libraries/Wire/examples/master_reader/master_reader.ino +++ b/libraries/Wire/examples/master_reader/master_reader.ino @@ -8,18 +8,17 @@ // This example code is in the public domain. - #include <Wire.h> #include <PolledTimeout.h> #define SDA_PIN 4 #define SCL_PIN 5 const int16_t I2C_MASTER = 0x42; -const int16_t I2C_SLAVE = 0x08; +const int16_t I2C_SLAVE = 0x08; void setup() { - Serial.begin(115200); // start serial for output - Wire.begin(SDA_PIN, SCL_PIN, I2C_MASTER); // join i2c bus (address optional for master) + Serial.begin(115200); // start serial for output + Wire.begin(SDA_PIN, SCL_PIN, I2C_MASTER); // join i2c bus (address optional for master) } void loop() { @@ -27,11 +26,11 @@ void loop() { static periodic nextPing(1000); if (nextPing) { - Wire.requestFrom(I2C_SLAVE, 6); // request 6 bytes from slave device #8 + Wire.requestFrom(I2C_SLAVE, 6); // request 6 bytes from slave device #8 - while (Wire.available()) { // slave may send less than requested - char c = Wire.read(); // receive a byte as character - Serial.print(c); // print the character + 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..727ff0a09d 100644 --- a/libraries/Wire/examples/master_writer/master_writer.ino +++ b/libraries/Wire/examples/master_writer/master_writer.ino @@ -8,17 +8,16 @@ // This example code is in the public domain. - #include <Wire.h> #include <PolledTimeout.h> #define SDA_PIN 4 #define SCL_PIN 5 const int16_t I2C_MASTER = 0x42; -const int16_t I2C_SLAVE = 0x08; +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 +27,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..04bbb06cec 100644 --- a/libraries/Wire/examples/slave_receiver/slave_receiver.ino +++ b/libraries/Wire/examples/slave_receiver/slave_receiver.ino @@ -8,34 +8,31 @@ // This example code is in the public domain. - #include <Wire.h> #define SDA_PIN 4 #define SCL_PIN 5 const int16_t I2C_MASTER = 0x42; -const int16_t I2C_SLAVE = 0x08; +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..7a3815852a 100644 --- a/libraries/Wire/examples/slave_sender/slave_sender.ino +++ b/libraries/Wire/examples/slave_sender/slave_sender.ino @@ -8,25 +8,23 @@ // This example code is in the public domain. - #include <Wire.h> #define SDA_PIN 4 #define SCL_PIN 5 const int16_t I2C_MASTER = 0x42; -const int16_t I2C_SLAVE = 0x08; +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..ad690c2d7a 100644 --- a/libraries/esp8266/examples/BlinkPolledTimeout/BlinkPolledTimeout.ino +++ b/libraries/esp8266/examples/BlinkPolledTimeout/BlinkPolledTimeout.ino @@ -22,11 +22,10 @@ Note that this sketch uses LED_BUILTIN to find the pin with the internal LED */ - #include <PolledTimeout.h> 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() { @@ -37,53 +36,58 @@ void ledToggle() { digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); // Change the state of the LED } - -esp8266::polledTimeout::periodicFastUs halfPeriod(500000); //use fully qualified type and avoid importing all ::esp8266 namespace to the global namespace +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() { Serial.begin(115200); Serial.println(); - Serial.printf("periodic/oneShotMs::timeMax() = %u ms\n", (uint32_t)esp8266::polledTimeout::periodicMs::timeMax()); - Serial.printf("periodic/oneShotFastMs::timeMax() = %u ms\n", (uint32_t)esp8266::polledTimeout::periodicFastMs::timeMax()); - 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 + Serial.printf("periodic/oneShotMs::timeMax() = %u ms\n", + (uint32_t)esp8266::polledTimeout::periodicMs::timeMax()); + Serial.printf("periodic/oneShotFastMs::timeMax() = %u ms\n", + (uint32_t)esp8266::polledTimeout::periodicFastMs::timeMax()); + 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 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(); } - //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(); } - //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) { diff --git a/libraries/esp8266/examples/BlinkWithoutDelay/BlinkWithoutDelay.ino b/libraries/esp8266/examples/BlinkWithoutDelay/BlinkWithoutDelay.ino index 24689f3a44..6e891cc8fd 100644 --- a/libraries/esp8266/examples/BlinkWithoutDelay/BlinkWithoutDelay.ino +++ b/libraries/esp8266/examples/BlinkWithoutDelay/BlinkWithoutDelay.ino @@ -13,11 +13,9 @@ int ledState = LOW; unsigned long previousMillis = 0; -const long interval = 1000; +const long interval = 1000; -void setup() { - pinMode(LED_BUILTIN, OUTPUT); -} +void setup() { pinMode(LED_BUILTIN, OUTPUT); } void loop() { unsigned long currentMillis = millis(); diff --git a/libraries/esp8266/examples/CallBackList/CallBackGeneric.ino b/libraries/esp8266/examples/CallBackList/CallBackGeneric.ino index ce4dac2470..ba2eb9451b 100644 --- a/libraries/esp8266/examples/CallBackList/CallBackGeneric.ino +++ b/libraries/esp8266/examples/CallBackList/CallBackGeneric.ino @@ -6,41 +6,29 @@ using namespace experimental::CBListImplentation; class exampleClass { public: - exampleClass() {}; + exampleClass() {}; - using exCallBack = std::function<void(int)>; - using exHandler = CallBackList<exCallBack>::CallBackHandler; + using exCallBack = std::function<void(int)>; + using exHandler = CallBackList<exCallBack>::CallBackHandler; - CallBackList<exCallBack> myHandlers; + CallBackList<exCallBack> 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; -void cb1(int in) { - Serial.printf("Callback 1, in = %d\n", in); -} +void cb1(int in) { Serial.printf("Callback 1, in = %d\n", in); } -void cb2(int in) { - Serial.printf("Callback 2, in = %d\n", in); -} +void cb2(int in) { Serial.printf("Callback 2, in = %d\n", in); } -void cb3(int in, int s) { - Serial.printf("Callback 3, in = %d, s = %d\n", in, s); -} +void cb3(int in, int s) { Serial.printf("Callback 3, in = %d, s = %d\n", in, s); } -Ticker tk, tk2, tk3; +Ticker tk, tk2, tk3; exampleClass::exHandler e1 = myExample.setHandler(cb1); exampleClass::exHandler e2 = myExample.setHandler(cb2); exampleClass::exHandler e3 = myExample.setHandler(std::bind(cb3, std::placeholders::_1, 10)); @@ -52,13 +40,8 @@ void setup() { Serial.printf("trigger %d\n", (uint32_t)millis()); myExample.trigger(millis()); }); - tk2.once_ms(10000, []() { - myExample.removeHandler(e2); - }); - tk3.once_ms(20000, []() { - e3.reset(); - }); + tk2.once_ms(10000, []() { myExample.removeHandler(e2); }); + tk3.once_ms(20000, []() { e3.reset(); }); } -void loop() { -} +void loop() { } diff --git a/libraries/esp8266/examples/CallSDKFunctions/CallSDKFunctions.ino b/libraries/esp8266/examples/CallSDKFunctions/CallSDKFunctions.ino index 77285a31b5..af62f405b9 100644 --- a/libraries/esp8266/examples/CallSDKFunctions/CallSDKFunctions.ino +++ b/libraries/esp8266/examples/CallSDKFunctions/CallSDKFunctions.ino @@ -18,9 +18,7 @@ extern "C" { } #endif -void setup() { - Serial.begin(115200); -} +void setup() { Serial.begin(115200); } void loop() { // Call Espressif SDK functionality - wrapped in ifdef so that it still diff --git a/libraries/esp8266/examples/CheckFlashCRC/CheckFlashCRC.ino b/libraries/esp8266/examples/CheckFlashCRC/CheckFlashCRC.ino index fa520722f6..62024b71a1 100644 --- a/libraries/esp8266/examples/CheckFlashCRC/CheckFlashCRC.ino +++ b/libraries/esp8266/examples/CheckFlashCRC/CheckFlashCRC.ino @@ -21,12 +21,12 @@ 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); - space[42] = 64; + 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); @@ -40,6 +40,4 @@ void setup() { 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..61fdd2f378 100644 --- a/libraries/esp8266/examples/CheckFlashConfig/CheckFlashConfig.ino +++ b/libraries/esp8266/examples/CheckFlashConfig/CheckFlashConfig.ino @@ -5,22 +5,23 @@ */ -void setup(void) { - Serial.begin(115200); -} +void setup(void) { Serial.begin(115200); } void loop() { - - uint32_t realSize = ESP.getFlashChipRealSize(); - uint32_t ideSize = ESP.getFlashChipSize(); - FlashMode_t ideMode = ESP.getFlashChipMode(); + uint32_t realSize = ESP.getFlashChipRealSize(); + uint32_t ideSize = ESP.getFlashChipSize(); + FlashMode_t ideMode = ESP.getFlashChipMode(); Serial.printf("Flash real id: %08X\n", ESP.getFlashChipId()); Serial.printf("Flash real size: %u bytes\n\n", realSize); 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..2b25a00390 100644 --- a/libraries/esp8266/examples/ConfigFile/ConfigFile.ino +++ b/libraries/esp8266/examples/ConfigFile/ConfigFile.ino @@ -22,13 +22,13 @@ bool loadConfig() { } StaticJsonDocument<200> doc; - auto error = deserializeJson(doc, configFile); + auto error = deserializeJson(doc, configFile); if (error) { Serial.println("Failed to parse config file"); return false; } - const char* serverName = doc["serverName"]; + const char* serverName = doc["serverName"]; const char* accessToken = doc["accessToken"]; // Real world application would store these values in some variables for @@ -43,7 +43,7 @@ bool loadConfig() { bool saveConfig() { StaticJsonDocument<200> doc; - doc["serverName"] = "api.example.com"; + doc["serverName"] = "api.example.com"; doc["accessToken"] = "128du9as8du12eoue8da98h123ueh9h98"; File configFile = LittleFS.open("/config.json", "w"); @@ -67,7 +67,6 @@ void setup() { return; } - if (!saveConfig()) { Serial.println("Failed to save config"); } else { @@ -81,5 +80,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..f614e59183 100644 --- a/libraries/esp8266/examples/FadePolledTimeout/FadePolledTimeout.ino +++ b/libraries/esp8266/examples/FadePolledTimeout/FadePolledTimeout.ino @@ -39,12 +39,12 @@ void setup() { // PWM-Locked generator: https://github.com/esp8266/Arduino/pull/7231 enablePhaseLockedWaveform(); - pinMode(LED_BUILTIN, OUTPUT); // Initialize the LED_BUILTIN pin as an output + pinMode(LED_BUILTIN, OUTPUT); // Initialize the LED_BUILTIN pin as an output analogWriteRange(1000); - using esp8266::polledTimeout::oneShotMs; //import the type to the local namespace + using esp8266::polledTimeout::oneShotMs; // import the type to the local namespace - digitalWrite(LED_BUILTIN, LOW); // Turn the LED on (Note that LOW is the voltage level + digitalWrite(LED_BUILTIN, LOW); // Turn the LED on (Note that LOW is the voltage level oneShotMs timeoutOn(2000); while (!timeoutOn) { @@ -54,17 +54,16 @@ void setup() { stepPeriod.reset(); } - void loop() { - static int val = 0; + static int val = 0; static int delta = 100; if (stepPeriod) { val += delta; if (val < 0) { - val = 100; + val = 100; delta = 100; } else if (val > 1000) { - val = 900; + val = 900; delta = -100; } analogWrite(LED_BUILTIN, val); diff --git a/libraries/esp8266/examples/HeapMetric/HeapMetric.ino b/libraries/esp8266/examples/HeapMetric/HeapMetric.ino index 5c7a27dbbe..d2cdff916e 100644 --- a/libraries/esp8266/examples/HeapMetric/HeapMetric.ino +++ b/libraries/esp8266/examples/HeapMetric/HeapMetric.ino @@ -11,7 +11,7 @@ void stats(const char* what) { // or all at once: uint32_t free; uint32_t max; - uint8_t frag; + uint8_t frag; ESP.getHeapStats(&free, &max, &frag); Serial.printf("free: %7u - max: %7u - frag: %3d%% <- ", free, max, frag); @@ -21,7 +21,7 @@ void stats(const char* what) { void tryit(int blocksize) { void** p; - int blocks; + int blocks; /* heap-used ~= blocks*sizeof(void*) + blocks*blocksize @@ -52,21 +52,19 @@ void tryit(int blocksize) { calculation of multiple elements combined with the rounding up for the 8-byte alignment of each allocation can make for some tricky calculations. */ - int rawMemoryMaxFreeBlockSize = ESP.getMaxFreeBlockSize(); + int rawMemoryMaxFreeBlockSize = ESP.getMaxFreeBlockSize(); // Remove the space for overhead component of the blocks*sizeof(void*) array. int maxFreeBlockSize = rawMemoryMaxFreeBlockSize - UMM_OVERHEAD_ADJUST; // Initial estimate to use all of the MaxFreeBlock with multiples of 8 rounding up. - blocks = maxFreeBlockSize / - (((blocksize + UMM_OVERHEAD_ADJUST + 7) & ~7) + sizeof(void*)); + blocks = maxFreeBlockSize / (((blocksize + UMM_OVERHEAD_ADJUST + 7) & ~7) + sizeof(void*)); /* While we allowed for the 8-byte alignment overhead for blocks*blocksize we were unable to compensate in advance for the later 8-byte aligning needed for the blocks*sizeof(void*) allocation. Thus blocks may be off by one count. We now validate the estimate and adjust as needed. */ - int rawMemoryEstimate = - blocks * ((blocksize + UMM_OVERHEAD_ADJUST + 7) & ~7) + - ((blocks * sizeof(void*) + UMM_OVERHEAD_ADJUST + 7) & ~7); + int rawMemoryEstimate = blocks * ((blocksize + UMM_OVERHEAD_ADJUST + 7) & ~7) + + ((blocks * sizeof(void*) + UMM_OVERHEAD_ADJUST + 7) & ~7); if (rawMemoryMaxFreeBlockSize < rawMemoryEstimate) { --blocks; } @@ -158,5 +156,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..1be63d4174 100644 --- a/libraries/esp8266/examples/HelloCrypto/HelloCrypto.ino +++ b/libraries/esp8266/examples/HelloCrypto/HelloCrypto.ino @@ -1,7 +1,9 @@ /** - This example demonstrates the usage of the ESP8266 Crypto implementation, which aims to contain easy-to-use cryptographic functions. - Crypto is currently primarily a frontend for the cryptographic library BearSSL which is used by `BearSSL::WiFiClientSecure` and `BearSSL::WiFiServerSecure` in the ESP8266 Arduino Core. - Extensive documentation can be found in the Crypto source code files and on the [BearSSL homepage](https://www.bearssl.org). + This example demonstrates the usage of the ESP8266 Crypto implementation, which aims to contain + easy-to-use cryptographic functions. Crypto is currently primarily a frontend for the + cryptographic library BearSSL which is used by `BearSSL::WiFiClientSecure` and + `BearSSL::WiFiServerSecure` in the ESP8266 Arduino Core. Extensive documentation can be found in + the Crypto source code files and on the [BearSSL homepage](https://www.bearssl.org). */ #include <ESP8266WiFi.h> @@ -12,20 +14,22 @@ namespace TypeCast = experimental::TypeConversion; /** NOTE: Although we could define the strings below as normal String variables, - here we are using PROGMEM combined with the FPSTR() macro (and also just the F() macro further down in the file). - The reason is that this approach will place the strings in flash memory which will help save RAM during program execution. - Reading strings from flash will be slower than reading them from RAM, - but this will be a negligible difference when printing them to Serial. + here we are using PROGMEM combined with the FPSTR() macro (and also just the F() macro further + down in the file). The reason is that this approach will place the strings in flash memory which + will help save RAM during program execution. Reading strings from flash will be slower than + reading them from RAM, but this will be a negligible difference when printing them to Serial. More on F(), FPSTR() and PROGMEM: 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 . - // This will however delay node WiFi start-up by about 700 ms. The delay is 900 ms if we otherwise would have stored the WiFi network we want to connect to. + // Prevents the flash memory from being worn out, see: + // https://github.com/esp8266/Arduino/issues/1054 . This will however delay node WiFi start-up by + // about 700 ms. The delay is 900 ms if we otherwise would have stored the WiFi network we want to + // connect to. WiFi.persistent(false); Serial.begin(115200); @@ -35,7 +39,8 @@ void setup() { } void loop() { - // This serves only to demonstrate the library use. See the header file for a full list of functions. + // This serves only to demonstrate the library use. See the header file for a full list of + // functions. using namespace experimental::crypto; @@ -47,40 +52,52 @@ void loop() { static uint32_t encryptionCounter = 0; - // Generate the salt to use for HKDF 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 SHA256::hash(exampleData.c_str(), exampleData.length(), resultArray); - Serial.println(String(F("\nThis is the SHA256 hash of our example data, in HEX format:\n")) + TypeCast::uint8ArrayToHexString(resultArray, sizeof resultArray)); - Serial.println(String(F("This is the SHA256 hash of our example data, in HEX format, using String output:\n")) + SHA256::hash(exampleData)); - + Serial.println(String(F("\nThis is the SHA256 hash of our example data, in HEX format:\n")) + + TypeCast::uint8ArrayToHexString(resultArray, sizeof resultArray)); + Serial.println( + String( + F("This is the SHA256 hash of our example data, in HEX format, using String output:\n")) + + SHA256::hash(exampleData)); // HMAC // Note that HMAC output length is limited - SHA256::hmac(exampleData.c_str(), exampleData.length(), derivedKey, sizeof derivedKey, resultArray, sizeof resultArray); - Serial.println(String(F("\nThis is the SHA256 HMAC of our example data, in HEX format:\n")) + TypeCast::uint8ArrayToHexString(resultArray, sizeof resultArray)); - Serial.println(String(F("This is the SHA256 HMAC of our example data, in HEX format, using String output:\n")) + SHA256::hmac(exampleData, derivedKey, sizeof derivedKey, SHA256::NATURAL_LENGTH)); - + SHA256::hmac(exampleData.c_str(), exampleData.length(), derivedKey, sizeof derivedKey, + resultArray, sizeof resultArray); + Serial.println(String(F("\nThis is the SHA256 HMAC of our example data, in HEX format:\n")) + + TypeCast::uint8ArrayToHexString(resultArray, sizeof resultArray)); + Serial.println( + String( + F("This is the SHA256 HMAC of our example data, in HEX format, using String output:\n")) + + SHA256::hmac(exampleData, derivedKey, sizeof derivedKey, SHA256::NATURAL_LENGTH)); // Authenticated Encryption with Associated Data (AEAD) - String dataToEncrypt = F("This data is not encrypted."); - uint8_t resultingNonce[12] { 0 }; // The nonce is always 12 bytes - uint8_t resultingTag[16] { 0 }; // The tag is always 16 bytes + 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 Serial.println(String(F("\nThis is the data to encrypt: ")) + dataToEncrypt); // Note that the key must be ENCRYPTION_KEY_LENGTH long. - ChaCha20Poly1305::encrypt(dataToEncrypt.begin(), dataToEncrypt.length(), derivedKey, &encryptionCounter, sizeof encryptionCounter, resultingNonce, resultingTag); + ChaCha20Poly1305::encrypt(dataToEncrypt.begin(), dataToEncrypt.length(), derivedKey, + &encryptionCounter, sizeof encryptionCounter, resultingNonce, + resultingTag); Serial.println(String(F("Encrypted data: ")) + dataToEncrypt); - bool decryptionSucceeded = ChaCha20Poly1305::decrypt(dataToEncrypt.begin(), dataToEncrypt.length(), derivedKey, &encryptionCounter, sizeof encryptionCounter, resultingNonce, resultingTag); + bool decryptionSucceeded = ChaCha20Poly1305::decrypt( + dataToEncrypt.begin(), dataToEncrypt.length(), derivedKey, &encryptionCounter, + sizeof encryptionCounter, resultingNonce, resultingTag); encryptionCounter++; if (decryptionSucceeded) { @@ -91,8 +108,8 @@ void loop() { Serial.println(dataToEncrypt); - - Serial.println(F("\n##########################################################################################################\n")); + Serial.println(F("\n#############################################################################" + "#############################\n")); delay(10000); } diff --git a/libraries/esp8266/examples/HwdtStackDump/HwdtStackDump.ino b/libraries/esp8266/examples/HwdtStackDump/HwdtStackDump.ino index ff1c41e93b..6b36f8718f 100644 --- a/libraries/esp8266/examples/HwdtStackDump/HwdtStackDump.ino +++ b/libraries/esp8266/examples/HwdtStackDump/HwdtStackDump.ino @@ -19,15 +19,15 @@ #include <ESP8266WiFi.h> #include <Esp.h> #include <user_interface.h> -#include <coredecls.h> // g_pcont - only needed for this debug demo +#include <coredecls.h> // g_pcont - only needed for this debug demo #include <StackThunk.h> #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; //////////////////////////////////////////////////////////////////// @@ -39,18 +39,19 @@ extern "C" { #define thunk_ets_uart_printf ets_uart_printf #else - int thunk_ets_uart_printf(const char *format, ...) __attribute__((format(printf, 1, 2))); - // Second stack thunked helper - this macro creates the global function thunk_ets_uart_printf - make_stack_thunk(ets_uart_printf); +int thunk_ets_uart_printf(const char* format, ...) __attribute__((format(printf, 1, 2))); +// Second stack thunked helper - this macro creates the global function thunk_ets_uart_printf +make_stack_thunk(ets_uart_printf); #endif }; //////////////////////////////////////////////////////////////////// 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 +78,9 @@ 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) @@ -94,7 +95,6 @@ void setup(void) { processKey(Serial, '?'); } - void loop(void) { if (Serial.available() > 0) { int hotKey = Serial.read(); diff --git a/libraries/esp8266/examples/HwdtStackDump/ProcessKey.ino b/libraries/esp8266/examples/HwdtStackDump/ProcessKey.ino index 7d182bf377..bed9954358 100644 --- a/libraries/esp8266/examples/HwdtStackDump/ProcessKey.ino +++ b/libraries/esp8266/examples/HwdtStackDump/ProcessKey.ino @@ -1,6 +1,6 @@ #include <esp8266_undocumented.h> -void crashMeIfYouCan(void)__attribute__((weak)); -int divideA_B(int a, int b); +void crashMeIfYouCan(void) __attribute__((weak)); +int divideA_B(int a, int b); int* nullPointer = NULL; @@ -15,16 +15,15 @@ void processKey(Print& out, int hotKey) { ESP.restart(); break; case 's': { - uint32_t startTime = millis(); - out.printf_P(PSTR("Now crashing with Software WDT. This will take about 3 seconds.\r\n")); - ets_install_putc1(ets_putc); - while (true) { - ets_printf("%9lu\r", (millis() - startTime)); - ets_delay_us(250000); - // stay in an loop blocking other system activity. - } + uint32_t startTime = millis(); + out.printf_P(PSTR("Now crashing with Software WDT. This will take about 3 seconds.\r\n")); + ets_install_putc1(ets_putc); + while (true) { + ets_printf("%9lu\r", (millis() - startTime)); + ets_delay_us(250000); + // stay in an loop blocking other system activity. } - break; + } break; case 'h': out.printf_P(PSTR("Now crashing with Hardware WDT. This will take about 6 seconds.\r\n")); asm volatile("mov.n a2, %0\n\t" @@ -32,7 +31,10 @@ 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(); @@ -61,7 +63,8 @@ void processKey(Print& out, int hotKey) { break; case 'w': out.println(F("Now calling: void crashMeIfYouCan(void)__attribute__((weak));")); - out.println(F("This function has a prototype but was missing when the sketch was linked. ...")); + out.println( + F("This function has a prototype but was missing when the sketch was linked. ...")); crashMeIfYouCan(); break; case 'b': @@ -89,8 +92,10 @@ void processKey(Print& out, int hotKey) { out.println(F(" s - Software WDT")); out.println(F(" h - Hardware WDT - looping with interrupts disabled")); out.println(F(" w - Hardware WDT - calling a missing (weak) function.")); - out.println(F(" 0 - Hardware WDT - a hard coded compiler breakpoint from a compile time detected divide by zero")); - out.println(F(" b - Hardware WDT - a forgotten hard coded 'break 1, 15;' and no GDB running.")); + out.println(F(" 0 - Hardware WDT - a hard coded compiler breakpoint from a compile time " + "detected divide by zero")); + out.println( + F(" b - Hardware WDT - a forgotten hard coded 'break 1, 15;' and no GDB running.")); out.println(F(" z - Divide by zero, exception(0);")); out.println(F(" p - panic();")); out.println(); @@ -105,12 +110,8 @@ void processKey(Print& out, int hotKey) { // With the current toolchain 10.1, using this to divide by zero will *not* be // caught at compile time. -int __attribute__((noinline)) divideA_B(int a, int b) { - return (a / b); -} +int __attribute__((noinline)) divideA_B(int a, int b) { return (a / b); } // With the current toolchain 10.1, using this to divide by zero *will* be // caught at compile time. And a hard coded breakpoint will be inserted. -int divideA_B_bp(int a, int b) { - return (a / b); -} +int divideA_B_bp(int a, int b) { return (a / b); } diff --git a/libraries/esp8266/examples/I2SInput/I2SInput.ino b/libraries/esp8266/examples/I2SInput/I2SInput.ino index 836da2685b..9c4aa50f37 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); @@ -50,6 +50,5 @@ void setup() { } } -void loop() { - /* Nothing here */ +void loop() { /* Nothing here */ } diff --git a/libraries/esp8266/examples/I2STransmit/I2STransmit.ino b/libraries/esp8266/examples/I2STransmit/I2STransmit.ino index 2eaab265d2..b14b3a7d15 100644 --- a/libraries/esp8266/examples/I2STransmit/I2STransmit.ino +++ b/libraries/esp8266/examples/I2STransmit/I2STransmit.ino @@ -14,19 +14,19 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif // Set your network here -const char *SSID = STASSID; -const char *PASS = STAPSK; +const char* SSID = STASSID; +const char* PASS = STAPSK; WiFiUDP udp; // Set your listener PC's IP here: const IPAddress listener = { 192, 168, 1, 2 }; -const int port = 8266; +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,7 +60,6 @@ void setup() { udp.beginPacket(listener, port); udp.write("I2S Receiver\r\n"); udp.endPacket(); - } void loop() { diff --git a/libraries/esp8266/examples/IramReserve/IramReserve.ino b/libraries/esp8266/examples/IramReserve/IramReserve.ino index 96d7479da4..11d1d17657 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 <sys/config.h> // For config/core-isa.h +#include <sys/config.h> // For config/core-isa.h #endif // durable - as in long life, persisting across reboots. @@ -29,7 +29,6 @@ struct durable { uint32_t chksum; }; - // Leave a durable block of IRAM after the 2nd heap. // The block should be in 8-byte increments and fall on an 8-byte alignment. @@ -39,7 +38,7 @@ struct durable { #define IRAM_RESERVE ((uintptr_t)XCHAL_INSTRAM1_VADDR + 0xC000UL - IRAM_RESERVE_SZ) // Define a reference with the right properties to make access easier. -#define DURABLE ((struct durable *)IRAM_RESERVE) +#define DURABLE ((struct durable*)IRAM_RESERVE) #define INCREMENT_BOOTCOUNT() (DURABLE->bootCounter)++ extern struct rst_info resetInfo; @@ -58,11 +57,9 @@ extern struct rst_info resetInfo; XOR sum on the IRAM data (or just a section of the IRAM data). */ inline bool is_iram_valid(void) { - return (REASON_WDT_RST <= resetInfo.reason && - REASON_SOFT_RESTART >= resetInfo.reason); + return (REASON_WDT_RST <= resetInfo.reason && REASON_SOFT_RESTART >= resetInfo.reason); } - void setup() { WiFi.persistent(false); WiFi.mode(WIFI_OFF); @@ -79,7 +76,6 @@ void setup() { Serial.printf("Number of reboots at %u\r\n", DURABLE->bootCounter); Serial.printf("\r\nSome less than direct, ways to restart:\r\n"); processKey(Serial, '?'); - } void loop(void) { @@ -109,10 +105,9 @@ 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 + sec_heap_sz -= IRAM_RESERVE_SZ; // Shrink IRAM heap if (0xC000UL > sec_heap_sz) { - - umm_init_iram_ex((void *)sec_heap, sec_heap_sz, true); + umm_init_iram_ex((void*)sec_heap, sec_heap_sz, true); } } @@ -122,9 +117,9 @@ void setup() { WiFi.mode(WIFI_OFF); Serial.begin(115200); delay(10); - Serial.println("\r\n\r\nThis sketch requires Tools Option: 'MMU: 16KB cache + 48KB IRAM and 2nd Heap (shared)'"); + 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..bed9954358 100644 --- a/libraries/esp8266/examples/IramReserve/ProcessKey.ino +++ b/libraries/esp8266/examples/IramReserve/ProcessKey.ino @@ -1,6 +1,6 @@ #include <esp8266_undocumented.h> -void crashMeIfYouCan(void)__attribute__((weak)); -int divideA_B(int a, int b); +void crashMeIfYouCan(void) __attribute__((weak)); +int divideA_B(int a, int b); int* nullPointer = NULL; @@ -15,16 +15,15 @@ void processKey(Print& out, int hotKey) { ESP.restart(); break; case 's': { - uint32_t startTime = millis(); - out.printf_P(PSTR("Now crashing with Software WDT. This will take about 3 seconds.\r\n")); - ets_install_putc1(ets_putc); - while (true) { - ets_printf("%9lu\r", (millis() - startTime)); - ets_delay_us(250000); - // stay in an loop blocking other system activity. - } + uint32_t startTime = millis(); + out.printf_P(PSTR("Now crashing with Software WDT. This will take about 3 seconds.\r\n")); + ets_install_putc1(ets_putc); + while (true) { + ets_printf("%9lu\r", (millis() - startTime)); + ets_delay_us(250000); + // stay in an loop blocking other system activity. } - break; + } break; case 'h': out.printf_P(PSTR("Now crashing with Hardware WDT. This will take about 6 seconds.\r\n")); asm volatile("mov.n a2, %0\n\t" @@ -32,7 +31,10 @@ 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(); @@ -61,7 +63,8 @@ void processKey(Print& out, int hotKey) { break; case 'w': out.println(F("Now calling: void crashMeIfYouCan(void)__attribute__((weak));")); - out.println(F("This function has a prototype but was missing when the sketch was linked. ...")); + out.println( + F("This function has a prototype but was missing when the sketch was linked. ...")); crashMeIfYouCan(); break; case 'b': @@ -89,8 +92,10 @@ void processKey(Print& out, int hotKey) { out.println(F(" s - Software WDT")); out.println(F(" h - Hardware WDT - looping with interrupts disabled")); out.println(F(" w - Hardware WDT - calling a missing (weak) function.")); - out.println(F(" 0 - Hardware WDT - a hard coded compiler breakpoint from a compile time detected divide by zero")); - out.println(F(" b - Hardware WDT - a forgotten hard coded 'break 1, 15;' and no GDB running.")); + out.println(F(" 0 - Hardware WDT - a hard coded compiler breakpoint from a compile time " + "detected divide by zero")); + out.println( + F(" b - Hardware WDT - a forgotten hard coded 'break 1, 15;' and no GDB running.")); out.println(F(" z - Divide by zero, exception(0);")); out.println(F(" p - panic();")); out.println(); @@ -105,12 +110,8 @@ void processKey(Print& out, int hotKey) { // With the current toolchain 10.1, using this to divide by zero will *not* be // caught at compile time. -int __attribute__((noinline)) divideA_B(int a, int b) { - return (a / b); -} +int __attribute__((noinline)) divideA_B(int a, int b) { return (a / b); } // With the current toolchain 10.1, using this to divide by zero *will* be // caught at compile time. And a hard coded breakpoint will be inserted. -int divideA_B_bp(int a, int b) { - return (a / b); -} +int divideA_B_bp(int a, int b) { return (a / b); } diff --git a/libraries/esp8266/examples/LowPowerDemo/LowPowerDemo.ino b/libraries/esp8266/examples/LowPowerDemo/LowPowerDemo.ino index 2c22416e0d..da424fa545 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 <ESP8266WiFi.h> -#include <coredecls.h> // crc32() +#include <coredecls.h> // crc32() #include <PolledTimeout.h> -#include <include/WiFiState.h> // WiFiState structure details +#include <include/WiFiState.h> // 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,14 +63,14 @@ 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 gateway(0, 0, 0, 0); -IPAddress subnet(0, 0, 0, 0); -IPAddress dns1(0, 0, 0, 0); -IPAddress dns2(0, 0, 0, 0); -uint32_t timeout = 30E3; // 30 second timeout on the WiFi connection +IPAddress staticIP(0, 0, 0, 0); // parameters below are for your static IP address, if used +IPAddress gateway(0, 0, 0, 0); +IPAddress subnet(0, 0, 0, 0); +IPAddress dns1(0, 0, 0, 0); +IPAddress dns2(0, 0, 0, 0); +uint32_t timeout = 30E3; // 30 second timeout on the WiFi connection //#define TESTPOINT // used to track the timing of several test cycles (optional) #ifdef TESTPOINT @@ -82,10 +82,11 @@ uint32_t timeout = 30E3; // 30 second timeout on the WiFi connection #define testPoint_LOW #endif -// 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 +// 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,18 +95,18 @@ 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 + 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")); } @@ -115,8 +116,8 @@ void setup() { pinMode(testPointPin, OUTPUT); // test point for Light Sleep and Deep Sleep tests testPoint_LOW; // Deep Sleep reset doesn't clear GPIOs, testPoint LOW shows boot time #endif - pinMode(LED, OUTPUT); // activity and status indicator - digitalWrite(LED, LOW); // turn on the LED + pinMode(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(); @@ -129,12 +130,12 @@ void setup() { } // Read previous resets (Deep Sleeps) from RTC memory, if any - uint32_t crcOfData = crc32((uint8_t*) &nv->rtcData.rstCount, sizeof(nv->rtcData.rstCount)); + uint32_t crcOfData = crc32((uint8_t*)&nv->rtcData.rstCount, sizeof(nv->rtcData.rstCount)); if ((crcOfData = nv->rtcData.crc32) && (resetCause == "Deep-Sleep Wake")) { resetCount = nv->rtcData.rstCount; // read the previous reset count resetCount++; } - nv->rtcData.rstCount = 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 +165,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 +182,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")); } @@ -196,15 +197,17 @@ void runTest2() { void runTest3() { Serial.println(F("\n3rd test - Forced Modem Sleep")); WiFi.shutdown(nv->wss); // shut the modem down and save the WiFi state for faster reconnection - // WiFi.forceSleepBegin(delay_in_uS); // alternate method of Forced Modem Sleep for an optional timed shutdown, - // with WiFi.forceSleepBegin(0xFFFFFFF); the modem sleeps until you wake it, with values <= 0xFFFFFFE it's timed + // WiFi.forceSleepBegin(delay_in_uS); // alternate method of Forced Modem Sleep for an optional + // timed shutdown, + // with WiFi.forceSleepBegin(0xFFFFFFF); the modem sleeps until you wake it, with values <= + // 0xFFFFFFE it's timed // delay(10); // it doesn't always go to sleep unless you delay(10); yield() wasn't reliable readVoltage(); // read internal VCC 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() { @@ -229,9 +232,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 +244,63 @@ 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) + gpio_pin_wakeup_enable(GPIO_ID_PIN(WAKE_UP_PIN), + GPIO_PIN_INTR_LOLEVEL); // GPIO wakeup (optional) // only LOLEVEL or HILEVEL interrupts work, no edge, that's an SDK or CPU limitation - wifi_fpm_set_wakeup_cb(wakeupCallback); // set wakeup callback - // the callback is optional, but without it the modem will wake in 10 seconds then delay(10 seconds) - // with the callback the sleep time is only 10 seconds total, no extra delay() afterward + wifi_fpm_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 + 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, + 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 + 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... + 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 @@ -304,49 +309,53 @@ void runTest7() { } void runTest8() { - Serial.println(F("\n8th test - in RF_DEFAULT, Deep Sleep for 10 seconds, reset and wake with RFCAL")); + Serial.println( + F("\n8th test - in RF_DEFAULT, Deep Sleep for 10 seconds, reset and wake with RFCAL")); 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, // 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... + 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 } void runTest9() { - Serial.println(F("\n9th test - in RFCAL, Deep Sleep Instant for 10 seconds, reset and wake with NO_RFCAL")); + Serial.println( + F("\n9th test - in RFCAL, Deep Sleep Instant for 10 seconds, reset and wake with NO_RFCAL")); 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... + 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 } void runTest10() { - Serial.println(F("\n10th test - in NO_RFCAL, Deep Sleep Instant for 10 seconds, reset and wake with RF_DISABLED")); + Serial.println(F("\n10th test - in NO_RFCAL, Deep Sleep Instant for 10 seconds, reset and wake " + "with RF_DISABLED")); 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... + 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 } void resetTests() { readVoltage(); // read internal VCC Serial.println(F("\nTests completed, in RF_DISABLED, press the switch to do an ESP.restart()")); - memset(&nv->wss, 0, sizeof(nv->wss) * 2); // wipe saved WiFi states, comment this if you want to keep them + memset(&nv->wss, 0, + sizeof(nv->wss) * 2); // wipe saved WiFi states, comment this if you want to keep them waitPushbutton(false, 1000); ESP.restart(); } @@ -362,24 +371,24 @@ 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 + 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 +400,20 @@ 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 + 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 +422,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 ")); diff --git a/libraries/esp8266/examples/MMU48K/MMU48K.ino b/libraries/esp8266/examples/MMU48K/MMU48K.ino index d75d91232b..74b2b47650 100644 --- a/libraries/esp8266/examples/MMU48K/MMU48K.ino +++ b/libraries/esp8266/examples/MMU48K/MMU48K.ino @@ -4,21 +4,21 @@ #include <umm_malloc/umm_heap_select.h> #if defined(CORE_MOCK) -#define XCHAL_INSTRAM1_VADDR 0x40100000 +#define XCHAL_INSTRAM1_VADDR 0x40100000 #else -#include <sys/config.h> // For config/core-isa.h +#include <sys/config.h> // 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); -int divideA_B(int a, int b); +uint32_t timed_byte_read(char* pc, uint32_t* o); +uint32_t timed_byte_read2(char* pc, uint32_t* o); +int divideA_B(int a, int b); int* nullPointer = NULL; -char *probe_b = NULL; -short *probe_s = NULL; -char *probe_c = (char *)0x40110000; -short *unaligned_probe_s = NULL; +char* probe_b = NULL; +short* probe_s = NULL; +char* probe_c = (char*)0x40110000; +short* unaligned_probe_s = NULL; uint32_t read_var = 0x11223344; @@ -30,19 +30,19 @@ uint32_t read_var = 0x11223344; */ #if defined(MMU_IRAM_HEAP) || defined(MMU_SEC_HEAP) -uint32_t *gobble; -size_t gobble_sz; +uint32_t* gobble; +size_t gobble_sz; -#elif (MMU_IRAM_SIZE > 32*1024) -uint32_t gobble[4 * 1024] IRAM_ATTR; +#elif (MMU_IRAM_SIZE > 32 * 1024) +uint32_t gobble[4 * 1024] IRAM_ATTR; constexpr size_t gobble_sz = sizeof(gobble); #else -uint32_t gobble[256] IRAM_ATTR; +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); @@ -50,7 +50,7 @@ bool isValid(uint32_t *probe) { } ets_uart_printf("\nTesting for valid memory at %p ...\n", probe); - uint32_t savePS = xt_rsil(15); + uint32_t savePS = xt_rsil(15); uint32_t saveData = *probe; for (size_t i = 0; i < 32; i++) { *probe = BIT(i); @@ -67,9 +67,8 @@ bool isValid(uint32_t *probe) { return rc; } - -void dump_mem32(const void * addr, const size_t len) { - uint32_t *addr32 = (uint32_t *)addr; +void dump_mem32(const void* addr, const size_t len) { + uint32_t* addr32 = (uint32_t*)addr; ets_uart_printf("\n"); if ((uintptr_t)addr32 & 3) { ets_uart_printf("non-32-bit access\n"); @@ -108,7 +107,8 @@ void print_mmu_status(Print& oStream) { #ifdef MMU_IRAM_SIZE oStream.printf_P(PSTR(" IRAM Size: %u"), MMU_IRAM_SIZE); oStream.println(); - const uint32_t iram_free = MMU_IRAM_SIZE - (uint32_t)((uintptr_t)_text_end - (uintptr_t)XCHAL_INSTRAM1_VADDR); + const uint32_t iram_free + = MMU_IRAM_SIZE - (uint32_t)((uintptr_t)_text_end - (uintptr_t)XCHAL_INSTRAM1_VADDR); oStream.printf_P(PSTR(" IRAM free: %u"), iram_free); oStream.println(); #endif @@ -122,7 +122,6 @@ void print_mmu_status(Print& oStream) { #endif } - void setup() { WiFi.persistent(false); WiFi.mode(WIFI_OFF); @@ -137,15 +136,15 @@ void setup() { { HeapSelectIram ephemeral; // Serial.printf_P(PSTR("ESP.getFreeHeap(): %u\n"), ESP.getFreeHeap()); - gobble_sz = ESP.getFreeHeap() - UMM_OVERHEAD_ADJUST; // - 4096; - gobble = (uint32_t *)malloc(gobble_sz); + gobble_sz = ESP.getFreeHeap() - UMM_OVERHEAD_ADJUST; // - 4096; + gobble = (uint32_t*)malloc(gobble_sz); } Serial.printf_P(PSTR("\r\nmalloc() from IRAM Heap:\r\n")); Serial.printf_P(PSTR(" gobble_sz: %u\r\n"), gobble_sz); Serial.printf_P(PSTR(" gobble: %p\r\n"), gobble); #elif defined(MMU_SEC_HEAP) - gobble = (uint32_t *)MMU_SEC_HEAP; + gobble = (uint32_t*)MMU_SEC_HEAP; gobble_sz = MMU_SEC_HEAP_SIZE; #endif @@ -165,41 +164,48 @@ void setup() { // Lets peak over the edge Serial.printf_P(PSTR("\r\nPeek over the edge of memory at 0x4010C000\r\n")); - dump_mem32((void *)(0x4010C000 - 16 * 4), 32); - - probe_b = (char *)gobble; - probe_s = (short *)((uintptr_t)gobble); - unaligned_probe_s = (short *)((uintptr_t)gobble + 1); + dump_mem32((void*)(0x4010C000 - 16 * 4), 32); + probe_b = (char*)gobble; + probe_s = (short*)((uintptr_t)gobble); + unaligned_probe_s = (short*)((uintptr_t)gobble + 1); } void processKey(Print& out, int hotKey) { switch (hotKey) { case 't': { - uint32_t tmp; - out.printf_P(PSTR("Test how much time is added by exception handling")); - out.println(); - out.printf_P(PSTR("Timed byte read from iCACHE %u cpu cycle count, 0x%02X."), timed_byte_read((char *)0x40200003, &tmp), tmp); - out.println(); - out.printf_P(PSTR("Timed byte read from iCACHE %u cpu cycle count, 0x%02X."), timed_byte_read((char *)0x40200003, &tmp), tmp); - out.println(); - out.printf_P(PSTR("Timed byte read from iRAM %u cpu cycle count, 0x%02X."), timed_byte_read((char *)0x40108000, &tmp), tmp); - out.println(); - out.printf_P(PSTR("Timed byte read from dRAM %u cpu cycle count, 0x%02X."), timed_byte_read((char *)((uintptr_t)&read_var + 1), &tmp), tmp); - out.println(); - out.printf_P(PSTR("Test how much time is used by the inline function method")); - out.println(); - out.printf_P(PSTR("Timed byte read from iCACHE %u cpu cycle count, 0x%02X."), timed_byte_read2((char *)0x40200003, &tmp), tmp); - out.println(); - out.printf_P(PSTR("Timed byte read from iCACHE %u cpu cycle count, 0x%02X."), timed_byte_read2((char *)0x40200003, &tmp), tmp); - out.println(); - out.printf_P(PSTR("Timed byte read from iRAM %u cpu cycle count, 0x%02X."), timed_byte_read2((char *)0x40108000, &tmp), tmp); - out.println(); - out.printf_P(PSTR("Timed byte read from dRAM %u cpu cycle count, 0x%02X."), timed_byte_read2((char *)((uintptr_t)&read_var + 1), &tmp), tmp); - out.println(); - out.println(); - break; - } + uint32_t tmp; + out.printf_P(PSTR("Test how much time is added by exception handling")); + out.println(); + out.printf_P(PSTR("Timed byte read from iCACHE %u cpu cycle count, 0x%02X."), + timed_byte_read((char*)0x40200003, &tmp), tmp); + out.println(); + out.printf_P(PSTR("Timed byte read from iCACHE %u cpu cycle count, 0x%02X."), + timed_byte_read((char*)0x40200003, &tmp), tmp); + out.println(); + out.printf_P(PSTR("Timed byte read from iRAM %u cpu cycle count, 0x%02X."), + timed_byte_read((char*)0x40108000, &tmp), tmp); + out.println(); + out.printf_P(PSTR("Timed byte read from dRAM %u cpu cycle count, 0x%02X."), + timed_byte_read((char*)((uintptr_t)&read_var + 1), &tmp), tmp); + out.println(); + out.printf_P(PSTR("Test how much time is used by the inline function method")); + out.println(); + out.printf_P(PSTR("Timed byte read from iCACHE %u cpu cycle count, 0x%02X."), + timed_byte_read2((char*)0x40200003, &tmp), tmp); + out.println(); + out.printf_P(PSTR("Timed byte read from iCACHE %u cpu cycle count, 0x%02X."), + timed_byte_read2((char*)0x40200003, &tmp), tmp); + out.println(); + out.printf_P(PSTR("Timed byte read from iRAM %u cpu cycle count, 0x%02X."), + timed_byte_read2((char*)0x40108000, &tmp), tmp); + out.println(); + out.printf_P(PSTR("Timed byte read from dRAM %u cpu cycle count, 0x%02X."), + timed_byte_read2((char*)((uintptr_t)&read_var + 1), &tmp), tmp); + out.println(); + out.println(); + break; + } case '9': out.printf_P(PSTR("Unaligned exception by reading short")); out.println(); @@ -217,7 +223,8 @@ void processKey(Print& out, int hotKey) { out.printf_P(PSTR("Read Byte, 0x%02X at %p"), probe_c[0], probe_c); xt_rsil(0); out.println(); - out.printf_P(PSTR("With Non32-bit access enabled, access range check is only done when 'Tools->Debug Level: CORE ...' is set.")); + out.printf_P(PSTR("With Non32-bit access enabled, access range check is only done when " + "'Tools->Debug Level: CORE ...' is set.")); out.println(); break; case 'b': @@ -228,17 +235,17 @@ void processKey(Print& out, int hotKey) { out.println(); break; case 'B': { - out.printf_P(PSTR("Load/Store exception by writing byte to iRAM")); - out.println(); - char val = 0x55; - out.printf_P(PSTR("Write byte, 0x%02X, to iRAM at %p"), val, probe_b); - out.println(); - out.flush(); - probe_b[0] = val; - out.printf_P(PSTR("Read Byte back from iRAM, 0x%02X at %p"), probe_b[0], probe_b); - out.println(); - break; - } + out.printf_P(PSTR("Load/Store exception by writing byte to iRAM")); + out.println(); + char val = 0x55; + out.printf_P(PSTR("Write byte, 0x%02X, to iRAM at %p"), val, probe_b); + out.println(); + out.flush(); + probe_b[0] = val; + out.printf_P(PSTR("Read Byte back from iRAM, 0x%02X at %p"), probe_b[0], probe_b); + out.println(); + break; + } case 's': out.printf_P(PSTR("Load/Store exception by reading short from iRAM")); out.println(); @@ -247,17 +254,17 @@ void processKey(Print& out, int hotKey) { out.println(); break; case 'S': { - out.printf_P(PSTR("Load/Store exception by writing short to iRAM")); - out.println(); - short int val = 0x0AA0; - out.printf_P(PSTR("Write short, 0x%04X, to iRAM at %p"), val, probe_s); - out.println(); - out.flush(); - probe_s[0] = val; - out.printf_P(PSTR("Read short back from iRAM, 0x%04X at %p"), probe_s[0], probe_s); - out.println(); - break; - } + out.printf_P(PSTR("Load/Store exception by writing short to iRAM")); + out.println(); + short int val = 0x0AA0; + out.printf_P(PSTR("Write short, 0x%04X, to iRAM at %p"), val, probe_s); + out.println(); + out.flush(); + probe_s[0] = val; + out.printf_P(PSTR("Read short back from iRAM, 0x%04X at %p"), probe_s[0], probe_s); + out.println(); + break; + } case 'R': out.printf_P(PSTR("Restart, ESP.restart(); ...")); out.println(); @@ -310,7 +317,6 @@ void processKey(Print& out, int hotKey) { } } - void serialClientLoop(void) { if (Serial.available() > 0) { int hotKey = Serial.read(); @@ -318,11 +324,6 @@ void serialClientLoop(void) { } } -void loop() { - serialClientLoop(); -} - +void loop() { serialClientLoop(); } -int __attribute__((noinline)) divideA_B(int a, int b) { - return (a / b); -} +int __attribute__((noinline)) divideA_B(int a, int b) { return (a / b); } diff --git a/libraries/esp8266/examples/NTP-TZ-DST/NTP-TZ-DST.ino b/libraries/esp8266/examples/NTP-TZ-DST/NTP-TZ-DST.ino index f6c2df08fc..c43bb0fccc 100644 --- a/libraries/esp8266/examples/NTP-TZ-DST/NTP-TZ-DST.ino +++ b/libraries/esp8266/examples/NTP-TZ-DST/NTP-TZ-DST.ino @@ -12,15 +12,13 @@ This example code is in the public domain. */ - #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif // initial time (possibly given by an external RTC) -#define RTC_UTC_TEST 1510592825 // 1510592825 = Monday 13 November 2017 17:07:05 UTC - +#define RTC_UTC_TEST 1510592825 // 1510592825 = Monday 13 November 2017 17:07:05 UTC // This database is autogenerated from IANA timezone database // https://www.iana.org/time-zones @@ -44,34 +42,34 @@ //////////////////////////////////////////////////////// #include <ESP8266WiFi.h> -#include <coredecls.h> // settimeofday_cb() +#include <coredecls.h> // settimeofday_cb() #include <Schedule.h> #include <PolledTimeout.h> -#include <time.h> // time() ctime() -#include <sys/time.h> // struct timeval +#include <time.h> // time() ctime() +#include <sys/time.h> // struct timeval -#include <sntp.h> // sntp_servermode_dhcp() +#include <sntp.h> // 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); //////////////////////////////////////////////////////// -static timeval tv; +static timeval tv; static timespec tp; -static time_t now; +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 bool time_machine_running = false; -static bool time_machine_run_once = false; +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,27 +78,33 @@ 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 //} -#define PTM(w) \ - Serial.print(" " #w "="); \ +#define PTM(w) \ + Serial.print(" " #w "="); \ Serial.print(tm->tm_##w); void printTm(const char* what, const tm* tm) { Serial.print(what); - PTM(isdst); PTM(yday); PTM(wday); - PTM(year); PTM(mon); PTM(mday); - PTM(hour); PTM(min); PTM(sec); + PTM(isdst); + PTM(yday); + PTM(wday); + PTM(year); + PTM(mon); + PTM(mday); + PTM(hour); + PTM(min); + PTM(sec); } void showTime() { gettimeofday(&tv, nullptr); clock_gettime(0, &tp); - now = time(nullptr); + now = time(nullptr); now_ms = millis(); now_us = micros(); @@ -135,7 +139,7 @@ void showTime() { Serial.println((uint32_t)now); // timezone and demo in the future - Serial.printf("timezone: %s\n", getenv("TZ") ? : "(none)"); + Serial.printf("timezone: %s\n", getenv("TZ") ?: "(none)"); // human readable Serial.print("ctime: "); @@ -143,7 +147,7 @@ void showTime() { // lwIP v2 is able to list more details about the currently configured SNTP servers for (int i = 0; i < SNTP_MAX_SERVERS; i++) { - IPAddress sntp = *sntp_getserver(i); + IPAddress sntp = *sntp_getserver(i); const char* name = sntp_getservername(i); if (sntp.isSet()) { Serial.printf("sntp%d: ", i); @@ -152,8 +156,7 @@ void showTime() { } else { Serial.printf("%s ", sntp.toString().c_str()); } - Serial.printf("- IPv6: %s - Reachability: %o\n", - sntp.isV6() ? "Yes" : "No", + Serial.printf("- IPv6: %s - Reachability: %o\n", sntp.isV6() ? "Yes" : "No", sntp_getreachability(i)); } } @@ -162,18 +165,17 @@ void showTime() { // show subsecond synchronisation timeval prevtv; - time_t prevtime = time(nullptr); + time_t prevtime = time(nullptr); gettimeofday(&prevtv, nullptr); 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); + (uint32_t)prevtime, (uint32_t)prevtv.tv_sec, (uint32_t)prevtv.tv_usec); Serial.printf("time(): %u gettimeofday(): %u.%06u <-- seconds have changed\n", - (uint32_t)(prevtime = time(nullptr)), - (uint32_t)tv.tv_sec, (uint32_t)tv.tv_usec); + (uint32_t)(prevtime = time(nullptr)), (uint32_t)tv.tv_sec, + (uint32_t)tv.tv_usec); break; } prevtv = tv; @@ -190,7 +192,7 @@ void time_is_set(bool from_sntp /* <= this parameter is optional */) { if (time_machine_days == 0) { if (time_machine_running) { time_machine_run_once = true; - time_machine_running = false; + time_machine_running = false; } else { time_machine_running = from_sntp && !time_machine_run_once; } @@ -210,10 +212,9 @@ void time_is_set(bool from_sntp /* <= this parameter is optional */) { // time machine demo if (time_machine_running) { - now = time(nullptr); + now = time(nullptr); const tm* tm = localtime(&now); - Serial.printf(": future=%3ddays: DST=%s - ", - time_machine_days, + Serial.printf(": future=%3ddays: DST=%s - ", time_machine_days, tm->tm_isdst ? "true " : "false"); Serial.print(ctime(&now)); gettimeofday(&tv, nullptr); @@ -247,8 +248,8 @@ void setup() { // setup RTC time // it will be used until NTP server will send us real current time Serial.println("Manually setting some time from some RTC:"); - time_t rtc = RTC_UTC_TEST; - timeval tv = { rtc, 0 }; + time_t rtc = RTC_UTC_TEST; + timeval tv = { rtc, 0 }; settimeofday(&tv, nullptr); // NTP servers may be overridden by your DHCP server for a more local one @@ -261,10 +262,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. diff --git a/libraries/esp8266/examples/RTCUserMemory/RTCUserMemory.ino b/libraries/esp8266/examples/RTCUserMemory/RTCUserMemory.ino index 9736995c74..4d25920f17 100644 --- a/libraries/esp8266/examples/RTCUserMemory/RTCUserMemory.ino +++ b/libraries/esp8266/examples/RTCUserMemory/RTCUserMemory.ino @@ -13,7 +13,7 @@ // This example code is in the public domain. // CRC function used to ensure data validity -uint32_t calculateCRC32(const uint8_t *data, size_t length); +uint32_t calculateCRC32(const uint8_t* data, size_t length); // helper function to dump memory contents as hex void printMemory(); @@ -25,7 +25,7 @@ void printMemory(); // We use byte array as an example. struct { uint32_t crc32; - byte data[508]; + byte data[508]; } rtcData; void setup() { @@ -34,11 +34,11 @@ void setup() { delay(1000); // Read struct from RTC memory - if (ESP.rtcUserMemoryRead(0, (uint32_t*) &rtcData, sizeof(rtcData))) { + if (ESP.rtcUserMemoryRead(0, (uint32_t*)&rtcData, sizeof(rtcData))) { Serial.println("Read: "); printMemory(); Serial.println(); - uint32_t crcOfData = calculateCRC32((uint8_t*) &rtcData.data[0], sizeof(rtcData.data)); + uint32_t crcOfData = calculateCRC32((uint8_t*)&rtcData.data[0], sizeof(rtcData.data)); Serial.print("CRC32 of data: "); Serial.println(crcOfData, HEX); Serial.print("CRC32 read from RTC: "); @@ -55,9 +55,9 @@ void setup() { rtcData.data[i] = random(0, 128); } // Update CRC32 of data - rtcData.crc32 = calculateCRC32((uint8_t*) &rtcData.data[0], sizeof(rtcData.data)); + rtcData.crc32 = calculateCRC32((uint8_t*)&rtcData.data[0], sizeof(rtcData.data)); // Write struct to RTC memory - if (ESP.rtcUserMemoryWrite(0, (uint32_t*) &rtcData, sizeof(rtcData))) { + if (ESP.rtcUserMemoryWrite(0, (uint32_t*)&rtcData, sizeof(rtcData))) { Serial.println("Write: "); printMemory(); Serial.println(); @@ -67,10 +67,9 @@ void setup() { ESP.deepSleep(5e6); } -void loop() { -} +void loop() { } -uint32_t calculateCRC32(const uint8_t *data, size_t length) { +uint32_t calculateCRC32(const uint8_t* data, size_t length) { uint32_t crc = 0xffffffff; while (length--) { uint8_t c = *data++; @@ -88,10 +87,10 @@ uint32_t calculateCRC32(const uint8_t *data, size_t length) { 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; + char buf[3]; + uint8_t* ptr = (uint8_t*)&rtcData; for (size_t i = 0; i < sizeof(rtcData); i++) { sprintf(buf, "%02X", ptr[i]); Serial.print(buf); diff --git a/libraries/esp8266/examples/SerialDetectBaudrate/SerialDetectBaudrate.ino b/libraries/esp8266/examples/SerialDetectBaudrate/SerialDetectBaudrate.ino index 61967c691f..5401e352ef 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: @@ -10,7 +10,8 @@ void setup() { unsigned long detectedBaudrate = Serial.detectBaudrate(TIMEOUT); if (detectedBaudrate) { - Serial.printf("\nDetected baudrate is %lu, switching to that baudrate now...\n", detectedBaudrate); + 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) { @@ -20,7 +21,8 @@ void setup() { // Clear Tx buffer to avoid extra characters being printed Serial.flush(); - // After this, any writing to Serial will print gibberish on the serial monitor if the baudrate doesn't match + // After this, any writing to Serial will print gibberish on the serial monitor if the baudrate + // doesn't match Serial.begin(detectedBaudrate); } else { Serial.println("\nNothing detected"); @@ -29,6 +31,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..5adc94d950 100644 --- a/libraries/esp8266/examples/SerialStress/SerialStress.ino +++ b/libraries/esp8266/examples/SerialStress/SerialStress.ino @@ -11,25 +11,25 @@ #include <ESP8266WiFi.h> #include <SoftwareSerial.h> -#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]; -bool reading = true; -size_t testReadBytesTimeout = 0; +uint8_t buf[BUFFER_SIZE]; +uint8_t temp[BUFFER_SIZE]; +bool reading = true; +size_t testReadBytesTimeout = 0; -static size_t out_idx = 0, in_idx = 0; -static size_t local_receive_size = 0; -static size_t size_for_1sec, size_for_led = 0; -static size_t maxavail = 0; +static size_t out_idx = 0, in_idx = 0; +static size_t local_receive_size = 0; +static size_t size_for_1sec, size_for_led = 0; +static size_t maxavail = 0; static uint64_t in_total = 0, in_prev = 0; static uint64_t start_ms, last_ms; static uint64_t timeout; @@ -37,18 +37,23 @@ 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); + 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); + 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] : '.')); + 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] : '.')); + logger->printf("%02x(%c) ", temp[i], + (unsigned char)((temp[i] > 31 && temp[i] < 128) ? temp[i] : '.')); } logger->println("\n\n"); @@ -61,7 +66,7 @@ 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,10 +80,10 @@ 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"); @@ -91,7 +96,8 @@ void setup() { // bind RX and TX USC0(0) |= (1 << UCLBE); - while (Serial.read() == -1); + while (Serial.read() == -1) + ; if (Serial.hasOverrun()) { logger->print("overrun?\n"); } @@ -107,15 +113,15 @@ void loop() { maxlen = BUFFER_SIZE - out_idx; } // check if not cycling more than buffer size relatively to input - size_t in_out = out_idx == in_idx ? - BUFFER_SIZE : - (in_idx + BUFFER_SIZE - out_idx - 1) % BUFFER_SIZE; + size_t in_out + = out_idx == in_idx ? BUFFER_SIZE : (in_idx + BUFFER_SIZE - out_idx - 1) % BUFFER_SIZE; if (maxlen > in_out) { maxlen = in_out; } 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())); + 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"); } @@ -170,9 +176,9 @@ void loop() { 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 ; + 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; logger->printf("bwavg=%d bwnow=%d kbps maxavail=%i\n", bwkbps_avg, bwkbps_now, maxavail); in_prev = in_total; diff --git a/libraries/esp8266/examples/SigmaDeltaDemo/SigmaDeltaDemo.ino b/libraries/esp8266/examples/SigmaDeltaDemo/SigmaDeltaDemo.ino index bdc1799eb7..2be0f88e9f 100644 --- a/libraries/esp8266/examples/SigmaDeltaDemo/SigmaDeltaDemo.ino +++ b/libraries/esp8266/examples/SigmaDeltaDemo/SigmaDeltaDemo.ino @@ -3,22 +3,19 @@ #include "sigma_delta.h" 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() { - uint8_t duty, iRepeat; Serial.println("Attaching the built in led to the sigma delta source now\n"); @@ -36,7 +33,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..3f3dc1af6a 100644 --- a/libraries/esp8266/examples/StreamString/StreamString.ino +++ b/libraries/esp8266/examples/StreamString/StreamString.ino @@ -4,9 +4,7 @@ #include <StreamDev.h> #include <StreamString.h> -void loop() { - delay(1000); -} +void loop() { delay(1000); } void checksketch(const char* what, const char* res1, const char* res2) { if (strcmp(res1, res2) == 0) { @@ -21,10 +19,10 @@ void checksketch(const char* what, const char* res1, const char* res2) { #endif void testStringPtrProgmem() { - static const char inProgmem [] PROGMEM = "I am in progmem"; - auto inProgmem2 = F("I am too in progmem"); + static const char inProgmem[] PROGMEM = "I am in progmem"; + auto inProgmem2 = F("I am too in progmem"); - int heap = (int)ESP.getFreeHeap(); + int heap = (int)ESP.getFreeHeap(); auto stream1 = StreamConstPtr(inProgmem, sizeof(inProgmem) - 1); auto stream2 = StreamConstPtr(inProgmem2); Serial << stream1 << " - " << stream2 << "\n"; @@ -33,7 +31,7 @@ void testStringPtrProgmem() { } void testStreamString() { - String inputString = "hello"; + String inputString = "hello"; StreamString result; // By default, reading a S2Stream(String) or a StreamString will consume the String. @@ -46,7 +44,6 @@ void testStreamString() { // In non-default non-consume mode, it will just move a pointer. That one // can be ::resetPointer(pos) anytime. See the example below. - // The String included in 'result' will not be modified by read: // (this is not the default) result.resetPointer(); @@ -110,7 +107,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); @@ -155,7 +152,7 @@ void testStreamString() { // .. but it does when S2Stream or StreamString is used { - int heap = (int)ESP.getFreeHeap(); + int heap = (int)ESP.getFreeHeap(); auto stream = StreamString(F("I am in progmem")); Serial << stream << "\n"; heap -= (int)ESP.getFreeHeap(); @@ -163,7 +160,8 @@ void testStreamString() { if (heap != 0) { check("heap is occupied by String/StreamString(progmem)", heapStr.c_str(), heapStr.c_str()); } else { - check("ERROR: heap should be occupied by String/StreamString(progmem)", heapStr.c_str(), "-1"); + check("ERROR: heap should be occupied by String/StreamString(progmem)", heapStr.c_str(), + "-1"); } } @@ -181,8 +179,8 @@ 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..f688fdad09 100644 --- a/libraries/esp8266/examples/TestEspApi/TestEspApi.ino +++ b/libraries/esp8266/examples/TestEspApi/TestEspApi.ino @@ -28,60 +28,33 @@ 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,12 +81,9 @@ 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(" ("); @@ -128,27 +98,27 @@ void wifi_event_handler_cb(System_Event_t * event) { break; case EVENT_SOFTAPMODE_STACONNECTED: case EVENT_SOFTAPMODE_STADISCONNECTED: { - char mac[32] = {0}; - snprintf(mac, 32, MACSTR ", aid: %d", MAC2STR(event->event_info.sta_connected.mac), event->event_info.sta_connected.aid); + char mac[32] = { 0 }; + snprintf(mac, 32, MACSTR ", aid: %d", MAC2STR(event->event_info.sta_connected.mac), + event->event_info.sta_connected.aid); - ehConsolePort.print(mac); - } - break; + ehConsolePort.print(mac); + } break; } ehConsolePort.println(")"); } -void print_softap_config(Stream & consolePort, softap_config const& config) { +void print_softap_config(Stream& consolePort, softap_config const& config) { consolePort.println(); consolePort.println(F("SoftAP Configuration")); consolePort.println(F("--------------------")); consolePort.print(F("ssid: ")); - consolePort.println((char *) config.ssid); + consolePort.println((char*)config.ssid); consolePort.print(F("password: ")); - consolePort.println((char *) config.password); + consolePort.println((char*)config.password); consolePort.print(F("ssid_len: ")); consolePort.println(config.ssid_len); @@ -173,8 +143,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]); @@ -202,7 +172,8 @@ void print_system_info(Stream & consolePort) { consolePort.println(system_get_userbin_addr(), HEX); consolePort.print(F("system_get_boot_mode(): ")); - consolePort.println(system_get_boot_mode() == 0 ? F("SYS_BOOT_ENHANCE_MODE") : F("SYS_BOOT_NORMAL_MODE")); + consolePort.println(system_get_boot_mode() == 0 ? F("SYS_BOOT_ENHANCE_MODE") : + F("SYS_BOOT_NORMAL_MODE")); consolePort.print(F("system_get_cpu_freq(): ")); consolePort.println(system_get_cpu_freq()); @@ -211,7 +182,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,9 +190,10 @@ 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); - size_t passwordLen = strlen(password) < sizeof(config->password) ? strlen(password) : sizeof(config->password); +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)); memcpy(config->ssid, ssid, ssidLen); @@ -293,4 +265,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..cba42b5d69 100644 --- a/libraries/esp8266/examples/UartDownload/UartDownload.ino +++ b/libraries/esp8266/examples/UartDownload/UartDownload.ino @@ -59,11 +59,10 @@ constexpr char slipFrameMarker = '\xC0'; // <0xC0><cmd><payload length><32 bit cksum><payload data ...><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 @@ -90,7 +89,7 @@ void proxyEspSync() { } // Assume RX FIFO data is garbled and flush all RX data. - while (0 <= Serial.read()) {} // Clear FIFO + while (0 <= Serial.read()) { } // Clear FIFO // If your Serial requirements need a specific timeout value, you would // restore those here. @@ -111,13 +110,13 @@ 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" - "Boot UART Download Demo - initialization started.\r\n" - "\r\n" - "For a quick test to see the UART Download work,\r\n" - "stop your serial terminal APP and run:\r\n" - " esptool.py --chip esp8266 --before no_reset --after soft_reset flash_id\r\n")); + Serial.println( + F("\r\n\r\n" + "Boot UART Download Demo - initialization started.\r\n" + "\r\n" + "For a quick test to see the UART Download work,\r\n" + "stop your serial terminal APP and run:\r\n" + " esptool.py --chip esp8266 --before no_reset --after soft_reset flash_id\r\n")); // ... } @@ -143,7 +142,7 @@ void cmdLoop(Print& oStream, int key) { ESP.restart(); break; - // ... + // ... case '?': oStream.println(F("\r\nHot key help:")); @@ -162,9 +161,7 @@ void cmdLoop(Print& oStream, int key) { oStream.println(); } - void loop() { - // In this example, we can have Serial data from a user keystroke for our // command loop or the esptool trying to SYNC up for flashing. If the // character matches the Slip Frame Marker (the 1st byte of the SYNC packet), diff --git a/libraries/esp8266/examples/interactive/interactive.ino b/libraries/esp8266/examples/interactive/interactive.ino index b3bd1ff931..c1b2dde100 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() { @@ -63,11 +61,18 @@ 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); } +#define TEST(name, var, varinit, func) \ + static decltype(func) var = (varinit); \ + if ((var) != (func)) { \ + var = (func); \ + Serial.printf("**** %s: ", name); \ + Serial.println(var); \ + } -#define DO(x...) Serial.println(F( #x )); x; break +#define DO(x...) \ + Serial.println(F(#x)); \ + x; \ + break TEST("Free Heap", freeHeap, 0, ESP.getFreeHeap()); TEST("WiFiStatus", status, WL_IDLE_STATUS, WiFi.status()); @@ -75,23 +80,41 @@ void loop() { TEST("AP-IP", apIp, (uint32_t)0, WiFi.softAPIP()); switch (Serial.read()) { - case 'F': DO(WiFiOff()); - case 'N': DO(WiFiOn()); - case '1': DO(WiFi.mode(WIFI_AP)); - case '2': DO(WiFi.mode(WIFI_AP_STA)); - case '3': DO(WiFi.mode(WIFI_STA)); - case 'R': DO(if (((GPI >> 16) & 0xf) == 1) ESP.reset() /* else must hard reset */); - case 'd': DO(WiFi.disconnect()); - case 'b': DO(WiFi.begin()); - case 'B': DO(WiFi.begin(SSID, PSK)); - case 'r': DO(WiFi.reconnect()); - case 'c': DO(wifi_station_connect()); - case 'a': DO(WiFi.setAutoReconnect(false)); - case 'A': DO(WiFi.setAutoReconnect(true)); - case 'n': DO(WiFi.setSleepMode(WIFI_NONE_SLEEP)); - case 'l': DO(WiFi.setSleepMode(WIFI_LIGHT_SLEEP)); - case 'm': DO(WiFi.setSleepMode(WIFI_MODEM_SLEEP)); - case 'S': DO(WiFi.config(staticip, gateway, subnet)); // use static address - case 's': DO(WiFi.config(0u, 0u, 0u)); // back to dhcp client + case 'F': + DO(WiFiOff()); + case 'N': + DO(WiFiOn()); + case '1': + DO(WiFi.mode(WIFI_AP)); + case '2': + DO(WiFi.mode(WIFI_AP_STA)); + case '3': + DO(WiFi.mode(WIFI_STA)); + case 'R': + DO(if (((GPI >> 16) & 0xf) == 1) ESP.reset() /* else must hard reset */); + case 'd': + DO(WiFi.disconnect()); + case 'b': + DO(WiFi.begin()); + case 'B': + DO(WiFi.begin(SSID, PSK)); + case 'r': + DO(WiFi.reconnect()); + case 'c': + DO(wifi_station_connect()); + case 'a': + DO(WiFi.setAutoReconnect(false)); + case 'A': + DO(WiFi.setAutoReconnect(true)); + case 'n': + DO(WiFi.setSleepMode(WIFI_NONE_SLEEP)); + case 'l': + DO(WiFi.setSleepMode(WIFI_LIGHT_SLEEP)); + case 'm': + DO(WiFi.setSleepMode(WIFI_MODEM_SLEEP)); + case 'S': + DO(WiFi.config(staticip, gateway, subnet)); // use static address + case 's': + DO(WiFi.config(0u, 0u, 0u)); // back to dhcp client } } diff --git a/libraries/esp8266/examples/irammem/irammem.ino b/libraries/esp8266/examples/irammem/irammem.ino index 5cd1db7b36..8972580abc 100644 --- a/libraries/esp8266/examples/irammem/irammem.ino +++ b/libraries/esp8266/examples/irammem/irammem.ino @@ -9,7 +9,6 @@ // #define USE_SET_IRAM_HEAP - #ifndef ETS_PRINTF #define ETS_PRINTF ets_uart_printf #endif @@ -21,9 +20,8 @@ #pragma GCC push_options // reference -#pragma GCC optimize("O0") // We expect -O0 to generate the correct results -__attribute__((noinline)) -void aliasTestReference(uint16_t *x) { +#pragma GCC optimize("O0") // We expect -O0 to generate the correct results +__attribute__((noinline)) void aliasTestReference(uint16_t* x) { // Without adhearance to strict-aliasing, this sequence of code would fail // when optimized by GCC Version 10.3 size_t len = 3; @@ -35,9 +33,8 @@ void aliasTestReference(uint16_t *x) { } } // Tests -#pragma GCC optimize("Os") -__attribute__((noinline)) -void aliasTestOs(uint16_t *x) { +#pragma GCC optimize("Os") +__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]); @@ -46,9 +43,8 @@ void aliasTestOs(uint16_t *x) { } } } -#pragma GCC optimize("O2") -__attribute__((noinline)) -void aliasTestO2(uint16_t *x) { +#pragma GCC optimize("O2") +__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]); @@ -57,9 +53,8 @@ void aliasTestO2(uint16_t *x) { } } } -#pragma GCC optimize("O3") -__attribute__((noinline)) -void aliasTestO3(uint16_t *x) { +#pragma GCC optimize("O3") +__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]); @@ -72,9 +67,8 @@ void aliasTestO3(uint16_t *x) { // Evaluate if optomizer may have changed 32-bit access to 8-bit. // 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) { +#pragma GCC optimize("O0") +__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 @@ -82,42 +76,40 @@ uint32_t timedRead_Reference(uint8_t *res) { // This section verifies that the workaround implimented by the inline // function mmu_get_uint8() is preventing this. See comments for function // mmu_get_uint8(() in mmu_iram.h for more details. - const uint8_t *x = (const uint8_t *)0x40100003ul; - uint32_t b = ESP.getCycleCount(); - *res = mmu_get_uint8(x); + const uint8_t* x = (const uint8_t*)0x40100003ul; + uint32_t b = ESP.getCycleCount(); + *res = mmu_get_uint8(x); return ESP.getCycleCount() - b; } -#pragma GCC optimize("Os") -__attribute__((noinline)) IRAM_ATTR -uint32_t timedRead_Os(uint8_t *res) { - const uint8_t *x = (const uint8_t *)0x40100003ul; - uint32_t b = ESP.getCycleCount(); - *res = mmu_get_uint8(x); +#pragma GCC optimize("Os") +__attribute__((noinline)) IRAM_ATTR uint32_t timedRead_Os(uint8_t* res) { + const uint8_t* x = (const uint8_t*)0x40100003ul; + uint32_t b = ESP.getCycleCount(); + *res = mmu_get_uint8(x); return ESP.getCycleCount() - b; } -#pragma GCC optimize("O2") -__attribute__((noinline)) IRAM_ATTR -uint32_t timedRead_O2(uint8_t *res) { - const uint8_t *x = (const uint8_t *)0x40100003ul; - uint32_t b = ESP.getCycleCount(); - *res = mmu_get_uint8(x); +#pragma GCC optimize("O2") +__attribute__((noinline)) IRAM_ATTR uint32_t timedRead_O2(uint8_t* res) { + const uint8_t* x = (const uint8_t*)0x40100003ul; + uint32_t b = ESP.getCycleCount(); + *res = mmu_get_uint8(x); return ESP.getCycleCount() - b; } -#pragma GCC optimize("O3") -__attribute__((noinline)) IRAM_ATTR -uint32_t timedRead_O3(uint8_t *res) { - const uint8_t *x = (const uint8_t *)0x40100003ul; - uint32_t b = ESP.getCycleCount(); - *res = mmu_get_uint8(x); +#pragma GCC optimize("O3") +__attribute__((noinline)) IRAM_ATTR uint32_t timedRead_O3(uint8_t* res) { + const uint8_t* x = (const uint8_t*)0x40100003ul; + uint32_t b = ESP.getCycleCount(); + *res = mmu_get_uint8(x); return ESP.getCycleCount() - b; } #pragma GCC pop_options bool test4_32bit_loads() { - bool result = true; - uint8_t res; + bool result = true; + uint8_t res; uint32_t cycle_count_ref, cycle_count; - Serial.printf("\r\nFor mmu_get_uint8, verify that 32-bit wide IRAM access is preserved across different optimizations:\r\n"); + Serial.printf("\r\nFor mmu_get_uint8, verify that 32-bit wide IRAM access is preserved across " + "different optimizations:\r\n"); cycle_count_ref = timedRead_Reference(&res); /* If the optimizer (for options -Os, -O2, and -O3) replaces the 32-bit wide @@ -153,7 +145,7 @@ bool test4_32bit_loads() { return result; } -void printPunFail(uint16_t *ref, uint16_t *x, size_t sz) { +void printPunFail(uint16_t* ref, uint16_t* x, size_t sz) { Serial.printf(" Expected:"); for (size_t i = 0; i < sz; i++) { Serial.printf(" %3u", ref[i]); @@ -168,12 +160,12 @@ void printPunFail(uint16_t *ref, uint16_t *x, size_t sz) { bool testPunning() { bool result = true; // Get reference result for verifing test - alignas(uint32_t) uint16_t x_ref[] = {1, 2, 3, 0}; + 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 +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 }; aliasTestO2(x); Serial.printf(" Option -O2 "); if (0 == memcmp(x_ref, x, sizeof(x_ref))) { @@ -197,7 +189,7 @@ bool testPunning() { } } { - alignas(alignof(uint32_t)) uint16_t x[] = {1, 2, 3, 0}; + alignas(alignof(uint32_t)) uint16_t x[] = { 1, 2, 3, 0 }; aliasTestO3(x); Serial.printf(" Option -O3 "); if (0 == memcmp(x_ref, x, sizeof(x_ref))) { @@ -211,9 +203,8 @@ bool testPunning() { return result; } - -uint32_t cyclesToRead_nKx32(int n, unsigned int *x, uint32_t *res) { - uint32_t b = ESP.getCycleCount(); +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++); @@ -222,8 +213,8 @@ uint32_t cyclesToRead_nKx32(int n, unsigned int *x, uint32_t *res) { return ESP.getCycleCount() - b; } -uint32_t cyclesToWrite_nKx32(int n, unsigned int *x) { - uint32_t b = ESP.getCycleCount(); +uint32_t cyclesToWrite_nKx32(int n, unsigned int* x) { + uint32_t b = ESP.getCycleCount(); uint32_t sum = 0; for (int i = 0; i < n * 1024; i++) { sum += i; @@ -232,8 +223,8 @@ uint32_t cyclesToWrite_nKx32(int n, unsigned int *x) { return ESP.getCycleCount() - b; } -uint32_t cyclesToRead_nKx16(int n, unsigned short *x, uint32_t *res) { - uint32_t b = ESP.getCycleCount(); +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++); @@ -242,8 +233,8 @@ uint32_t cyclesToRead_nKx16(int n, unsigned short *x, uint32_t *res) { return ESP.getCycleCount() - b; } -uint32_t cyclesToWrite_nKx16(int n, unsigned short *x) { - uint32_t b = ESP.getCycleCount(); +uint32_t cyclesToWrite_nKx16(int n, unsigned short* x) { + uint32_t b = ESP.getCycleCount(); uint32_t sum = 0; for (int i = 0; i < n * 1024; i++) { sum += i; @@ -252,9 +243,9 @@ uint32_t cyclesToWrite_nKx16(int n, unsigned short *x) { return ESP.getCycleCount() - b; } -uint32_t cyclesToRead_nKxs16(int n, short *x, int32_t *res) { - uint32_t b = ESP.getCycleCount(); - int32_t sum = 0; +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++); } @@ -262,9 +253,9 @@ uint32_t cyclesToRead_nKxs16(int n, short *x, int32_t *res) { return ESP.getCycleCount() - b; } -uint32_t cyclesToWrite_nKxs16(int n, short *x) { - uint32_t b = ESP.getCycleCount(); - int32_t sum = 0; +uint32_t cyclesToWrite_nKxs16(int n, short* x) { + uint32_t b = ESP.getCycleCount(); + int32_t sum = 0; for (int i = 0; i < n * 1024; i++) { sum += i; *(x++) = sum; @@ -272,8 +263,8 @@ 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 b = ESP.getCycleCount(); +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++); @@ -282,8 +273,8 @@ uint32_t cyclesToRead_nKx8(int n, unsigned char*x, uint32_t *res) { return ESP.getCycleCount() - b; } -uint32_t cyclesToWrite_nKx8(int n, unsigned char*x) { - uint32_t b = ESP.getCycleCount(); +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++) { sum += i; @@ -293,18 +284,18 @@ uint32_t cyclesToWrite_nKx8(int n, unsigned char*x) { } // Compare with Inline -uint32_t cyclesToRead_nKx16_viaInline(int n, unsigned short *x, uint32_t *res) { - uint32_t b = ESP.getCycleCount(); +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; } -uint32_t cyclesToWrite_nKx16_viaInline(int n, unsigned short *x) { - uint32_t b = ESP.getCycleCount(); +uint32_t cyclesToWrite_nKx16_viaInline(int n, unsigned short* x) { + uint32_t b = ESP.getCycleCount(); uint32_t sum = 0; for (int i = 0; i < n * 1024; i++) { sum += i; @@ -314,19 +305,19 @@ uint32_t cyclesToWrite_nKx16_viaInline(int n, unsigned short *x) { return ESP.getCycleCount() - b; } -uint32_t cyclesToRead_nKxs16_viaInline(int n, short *x, int32_t *res) { - uint32_t b = ESP.getCycleCount(); - int32_t sum = 0; +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; } -uint32_t cyclesToWrite_nKxs16_viaInline(int n, short *x) { - uint32_t b = ESP.getCycleCount(); - int32_t sum = 0; +uint32_t cyclesToWrite_nKxs16_viaInline(int n, short* x) { + uint32_t b = ESP.getCycleCount(); + int32_t sum = 0; for (int i = 0; i < n * 1024; i++) { sum += i; // *(x++) = sum; @@ -335,18 +326,18 @@ 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 b = ESP.getCycleCount(); +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 b = ESP.getCycleCount(); +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++) { sum += i; @@ -356,27 +347,40 @@ uint32_t cyclesToWrite_nKx8_viaInline(int n, unsigned char*x) { return ESP.getCycleCount() - b; } - -bool perfTest_nK(int nK, uint32_t *mem, uint32_t *imem) { +bool perfTest_nK(int nK, uint32_t* mem, uint32_t* imem) { uint32_t res, verify_res; uint32_t t; - bool success = true; - int sres, verify_sres; + bool success = true; + int sres, verify_sres; - Serial.printf("\r\nPerformance numbers for 16 bit access - using inline macros or exception handling for IRAM.\r\n");; + Serial.printf("\r\nPerformance numbers for 16 bit access - using inline macros or exception " + "handling for IRAM.\r\n"); + ; t = cyclesToWrite_nKx16(nK, (uint16_t*)mem); - Serial.printf("DRAM Memory Write: %7d cycles for %dK by uint16, %3d AVG cycles/transfer\r\n", t, nK, t / (nK * 1024)); + 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); - 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); + 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); - Serial.printf("DRAM Memory Write: %7d cycles for %dK by int16, %3d AVG cycles/transfer\r\n", t, nK, t / (nK * 1024)); + 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); - 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); + 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); - Serial.printf("IRAM Memory Write Inline: %7d cycles for %dK by uint16, %3d AVG cycles/transfer\r\n", t, nK, t / (nK * 1024)); + 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); - Serial.printf("IRAM Memory Read Inline: %7d cycles for %dK by uint16, %3d AVG cycles/transfer (sum %08x) ", t, nK, t / (nK * 1024), 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"); } else { @@ -385,9 +389,13 @@ bool perfTest_nK(int nK, uint32_t *mem, uint32_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)); + 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); - Serial.printf("IRAM Memory Read Inline: %7d cycles for %dK by int16, %3d AVG cycles/transfer (sum %08x) ", t, nK, t / (nK * 1024), 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"); } else { @@ -396,9 +404,13 @@ bool perfTest_nK(int nK, uint32_t *mem, uint32_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)); + 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); - Serial.printf("IRAM Memory Read: %7d cycles for %dK by uint16, %3d AVG cycles/transfer (sum %08x) ", t, nK, t / (nK * 1024), 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"); } else { @@ -406,9 +418,13 @@ bool perfTest_nK(int nK, uint32_t *mem, uint32_t *imem) { success = false; } 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)); + 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); - Serial.printf("IRAM Memory Read: %7d cycles for %dK by int16, %3d AVG cycles/transfer (sum %08x) ", t, nK, t / (nK * 1024), 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"); } else { @@ -416,16 +432,26 @@ bool perfTest_nK(int nK, uint32_t *mem, uint32_t *imem) { success = false; } - Serial.printf("\r\nPerformance numbers for 8 bit access - using inline macros or exception handling for IRAM access.\r\n");; + Serial.printf("\r\nPerformance numbers for 8 bit access - using inline macros or exception " + "handling for IRAM access.\r\n"); + ; t = cyclesToWrite_nKx8(nK, (uint8_t*)mem); - Serial.printf("DRAM Memory Write: %7d cycles for %dK by uint8, %3d AVG cycles/transfer\r\n", t, nK, t / (nK * 1024)); + 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); - 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); + 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); - Serial.printf("IRAM Memory Write Inline: %7d cycles for %dK by uint8, %3d AVG cycles/transfer\r\n", t, nK, t / (nK * 1024)); + 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); - Serial.printf("IRAM Memory Read Inline: %7d cycles for %dK by uint8, %3d AVG cycles/transfer (sum %08x) ", t, nK, t / (nK * 1024), 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"); } else { @@ -434,9 +460,13 @@ bool perfTest_nK(int nK, uint32_t *mem, uint32_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)); + 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); - Serial.printf("IRAM Memory Read: %7d cycles for %dK by uint8, %3d AVG cycles/transfer (sum %08x) ", t, nK, t / (nK * 1024), 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"); } else { @@ -456,18 +486,19 @@ void setup() { delay(20); Serial.printf_P(PSTR("\n\nSetup ...\r\n")); #ifndef UMM_HEAP_IRAM - Serial.printf("\r\n" - "This example needs IRAM Heap support enabled.\r\n" - " eg. Arduino IDE 'Tools->MMU:\"16KB cache + 48KB IRAM and 2nd Heap (shared)\"'\r\n" - "This build has IRAM Heap support disabled.\r\n" - "In this situation, all IRAM requests are satisfied with DRAM.\r\n\r\n"); + Serial.printf( + "\r\n" + "This example needs IRAM Heap support enabled.\r\n" + " eg. Arduino IDE 'Tools->MMU:\"16KB cache + 48KB IRAM and 2nd Heap (shared)\"'\r\n" + "This build has IRAM Heap support disabled.\r\n" + "In this situation, all IRAM requests are satisfied with DRAM.\r\n\r\n"); #endif // Compiling with Secondary Heap option does not change malloc to use the // IRAM region. It will continue to use the builtin DRAM until we request // otherwise. Serial.printf("DRAM free: %6d\r\n", ESP.getFreeHeap()); - uint32_t *mem = (uint32_t *)malloc(2 * 1024 * sizeof(uint32_t)); + uint32_t* mem = (uint32_t*)malloc(2 * 1024 * sizeof(uint32_t)); Serial.printf("DRAM buffer: Address %p, free %d\r\n", mem, ESP.getFreeHeap()); if (!mem) { return; @@ -477,12 +508,12 @@ void setup() { #ifdef USE_SET_IRAM_HEAP ESP.setIramHeap(); Serial.printf("IRAM free: %6d\r\n", ESP.getFreeHeap()); - uint32_t *imem = (uint32_t *)malloc(2 * 1024 * sizeof(uint32_t)); + uint32_t* imem = (uint32_t*)malloc(2 * 1024 * sizeof(uint32_t)); Serial.printf("IRAM buffer: Address %p, free %d\r\n", imem, ESP.getFreeHeap()); // Make sure we go back to the DRAM heap for other allocations. Don't forget to ESP.resetHeap()! ESP.resetHeap(); #else - uint32_t *imem; + uint32_t* imem; { HeapSelectIram ephemeral; // This class effectively does this @@ -491,7 +522,7 @@ void setup() { // ... // umm_set_heap_by_id(_heap_id); Serial.printf("IRAM free: %6d\r\n", ESP.getFreeHeap()); - imem = (uint32_t *)malloc(2 * 1024 * sizeof(uint32_t)); + imem = (uint32_t*)malloc(2 * 1024 * sizeof(uint32_t)); Serial.printf("IRAM buffer: Address %p, free %d\r\n", imem, ESP.getFreeHeap()); } #endif @@ -501,20 +532,29 @@ void setup() { uint32_t res; uint32_t t; - int nK = 1; - Serial.printf("\r\nPerformance numbers for 32 bit access - no exception handler or inline macros needed.\r\n");; + int nK = 1; + 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)); + 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); - Serial.printf("DRAM Memory Read: %7d cycles for %dK by uint32, %3d AVG cycles/transfer (sum %08x)\r\n", t, nK, t / (nK * 1024), res); + Serial.printf("DRAM Memory Read: %7d cycles for %dK by uint32, %3d AVG cycles/transfer " + "(sum %08x)\r\n", + t, nK, t / (nK * 1024), res); t = cyclesToWrite_nKx32(nK, imem); - Serial.printf("IRAM Memory Write: %7d cycles for %dK by uint32, %3d AVG cycles/transfer\r\n", t, nK, t / (nK * 1024)); + Serial.printf( + "IRAM Memory Write: %7d cycles for %dK by uint32, %3d AVG cycles/transfer\r\n", t, nK, + t / (nK * 1024)); t = cyclesToRead_nKx32(nK, imem, &res); - Serial.printf("IRAM Memory Read: %7d cycles for %dK by uint32, %3d AVG cycles/transfer (sum %08x)\r\n", t, nK, t / (nK * 1024), res); + Serial.printf("IRAM Memory Read: %7d cycles for %dK by uint32, %3d AVG cycles/transfer " + "(sum %08x)\r\n", + t, nK, t / (nK * 1024), res); Serial.println(); - if (perfTest_nK(1, mem, imem) && testPunning() && test4_32bit_loads()) { Serial.println(); } else { @@ -549,7 +589,7 @@ void setup() { { // Let's use IRAM heap to make a big ole' String HeapSelectIram ephemeral; - String s = ""; + String s = ""; for (int i = 0; i < 100; i++) { s += i; s += ' '; @@ -573,7 +613,7 @@ void setup() { free(imem); free(mem); imem = NULL; - mem = NULL; + mem = NULL; Serial.printf("DRAM free: %6d\r\n", ESP.getFreeHeap()); #ifdef USE_SET_IRAM_HEAP @@ -589,16 +629,15 @@ void setup() { { ETS_PRINTF("Try and allocate all of the heap in one chunk\n"); HeapSelectIram ephemeral; - size_t free_iram = ESP.getFreeHeap(); + size_t free_iram = ESP.getFreeHeap(); ETS_PRINTF("IRAM free: %6d\n", free_iram); uint32_t hfree; uint32_t hmax; - uint8_t hfrag; + 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); + void* all = malloc(free_iram - UMM_OVERHEAD_ADJUST); ETS_PRINTF("%p = malloc(%u)\n", all, free_iram); umm_info(NULL, true); @@ -614,26 +653,26 @@ void setup() { void processKey(Print& out, int hotKey) { switch (hotKey) { case 'd': { - HeapSelectDram ephemeral; - umm_info(NULL, true); - break; - } + HeapSelectDram ephemeral; + umm_info(NULL, true); + break; + } case 'i': { + HeapSelectIram ephemeral; + umm_info(NULL, true); + break; + } + case 'h': { + { HeapSelectIram ephemeral; - umm_info(NULL, true); - break; + Serial.printf(PSTR("IRAM ESP.getFreeHeap: %u\n"), ESP.getFreeHeap()); } - case 'h': { - { - HeapSelectIram ephemeral; - Serial.printf(PSTR("IRAM ESP.getFreeHeap: %u\n"), ESP.getFreeHeap()); - } - { - HeapSelectDram ephemeral; - Serial.printf(PSTR("DRAM ESP.getFreeHeap: %u\r\n"), ESP.getFreeHeap()); - } - break; + { + HeapSelectDram ephemeral; + Serial.printf(PSTR("DRAM ESP.getFreeHeap: %u\r\n"), ESP.getFreeHeap()); } + break; + } case 'R': out.printf_P(PSTR("Restart, ESP.restart(); ...\r\n")); ESP.restart(); @@ -660,7 +699,6 @@ void processKey(Print& out, int hotKey) { } } - void loop(void) { if (Serial.available() > 0) { int hotKey = Serial.read(); diff --git a/libraries/esp8266/examples/virtualmem/virtualmem.ino b/libraries/esp8266/examples/virtualmem/virtualmem.ino index 47b9396cc7..f397fb347c 100644 --- a/libraries/esp8266/examples/virtualmem/virtualmem.ino +++ b/libraries/esp8266/examples/virtualmem/virtualmem.ino @@ -1,6 +1,6 @@ -uint32_t cyclesToRead1Kx32(unsigned int *x, uint32_t *res) { - uint32_t b = ESP.getCycleCount(); +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++); @@ -9,8 +9,8 @@ uint32_t cyclesToRead1Kx32(unsigned int *x, uint32_t *res) { return ESP.getCycleCount() - b; } -uint32_t cyclesToWrite1Kx32(unsigned int *x) { - uint32_t b = ESP.getCycleCount(); +uint32_t cyclesToWrite1Kx32(unsigned int* x) { + uint32_t b = ESP.getCycleCount(); uint32_t sum = 0; for (int i = 0; i < 1024; i++) { sum += i; @@ -19,9 +19,8 @@ uint32_t cyclesToWrite1Kx32(unsigned int *x) { return ESP.getCycleCount() - b; } - -uint32_t cyclesToRead1Kx16(unsigned short *x, uint32_t *res) { - uint32_t b = ESP.getCycleCount(); +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++); @@ -30,8 +29,8 @@ uint32_t cyclesToRead1Kx16(unsigned short *x, uint32_t *res) { return ESP.getCycleCount() - b; } -uint32_t cyclesToWrite1Kx16(unsigned short *x) { - uint32_t b = ESP.getCycleCount(); +uint32_t cyclesToWrite1Kx16(unsigned short* x) { + uint32_t b = ESP.getCycleCount(); uint32_t sum = 0; for (int i = 0; i < 1024; i++) { sum += i; @@ -40,8 +39,8 @@ uint32_t cyclesToWrite1Kx16(unsigned short *x) { return ESP.getCycleCount() - b; } -uint32_t cyclesToRead1Kx8(unsigned char*x, uint32_t *res) { - uint32_t b = ESP.getCycleCount(); +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++); @@ -50,8 +49,8 @@ uint32_t cyclesToRead1Kx8(unsigned char*x, uint32_t *res) { return ESP.getCycleCount() - b; } -uint32_t cyclesToWrite1Kx8(unsigned char*x) { - uint32_t b = ESP.getCycleCount(); +uint32_t cyclesToWrite1Kx8(unsigned char* x) { + uint32_t b = ESP.getCycleCount(); uint32_t sum = 0; for (int i = 0; i < 1024; i++) { sum += i; @@ -66,14 +65,15 @@ void setup() { // Enabling VM does not change malloc to use the external region. It will continue to // use the normal RAM until we request otherwise. - uint32_t *mem = (uint32_t *)malloc(1024 * sizeof(uint32_t)); + uint32_t* mem = (uint32_t*)malloc(1024 * sizeof(uint32_t)); Serial.printf("Internal buffer: Address %p, free %d\n", mem, ESP.getFreeHeap()); // Now request from the VM heap ESP.setExternalHeap(); - uint32_t *vm = (uint32_t *)malloc(1024 * sizeof(uint32_t)); + uint32_t* vm = (uint32_t*)malloc(1024 * sizeof(uint32_t)); Serial.printf("External buffer: Address %p, free %d\n", vm, ESP.getFreeHeap()); - // Make sure we go back to the internal heap for other allocations. Don't forget to ESP.resetHeap()! + // Make sure we go back to the internal heap for other allocations. Don't forget to + // ESP.resetHeap()! ESP.resetHeap(); uint32_t res; @@ -133,6 +133,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..58b8b6d115 100644 --- a/libraries/lwIP_PPP/examples/PPPServer/PPPServer.ino +++ b/libraries/lwIP_PPP/examples/PPPServer/PPPServer.ino @@ -7,8 +7,8 @@ // this example is subject for changes once everything is stabilized // 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 @@ -25,7 +25,7 @@ #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif #define LOGGERBAUD 115200 @@ -34,16 +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); +SoftwareSerial ppplink(RX, TX); HardwareSerial& logger = Serial; -PPPServer ppp(&ppplink); +PPPServer ppp(&ppplink); void PPPConnectedCallback(netif* nif) { - logger.printf("ppp: ip=%s/mask=%s/gw=%s\n", - IPAddress(&nif->ip_addr).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()); @@ -59,9 +58,12 @@ void PPPConnectedCallback(netif* nif) { // could not make this work yet, // but packets are arriving on ppp client (= linux host) - logger.printf("redirect22=%d\n", ip_portmap_add(IP_PROTO_TCP, ip_2_ip4(&nif->ip_addr)->addr, 22, ip_2_ip4(&nif->gw)->addr, 22)); - logger.printf("redirect80=%d\n", ip_portmap_add(IP_PROTO_TCP, ip_2_ip4(&nif->ip_addr)->addr, 80, ip_2_ip4(&nif->gw)->addr, 80)); - 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("redirect22=%d\n", ip_portmap_add(IP_PROTO_TCP, ip_2_ip4(&nif->ip_addr)->addr, 22, + ip_2_ip4(&nif->gw)->addr, 22)); + logger.printf("redirect80=%d\n", ip_portmap_add(IP_PROTO_TCP, ip_2_ip4(&nif->ip_addr)->addr, 80, + ip_2_ip4(&nif->gw)->addr, 80)); + 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) { @@ -79,25 +81,26 @@ 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); logger.println(); logger.printf("\n\nhey, trying to be a PPP server here\n\n"); logger.printf("Now try this on your linux host:\n\n"); - logger.printf("connect a serial<->usb module (e.g. to /dev/ttyUSB1) and link it to the ESP (esprx=%d esptx=%d), then run:\n\n", RX, TX); - logger.printf("sudo /usr/sbin/pppd /dev/ttyUSB1 %d noipdefault nocrtscts local defaultroute noauth nodetach debug dump\n\n", PPPLINKBAUD); + logger.printf("connect a serial<->usb module (e.g. to /dev/ttyUSB1) and link it to the ESP " + "(esprx=%d esptx=%d), then run:\n\n", + RX, TX); + logger.printf("sudo /usr/sbin/pppd /dev/ttyUSB1 %d noipdefault nocrtscts local defaultroute " + "noauth nodetach debug dump\n\n", + PPPLINKBAUD); ppp.ifUpCb(PPPConnectedCallback); bool ret = ppp.begin(WiFi.localIP()); logger.printf("ppp: %d\n", ret); } - #else void setup() { @@ -107,5 +110,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..e474a442ab 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,19 @@ 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..ecb8d70421 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,38 +39,29 @@ class PPPServer { public: - PPPServer(Stream* sio); bool begin(const IPAddress& ourAddress, const IPAddress& peer = IPAddress(172, 31, 255, 254)); void stop(); - void ifUpCb(void (*cb)(netif*)) - { - _cb = cb; - } - const ip_addr_t* getPeerAddress() const - { - return &_netif.gw; - } + void ifUpCb(void (*cb)(netif*)) { _cb = cb; } + const ip_addr_t* getPeerAddress() const { return &_netif.gw; } 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<ENC28J60>; -#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..7bcd5150c8 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,9 @@ ENC28J60::writedata(const uint8_t *data, int datalen) enc28j60_arch_spi_deselect(); } /*---------------------------------------------------------------------------*/ -void -ENC28J60::writedatabyte(uint8_t byte) -{ - writedata(&byte, 1); -} +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 +270,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 +278,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 +289,7 @@ ENC28J60::softreset(void) /*---------------------------------------------------------------------------*/ //#if DEBUG -uint8_t -ENC28J60::readrev(void) +uint8_t ENC28J60::readrev(void) { uint8_t rev; setregbank(MAADRX_BANK); @@ -324,8 +308,7 @@ ENC28J60::readrev(void) /*---------------------------------------------------------------------------*/ -bool -ENC28J60::reset(void) +bool ENC28J60::reset(void) { PRINTF("enc28j60: resetting chip\n"); @@ -398,7 +381,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 +453,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 +513,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 +527,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 +578,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 +593,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 +640,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 +660,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 +708,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..ebebbceac4 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,14 +77,10 @@ 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; - } + static constexpr bool interruptIsPossible() { return false; } /** Read an Ethernet frame size @@ -109,38 +104,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<Wiznet5100>; -#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..327acb33e8 100644 --- a/libraries/lwIP_w5100/src/utility/w5100.cpp +++ b/libraries/lwIP_w5100/src/utility/w5100.cpp @@ -35,15 +35,14 @@ #include <SPI.h> #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,14 @@ 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) { (void)intr; } -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 +249,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 +281,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 +300,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 +322,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..0f03ecbd39 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 <stdint.h> #include <Arduino.h> #include <SPI.h> - 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,14 +77,10 @@ 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; - } + static constexpr bool interruptIsPossible() { return false; } /** Read an Ethernet frame size @@ -110,43 +104,39 @@ 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() - { - digitalWrite(_cs, LOW); - } + inline void wizchip_cs_select() { digitalWrite(_cs, LOW); } /** 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() - { - digitalWrite(_cs, HIGH); - } + inline void wizchip_cs_deselect() { digitalWrite(_cs, HIGH); } /** Read a 1 byte value from a register. @@ -194,7 +184,6 @@ class Wiznet5100 */ void wizchip_write_buf(uint16_t address, const uint8_t* pBuf, uint16_t len); - /** Reset WIZCHIP by softly. */ @@ -204,15 +193,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 <i>wizdata(pointer buffer)</i> of the length of <i>len(variable)</i> 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 <i>wizdata(pointer buffer)</i> of the length of <i>len(variable)</i> 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 +215,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 <i>len(variable)</i> bytes in internal RX memory. + @details It discards the data of the length of <i>len(variable)</i> bytes in internal RX + memory. @param len Data length */ void wizchip_recv_ignore(uint16_t len); @@ -247,106 +237,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 }; /** @@ -354,100 +343,72 @@ class Wiznet5100 @param (uint8_t)mr The value to be set. @sa getMR() */ - inline void setMR(uint8_t mode) - { - wizchip_write(MR, mode); - } + inline void setMR(uint8_t mode) { wizchip_write(MR, mode); } /** Get Mode Register @return uint8_t. The value of Mode register. @sa setMR() */ - inline uint8_t getMR() - { - return wizchip_read(MR); - } + inline uint8_t getMR() { return wizchip_read(MR); } /** 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) - { - wizchip_write_buf(SHAR, macaddr, 6); - } + inline void setSHAR(const uint8_t* macaddr) { wizchip_write_buf(SHAR, macaddr, 6); } /** 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) - { - wizchip_read_buf(SHAR, macaddr, 6); - } + inline void getSHAR(uint8_t* macaddr) { wizchip_read_buf(SHAR, macaddr, 6); } /** Get @ref Sn_TX_WR register @param (uint16_t)txwr Value to set @ref Sn_TX_WR @sa GetSn_TX_WR() */ - inline uint16_t getSn_TX_WR() - { - return wizchip_read_word(Sn_TX_WR); - } + inline uint16_t getSn_TX_WR() { return wizchip_read_word(Sn_TX_WR); } /** Set @ref Sn_TX_WR register @param (uint16_t)txwr Value to set @ref Sn_TX_WR @sa GetSn_TX_WR() */ - inline void setSn_TX_WR(uint16_t txwr) - { - wizchip_write_word(Sn_TX_WR, txwr); - } + inline void setSn_TX_WR(uint16_t txwr) { wizchip_write_word(Sn_TX_WR, txwr); } /** Get @ref Sn_RX_RD register @regurn uint16_t. Value of @ref Sn_RX_RD. @sa setSn_RX_RD() */ - inline uint16_t getSn_RX_RD() - { - return wizchip_read_word(Sn_RX_RD); - } + inline uint16_t getSn_RX_RD() { return wizchip_read_word(Sn_RX_RD); } /** Set @ref Sn_RX_RD register @param (uint16_t)rxrd Value to set @ref Sn_RX_RD @sa getSn_RX_RD() */ - inline void setSn_RX_RD(uint16_t rxrd) - { - wizchip_write_word(Sn_RX_RD, rxrd); - } + inline void setSn_RX_RD(uint16_t rxrd) { wizchip_write_word(Sn_RX_RD, rxrd); } /** Set @ref Sn_MR register @param (uint8_t)mr Value to set @ref Sn_MR @sa getSn_MR() */ - inline void setSn_MR(uint8_t mr) - { - wizchip_write(Sn_MR, mr); - } + inline void setSn_MR(uint8_t mr) { wizchip_write(Sn_MR, mr); } /** Get @ref Sn_MR register @return uint8_t. Value of @ref Sn_MR. @sa setSn_MR() */ - inline uint8_t getSn_MR() - { - return wizchip_read(Sn_MR); - } + inline uint8_t getSn_MR() { return wizchip_read(Sn_MR); } /** Set @ref Sn_CR register, then wait for the command to execute @@ -461,39 +422,27 @@ class Wiznet5100 @return uint8_t. Value of @ref Sn_CR. @sa setSn_CR() */ - inline uint8_t getSn_CR() - { - return wizchip_read(Sn_CR); - } + inline uint8_t getSn_CR() { return wizchip_read(Sn_CR); } /** Get @ref Sn_SR register @return uint8_t. Value of @ref Sn_SR. */ - inline uint8_t getSn_SR() - { - return wizchip_read(Sn_SR); - } + inline uint8_t getSn_SR() { return wizchip_read(Sn_SR); } /** Get @ref Sn_IR register @return uint8_t. Value of @ref Sn_IR. @sa setSn_IR() */ - inline uint8_t getSn_IR() - { - return wizchip_read(Sn_IR); - } + inline uint8_t getSn_IR() { return wizchip_read(Sn_IR); } /** Set @ref Sn_IR register @param (uint8_t)ir Value to set @ref Sn_IR @sa getSn_IR() */ - inline void setSn_IR(uint8_t ir) - { - wizchip_write(Sn_IR, ir); - } + inline void setSn_IR(uint8_t ir) { wizchip_write(Sn_IR, ir); } }; -#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..879be82b77 100644 --- a/libraries/lwIP_w5500/examples/TCPClient/TCPClient.ino +++ b/libraries/lwIP_w5500/examples/TCPClient/TCPClient.ino @@ -5,27 +5,27 @@ #include <SPI.h> #include <W5500lwIP.h> -//or #include <W5100lwIP.h> -//or #include <ENC28J60lwIP.h> +// or #include <W5100lwIP.h> +// or #include <ENC28J60lwIP.h> -#include <WiFiClient.h> // WiFiClient (-> TCPClient) +#include <WiFiClient.h> // WiFiClient (-> TCPClient) -const char* host = "djxmmx.net"; +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) { @@ -89,7 +89,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<Wiznet5500>; -#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..5852652864 100644 --- a/libraries/lwIP_w5500/src/utility/w5500.cpp +++ b/libraries/lwIP_w5500/src/utility/w5500.cpp @@ -35,7 +35,6 @@ #include <SPI.h> #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,9 @@ int8_t Wiznet5500::wizphy_setphypmode(uint8_t pmode) return -1; } +Wiznet5500::Wiznet5500(int8_t cs, SPIClass& spi, int8_t intr) : _spi(spi), _cs(cs) { (void)intr; } -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 +324,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 +356,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 +375,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 +398,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..0a9e16c7ee 100644 --- a/libraries/lwIP_w5500/src/utility/w5500.h +++ b/libraries/lwIP_w5500/src/utility/w5500.h @@ -39,11 +39,8 @@ #include <Arduino.h> #include <SPI.h> - - 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,14 +77,10 @@ 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; - } + static constexpr bool interruptIsPossible() { return false; } /** Read an Ethernet frame size @@ -112,11 +104,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,52 +125,37 @@ 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() - { - digitalWrite(_cs, LOW); - } + inline void wizchip_cs_select() { digitalWrite(_cs, LOW); } /** 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() - { - digitalWrite(_cs, HIGH); - } + inline void wizchip_cs_deselect() { digitalWrite(_cs, HIGH); } /** 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() - { - return _spi.transfer(0); - } + inline uint8_t wizchip_spi_read_byte() { return _spi.transfer(0); } /** 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); - } - + inline void wizchip_spi_write_byte(uint8_t wb) { _spi.transfer(wb); } /** Read a 1 byte value from a register. @@ -240,7 +215,6 @@ class Wiznet5500 */ uint16_t getSn_RX_RSR(); - /** Reset WIZCHIP by softly. */ @@ -262,7 +236,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 +246,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 <i>wizdata(pointer buffer)</i> of the length of <i>len(variable)</i> 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 <i>wizdata(pointer buffer)</i> of the length of <i>len(variable)</i> 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,206 +268,198 @@ 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 <i>len(variable)</i> bytes in internal RX memory. + @details It discards the data of the length of <i>len(variable)</i> 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. @sa getMR() */ - inline void setMR(uint8_t mode) - { - wizchip_write(BlockSelectCReg, MR, mode); - } + inline void setMR(uint8_t mode) { wizchip_write(BlockSelectCReg, MR, mode); } /** Get Mode Register @return uint8_t. The value of Mode register. @sa setMR() */ - inline uint8_t getMR() - { - return wizchip_read(BlockSelectCReg, MR); - } + inline uint8_t getMR() { return wizchip_read(BlockSelectCReg, MR); } /** 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,102 +469,73 @@ 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) - { - wizchip_read_buf(BlockSelectCReg, SHAR, macaddr, 6); - } + inline void getSHAR(uint8_t* macaddr) { wizchip_read_buf(BlockSelectCReg, SHAR, macaddr, 6); } /** Set @ref IR register @param (uint8_t)ir Value to set @ref IR register. @sa getIR() */ - inline void setIR(uint8_t ir) - { - wizchip_write(BlockSelectCReg, IR, (ir & 0xF0)); - } + inline void setIR(uint8_t ir) { wizchip_write(BlockSelectCReg, IR, (ir & 0xF0)); } /** Get @ref IR register @return uint8_t. Value of @ref IR register. @sa setIR() */ - inline uint8_t getIR() - { - return wizchip_read(BlockSelectCReg, IR) & 0xF0; - } + inline uint8_t getIR() { return wizchip_read(BlockSelectCReg, IR) & 0xF0; } /** Set @ref _IMR_ register @param (uint8_t)imr Value to set @ref _IMR_ register. @sa getIMR() */ - inline void setIMR(uint8_t imr) - { - wizchip_write(BlockSelectCReg, _IMR_, imr); - } + inline void setIMR(uint8_t imr) { wizchip_write(BlockSelectCReg, _IMR_, imr); } /** Get @ref _IMR_ register @return uint8_t. Value of @ref _IMR_ register. @sa setIMR() */ - inline uint8_t getIMR() - { - return wizchip_read(BlockSelectCReg, _IMR_); - } + inline uint8_t getIMR() { return wizchip_read(BlockSelectCReg, _IMR_); } /** Set @ref PHYCFGR register @param (uint8_t)phycfgr Value to set @ref PHYCFGR register. @sa getPHYCFGR() */ - inline void setPHYCFGR(uint8_t phycfgr) - { - wizchip_write(BlockSelectCReg, PHYCFGR, phycfgr); - } + inline void setPHYCFGR(uint8_t phycfgr) { wizchip_write(BlockSelectCReg, PHYCFGR, phycfgr); } /** Get @ref PHYCFGR register @return uint8_t. Value of @ref PHYCFGR register. @sa setPHYCFGR() */ - inline uint8_t getPHYCFGR() - { - return wizchip_read(BlockSelectCReg, PHYCFGR); - } + inline uint8_t getPHYCFGR() { return wizchip_read(BlockSelectCReg, PHYCFGR); } /** Get @ref VERSIONR register @return uint8_t. Value of @ref VERSIONR register. */ - inline uint8_t getVERSIONR() - { - return wizchip_read(BlockSelectCReg, VERSIONR); - } + inline uint8_t getVERSIONR() { return wizchip_read(BlockSelectCReg, VERSIONR); } /** Set @ref Sn_MR register @param (uint8_t)mr Value to set @ref Sn_MR @sa getSn_MR() */ - inline void setSn_MR(uint8_t mr) - { - wizchip_write(BlockSelectSReg, Sn_MR, mr); - } + inline void setSn_MR(uint8_t mr) { wizchip_write(BlockSelectSReg, Sn_MR, mr); } /** Get @ref Sn_MR register @return uint8_t. Value of @ref Sn_MR. @sa setSn_MR() */ - inline uint8_t getSn_MR() - { - return wizchip_read(BlockSelectSReg, Sn_MR); - } + inline uint8_t getSn_MR() { return wizchip_read(BlockSelectSReg, Sn_MR); } /** Set @ref Sn_CR register, then wait for the command to execute @@ -611,59 +549,41 @@ class Wiznet5500 @return uint8_t. Value of @ref Sn_CR. @sa setSn_CR() */ - inline uint8_t getSn_CR() - { - return wizchip_read(BlockSelectSReg, Sn_CR); - } + inline uint8_t getSn_CR() { return wizchip_read(BlockSelectSReg, Sn_CR); } /** Set @ref Sn_IR register @param (uint8_t)ir Value to set @ref Sn_IR @sa getSn_IR() */ - inline void setSn_IR(uint8_t ir) - { - wizchip_write(BlockSelectSReg, Sn_IR, (ir & 0x1F)); - } + inline void setSn_IR(uint8_t ir) { wizchip_write(BlockSelectSReg, Sn_IR, (ir & 0x1F)); } /** Get @ref Sn_IR register @return uint8_t. Value of @ref Sn_IR. @sa setSn_IR() */ - inline uint8_t getSn_IR() - { - return (wizchip_read(BlockSelectSReg, Sn_IR) & 0x1F); - } + inline uint8_t getSn_IR() { return (wizchip_read(BlockSelectSReg, Sn_IR) & 0x1F); } /** Set @ref Sn_IMR register @param (uint8_t)imr Value to set @ref Sn_IMR @sa getSn_IMR() */ - inline void setSn_IMR(uint8_t imr) - { - wizchip_write(BlockSelectSReg, Sn_IMR, (imr & 0x1F)); - } + inline void setSn_IMR(uint8_t imr) { wizchip_write(BlockSelectSReg, Sn_IMR, (imr & 0x1F)); } /** Get @ref Sn_IMR register @return uint8_t. Value of @ref Sn_IMR. @sa setSn_IMR() */ - inline uint8_t getSn_IMR() - { - return (wizchip_read(BlockSelectSReg, Sn_IMR) & 0x1F); - } + inline uint8_t getSn_IMR() { return (wizchip_read(BlockSelectSReg, Sn_IMR) & 0x1F); } /** Get @ref Sn_SR register @return uint8_t. Value of @ref Sn_SR. */ - inline uint8_t getSn_SR() - { - return wizchip_read(BlockSelectSReg, Sn_SR); - } + inline uint8_t getSn_SR() { return wizchip_read(BlockSelectSReg, Sn_SR); } /** Set @ref Sn_RXBUF_SIZE register @@ -680,10 +600,7 @@ class Wiznet5500 @return uint8_t. Value of @ref Sn_RXBUF_SIZE. @sa setSn_RXBUF_SIZE() */ - inline uint8_t getSn_RXBUF_SIZE() - { - return wizchip_read(BlockSelectSReg, Sn_RXBUF_SIZE); - } + inline uint8_t getSn_RXBUF_SIZE() { return wizchip_read(BlockSelectSReg, Sn_RXBUF_SIZE); } /** Set @ref Sn_TXBUF_SIZE register @@ -700,68 +617,47 @@ class Wiznet5500 @return uint8_t. Value of @ref Sn_TXBUF_SIZE. @sa setSn_TXBUF_SIZE() */ - inline uint8_t getSn_TXBUF_SIZE() - { - return wizchip_read(BlockSelectSReg, Sn_TXBUF_SIZE); - } + inline uint8_t getSn_TXBUF_SIZE() { return wizchip_read(BlockSelectSReg, Sn_TXBUF_SIZE); } /** Get @ref Sn_TX_RD register @return uint16_t. Value of @ref Sn_TX_RD. */ - inline uint16_t getSn_TX_RD() - { - return wizchip_read_word(BlockSelectSReg, Sn_TX_RD); - } + inline uint16_t getSn_TX_RD() { return wizchip_read_word(BlockSelectSReg, Sn_TX_RD); } /** Set @ref Sn_TX_WR register @param (uint16_t)txwr Value to set @ref Sn_TX_WR @sa GetSn_TX_WR() */ - inline void setSn_TX_WR(uint16_t txwr) - { - wizchip_write_word(BlockSelectSReg, Sn_TX_WR, txwr); - } + inline void setSn_TX_WR(uint16_t txwr) { wizchip_write_word(BlockSelectSReg, Sn_TX_WR, txwr); } /** Get @ref Sn_TX_WR register @return uint16_t. Value of @ref Sn_TX_WR. @sa setSn_TX_WR() */ - inline uint16_t getSn_TX_WR() - { - return wizchip_read_word(BlockSelectSReg, Sn_TX_WR); - } + inline uint16_t getSn_TX_WR() { return wizchip_read_word(BlockSelectSReg, Sn_TX_WR); } /** Set @ref Sn_RX_RD register @param (uint16_t)rxrd Value to set @ref Sn_RX_RD @sa getSn_RX_RD() */ - inline void setSn_RX_RD(uint16_t rxrd) - { - wizchip_write_word(BlockSelectSReg, Sn_RX_RD, rxrd); - } + inline void setSn_RX_RD(uint16_t rxrd) { wizchip_write_word(BlockSelectSReg, Sn_RX_RD, rxrd); } /** Get @ref Sn_RX_RD register @return uint16_t. Value of @ref Sn_RX_RD. @sa setSn_RX_RD() */ - inline uint16_t getSn_RX_RD() - { - return wizchip_read_word(BlockSelectSReg, Sn_RX_RD); - } + inline uint16_t getSn_RX_RD() { return wizchip_read_word(BlockSelectSReg, Sn_RX_RD); } /** Get @ref Sn_RX_WR register @return uint16_t. Value of @ref Sn_RX_WR. */ - inline uint16_t getSn_RX_WR() - { - return wizchip_read_word(BlockSelectSReg, Sn_RX_WR); - } + inline uint16_t getSn_RX_WR() { return wizchip_read_word(BlockSelectSReg, Sn_RX_WR); } }; -#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/device/libraries/BSTest/src/BSArduino.h b/tests/device/libraries/BSTest/src/BSArduino.h index 2fd4dc66e0..d2b9df3566 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,8 @@ class ArduinoIOHelper typedef ArduinoIOHelper IOHelper; -inline void fatal() { - ESP.restart(); -} +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..fd999be040 100644 --- a/tests/device/libraries/BSTest/src/BSArgs.h +++ b/tests/device/libraries/BSTest/src/BSArgs.h @@ -15,137 +15,164 @@ namespace bs { 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; - } - 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 */ + 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; } - 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..64775e846e 100644 --- a/tests/device/libraries/BSTest/src/BSProtocol.h +++ b/tests/device/libraries/BSTest/src/BSProtocol.h @@ -11,108 +11,111 @@ namespace bs { namespace protocol { -template<typename IO> -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<typename IO> -void output_check_failure(IO& io, size_t line) -{ - io.printf(BS_LINE_PREFIX "check_failure line=%d\n", line); -} - -template<typename IO> -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 <typename IO> + 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<typename IO> -void output_menu_begin(IO& io) -{ - io.printf(BS_LINE_PREFIX "menu_begin\n"); -} + template <typename IO> void output_check_failure(IO& io, size_t line) + { + io.printf(BS_LINE_PREFIX "check_failure line=%d\n", line); + } -template<typename IO> -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 <typename IO> + 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<typename IO> -void output_menu_end(IO& io) -{ - io.printf(BS_LINE_PREFIX "menu_end\n"); -} + template <typename IO> void output_menu_begin(IO& io) + { + io.printf(BS_LINE_PREFIX "menu_begin\n"); + } -template<typename IO> -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 <typename IO> + 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<typename IO> -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 <typename IO> void output_menu_end(IO& io) { io.printf(BS_LINE_PREFIX "menu_end\n"); } -template<typename IO> -void output_pretest_result(IO& io, bool res) -{ - io.printf(BS_LINE_PREFIX "pretest result=%d\n", res?1:0); -} + template <typename IO> 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<typename IO> -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 <typename IO> 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 <typename IO> 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 <typename IO> + 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..37feff5fd6 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,8 @@ class StdIOHelper typedef StdIOHelper IOHelper; -inline void fatal() { - throw std::runtime_error("fatal error"); -} +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..c93a398b3e 100644 --- a/tests/device/libraries/BSTest/src/BSTest.h +++ b/tests/device/libraries/BSTest/src/BSTest.h @@ -20,109 +20,96 @@ 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; } } - void run() const - { - (*m_func)(); - } + void run() const { (*m_func)(); } - TestCase* next() const - { - return m_next; - } + TestCase* next() const { return m_next; } - const char* file() const - { - return m_file; - } + const char* file() const { return m_file; } - size_t line() const - { - return m_line; - } + size_t line() const { return m_line; } - const char* name() const - { - return m_name; - } + const char* name() const { return m_name; } - const char* desc() const - { - return (m_desc)?m_desc:""; - } + const char* desc() const { 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<void(void)> m_check_pass; +struct Env +{ + std::function<void(void)> m_check_pass; std::function<void(size_t)> m_check_fail; std::function<void(size_t)> m_fail; - Registry m_registry; + Registry m_registry; }; extern Env g_env; -template<typename IO> -class Runner +template <typename IO> class Runner { typedef Runner<IO> 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() - { - ++m_check_pass_count; - } + void check_pass() { ++m_check_pass_count; } void check_fail(size_t line) { @@ -132,7 +119,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 +129,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 +158,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 +172,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 +181,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<bs::IOHelper> runner(helper); runner.run(); } while(0); +#define BS_ENV_DECLARE() \ + namespace bs \ + { \ + Env g_env; \ + } +#define BS_RUN(...) \ + do \ + { \ + bs::IOHelper helper = bs::IOHelper(__VA_ARGS__); \ + bs::Runner<bs::IOHelper> runner(helper); \ + runner.run(); \ + } while (0); -#endif //BSTEST_H +#endif // BSTEST_H diff --git a/tests/device/libraries/BSTest/test/test.cpp b/tests/device/libraries/BSTest/test/test.cpp index 863373e0de..fc344d474d 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,9 @@ TEST_CASE("another test which fails and crashes", "[bluesmoke][fail]") REQUIRE(false); } +TEST_CASE("third test which should be skipped", "[.]") { FAIL(); } -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 +51,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 <stdlib.h> #include <errno.h> - - #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 = "<UNSET>"; /* Routine name for message routines. */ -static int errors = 0; +_CONST char* it = "<UNSET>"; /* 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 <stdio.h> #include <stdarg.h> - #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 1c651e7e1f..ba9fea1dd4 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,11 +41,7 @@ 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(); -} +extern "C" void yield() { run_scheduled_recurrent_functions(); } extern "C" void loop_end() { @@ -53,61 +49,41 @@ extern "C" void loop_end() run_scheduled_recurrent_functions(); } -extern "C" bool can_yield() -{ - return true; -} +extern "C" bool can_yield() { return true; } -extern "C" void optimistic_yield (uint32_t interval_us) -{ - (void)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) -{ - usleep(ms * 1000); -} +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; abort(); } -extern "C" void delay(unsigned long ms) -{ - esp_delay(ms); -} +extern "C" void delay(unsigned long ms) { esp_delay(ms); } -extern "C" void delayMicroseconds(unsigned int us) -{ - usleep(us); -} +extern "C" void delayMicroseconds(unsigned int us) { usleep(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*) { } 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 <catch.hpp> #include <sys/time.h> #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 <Arduino.h> -#include <user_interface.h> // wifi_get_ip_info() +#include <user_interface.h> // wifi_get_ip_info() #include <signal.h> #include <unistd.h> @@ -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 <interface> - 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 <interface> - 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 <poll.h> #include <map> -std::map<int,UdpContext*> udps; +std::map<int, UdpContext*> 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 <fcntl.h> #include <errno.h> -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 <WiFiClient.h> #include <include/ClientContext.h> -#include <netdb.h> // gethostbyname +#include <netdb.h> // 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..a146c14475 100644 --- a/tests/host/common/EEPROM.h +++ b/tests/host/common/EEPROM.h @@ -32,46 +32,45 @@ #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<typename T> - 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 <typename T> 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<typename T> - 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 <typename T> const T& put(int const address, const T& t) + { + if (address < 0 || address + sizeof(T) > _size) + return t; + for (size_t i = 0; i < sizeof(T); i++) + write(i, ((uint8_t*)&t)[i]); + return t; + } - size_t length() { return _size; } + size_t length() { return _size; } - //uint8_t& operator[](int const address) { return read(address); } - uint8_t operator[] (int address) { return read(address); } + // uint8_t& operator[](int const address) { return read(address); } + uint8_t operator[](int address) { return read(address); } protected: - size_t _size = 0; - int _fd = -1; + size_t _size = 0; + int _fd = -1; }; #if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_EEPROM) diff --git a/tests/host/common/HostWiring.cpp b/tests/host/common/HostWiring.cpp index 765d4297b6..dc93fd2f85 100644 --- a/tests/host/common/HostWiring.cpp +++ b/tests/host/common/HostWiring.cpp @@ -37,49 +37,58 @@ #define VERBOSE(x...) mockverbose(x) #endif -void pinMode (uint8_t pin, uint8_t mode) +void pinMode(uint8_t pin, uint8_t mode) { - #define xxx(mode) case mode: m=STRHELPER(mode); break - const char* m; - switch (mode) - { - case INPUT: m="INPUT"; break; - case OUTPUT: m="OUTPUT"; break; - case INPUT_PULLUP: m="INPUT_PULLUP"; break; - case OUTPUT_OPEN_DRAIN: m="OUTPUT_OPEN_DRAIN"; break; - case INPUT_PULLDOWN_16: m="INPUT_PULLDOWN_16"; break; - case WAKEUP_PULLUP: m="WAKEUP_PULLUP"; break; - case WAKEUP_PULLDOWN: m="WAKEUP_PULLDOWN"; break; - default: m="(special)"; - } - VERBOSE("gpio%d: mode='%s'\n", pin, m); +#define xxx(mode) \ + case mode: \ + m = STRHELPER(mode); \ + break + const char* m; + switch (mode) + { + case INPUT: + m = "INPUT"; + break; + case OUTPUT: + m = "OUTPUT"; + break; + case INPUT_PULLUP: + m = "INPUT_PULLUP"; + break; + case OUTPUT_OPEN_DRAIN: + m = "OUTPUT_OPEN_DRAIN"; + break; + case INPUT_PULLDOWN_16: + m = "INPUT_PULLDOWN_16"; + break; + case WAKEUP_PULLUP: + m = "WAKEUP_PULLUP"; + break; + case WAKEUP_PULLDOWN: + m = "WAKEUP_PULLDOWN"; + break; + default: + m = "(special)"; + } + VERBOSE("gpio%d: mode='%s'\n", pin, m); } -void digitalWrite(uint8_t pin, uint8_t val) -{ - VERBOSE("digitalWrite(pin=%d val=%d)\n", pin, val); -} +void digitalWrite(uint8_t pin, uint8_t val) { VERBOSE("digitalWrite(pin=%d val=%d)\n", pin, val); } -void analogWrite(uint8_t pin, int val) -{ - VERBOSE("analogWrite(pin=%d, val=%d\n", pin, val); -} +void analogWrite(uint8_t pin, int 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); -} +void analogWriteRange(uint32_t range) { VERBOSE("analogWriteRange(range=%d)\n", range); } int digitalRead(uint8_t pin) { - VERBOSE("digitalRead(%d)\n", pin); + VERBOSE("digitalRead(%d)\n", pin); - // pin 0 is most likely a low active input - return pin ? 0 : 1; + // pin 0 is most likely a low active input + return pin ? 0 : 1; } diff --git a/tests/host/common/MockDigital.cpp b/tests/host/common/MockDigital.cpp index aa04527ab5..0820ea63f1 100644 --- a/tests/host/common/MockDigital.cpp +++ b/tests/host/common/MockDigital.cpp @@ -28,29 +28,36 @@ #include "core_esp8266_waveform.h" #include "interrupts.h" -extern "C" { - -static uint8_t _mode[17]; -static uint8_t _gpio[17]; - -extern void pinMode(uint8_t pin, uint8_t mode) { - if (pin < 17) { - _mode[pin] = mode; - } -} - -extern void digitalWrite(uint8_t pin, uint8_t val) { - if (pin < 17) { - _gpio[pin] = val; - } -} - -extern int digitalRead(uint8_t pin) { - if (pin < 17) { - return _gpio[pin] != 0; - } else { - return 0; - } -} - +extern "C" +{ + static uint8_t _mode[17]; + static uint8_t _gpio[17]; + + extern void pinMode(uint8_t pin, uint8_t mode) + { + if (pin < 17) + { + _mode[pin] = mode; + } + } + + extern void digitalWrite(uint8_t pin, uint8_t val) + { + if (pin < 17) + { + _gpio[pin] = val; + } + } + + extern int digitalRead(uint8_t pin) + { + if (pin < 17) + { + return _gpio[pin] != 0; + } + else + { + return 0; + } + } }; diff --git a/tests/host/common/MockEEPROM.cpp b/tests/host/common/MockEEPROM.cpp index 6357c73dd2..34eda86d39 100644 --- a/tests/host/common/MockEEPROM.cpp +++ b/tests/host/common/MockEEPROM.cpp @@ -42,52 +42,49 @@ #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; -} +bool EEPROMClass::commit() { return true; } -uint8_t EEPROMClass::read (int x) +uint8_t EEPROMClass::read(int x) { - char c = 0; - if (pread(_fd, &c, 1, x) != 1) - fprintf(stderr, MOCK "eeprom: %s\n\r", strerror(errno)); - return c; + char c = 0; + if (pread(_fd, &c, 1, x) != 1) + fprintf(stderr, MOCK "eeprom: %s\n\r", strerror(errno)); + return c; } -void EEPROMClass::write (int x, uint8_t c) +void EEPROMClass::write(int x, uint8_t c) { - if (x > (int)_size) - fprintf(stderr, MOCK "### eeprom beyond\r\n"); - else if (pwrite(_fd, &c, 1, x) != 1) - fprintf(stderr, MOCK "eeprom: %s\n\r", strerror(errno)); + if (x > (int)_size) + fprintf(stderr, MOCK "### eeprom beyond\r\n"); + else if (pwrite(_fd, &c, 1, x) != 1) + fprintf(stderr, MOCK "eeprom: %s\n\r", strerror(errno)); } #if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_EEPROM) diff --git a/tests/host/common/MockEsp.cpp b/tests/host/common/MockEsp.cpp index d11a39e940..42a70d7096 100644 --- a/tests/host/common/MockEsp.cpp +++ b/tests/host/common/MockEsp.cpp @@ -36,210 +36,151 @@ #include <stdlib.h> -unsigned long long operator"" _kHz(unsigned long long x) { - return x * 1000; -} +unsigned long long operator"" _kHz(unsigned long long x) { return x * 1000; } -unsigned long long operator"" _MHz(unsigned long long x) { - return x * 1000 * 1000; -} +unsigned long long operator"" _MHz(unsigned long long x) { return x * 1000 * 1000; } -unsigned long long operator"" _GHz(unsigned long long x) { - return x * 1000 * 1000 * 1000; -} +unsigned long long operator"" _GHz(unsigned long long x) { return x * 1000 * 1000 * 1000; } -unsigned long long operator"" _kBit(unsigned long long x) { - return x * 1024; -} +unsigned long long operator"" _kBit(unsigned long long x) { return x * 1024; } -unsigned long long operator"" _MBit(unsigned long long x) { - return x * 1024 * 1024; -} +unsigned long long operator"" _MBit(unsigned long long x) { return x * 1024 * 1024; } -unsigned long long operator"" _GBit(unsigned long long x) { - return x * 1024 * 1024 * 1024; -} +unsigned long long operator"" _GBit(unsigned long long x) { return x * 1024 * 1024 * 1024; } -unsigned long long operator"" _kB(unsigned long long x) { - return x * 1024; -} +unsigned long long operator"" _kB(unsigned long long x) { return x * 1024; } -unsigned long long operator"" _MB(unsigned long long x) { - return x * 1024 * 1024; -} +unsigned long long operator"" _MB(unsigned long long x) { return x * 1024 * 1024; } -unsigned long long operator"" _GB(unsigned long long x) { - return x * 1024 * 1024 * 1024; -} +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)cmd; -} +void eboot_command_write(struct eboot_command* 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; -} +uint32_t EspClass::getChipId() { return 0xee1337; } bool EspClass::checkFlashConfig(bool needsEquals) { - (void) needsEquals; - return true; + (void)needsEquals; + return true; } -uint32_t EspClass::getSketchSize() -{ - return 400000; -} +uint32_t EspClass::getSketchSize() { return 400000; } -uint32_t EspClass::getFreeHeap() -{ - return 30000; -} +uint32_t EspClass::getFreeHeap() { return 30000; } -uint32_t EspClass::getMaxFreeBlockSize() -{ - return 20000; -} +uint32_t EspClass::getMaxFreeBlockSize() { return 20000; } -String EspClass::getResetReason() -{ - return "Power on"; -} +String EspClass::getResetReason() { return "Power on"; } -uint32_t EspClass::getFreeSketchSpace() -{ - return 4 * 1024 * 1024; -} +uint32_t EspClass::getFreeSketchSpace() { return 4 * 1024 * 1024; } -const char *EspClass::getSdkVersion() -{ - return "2.5.0"; -} +const char* EspClass::getSdkVersion() { return "2.5.0"; } -uint32_t EspClass::getFlashChipSpeed() -{ - return 40; -} +uint32_t EspClass::getFlashChipSpeed() { return 40; } -void EspClass::getHeapStats(uint32_t* hfree, uint16_t* hmax, uint8_t* hfrag) { - uint32_t hf = 10 * 1024; - float hm = 1 * 1024; +void EspClass::getHeapStats(uint32_t* hfree, uint16_t* hmax, uint8_t* hfrag) +{ + uint32_t hf = 10 * 1024; + float hm = 1 * 1024; - if (hfree) *hfree = hf; - if (hmax) *hmax = hm; - if (hfrag) *hfrag = 100 - (sqrt(hm) * 100) / hf; + if (hfree) + *hfree = hf; + if (hmax) + *hmax = hm; + if (hfrag) + *hfrag = 100 - (sqrt(hm) * 100) / hf; } bool EspClass::flashEraseSector(uint32_t sector) { - (void) sector; - return true; + (void)sector; + return true; } -FlashMode_t EspClass::getFlashChipMode() -{ - return FM_DOUT; -} +FlashMode_t EspClass::getFlashChipMode() { 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); -} +uint32_t EspClass::getFlashChipRealSize(void) { return magicFlashChipSize(4); } -uint32_t EspClass::getFlashChipSize(void) -{ - return magicFlashChipSize(4); -} +uint32_t EspClass::getFlashChipSize(void) { return magicFlashChipSize(4); } -String EspClass::getFullVersion () -{ - return "emulation-on-host"; -} +String EspClass::getFullVersion() { return "emulation-on-host"; } -uint32_t EspClass::getFreeContStack() -{ - return 4000; -} +uint32_t EspClass::getFreeContStack() { return 4000; } -void EspClass::resetFreeContStack() -{ -} +void EspClass::resetFreeContStack() { } -uint32_t EspClass::getCycleCount() -{ - return esp_get_cycle_count(); -} +uint32_t EspClass::getCycleCount() { return esp_get_cycle_count(); } uint32_t esp_get_cycle_count() { @@ -248,18 +189,10 @@ 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() { } diff --git a/tests/host/common/MockSPI.cpp b/tests/host/common/MockSPI.cpp index 251cad914a..ba6e5d4368 100644 --- a/tests/host/common/MockSPI.cpp +++ b/tests/host/common/MockSPI.cpp @@ -35,29 +35,14 @@ SPIClass SPI; #endif -SPIClass::SPIClass () -{ -} - -uint8_t SPIClass::transfer(uint8_t data) -{ - return data; -} - -void SPIClass::begin() -{ -} - -void SPIClass::end() -{ -} - -void SPIClass::setFrequency(uint32_t freq) -{ - (void)freq; -} - -void SPIClass::setHwCs(bool use) -{ - (void)use; -} +SPIClass::SPIClass() { } + +uint8_t SPIClass::transfer(uint8_t data) { return data; } + +void SPIClass::begin() { } + +void SPIClass::end() { } + +void SPIClass::setFrequency(uint32_t freq) { (void)freq; } + +void SPIClass::setHwCs(bool use) { (void)use; } diff --git a/tests/host/common/MockTools.cpp b/tests/host/common/MockTools.cpp index 5eb7969de7..3a1847c802 100644 --- a/tests/host/common/MockTools.cpp +++ b/tests/host/common/MockTools.cpp @@ -34,47 +34,46 @@ extern "C" { + uint32_t lwip_htonl(uint32_t hostlong) { return htonl(hostlong); } + uint16_t lwip_htons(uint16_t hostshort) { return htons(hostshort); } + uint32_t lwip_ntohl(uint32_t netlong) { return ntohl(netlong); } + uint16_t lwip_ntohs(uint16_t netshort) { return ntohs(netshort); } -uint32_t lwip_htonl (uint32_t hostlong) { return htonl(hostlong); } -uint16_t lwip_htons (uint16_t hostshort) { return htons(hostshort); } -uint32_t lwip_ntohl (uint32_t netlong) { return ntohl(netlong); } -uint16_t lwip_ntohs (uint16_t netshort) { return ntohs(netshort); } + char* ets_strcpy(char* d, const char* s) { return strcpy(d, s); } + char* ets_strncpy(char* d, const char* s, size_t n) { return strncpy(d, s, n); } + size_t ets_strlen(const char* s) { return strlen(s); } -char* ets_strcpy (char* d, const char* s) { return strcpy(d, s); } -char* ets_strncpy (char* d, const char* s, size_t n) { return strncpy(d, s, n); } -size_t ets_strlen (const char* s) { return strlen(s); } - -int ets_printf (const char* fmt, ...) -{ + 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); } diff --git a/tests/host/common/MockUART.cpp b/tests/host/common/MockUART.cpp index dc6514ae40..72d5a54d73 100644 --- a/tests/host/common/MockUART.cpp +++ b/tests/host/common/MockUART.cpp @@ -28,475 +28,437 @@ is responsible for feeding the RX FIFO new data by calling uart_new_data(). */ -#include <unistd.h> // write -#include <sys/time.h> // gettimeofday -#include <time.h> // localtime +#include <unistd.h> // write +#include <sys/time.h> // gettimeofday +#include <time.h> // 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; -} - -// 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]; + } + rx_buffer->buffer[rx_buffer->wpos] = data; + rx_buffer->wpos = nextPos; + } - if(uart == NULL || !uart->rx_enabled) { - return; - } + // 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]; - uart_handle_data(uart, data); -} + if (uart == NULL || !uart->rx_enabled) + { + return; + } -static size_t -uart_rx_available_unsafe(const struct uart_rx_buffer_ * rx_buffer) -{ - size_t ret = rx_buffer->wpos - rx_buffer->rpos; + uart_handle_data(uart, data); + } - if(rx_buffer->wpos < rx_buffer->rpos) - ret = (rx_buffer->wpos + rx_buffer->size) - 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; - return ret; -} + if (rx_buffer->wpos < rx_buffer->rpos) + ret = (rx_buffer->wpos + rx_buffer->size) - rx_buffer->rpos; -// 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; -} + return ret; + } -/**********************************************************/ -/************ UART API FUNCTIONS **************************/ -/**********************************************************/ + // 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; + } -size_t -uart_rx_available(uart_t* uart) -{ - if(uart == NULL || !uart->rx_enabled) - return 0; + /**********************************************************/ + /************ UART API FUNCTIONS **************************/ + /**********************************************************/ - return uart_rx_available_unsafe(uart->rx_buffer); -} + size_t uart_rx_available(uart_t* uart) + { + if (uart == NULL || !uart->rx_enabled) + return 0; -int -uart_peek_char(uart_t* uart) -{ - if(uart == NULL || !uart->rx_enabled) - return -1; + return uart_rx_available_unsafe(uart->rx_buffer); + } - if (!uart_rx_available_unsafe(uart->rx_buffer)) - return -1; + int uart_peek_char(uart_t* uart) + { + if (uart == NULL || !uart->rx_enabled) + return -1; - return uart->rx_buffer->buffer[uart->rx_buffer->rpos]; -} + if (!uart_rx_available_unsafe(uart->rx_buffer)) + return -1; -int -uart_read_char(uart_t* uart) -{ - uint8_t ret; - return uart_read(uart, (char*)&ret, 1) ? ret : -1; -} + return uart->rx_buffer->buffer[uart->rx_buffer->rpos]; + } -size_t -uart_read(uart_t* uart, char* userbuffer, size_t usersize) -{ - if(uart == NULL || !uart->rx_enabled) - return 0; + int uart_read_char(uart_t* uart) + { + uint8_t ret; + return uart_read(uart, (char*)&ret, 1) ? ret : -1; + } - if (!blocking_uart) + size_t uart_read(uart_t* uart, char* userbuffer, size_t usersize) { - char c; - if (read(0, &c, 1) == 1) - uart_new_data(0, c); + 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 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() { return s_uart_debug_nr; } -int -uart_get_debug() -{ - return s_uart_debug_nr; -} + void uart_start_detect_baudrate(int uart_nr) { (void)uart_nr; } -void -uart_start_detect_baudrate(int uart_nr) -{ - (void) uart_nr; -} + int uart_detect_baudrate(int uart_nr) + { + (void)uart_nr; + return 115200; + } +}; -int -uart_detect_baudrate(int uart_nr) +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_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..6e26e8d146 100644 --- a/tests/host/common/MockWiFiServer.cpp +++ b/tests/host/common/MockWiFiServer.cpp @@ -44,32 +44,28 @@ 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) -{ - _port = port; -} +WiFiServer::WiFiServer(uint16_t 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 <include/UdpContext.h> uint32_t UdpContext::staticMCastAddr = 0; - diff --git a/tests/host/common/MockWiFiServerSocket.cpp b/tests/host/common/MockWiFiServerSocket.cpp index 9ab344bf50..f23c79b20e 100644 --- a/tests/host/common/MockWiFiServerSocket.cpp +++ b/tests/host/common/MockWiFiServerSocket.cpp @@ -44,26 +44,23 @@ // 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) -{ - return begin(port, !0); -} +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 +68,83 @@ 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 () -{ - close(); -} +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..cec1bfae4d 100644 --- a/tests/host/common/MocklwIP.cpp +++ b/tests/host/common/MocklwIP.cpp @@ -7,58 +7,51 @@ 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 <user_interface.h> #include <lwip/netif.h> -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 <assert.h> #include <net/if.h> -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..10e17b04a1 100644 --- a/tests/host/common/WMath.cpp +++ b/tests/host/common/WMath.cpp @@ -4,59 +4,63 @@ 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 <stdlib.h> #include <stdint.h> } -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) { - return w; -} +uint16_t makeWord(unsigned int w) { return w; } -uint16_t makeWord(unsigned char h, unsigned char l) { - return (h << 8) | 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 <stdarg.h> #include <sys/cdefs.h> -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_mock.cpp b/tests/host/common/flash_hal_mock.cpp index 5304d7553a..65d7c4d355 100644 --- a/tests/host/common/flash_hal_mock.cpp +++ b/tests/host/common/flash_hal_mock.cpp @@ -5,31 +5,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/flash_hal_mock.h b/tests/host/common/flash_hal_mock.h index af5035eaa5..bacd375e2e 100644 --- a/tests/host/common/flash_hal_mock.h +++ b/tests/host/common/flash_hal_mock.h @@ -12,8 +12,8 @@ extern "C" extern uint8_t* s_phys_data; } -extern int32_t flash_hal_read(uint32_t addr, uint32_t size, uint8_t *dst); -extern int32_t flash_hal_write(uint32_t addr, uint32_t size, const uint8_t *src); +extern int32_t flash_hal_read(uint32_t addr, uint32_t size, uint8_t* dst); +extern int32_t flash_hal_write(uint32_t addr, uint32_t size, const uint8_t* src); extern int32_t flash_hal_erase(uint32_t addr, uint32_t size); #endif diff --git a/tests/host/common/include/ClientContext.h b/tests/host/common/include/ClientContext.h index bd9c9b80a5..4f10bb93ce 100644 --- a/tests/host/common/include/ClientContext.h +++ b/tests/host/common/include/ClientContext.h @@ -26,7 +26,7 @@ class WiFiClient; #include <assert.h> -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; @@ -63,15 +63,9 @@ class ClientContext return ERR_OK; } - ~ClientContext() - { - abort(); - } + ~ClientContext() { abort(); } - ClientContext* next() const - { - return _next; - } + ClientContext* next() const { return _next; } ClientContext* next(ClientContext* new_next) { @@ -88,11 +82,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; } @@ -109,10 +104,7 @@ class ClientContext return 512; } - void setNoDelay(bool nodelay) - { - mockverbose("TODO setNoDelay(%d)\n", (int)nodelay); - } + void setNoDelay(bool nodelay) { mockverbose("TODO setNoDelay(%d)\n", (int)nodelay); } bool getNoDelay() const { @@ -120,15 +112,9 @@ class ClientContext return false; } - void setTimeout(int timeout_ms) - { - _timeout_ms = timeout_ms; - } + void setTimeout(int timeout_ms) { _timeout_ms = timeout_ms; } - int getTimeout() const - { - return _timeout_ms; - } + int getTimeout() const { return _timeout_ms; } uint32_t getRemoteAddress() const { @@ -172,10 +158,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 +175,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) @@ -203,10 +189,7 @@ class ClientContext return ret; } - void discard_received() - { - mockverbose("TODO: ClientContext::discard_received()\n"); - } + void discard_received() { mockverbose("TODO: ClientContext::discard_received()\n"); } bool wait_until_acked(int max_wait_ms = WIFICLIENT_MAX_FLUSH_WAIT_MS) { @@ -216,60 +199,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 +262,10 @@ class ClientContext // return a pointer to available data buffer (size = peekAvailable()) // semantic forbids any kind of read() before calling peekConsume() - const char* peekBuffer () - { - return _inbuf; - } + 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 +277,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 +285,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..b32c67b761 100644 --- a/tests/host/common/include/UdpContext.h +++ b/tests/host/common/include/UdpContext.h @@ -37,22 +37,13 @@ extern netif netif0; class UdpContext { public: - typedef std::function<void(void)> rxhandler_t; - UdpContext(): _on_rx(nullptr), _refcnt(0) - { - _sock = mockUDPSocket(); - } + UdpContext() : _on_rx(nullptr), _refcnt(0) { _sock = mockUDPSocket(); } - ~UdpContext() - { - } + ~UdpContext() { } - void ref() - { - ++_refcnt; - } + void ref() { ++_refcnt; } void unref() { @@ -64,7 +55,7 @@ class UdpContext bool connect(const ip_addr_t* addr, uint16_t port) { - _dst = *addr; + _dst = *addr; _dstport = port; return true; } @@ -103,30 +94,18 @@ class UdpContext void setMulticastTTL(int ttl) { (void)ttl; - //mockverbose("TODO: UdpContext::setMulticastTTL\n"); + // mockverbose("TODO: UdpContext::setMulticastTTL\n"); } - netif* getInputNetif() const - { - return &netif0; - } + netif* getInputNetif() const { return &netif0; } // warning: handler is called from tcp stack context // esp_yield and non-reentrant functions which depend on it will fail - void onRx(rxhandler_t handler) - { - _on_rx = handler; - } + void onRx(rxhandler_t handler) { _on_rx = handler; } - size_t getSize() - { - return _inbufsize; - } + size_t getSize() { return _inbufsize; } - size_t tell() const - { - return 0; - } + size_t tell() const { return 0; } void seek(const size_t pos) { @@ -138,31 +117,22 @@ class UdpContext mockUDPSwallow(pos, _inbuf, _inbufsize); } - bool isValidOffset(const size_t pos) const - { - return pos <= _inbufsize; - } + bool isValidOffset(const size_t pos) const { return pos <= _inbufsize; } - IPAddress getRemoteAddress() - { - return _dst.addr; - } + IPAddress getRemoteAddress() { return _dst.addr; } - uint16_t getRemotePort() - { - return _dstport; - } + uint16_t getRemotePort() { return _dstport; } 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,13 +161,13 @@ 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); + // mockverbose("UdpContext::flush() does not follow arduino's flush concept\n"); + // exit(EXIT_FAILURE); // would be: _inbufsize = 0; } @@ -206,7 +176,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,19 +188,17 @@ 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(); return ret; } - void cancelBuffer() - { - _outbufsize = 0; - } + void cancelBuffer() { _outbufsize = 0; } bool send(ip_addr_t* addr = 0, uint16_t port = 0) { @@ -239,7 +208,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 +219,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 +235,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 +259,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 0d99e82b1e..2d061d9b81 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" @@ -57,7 +56,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(); } @@ -73,47 +73,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 0905fa9322..4bc405d8f1 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<uint8_t> 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..df43fc998b 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 <stddef.h> #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -// TODO: #include <stdlib_noniso.h> ? -char* itoa (int val, char *s, int radix); -char* ltoa (long val, char *s, int radix); + // TODO: #include <stdlib_noniso.h> ? + 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 <stdint.h> -typedef uint8_t uint8; +typedef uint8_t uint8; typedef uint32_t uint32; // @@ -97,26 +98,27 @@ uint32_t esp_get_cycle_count(); // #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif #include <osapi.h> -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 +134,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 +183,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..31d239dc45 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 <stdlib.h> #include <string.h> #include <stdbool.h> @@ -21,61 +20,69 @@ #include <math.h> #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,16 @@ 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..0bd32e50d8 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 <machine/ansi.h> /* for __offsetof */ +#include <machine/ansi.h> /* 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 <vector> #include <FS.h> -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 c7f9f53aba..6406dc9a7d 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" @@ -56,7 +55,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(); } @@ -72,18 +72,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) { @@ -91,28 +91,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; @@ -132,4 +136,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 4c265964f5..a6227582c9 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<uint8_t> 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..951a4a8d85 100644 --- a/tests/host/common/user_interface.cpp +++ b/tests/host/common/user_interface.cpp @@ -43,7 +43,7 @@ #include <LwipDhcpServer.h> -bool DhcpServer::set_dhcps_lease(struct dhcps_lease *please) +bool DhcpServer::set_dhcps_lease(struct dhcps_lease* please) { (void)please; return false; @@ -62,72 +62,45 @@ 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) -{ - (void)netif; -} +DhcpServer::DhcpServer(netif* netif) { (void)netif; } -DhcpServer::~DhcpServer () -{ - end(); -} +DhcpServer::~DhcpServer() { end(); } DhcpServer dhcpSoftAP(nullptr); extern "C" { - #include <user_interface.h> #include <lwip/netif.h> - uint8 wifi_get_opmode(void) - { - return STATION_MODE; - } + uint8 wifi_get_opmode(void) { return STATION_MODE; } - phy_mode_t wifi_get_phy_mode(void) - { - return PHY_MODE_11N; - } + phy_mode_t wifi_get_phy_mode(void) { return PHY_MODE_11N; } - uint8 wifi_get_channel(void) - { - return 1; - } + uint8 wifi_get_channel(void) { return 1; } - uint8 wifi_station_get_current_ap_id(void) - { - return 0; - } + uint8 wifi_station_get_current_ap_id(void) { return 0; } - station_status_t wifi_station_get_connect_status(void) - { - return STATION_GOT_IP; - } + station_status_t wifi_station_get_connect_status(void) { return STATION_GOT_IP; } - uint8 wifi_station_get_auto_connect(void) - { - return 1; - } + uint8 wifi_station_get_auto_connect(void) { 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 +108,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 +116,27 @@ 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; - } + 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 +150,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 +182,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,26 +190,23 @@ 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; } - uint8 wifi_get_listen_interval(void) - { - return 1; - } + uint8 wifi_get_listen_interval(void) { 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; @@ -255,24 +218,15 @@ extern "C" return true; } - uint8 wifi_get_opmode_default(void) - { - return STATION_MODE; - } + uint8 wifi_get_opmode_default(void) { return STATION_MODE; } #ifdef NONOSDK3V0 - sleep_level_t wifi_get_sleep_level(void) - { - return MIN_SLEEP_T; - } + sleep_level_t wifi_get_sleep_level(void) { return MIN_SLEEP_T; } -#endif // nonos-sdk-pre-3 +#endif // nonos-sdk-pre-3 - sleep_type_t wifi_get_sleep_type(void) - { - return NONE_SLEEP_T; - } + sleep_type_t wifi_get_sleep_type(void) { return NONE_SLEEP_T; } bool wifi_set_channel(uint8 channel) { @@ -281,13 +235,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; @@ -332,65 +286,44 @@ extern "C" return true; } - bool wifi_station_connect(void) - { - return true; - } + bool wifi_station_connect(void) { return true; } - bool wifi_station_dhcpc_start(void) - { - return true; - } + bool wifi_station_dhcpc_start(void) { return true; } - bool wifi_station_dhcpc_stop(void) - { - return true; - } + bool wifi_station_dhcpc_stop(void) { return true; } - bool wifi_station_disconnect(void) - { - return true; - } + bool wifi_station_disconnect(void) { 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"); } - bool wifi_station_get_reconnect_policy() - { - return true; - } + bool wifi_station_get_reconnect_policy() { return true; } - sint8 wifi_station_get_rssi(void) - { - return 5; - } + sint8 wifi_station_get_rssi(void) { return 5; } - bool wifi_station_set_auto_connect(uint8 set) - { - return set != 0; - } + bool wifi_station_set_auto_connect(uint8 set) { 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; @@ -402,62 +335,47 @@ extern "C" return true; } - void system_phy_set_max_tpw(uint8 max_tpw) - { - (void)max_tpw; - } + void system_phy_set_max_tpw(uint8 max_tpw) { (void)max_tpw; } - bool wifi_softap_dhcps_start(void) - { - return true; - } + bool wifi_softap_dhcps_start(void) { return true; } - enum dhcp_status wifi_softap_dhcps_status(void) - { - return DHCP_STARTED; - } + enum dhcp_status wifi_softap_dhcps_status(void) { return DHCP_STARTED; } - bool wifi_softap_dhcps_stop(void) - { - return true; - } + bool wifi_softap_dhcps_stop(void) { 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); } - uint8 wifi_softap_get_station_num(void) - { - return 2; - } + uint8 wifi_softap_get_station_num(void) { 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 +394,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); @@ -488,17 +406,11 @@ extern "C" /////////////////////////////////////// // not user_interface - void ets_isr_mask(int intr) - { - (void)intr; - } + void ets_isr_mask(int intr) { (void)intr; } - void ets_isr_unmask(int intr) - { - (void)intr; - } + void ets_isr_unmask(int intr) { (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,23 +423,16 @@ extern "C" return addr; } - #include <smartconfig.h> bool smartconfig_start(sc_callback_t cb, ...) { - //XXXFIXME ... -> ptr + // XXXFIXME ... -> ptr cb(SC_STATUS_LINK, NULL); return true; } - bool smartconfig_stop(void) - { - return true; - } + bool smartconfig_stop(void) { return true; } - sleep_type_t wifi_fpm_get_sleep_type(void) - { - return NONE_SLEEP_T; - } + sleep_type_t wifi_fpm_get_sleep_type(void) { 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..f37eaa26ef 100644 --- a/tests/host/core/test_PolledTimeout.cpp +++ b/tests/host/core/test_PolledTimeout.cpp @@ -2,245 +2,238 @@ #include "PolledTimeout.h" #define mockverbose printf -#include "common/MockEsp.cpp" // getCycleCount +#include "common/MockEsp.cpp" // getCycleCount -//This won't work for -template<typename argT> -inline bool -fuzzycomp(argT a, argT b) +// This won't work for +template <typename argT> 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<false, YieldOrSkipPolicy>; - using timeType = oneShotMsYield::timeType; - timeType before, after, delta; + using YieldOrSkipPolicy = esp8266::polledTimeout::YieldPolicy::YieldOrSkip; + using oneShotMsYield = esp8266::polledTimeout::timeoutTemplate<false, YieldOrSkipPolicy>; + 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 <catch.hpp> #include <Updater.h> - // 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 <new> @@ -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<const void*>(result.c_str()) == static_cast<const void*>(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<const void*>(result.c_str()) == static_cast<const void*>(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..e48a945fe5 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,43 @@ #endif #ifdef __cplusplus - #define pgm_read_byte(addr) (*reinterpret_cast<const uint8_t*>(addr)) - #define pgm_read_word(addr) (*reinterpret_cast<const uint16_t*>(addr)) - #define pgm_read_dword(addr) (*reinterpret_cast<const uint32_t*>(addr)) - #define pgm_read_float(addr) (*reinterpret_cast<const float*>(addr)) - #define pgm_read_ptr(addr) (*reinterpret_cast<const void* const *>(addr)) +#define pgm_read_byte(addr) (*reinterpret_cast<const uint8_t*>(addr)) +#define pgm_read_word(addr) (*reinterpret_cast<const uint16_t*>(addr)) +#define pgm_read_dword(addr) (*reinterpret_cast<const uint32_t*>(addr)) +#define pgm_read_float(addr) (*reinterpret_cast<const float*>(addr)) +#define pgm_read_ptr(addr) (*reinterpret_cast<const void* const*>(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 <stdio.h> #include <string.h> -inline const char *strstr_P(const char *haystack, const char *needle) { return strstr(haystack, needle); } -inline char *strcpy_P(char *dest, const char *src) { return strcpy(dest, src); } -inline size_t strlen_P(const char *s) { return strlen(s); } -inline int vsnprintf_P(char *str, size_t size, const char *format, va_list ap) { return vsnprintf(str, size, format, ap); } +inline const char* strstr_P(const char* haystack, const char* needle) +{ + return strstr(haystack, needle); +} +inline char* strcpy_P(char* dest, const char* src) { return strcpy(dest, src); } +inline size_t strlen_P(const char* s) { return strlen(s); } +inline int vsnprintf_P(char* str, size_t size, const char* format, va_list ap) +{ + return vsnprintf(str, size, format, ap); +} #define memcpy_P memcpy #define memmove_P memmove diff --git a/tests/restyle.sh b/tests/restyle.sh index ea454069c5..d5afbe504e 100755 --- a/tests/restyle.sh +++ b/tests/restyle.sh @@ -8,7 +8,43 @@ pwd test -d cores/esp8266 test -d libraries -# should be: all="cores/esp8266 libraries" +######################################### + +makeClangConf() +{ + IndentWidth="$1" + IndentCaseLabels="$2" + BreakBeforeBraces="$3" + + cat << EOF > .clang-format +BasedOnStyle: WebKit +SortIncludes: false +AlignTrailingComments: true +ColumnLimit: 100 +KeepEmptyLinesAtTheStartOfBlocks: false +SpaceBeforeInheritanceColon: false +SpacesBeforeTrailingComments: 2 +AlignTrailingComments: true +AlignConsecutiveAssignments: Consecutive +AlignConsecutiveBitFields: Consecutive +AlignConsecutiveDeclarations: Consecutive +AlignAfterOpenBracket: Align +AlignOperands: Align +BreakConstructorInitializers: AfterColon +BreakBeforeBinaryOperators: All +BreakBeforeTernaryOperators: false +BreakBeforeConceptDeclarations: true +FixNamespaceComments: true +NamespaceIndentation: Inner +BreakBeforeBraces: ${BreakBeforeBraces} +IndentWidth: ${IndentWidth} +IndentCaseLabels: ${IndentCaseLabels} +EOF + +} + +######################################### +# 'all' variable should be "cores/esp8266 libraries" all=" libraries/ESP8266mDNS @@ -20,31 +56,36 @@ cores/esp8266/core_esp8266_si2c.cpp cores/esp8266/StreamString.* cores/esp8266/StreamSend.* libraries/Netdump +tests " -# core +######################################### +# restyling core + +makeClangConf 4 false Allman for d in $all; do if [ -d "$d" ]; then echo "-------- directory $d:" for e in c cpp h; do - find $d -name "*.$e" -exec \ - astyle \ - --suffix=none \ - --options=${org}/astyle_core.conf {} \; + find $d -name "*.$e" -exec clang-format-12 -i {} \; done else echo "-------- file $d:" - astyle --suffix=none --options=${org}/astyle_core.conf "$d" + clang-format-12 -i ${d} fi done -# examples +######################################### +# restyling arduino examples + +makeClangConf 2 true Attach for d in libraries; do echo "-------- examples in $d:" - find $d -name "*.ino" -exec \ - astyle \ - --suffix=none \ - --options=${org}/astyle_examples.conf {} \; + find $d -name "*.ino" -exec clang-format-12 -i {} \; done + +######################################### + +rm -f .clang-format