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_VERSION +#include // LWIP_VERSION #include #include "LwipDhcpServer.h" @@ -35,8 +35,7 @@ DhcpServer dhcpSoftAP(&netif_git[SOFTAP_IF]); extern "C" { - - void dhcps_start(struct ip_info *info, netif* apnetif) + void dhcps_start(struct ip_info* info, netif* apnetif) { // apnetif is esp interface, replaced by lwip2's // netif_git[SOFTAP_IF] interface in constructor @@ -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_VERSION +#include // LWIP_VERSION -#define DHCPS_LEASE_TIME_DEF (120) +#define DHCPS_LEASE_TIME_DEF (120) #define USE_DNS @@ -59,30 +59,30 @@ typedef struct dhcps_state typedef struct dhcps_msg { - uint8_t op, htype, hlen, hops; - uint8_t xid[4]; + uint8_t op, htype, hlen, hops; + uint8_t xid[4]; uint16_t secs, flags; - uint8_t ciaddr[4]; - uint8_t yiaddr[4]; - uint8_t siaddr[4]; - uint8_t giaddr[4]; - uint8_t chaddr[16]; - uint8_t sname[64]; - uint8_t file[128]; - uint8_t options[312]; + uint8_t ciaddr[4]; + uint8_t yiaddr[4]; + uint8_t siaddr[4]; + uint8_t giaddr[4]; + uint8_t chaddr[16]; + uint8_t sname[64]; + uint8_t file[128]; + uint8_t options[312]; } dhcps_msg; #ifndef LWIP_OPEN_SRC struct dhcps_lease { - bool enable; + bool enable; struct ipv4_addr start_ip; struct ipv4_addr end_ip; }; enum dhcps_offer_option { - OFFER_START = 0x00, + OFFER_START = 0x00, OFFER_ROUTER = 0x01, OFFER_END }; @@ -103,50 +103,49 @@ typedef enum struct dhcps_pool { struct ipv4_addr ip; - uint8 mac[6]; - uint32 lease_timer; - dhcps_type_t type; - dhcps_state_t state; - + uint8 mac[6]; + uint32 lease_timer; + dhcps_type_t type; + dhcps_state_t state; }; -#define DHCPS_LEASE_TIMER dhcps_lease_time //0x05A0 +#define DHCPS_LEASE_TIMER dhcps_lease_time // 0x05A0 #define DHCPS_MAX_LEASE 0x64 #define BOOTP_BROADCAST 0x8000 -#define DHCP_REQUEST 1 -#define DHCP_REPLY 2 +#define DHCP_REQUEST 1 +#define DHCP_REPLY 2 #define DHCP_HTYPE_ETHERNET 1 -#define DHCP_HLEN_ETHERNET 6 -#define DHCP_MSG_LEN 236 - -#define DHCPS_SERVER_PORT 67 -#define DHCPS_CLIENT_PORT 68 - -#define DHCPDISCOVER 1 -#define DHCPOFFER 2 -#define DHCPREQUEST 3 -#define DHCPDECLINE 4 -#define DHCPACK 5 -#define DHCPNAK 6 -#define DHCPRELEASE 7 - -#define DHCP_OPTION_SUBNET_MASK 1 -#define DHCP_OPTION_ROUTER 3 -#define DHCP_OPTION_DNS_SERVER 6 -#define DHCP_OPTION_REQ_IPADDR 50 -#define DHCP_OPTION_LEASE_TIME 51 -#define DHCP_OPTION_MSG_TYPE 53 -#define DHCP_OPTION_SERVER_ID 54 +#define DHCP_HLEN_ETHERNET 6 +#define DHCP_MSG_LEN 236 + +#define DHCPS_SERVER_PORT 67 +#define DHCPS_CLIENT_PORT 68 + +#define DHCPDISCOVER 1 +#define DHCPOFFER 2 +#define DHCPREQUEST 3 +#define DHCPDECLINE 4 +#define DHCPACK 5 +#define DHCPNAK 6 +#define DHCPRELEASE 7 + +#define DHCP_OPTION_SUBNET_MASK 1 +#define DHCP_OPTION_ROUTER 3 +#define DHCP_OPTION_DNS_SERVER 6 +#define DHCP_OPTION_REQ_IPADDR 50 +#define DHCP_OPTION_LEASE_TIME 51 +#define DHCP_OPTION_MSG_TYPE 53 +#define DHCP_OPTION_SERVER_ID 54 #define DHCP_OPTION_INTERFACE_MTU 26 #define DHCP_OPTION_PERFORM_ROUTER_DISCOVERY 31 #define DHCP_OPTION_BROADCAST_ADDRESS 28 -#define DHCP_OPTION_REQ_LIST 55 -#define DHCP_OPTION_END 255 +#define DHCP_OPTION_REQ_LIST 55 +#define DHCP_OPTION_END 255 //#define USE_CLASS_B_NET 1 -#define DHCPS_DEBUG 0 -#define MAX_STATION_NUM 8 +#define DHCPS_DEBUG 0 +#define MAX_STATION_NUM 8 #define DHCPS_STATE_OFFER 1 #define DHCPS_STATE_DECLINE 2 @@ -155,32 +154,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(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_VERSION +#include // LWIP_VERSION class DhcpServer { public: - DhcpServer(netif* netif); ~DhcpServer(); @@ -53,72 +52,64 @@ class DhcpServer // legacy public C structure and API to eventually turn into C++ - void init_dhcps_lease(uint32 ip); - bool set_dhcps_lease(struct dhcps_lease *please); - bool get_dhcps_lease(struct dhcps_lease *please); - bool set_dhcps_offer_option(uint8 level, void* optarg); - bool set_dhcps_lease_time(uint32 minute); - bool reset_dhcps_lease_time(void); + void init_dhcps_lease(uint32 ip); + bool set_dhcps_lease(struct dhcps_lease* please); + bool get_dhcps_lease(struct dhcps_lease* please); + bool set_dhcps_offer_option(uint8 level, void* optarg); + bool set_dhcps_lease_time(uint32 minute); + bool reset_dhcps_lease_time(void); uint32 get_dhcps_lease_time(void); - bool add_dhcps_lease(uint8 *macaddr); + bool add_dhcps_lease(uint8* macaddr); void dhcps_set_dns(int num, const ipv4_addr_t* dns); protected: - // legacy C structure and API to eventually turn into C++ typedef struct _list_node { - void *pnode; - struct _list_node *pnext; + void* pnode; + struct _list_node* pnext; } list_node; - void node_insert_to_list(list_node **phead, list_node* pinsert); - void node_remove_from_list(list_node **phead, list_node* pdelete); - uint8_t* add_msg_type(uint8_t *optptr, uint8_t type); - uint8_t* add_offer_options(uint8_t *optptr); - uint8_t* add_end(uint8_t *optptr); - void create_msg(struct dhcps_msg *m); - void send_offer(struct dhcps_msg *m); - void send_nak(struct dhcps_msg *m); - void send_ack(struct dhcps_msg *m); - uint8_t parse_options(uint8_t *optptr, sint16_t len); - sint16_t parse_msg(struct dhcps_msg *m, u16_t len); - static void S_handle_dhcp(void *arg, - struct udp_pcb *pcb, - struct pbuf *p, - const ip_addr_t *addr, + void node_insert_to_list(list_node** phead, list_node* pinsert); + void node_remove_from_list(list_node** phead, list_node* pdelete); + uint8_t* add_msg_type(uint8_t* optptr, uint8_t type); + uint8_t* add_offer_options(uint8_t* optptr); + uint8_t* add_end(uint8_t* optptr); + void create_msg(struct dhcps_msg* m); + void send_offer(struct dhcps_msg* m); + void send_nak(struct dhcps_msg* m); + void send_ack(struct dhcps_msg* m); + uint8_t parse_options(uint8_t* optptr, sint16_t len); + sint16_t parse_msg(struct dhcps_msg* m, u16_t len); + static void S_handle_dhcp(void* arg, struct udp_pcb* pcb, struct pbuf* p, const ip_addr_t* addr, uint16_t port); - void handle_dhcp( - struct udp_pcb *pcb, - struct pbuf *p, - const ip_addr_t *addr, - uint16_t port); - void kill_oldest_dhcps_pool(void); - void dhcps_coarse_tmr(void); // CURRENTLY NOT CALLED - void dhcps_client_leave(u8 *bssid, struct ipv4_addr *ip, bool force); - uint32 dhcps_client_update(u8 *bssid, struct ipv4_addr *ip); + void handle_dhcp(struct udp_pcb* pcb, struct pbuf* p, const ip_addr_t* addr, uint16_t port); + void kill_oldest_dhcps_pool(void); + void dhcps_coarse_tmr(void); // CURRENTLY NOT CALLED + void dhcps_client_leave(u8* bssid, struct ipv4_addr* ip, bool force); + uint32 dhcps_client_update(u8* bssid, struct ipv4_addr* ip); netif* _netif; - struct udp_pcb *pcb_dhcps; - ip_addr_t broadcast_dhcps; + struct udp_pcb* pcb_dhcps; + ip_addr_t broadcast_dhcps; struct ipv4_addr server_address; struct ipv4_addr client_address; struct ipv4_addr dns_address; - uint32 dhcps_lease_time; + uint32 dhcps_lease_time; struct dhcps_lease dhcps_lease; - list_node *plist; - uint8 offer; - bool renew; + list_node* plist; + uint8 offer; + bool renew; static const uint32 magic_cookie; }; // SoftAP DHCP server always exists and is started on boot extern DhcpServer dhcpSoftAP; -extern "C" int fw_has_started_softap_dhcps; +extern "C" int fw_has_started_softap_dhcps; -#endif // __DHCPS_H__ +#endif // __DHCPS_H__ diff --git a/cores/esp8266/LwipIntf.cpp b/cores/esp8266/LwipIntf.cpp index b4a4807b9a..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 @@ -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 ; + using CBType = std::function; 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 #include -#include // wifi_get_macaddr() +#include // wifi_get_macaddr() #include "SPI.h" #include "Schedule.h" @@ -25,64 +25,42 @@ #define DEFAULT_MTU 1500 #endif -template -class LwipIntfDev: public LwipIntf, public RawDev +template class LwipIntfDev: public LwipIntf, public RawDev { - public: - - LwipIntfDev(int8_t cs = SS, SPIClass& spi = SPI, int8_t intr = -1): - RawDev(cs, spi, intr), - _mtu(DEFAULT_MTU), - _intrPin(intr), - _started(false), - _default(false) + LwipIntfDev(int8_t cs = SS, SPIClass& spi = SPI, int8_t intr = -1) : + RawDev(cs, spi, intr), _mtu(DEFAULT_MTU), _intrPin(intr), _started(false), _default(false) { memset(&_netif, 0, sizeof(_netif)); } - boolean config(const IPAddress& local_ip, const IPAddress& arg1, const IPAddress& arg2, const IPAddress& arg3 = IPADDR_NONE, const IPAddress& dns2 = IPADDR_NONE); + boolean config(const IPAddress& local_ip, const IPAddress& arg1, const IPAddress& arg2, + const IPAddress& arg3 = IPADDR_NONE, const IPAddress& dns2 = IPADDR_NONE); // default mac-address is inferred from esp8266's STA interface - boolean begin(const uint8_t *macAddress = nullptr, const uint16_t mtu = DEFAULT_MTU); + boolean begin(const uint8_t* macAddress = nullptr, const uint16_t mtu = DEFAULT_MTU); - const netif* getNetIf() const - { - return &_netif; - } + 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 -boolean LwipIntfDev::config(const IPAddress& localIP, const IPAddress& gateway, const IPAddress& netmask, const IPAddress& dns1, const IPAddress& dns2) +boolean LwipIntfDev::config(const IPAddress& localIP, const IPAddress& gateway, + const IPAddress& netmask, const IPAddress& dns1, + const IPAddress& dns2) { if (_started) { @@ -162,9 +141,9 @@ boolean LwipIntfDev::begin(const uint8_t* macAddress, const uint16_t mtu memset(_macAddress, 0, 6); _macAddress[0] = 0xEE; #endif - _macAddress[3] += _netif.num; // alter base mac address - _macAddress[0] &= 0xfe; // set as locally administered, unicast, per - _macAddress[0] |= 0x02; // https://en.wikipedia.org/wiki/MAC_address#Universal_vs._local + _macAddress[3] += _netif.num; // alter base mac address + _macAddress[0] &= 0xfe; // set as locally administered, unicast, per + _macAddress[0] |= 0x02; // https://en.wikipedia.org/wiki/MAC_address#Universal_vs._local } if (!RawDev::begin(_macAddress)) @@ -183,7 +162,8 @@ boolean LwipIntfDev::begin(const uint8_t* macAddress, const uint16_t mtu ip_addr_copy(netmask, _netif.netmask); ip_addr_copy(gw, _netif.gw); - if (!netif_add(&_netif, ip_2_ip4(&ip_addr), ip_2_ip4(&netmask), ip_2_ip4(&gw), this, netif_init_s, ethernet_input)) + if (!netif_add(&_netif, ip_2_ip4(&ip_addr), ip_2_ip4(&netmask), ip_2_ip4(&gw), this, + netif_init_s, ethernet_input)) { return false; } @@ -212,20 +192,24 @@ boolean LwipIntfDev::begin(const uint8_t* macAddress, const uint16_t mtu { if (RawDev::interruptIsPossible()) { - //attachInterrupt(_intrPin, [&]() { this->handlePackets(); }, FALLING); + // attachInterrupt(_intrPin, [&]() { this->handlePackets(); }, FALLING); } else { - ::printf((PGM_P)F("lwIP_Intf: Interrupt not implemented yet, enabling transparent polling\r\n")); + ::printf((PGM_P)F( + "lwIP_Intf: Interrupt not implemented yet, enabling transparent polling\r\n")); _intrPin = -1; } } - if (_intrPin < 0 && !schedule_recurrent_function_us([&]() -{ - this->handlePackets(); - return true; - }, 100)) + if (_intrPin < 0 + && !schedule_recurrent_function_us( + [&]() + { + this->handlePackets(); + return true; + }, + 100)) { netif_remove(&_netif); return false; @@ -234,14 +218,12 @@ boolean LwipIntfDev::begin(const uint8_t* macAddress, const uint16_t mtu return true; } -template -wl_status_t LwipIntfDev::status() +template wl_status_t LwipIntfDev::status() { return _started ? (connected() ? WL_CONNECTED : WL_DISCONNECTED) : WL_NO_SHIELD; } -template -err_t LwipIntfDev::linkoutput_s(netif *netif, struct pbuf *pbuf) +template err_t LwipIntfDev::linkoutput_s(netif* netif, struct pbuf* pbuf) { LwipIntfDev* ths = (LwipIntfDev*)netif->state; @@ -255,37 +237,31 @@ err_t LwipIntfDev::linkoutput_s(netif *netif, struct pbuf *pbuf) #if PHY_HAS_CAPTURE if (phy_capture) { - phy_capture(ths->_netif.num, (const char*)pbuf->payload, pbuf->len, /*out*/1, /*success*/len == pbuf->len); + phy_capture(ths->_netif.num, (const char*)pbuf->payload, pbuf->len, /*out*/ 1, + /*success*/ len == pbuf->len); } #endif return len == pbuf->len ? ERR_OK : ERR_MEM; } -template -err_t LwipIntfDev::netif_init_s(struct netif* netif) +template err_t LwipIntfDev::netif_init_s(struct netif* netif) { return ((LwipIntfDev*)netif->state)->netif_init(); } -template -void LwipIntfDev::netif_status_callback_s(struct netif* netif) +template void LwipIntfDev::netif_status_callback_s(struct netif* netif) { ((LwipIntfDev*)netif->state)->netif_status_callback(); } -template -err_t LwipIntfDev::netif_init() +template err_t LwipIntfDev::netif_init() { - _netif.name[0] = 'e'; - _netif.name[1] = '0' + _netif.num; - _netif.mtu = _mtu; + _netif.name[0] = 'e'; + _netif.name[1] = '0' + _netif.num; + _netif.mtu = _mtu; _netif.chksum_flags = NETIF_CHECKSUM_ENABLE_ALL; - _netif.flags = - NETIF_FLAG_ETHARP - | NETIF_FLAG_IGMP - | NETIF_FLAG_BROADCAST - | NETIF_FLAG_LINK_UP; + _netif.flags = NETIF_FLAG_ETHARP | NETIF_FLAG_IGMP | NETIF_FLAG_BROADCAST | NETIF_FLAG_LINK_UP; // lwIP's doc: This function typically first resolves the hardware // address, then sends the packet. For ethernet physical layer, this is @@ -301,8 +277,7 @@ err_t LwipIntfDev::netif_init() return ERR_OK; } -template -void LwipIntfDev::netif_status_callback() +template void LwipIntfDev::netif_status_callback() { if (connected()) { @@ -321,14 +296,13 @@ void LwipIntfDev::netif_status_callback() } } -template -err_t LwipIntfDev::handlePackets() +template err_t LwipIntfDev::handlePackets() { int pkt = 0; while (1) { if (++pkt == 10) - // prevent starvation + // prevent starvation { return ERR_OK; } @@ -374,7 +348,8 @@ err_t LwipIntfDev::handlePackets() #if PHY_HAS_CAPTURE if (phy_capture) { - phy_capture(_netif.num, (const char*)pbuf->payload, tot_len, /*out*/0, /*success*/err == ERR_OK); + phy_capture(_netif.num, (const char*)pbuf->payload, tot_len, /*out*/ 0, + /*success*/ err == ERR_OK); } #endif @@ -384,12 +359,10 @@ err_t LwipIntfDev::handlePackets() return err; } // (else) allocated pbuf is now lwIP's responsibility - } } -template -void LwipIntfDev::setDefault() +template void LwipIntfDev::setDefault() { _default = true; if (connected()) @@ -398,4 +371,4 @@ void LwipIntfDev::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 #include -size_t Stream::sendGeneric(Print* to, - const ssize_t len, - const int readUntilChar, +size_t Stream::sendGeneric(Print* to, const ssize_t len, const int readUntilChar, const esp8266::polledTimeout::oneShotFastMs::timeType timeoutMs) { setReport(Report::Success); if (len == 0) { - return 0; // conveniently avoids timeout for no requested data + return 0; // conveniently avoids timeout for no requested data } // There are two timeouts: @@ -57,14 +54,17 @@ size_t Stream::sendGeneric(Print* to, return SendGenericRegular(to, len, timeoutMs); } - -size_t Stream::SendGenericPeekBuffer(Print* to, const ssize_t len, const int readUntilChar, const esp8266::polledTimeout::oneShotFastMs::timeType timeoutMs) +size_t +Stream::SendGenericPeekBuffer(Print* to, const ssize_t len, const int readUntilChar, + const esp8266::polledTimeout::oneShotFastMs::timeType timeoutMs) { // "neverExpires (default, impossible)" is translated to default timeout - esp8266::polledTimeout::oneShotFastMs timedOut(timeoutMs >= esp8266::polledTimeout::oneShotFastMs::neverExpires ? getTimeout() : timeoutMs); + esp8266::polledTimeout::oneShotFastMs timedOut( + timeoutMs >= esp8266::polledTimeout::oneShotFastMs::neverExpires ? getTimeout() : + timeoutMs); // len==-1 => maxLen=0 <=> until starvation - const size_t maxLen = std::max((ssize_t)0, len); - size_t written = 0; + const size_t maxLen = std::max((ssize_t)0, len); + size_t written = 0; while (!maxLen || written < maxLen) { @@ -90,13 +90,13 @@ size_t Stream::SendGenericPeekBuffer(Print* to, const ssize_t len, const int rea if (w) { const char* directbuf = peekBuffer(); - bool foundChar = false; + bool foundChar = false; if (readUntilChar >= 0) { const char* last = (const char*)memchr(directbuf, readUntilChar, w); if (last) { - w = std::min((size_t)(last - directbuf), w); + w = std::min((size_t)(last - directbuf), w); foundChar = true; } } @@ -104,7 +104,7 @@ size_t Stream::SendGenericPeekBuffer(Print* to, const ssize_t len, const int rea { peekConsume(w); written += w; - timedOut.reset(); // something has been written + timedOut.reset(); // something has been written } if (foundChar) { @@ -145,16 +145,20 @@ size_t Stream::SendGenericPeekBuffer(Print* to, const ssize_t len, const int rea return written; } -size_t Stream::SendGenericRegularUntil(Print* to, const ssize_t len, const int readUntilChar, const esp8266::polledTimeout::oneShotFastMs::timeType timeoutMs) +size_t +Stream::SendGenericRegularUntil(Print* to, const ssize_t len, const int readUntilChar, + const esp8266::polledTimeout::oneShotFastMs::timeType timeoutMs) { // regular Stream API // no other choice than reading byte by byte // "neverExpires (default, impossible)" is translated to default timeout - esp8266::polledTimeout::oneShotFastMs timedOut(timeoutMs >= esp8266::polledTimeout::oneShotFastMs::neverExpires ? getTimeout() : timeoutMs); + esp8266::polledTimeout::oneShotFastMs timedOut( + timeoutMs >= esp8266::polledTimeout::oneShotFastMs::neverExpires ? getTimeout() : + timeoutMs); // len==-1 => maxLen=0 <=> until starvation - const size_t maxLen = std::max((ssize_t)0, len); - size_t written = 0; + const size_t maxLen = std::max((ssize_t)0, len); + size_t written = 0; while (!maxLen || written < maxLen) { @@ -186,7 +190,7 @@ size_t Stream::SendGenericRegularUntil(Print* to, const ssize_t len, const int r break; } written += 1; - timedOut.reset(); // something has been written + timedOut.reset(); // something has been written } if (timedOut) @@ -221,16 +225,19 @@ size_t Stream::SendGenericRegularUntil(Print* to, const ssize_t len, const int r return written; } -size_t Stream::SendGenericRegular(Print* to, const ssize_t len, const esp8266::polledTimeout::oneShotFastMs::timeType timeoutMs) +size_t Stream::SendGenericRegular(Print* to, const ssize_t len, + const esp8266::polledTimeout::oneShotFastMs::timeType timeoutMs) { // regular Stream API // use an intermediary buffer // "neverExpires (default, impossible)" is translated to default timeout - esp8266::polledTimeout::oneShotFastMs timedOut(timeoutMs >= esp8266::polledTimeout::oneShotFastMs::neverExpires ? getTimeout() : timeoutMs); + esp8266::polledTimeout::oneShotFastMs timedOut( + timeoutMs >= esp8266::polledTimeout::oneShotFastMs::neverExpires ? getTimeout() : + timeoutMs); // len==-1 => maxLen=0 <=> until starvation - const size_t maxLen = std::max((ssize_t)0, len); - size_t written = 0; + const size_t maxLen = std::max((ssize_t)0, len); + size_t written = 0; while (!maxLen || written < maxLen) { @@ -243,7 +250,7 @@ size_t Stream::SendGenericRegular(Print* to, const ssize_t len, const esp8266::p size_t w = to->availableForWrite(); if (w == 0 && !to->outputCanTimeout()) - // no more data can be written, ever + // no more data can be written, ever { break; } @@ -256,7 +263,7 @@ size_t Stream::SendGenericRegular(Print* to, const ssize_t len, const esp8266::p w = std::min(w, (decltype(w))temporaryStackBufferSize); if (w) { - char temp[w]; + char temp[w]; ssize_t r = read(temp, w); if (r < 0) { @@ -270,7 +277,7 @@ size_t Stream::SendGenericRegular(Print* to, const ssize_t len, const esp8266::p setReport(Report::WriteError); break; } - timedOut.reset(); // something has been written + timedOut.reset(); // something has been written } if (timedOut) @@ -305,19 +312,19 @@ size_t Stream::SendGenericRegular(Print* to, const ssize_t len, const esp8266::p return written; } -Stream& operator << (Stream& out, String& string) +Stream& operator<<(Stream& out, String& string) { StreamConstPtr(string).sendAll(out); return out; } -Stream& operator << (Stream& out, StreamString& stream) +Stream& operator<<(Stream& out, StreamString& stream) { stream.sendAll(out); return out; } -Stream& operator << (Stream& out, Stream& stream) +Stream& operator<<(Stream& out, Stream& stream) { if (stream.streamRemaining() < 0) { @@ -339,13 +346,13 @@ Stream& operator << (Stream& out, Stream& stream) return out; } -Stream& operator << (Stream& out, const char* text) +Stream& operator<<(Stream& out, const char* text) { StreamConstPtr(text, strlen_P(text)).sendAll(out); return out; } -Stream& operator << (Stream& out, const __FlashStringHelper* text) +Stream& operator<<(Stream& out, const __FlashStringHelper* text) { StreamConstPtr(text).sendAll(out); return out; diff --git a/cores/esp8266/StreamString.h b/cores/esp8266/StreamString.h index be11669a79..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::max(); - } + virtual int availableForWrite() override { return std::numeric_limits::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 #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 #include -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( - "" + Page += F("" "" "CaptivePortal" "

HELLO WORLD!!

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

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

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

You may want to config the wifi connection.

" + Page += F("

You may want to config the wifi connection.

" ""); server.send(200, "text/html", Page); } -/** 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( - "" + Page += F("" "" "CaptivePortal" "

Wifi config

"); @@ -54,40 +53,39 @@ void handleWifi() { } else { Page += String(F("

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

"); } - Page += - String(F( - "\r\n
" - "" - "" - "" - "
SoftAP config
SSID ")) + - String(softAP_ssid) + - F("
IP ") + - toStringIp(WiFi.softAPIP()) + - F("
" - "\r\n
" - "" - "" - "" - "
WLAN config
SSID ") + - String(ssid) + - F("
IP ") + - toStringIp(WiFi.localIP()) + - F("
" - "\r\n
" - ""); + Page += String(F("\r\n
" + "
WLAN list (refresh if any missing)
" + "" + "" + "
SoftAP config
SSID ")) + + String(softAP_ssid) + + F("
IP ") + + toStringIp(WiFi.softAPIP()) + + F("
" + "\r\n
" + "" + "" + "" + "
WLAN config
SSID ") + + String(ssid) + + F("
IP ") + + toStringIp(WiFi.localIP()) + + F("
" + "\r\n
" + ""); Serial.println("scan start"); int n = WiFi.scanNetworks(); Serial.println("scan done"); if (n > 0) { for (int i = 0; i < n; i++) { - Page += String(F("\r\n"); + Page += String(F("\r\n"); } } else { Page += F(""); } - Page += F( - "
WLAN list (refresh if any missing)
SSID ")) + WiFi.SSID(i) + ((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? F(" ") : F(" *")) + F(" (") + WiFi.RSSI(i) + F(")
SSID ")) + WiFi.SSID(i) + + ((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? F(" ") : F(" *")) + F(" (") + + WiFi.RSSI(i) + F(")
No WLAN found
" + Page += F("" "\r\n

Connect to network:

" "" "
" @@ -95,7 +93,7 @@ void handleWifi() { "

You may want to return to the home page.

" ""); server.send(200, "text/html", Page); - server.client().stop(); // Stop is needed because we sent no content length + server.client().stop(); // Stop is needed because we sent no content length } /** Handle the WLAN save form and redirect to WLAN config page again */ @@ -107,14 +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 #include -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 // 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 // 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_ptrclient(new BearSSL::WiFiClientSecure); + std::unique_ptr client(new BearSSL::WiFiClientSecure); client->setFingerprint(fingerprint); // Or, if you happy to ignore the SSL certificate, then use the following line instead: diff --git a/libraries/ESP8266HTTPClient/examples/DigestAuthorization/DigestAuthorization.ino b/libraries/ESP8266HTTPClient/examples/DigestAuthorization/DigestAuthorization.ino index db8fe8cbd4..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 #include #include #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 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 @@ -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 @@ -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("\nHello 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() { \ ", - 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 += "\n"; - out += "\n"; + out += "\n"; + out += "\n"; out += "\n"; int y = rand() % 130; for (int x = 10; x < 390; x += 10) { int y2 = rand() % 130; - sprintf(temp, "\n", x, 140 - y, x + 10, 140 - y2); + sprintf(temp, "\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 -const char* fsName = "SPIFFS"; -FS* fileSystem = &SPIFFS; -SPIFFSConfig fileSystemConfig = SPIFFSConfig(); +const char* fsName = "SPIFFS"; +FS* fileSystem = &SPIFFS; +SPIFFSConfig fileSystemConfig = SPIFFSConfig(); #elif defined USE_LITTLEFS #include -const char* fsName = "LittleFS"; -FS* fileSystem = &LittleFS; +const char* fsName = "LittleFS"; +FS* fileSystem = &LittleFS; LittleFSConfig fileSystemConfig = LittleFSConfig(); #elif defined USE_SDFS #include -const char* fsName = "SDFS"; -FS* fileSystem = &SDFS; -SDFSConfig fileSystemConfig = SDFSConfig(); +const char* fsName = "SDFS"; +FS* fileSystem = &SDFS; +SDFSConfig fileSystemConfig = SDFSConfig(); // fileSystemConfig.setCSPin(chipSelectPin); #else #error Please select a filesystem first by uncommenting one of the "#define USE_xxx" lines at the beginning of the sketch. #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* fileSystem = &SPIFFS; -SPIFFSConfig fileSystemConfig = SPIFFSConfig(); +FS* fileSystem = &SPIFFS; +SPIFFSConfig fileSystemConfig = SPIFFSConfig(); #elif defined USE_LITTLEFS #include -FS* fileSystem = &LittleFS; +FS* fileSystem = &LittleFS; LittleFSConfig fileSystemConfig = LittleFSConfig(); #elif defined USE_SDFS #include -FS* fileSystem = &SDFS; +FS* fileSystem = &SDFS; SDFSConfig fileSystemConfig = SDFSConfig(); // fileSystemConfig.setCSPin(chipSelectPin); #else #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 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 @@ -15,21 +16,24 @@ #include #include -//Unfortunately it is not possible to have persistent WiFi credentials stored as anything but plain text. Obfuscation would be the only feasible barrier. +// Unfortunately it is not possible to have persistent WiFi credentials stored as anything but plain +// text. Obfuscation would be the only feasible barrier. #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -const char* ssid = STASSID; +const char* 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"()"; - page+= - R"( + page += + R"(

Login Credentials


- + Login:

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


- )" - ; + )"; page += R"()"; @@ -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://:/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 : event bus location: http://:/rest/events/ + 2. on the client(s), register it for the event bus using a REST API call: curl -sS "http://:/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 : event bus location: http://:/rest/events/ - you will also see that the sensors are ready to broadcast state changes, but the client is not yet listening: - SSEBroadcastState - client > 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 > registered but not listening - 3. on the client(s), start listening for events with: curl -sS "http://:/rest/events/" - 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://:/rest/events/" if all is well, the following is being displayed on the ESP console SSEHandler - registered client with IP is listening... - broadcast status change to client IP > for sensor[A|B] with new state > - every minute you will see on the ESP: SSEKeepAlive - client is still connected + broadcast status change to client IP > for sensor[A|B] with new state > 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 = "
To log in, please use : admin/admin
"; + String content + = "To log in, please use : admin/admin
"; content += "User:
"; content += "Password:
"; content += "
" + msg + "
"; @@ -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") + "

"; } - content += "You can access this page until you disconnect"; + content += "You can access this page until you disconnect"; server.send(200, "text/html", content); } -//no need authentication +// no need authentication void handleNotFound() { String message = "File Not Found\n\n"; message += "URI: "; @@ -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 #include -#include "secrets.h" // add WLAN Credentials in here. +#include "secrets.h" // add WLAN Credentials in here. -#include // File System for Web Server Files -#include // This file system is used. +#include // File System for Web Server Files +#include // This file system is used. // mark parameters not used in example #define UNUSED __attribute__((unused)) @@ -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 @@ -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 = "
"; +const char* serverIndex + = "
"; 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" - "\r\n" - "\r\n" - "

Hello from ESP8266!

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

Hello from ESP8266!

\r\n" + "\r\n" + "\r\n"; void loop() { - static int cnt; + 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" - "\r\n" - "\r\n" - "

Hello my friend!

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

Hello my friend!

\r\n" + "\r\n" + "\r\n"; void loop() { BearSSL::WiFiClientSecure incoming = server.accept(); @@ -232,12 +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 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 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 or 'nc -u 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 or 'nc -u 23')")); for (auto a : addrList) { - out.printf("IF='%s' IPv6=%d local=%d hostname='%s' addr= %s", - a.ifname().c_str(), - a.isV6(), - a.isLocal(), - a.ifhostname(), - a.toString().c_str()); + 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 @@ -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 /* 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 = "

Total Connected Clients : "; result += String(number_client); result += "


"; 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 #include #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif -unsigned int localPort = 8888; // local port to listen on +unsigned int localPort = 8888; // local port to listen on // buffers for receiving and sending data -char packetBuffer[UDP_TX_PACKET_MAX_SIZE + 1]; //buffer to hold incoming packet, -char ReplyBuffer[] = "acknowledged\r\n"; // a string to send back +char 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", "

You are connected

"); -} +void handleRoot() { server.send(200, "text/html", "

You are connected

"); } 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 #include #include -#include // std::min +#include // std::min #ifndef STASSID #define STASSID "your-ssid" -#define STAPSK "your-password" +#define STAPSK "your-password" #endif constexpr int port = 23; @@ -19,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\r\n\r\nGPIO is now ")); + client.print(F("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n\r\n\r\nGPIO is now ")); client.print((val) ? F("high") : F("low")); client.print(F("

Click