2 * libwebsockets - small server side websockets and web server implementation
4 * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation:
9 * version 2.1 of the License.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
22 #include "private-libwebsockets.h"
23 #include "freertos/timers.h"
25 #include <esp_system.h>
28 * included from libwebsockets.c for unix builds
31 unsigned long long time_in_microseconds(void)
34 gettimeofday(&tv, NULL);
35 return ((unsigned long long)tv.tv_sec * 1000000LL) + tv.tv_usec;
39 lws_get_random(struct lws_context *context, void *buf, int len)
44 uint32_t r = esp_random();
45 uint8_t *p = (uint8_t *)&r;
57 return pb - (uint8_t *)buf;
61 lws_send_pipe_choked(struct lws *wsi)
64 struct timeval tv = { 0, 0 };
66 /* treat the fact we got a truncated send pending as if we're choked */
71 FD_SET(wsi->desc.sockfd, &writefds);
73 if (select(wsi->desc.sockfd + 1, NULL, &writefds, NULL, &tv) < 1)
80 lws_poll_listen_fd(struct lws_pollfd *fd)
83 struct timeval tv = { 0, 0 };
86 FD_SET(fd->fd, &readfds);
88 return select(fd->fd + 1, &readfds, NULL, NULL, &tv);
92 lws_cancel_service_pt(struct lws *wsi)
97 lws_cancel_service(struct lws_context *context)
101 LWS_VISIBLE void lwsl_emit_syslog(int level, const char *line)
103 printf("%d: %s", level, line);
106 LWS_VISIBLE LWS_EXTERN int
107 _lws_plat_service_tsi(struct lws_context *context, int timeout_ms, int tsi)
109 struct lws_context_per_thread *pt;
112 /* stay dead once we are dead */
114 if (!context || !context->vhost_list)
117 pt = &context->pt[tsi];
118 lws_stats_atomic_bump(context, pt, LWSSTATS_C_SERVICE_ENTRY, 1);
123 if (!context->service_tid_detected) {
126 memset(&_lws, 0, sizeof(_lws));
127 _lws.context = context;
129 context->service_tid_detected =
130 context->vhost_list->protocols[0].callback(
131 &_lws, LWS_CALLBACK_GET_THREAD_ID, NULL, NULL, 0);
133 context->service_tid = context->service_tid_detected;
136 * is there anybody with pending stuff that needs service forcing?
138 if (!lws_service_adjust_timeout(context, 1, tsi)) {
139 /* -1 timeout means just do forced service */
140 _lws_plat_service_tsi(context, -1, pt->tid);
141 /* still somebody left who wants forced service? */
142 if (!lws_service_adjust_timeout(context, 1, pt->tid))
143 /* yes... come back again quickly */
147 // n = poll(pt->fds, pt->fds_count, timeout_ms);
149 fd_set readfds, writefds, errfds;
150 struct timeval tv = { timeout_ms / 1000,
151 (timeout_ms % 1000) * 1000 }, *ptv = &tv;
157 for (n = 0; n < pt->fds_count; n++) {
158 pt->fds[n].revents = 0;
159 if (pt->fds[n].fd >= max_fd)
160 max_fd = pt->fds[n].fd;
161 if (pt->fds[n].events & LWS_POLLIN)
162 FD_SET(pt->fds[n].fd, &readfds);
163 if (pt->fds[n].events & LWS_POLLOUT)
164 FD_SET(pt->fds[n].fd, &writefds);
165 FD_SET(pt->fds[n].fd, &errfds);
168 n = select(max_fd + 1, &readfds, &writefds, &errfds, ptv);
169 for (n = 0; n < pt->fds_count; n++) {
170 if (FD_ISSET(pt->fds[n].fd, &readfds))
171 pt->fds[n].revents |= LWS_POLLIN;
172 if (FD_ISSET(pt->fds[n].fd, &writefds))
173 pt->fds[n].revents |= LWS_POLLOUT;
174 if (FD_ISSET(pt->fds[n].fd, &errfds))
175 pt->fds[n].revents |= LWS_POLLHUP;
180 #ifdef LWS_OPENSSL_SUPPORT
181 if (!pt->rx_draining_ext_list &&
182 !lws_ssl_anybody_has_buffered_read_tsi(context, tsi) && !n) {
184 if (!pt->rx_draining_ext_list && !n) /* poll timeout */ {
186 lws_service_fd_tsi(context, NULL, tsi);
191 m = lws_service_flag_pending(context, tsi);
193 c = -1; /* unknown limit */
196 if (LWS_ERRNO != LWS_EINTR)
202 /* any socket with events to service? */
203 for (n = 0; n < pt->fds_count && c; n++) {
204 if (!pt->fds[n].revents)
209 m = lws_service_fd_tsi(context, &pt->fds[n], tsi);
212 /* if something closed, retry this slot */
221 lws_plat_check_connection_error(struct lws *wsi)
227 lws_plat_service(struct lws_context *context, int timeout_ms)
229 return _lws_plat_service_tsi(context, timeout_ms, 0);
233 lws_plat_set_socket_options(struct lws_vhost *vhost, int fd)
236 socklen_t optlen = sizeof(optval);
238 #if defined(__APPLE__) || \
239 defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || \
240 defined(__NetBSD__) || \
242 struct protoent *tcp_proto;
245 if (vhost->ka_time) {
246 /* enable keepalive on this socket */
248 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
249 (const void *)&optval, optlen) < 0)
252 #if defined(__APPLE__) || \
253 defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || \
254 defined(__NetBSD__) || \
255 defined(__CYGWIN__) || defined(__OpenBSD__) || defined (__sun)
258 * didn't find a way to set these per-socket, need to
259 * tune kernel systemwide values
262 /* set the keepalive conditions we want on it too */
263 optval = vhost->ka_time;
264 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE,
265 (const void *)&optval, optlen) < 0)
268 optval = vhost->ka_interval;
269 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL,
270 (const void *)&optval, optlen) < 0)
273 optval = vhost->ka_probes;
274 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT,
275 (const void *)&optval, optlen) < 0)
282 // if (setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&optval, optlen) < 0)
284 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &optval, optlen) < 0)
287 /* We are nonblocking... */
288 if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
295 lws_plat_drop_app_privileges(struct lws_context_creation_info *info)
300 lws_plat_context_early_init(void)
302 //signal(SIGPIPE, SIG_IGN);
304 // signal(SIGABRT, sigabrt_handler);
310 lws_plat_context_early_destroy(struct lws_context *context)
315 lws_plat_context_late_destroy(struct lws_context *context)
317 #ifdef LWS_WITH_PLUGINS
318 if (context->plugin_list)
319 lws_plat_plugins_destroy(context);
322 if (context->lws_lookup)
323 lws_free(context->lws_lookup);
326 /* cast a struct sockaddr_in6 * into addr for ipv6 */
329 lws_interface_to_sa(int ipv6, const char *ifname, struct sockaddr_in *addr,
338 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
342 for (ifc = ifr; ifc != NULL && rc; ifc = ifc->ifa_next) {
346 lwsl_info(" interface %s vs %s\n", ifc->ifa_name, ifname);
348 if (strcmp(ifc->ifa_name, ifname))
351 switch (ifc->ifa_addr->sa_family) {
355 /* map IPv4 to IPv6 */
356 bzero((char *)&addr6->sin6_addr,
357 sizeof(struct in6_addr));
358 addr6->sin6_addr.s6_addr[10] = 0xff;
359 addr6->sin6_addr.s6_addr[11] = 0xff;
360 memcpy(&addr6->sin6_addr.s6_addr[12],
361 &((struct sockaddr_in *)ifc->ifa_addr)->sin_addr,
362 sizeof(struct in_addr));
366 (struct sockaddr_in *)ifc->ifa_addr,
367 sizeof(struct sockaddr_in));
371 memcpy(&addr6->sin6_addr,
372 &((struct sockaddr_in6 *)ifc->ifa_addr)->sin6_addr,
373 sizeof(struct in6_addr));
385 /* check if bind to IP address */
387 if (inet_pton(AF_INET6, ifname, &addr6->sin6_addr) == 1)
391 if (inet_pton(AF_INET, ifname, &addr->sin_addr) == 1)
402 lws_plat_insert_socket_into_fds(struct lws_context *context, struct lws *wsi)
404 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
406 pt->fds[pt->fds_count++].revents = 0;
410 lws_plat_delete_socket_from_fds(struct lws_context *context,
411 struct lws *wsi, int m)
413 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
419 lws_plat_service_periodic(struct lws_context *context)
424 lws_plat_change_pollfd(struct lws_context *context,
425 struct lws *wsi, struct lws_pollfd *pfd)
430 LWS_VISIBLE const char *
431 lws_plat_inet_ntop(int af, const void *src, char *dst, int cnt)
433 return inet_ntop(af, src, dst, cnt);
436 LWS_VISIBLE lws_fop_fd_t IRAM_ATTR
437 _lws_plat_file_open(const struct lws_plat_file_ops *fops, const char *filename,
438 const char *vpath, lws_fop_flags_t *flags)
440 struct stat stat_buf;
442 int ret = open(filename, *flags, 0664);
447 if (fstat(ret, &stat_buf) < 0)
450 fop_fd = malloc(sizeof(*fop_fd));
456 fop_fd->flags = *flags;
457 fop_fd->filesystem_priv = NULL; /* we don't use it */
459 fop_fd->len = stat_buf.st_size;
469 LWS_VISIBLE int IRAM_ATTR
470 _lws_plat_file_close(lws_fop_fd_t *fops_fd)
472 int fd = (*fops_fd)->fd;
480 LWS_VISIBLE lws_fileofs_t IRAM_ATTR
481 _lws_plat_file_seek_cur(lws_fop_fd_t fops_fd, lws_fileofs_t offset)
483 return lseek(fops_fd->fd, offset, SEEK_CUR);
486 LWS_VISIBLE int IRAM_ATTR
487 _lws_plat_file_read(lws_fop_fd_t fops_fd, lws_filepos_t *amount,
488 uint8_t *buf, lws_filepos_t len)
492 n = read(fops_fd->fd, buf, len);
503 LWS_VISIBLE int IRAM_ATTR
504 _lws_plat_file_write(lws_fop_fd_t fops_fd, lws_filepos_t *amount,
505 uint8_t *buf, lws_filepos_t len)
509 n = write(fops_fd->fd, buf, len);
522 lws_plat_init(struct lws_context *context,
523 struct lws_context_creation_info *info)
525 /* master context has the global fd lookup array */
526 context->lws_lookup = lws_zalloc(sizeof(struct lws *) *
528 if (context->lws_lookup == NULL) {
529 lwsl_err("OOM on lws_lookup array for %d connections\n",
534 lwsl_notice(" mem: platform fd map: %5lu bytes\n",
535 (unsigned long)(sizeof(struct lws *) * context->max_fds));
537 #ifdef LWS_WITH_PLUGINS
538 if (info->plugin_dirs)
539 lws_plat_plugins_init(context, info->plugin_dirs);
546 LWS_VISIBLE void esp32_uvtimer_cb(TimerHandle_t t)
548 struct timer_mapping *p = pvTimerGetTimerID(t);
553 void ERR_error_string_n(unsigned long e, char *buf, size_t len)
555 strncpy(buf, "unknown", len);
558 void ERR_free_strings(void)
562 char *ERR_error_string(unsigned long e, char *buf)
565 strcpy(buf, "unknown");
571 /* helper functionality */
574 #include <esp_ota_ops.h>
575 #include <tcpip_adapter.h>
576 #include <esp_image_format.h>
577 #include <esp_task_wdt.h>
578 #include "soc/ledc_reg.h"
579 #include "driver/ledc.h"
581 struct lws_esp32 lws_esp32 = {
582 .model = CONFIG_LWS_MODEL_NAME,
584 .region = WIFI_COUNTRY_US, // default to safest option
588 * Group AP / Station State
592 LWS_GAPSS_INITIAL, /* just started up, init and move to LWS_GAPSS_SCAN */
594 * Unconnected, scanning: AP known in one of the config
595 * slots -> configure it, start timeout + LWS_GAPSS_STAT,
596 * if no AP already up in same group with lower MAC,
597 * after a random period start up our AP (LWS_GAPSS_AP)
600 * Trying to be the group AP... periodically do a scan
601 * LWS_GAPSS_AP_SCAN, faster and then slower
603 LWS_GAPSS_AP_SCAN, /*
604 * doing a scan while trying to be the group AP... if
605 * we see a lower MAC being the AP for the same group
606 * AP, abandon being an AP and join that AP as a
609 LWS_GAPSS_STAT_GRP_AP, /*
610 * We have decided to join another group member who is
611 * being the AP, as its MAC is lower than ours. This
612 * is a stable state, but we still do periodic scans
613 * (LWS_GAPSS_STAT_GRP_AP_SCAN) and will always prefer
614 * an AP configured in a slot.
616 LWS_GAPSS_STAT_GRP_AP_SCAN,
618 * We have joined a group member who is doing the AP
619 * job... we want to check every now and then if a
620 * configured AP has appeared that we should better
621 * use instead. Otherwise stay in LWS_GAPSS_STAT_GRP_AP
624 * trying to connect to another non-group AP. If we
625 * don't get an IP within a timeout and retries,
626 * blacklist it and go back
630 static romfs_t lws_esp32_romfs;
631 static TimerHandle_t leds_timer;
632 //static enum lws_gapss gapss = LWS_GAPSS_INITIAL;
635 const struct inode *i;
638 uint32_t lws_esp32_get_reboot_type(void)
640 uint32_t *p = (uint32_t *)LWS_MAGIC_REBOOT_TYPE_ADS, val = *p;
645 ESP_ERROR_CHECK(nvs_open("lws-station", NVS_READWRITE, &nvh));
646 if (nvs_get_blob(nvh, "ssl-pub.pem", NULL, &s) == ESP_OK)
648 if (nvs_get_blob(nvh, "ssl-pri.pem", NULL, &s) == ESP_OK)
653 * in the case the SSL certs are not there, don't require
654 * the button to be down to access all features.
657 val = LWS_MAGIC_REBOOT_TYPE_FORCED_FACTORY_BUTTON;
662 static void render_ip(char *dest, int len, uint8_t *ip)
664 snprintf(dest, len, "%u.%u.%u.%u", ip[0], ip[1], ip[2], ip[3]);
667 void lws_esp32_restart_guided(uint32_t type)
669 uint32_t *p_force_factory_magic = (uint32_t *)LWS_MAGIC_REBOOT_TYPE_ADS;
671 lwsl_notice("%s: %x\n", __func__, type);
672 *p_force_factory_magic = type;
677 esp_err_t lws_esp32_event_passthru(void *ctx, system_event_t *event)
679 switch(event->event_id) {
680 case SYSTEM_EVENT_STA_START:
683 case SYSTEM_EVENT_STA_DISCONNECTED:
687 case SYSTEM_EVENT_STA_GOT_IP:
689 render_ip(lws_esp32.sta_ip, sizeof(lws_esp32.sta_ip) - 1,
690 (uint8_t *)&event->event_info.got_ip.ip_info.ip);
691 render_ip(lws_esp32.sta_mask, sizeof(lws_esp32.sta_mask) - 1,
692 (uint8_t *)&event->event_info.got_ip.ip_info.netmask);
693 render_ip(lws_esp32.sta_gw, sizeof(lws_esp32.sta_gw) - 1,
694 (uint8_t *)&event->event_info.got_ip.ip_info.gw);
696 case SYSTEM_EVENT_SCAN_DONE:
705 static lws_fop_fd_t IRAM_ATTR
706 esp32_lws_fops_open(const struct lws_plat_file_ops *fops, const char *filename,
707 const char *vfs_path, lws_fop_flags_t *flags)
709 struct esp32_file *f = malloc(sizeof(*f));
713 lwsl_notice("%s: %s\n", __func__, filename);
717 f->i = romfs_get_info(lws_esp32_romfs, filename, &len, &csum);
721 fop_fd = malloc(sizeof(*fop_fd));
726 fop_fd->filesystem_priv = f;
727 fop_fd->mod_time = csum;
728 *flags |= LWS_FOP_FLAG_MOD_TIME_VALID;
729 fop_fd->flags = *flags;
743 esp32_lws_fops_close(lws_fop_fd_t *fop_fd)
745 free((*fop_fd)->filesystem_priv);
752 static lws_fileofs_t IRAM_ATTR
753 esp32_lws_fops_seek_cur(lws_fop_fd_t fop_fd, lws_fileofs_t offset_from_cur_pos)
755 fop_fd->pos += offset_from_cur_pos;
757 if (fop_fd->pos > fop_fd->len)
758 fop_fd->pos = fop_fd->len;
764 esp32_lws_fops_read(lws_fop_fd_t fop_fd, lws_filepos_t *amount, uint8_t *buf,
767 struct esp32_file *f = fop_fd->filesystem_priv;
770 lwsl_err("misaligned buf\n");
775 if (fop_fd->pos >= fop_fd->len)
778 if (len > fop_fd->len - fop_fd->pos)
779 len = fop_fd->len - fop_fd->pos;
781 spi_flash_read((uint32_t)(char *)f->i + fop_fd->pos, buf, len);
789 static const struct lws_plat_file_ops fops = {
791 .LWS_FOP_OPEN = esp32_lws_fops_open,
792 .LWS_FOP_CLOSE = esp32_lws_fops_close,
793 .LWS_FOP_READ = esp32_lws_fops_read,
794 .LWS_FOP_SEEK_CUR = esp32_lws_fops_seek_cur,
797 static wifi_config_t config = {
800 .authmode = WIFI_AUTH_OPEN,
808 lws_esp32_wlan_nvs_get(int retry)
811 char r[2], lws_esp32_force_ap = 0;
815 esp_efuse_read_mac(mac);
816 mac[5] |= 1; /* match the AP MAC */
817 snprintf(lws_esp32.serial, sizeof(lws_esp32.serial) - 1, "%02X%02X%02X", mac[3], mac[4], mac[5]);
819 ESP_ERROR_CHECK(nvs_open("lws-station", NVS_READWRITE, &nvh));
821 s = sizeof(config.sta.ssid) - 1;
822 if (nvs_get_str(nvh, "ssid0", (char *)sta_config.sta.ssid, &s) != ESP_OK)
823 lws_esp32_force_ap = 1;
825 /* set the ssid we last tried to connect to */
826 strncpy(lws_esp32.active_ssid, (char *)sta_config.sta.ssid, sizeof(lws_esp32.active_ssid) - 1);
827 lws_esp32.active_ssid[sizeof(lws_esp32.active_ssid) - 1] = '\0';
829 s = sizeof(config.sta.password) - 1;
830 if (nvs_get_str(nvh, "password0", (char *)sta_config.sta.password, &s) != ESP_OK)
831 lws_esp32_force_ap = 1;
832 s = sizeof(lws_esp32.serial) - 1;
833 if (nvs_get_str(nvh, "serial", lws_esp32.serial, &s) != ESP_OK)
834 lws_esp32_force_ap = 1;
836 snprintf((char *)config.ap.ssid, sizeof(config.ap.ssid) - 1,
837 "config-%s-%s", lws_esp32.model, lws_esp32.serial);
838 s = sizeof(lws_esp32.opts) - 1;
839 if (nvs_get_str(nvh, "opts", lws_esp32.opts, &s) != ESP_OK)
840 lws_esp32_force_ap = 1;
843 if (nvs_get_str(nvh, "region", r, &s) != ESP_OK)
844 lws_esp32_force_ap = 1;
846 lws_esp32.region = atoi(r);
847 lws_esp32.access_pw[0] = '\0';
848 nvs_get_str(nvh, "access_pw", lws_esp32.access_pw, &s);
850 lws_esp32.group[0] = '\0';
851 s = sizeof(lws_esp32.group);
852 nvs_get_str(nvh, "group", lws_esp32.group, &s);
854 lws_esp32.role[0] = '\0';
855 s = sizeof(lws_esp32.role);
856 nvs_get_str(nvh, "role", lws_esp32.role, &s);
860 if (retry && sta_config.sta.ssid[0]) {
861 tcpip_adapter_set_hostname(TCPIP_ADAPTER_IF_STA, (const char *)&config.ap.ssid[7]);
862 ESP_ERROR_CHECK( esp_wifi_set_config(WIFI_IF_STA, &sta_config));
863 ESP_ERROR_CHECK( esp_wifi_connect());
865 ESP_ERROR_CHECK(mdns_init(TCPIP_ADAPTER_IF_STA, &lws_esp32.mdns));
866 mdns_set_hostname(lws_esp32.mdns, (const char *)&config.ap.ssid[7]);
867 mdns_set_instance(lws_esp32.mdns, "instance");
870 return lws_esp32_force_ap;
874 lws_esp32_wlan_config(void)
876 lws_esp32_wlan_nvs_get(0);
877 tcpip_adapter_init();
881 lws_esp32_wlan_start_ap(void)
883 wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
885 ESP_ERROR_CHECK( esp_wifi_init(&cfg));
886 ESP_ERROR_CHECK( esp_wifi_set_storage(WIFI_STORAGE_RAM));
887 esp_wifi_set_country(lws_esp32.region);
889 ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_APSTA) );
890 ESP_ERROR_CHECK( esp_wifi_set_config(WIFI_IF_AP, &config) );
891 ESP_ERROR_CHECK( esp_wifi_set_config(WIFI_IF_STA, &sta_config));
892 ESP_ERROR_CHECK( esp_wifi_start());
894 if (sta_config.sta.ssid[0]) {
895 tcpip_adapter_set_hostname(TCPIP_ADAPTER_IF_STA, (const char *)&config.ap.ssid[7]);
896 esp_wifi_set_auto_connect(1);
897 ESP_ERROR_CHECK( esp_wifi_connect());
898 ESP_ERROR_CHECK( esp_wifi_set_config(WIFI_IF_STA, &sta_config));
899 ESP_ERROR_CHECK( esp_wifi_connect());
904 lws_esp32_wlan_start_station(void)
906 wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
908 ESP_ERROR_CHECK( esp_wifi_init(&cfg));
909 ESP_ERROR_CHECK( esp_wifi_set_storage(WIFI_STORAGE_RAM));
910 esp_wifi_set_country(lws_esp32.region);
912 ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_STA));
913 ESP_ERROR_CHECK( esp_wifi_set_config(WIFI_IF_STA, &sta_config));
915 ESP_ERROR_CHECK( esp_wifi_start());
917 tcpip_adapter_set_hostname(TCPIP_ADAPTER_IF_STA, (const char *)&config.ap.ssid[7]);
918 esp_wifi_set_auto_connect(1);
919 ESP_ERROR_CHECK( esp_wifi_connect());
921 ESP_ERROR_CHECK(mdns_init(TCPIP_ADAPTER_IF_STA, &lws_esp32.mdns));
922 mdns_set_hostname(lws_esp32.mdns, (const char *)&config.ap.ssid[7]);
923 mdns_set_instance(lws_esp32.mdns, "instance");
926 const esp_partition_t *
927 lws_esp_ota_get_boot_partition(void)
929 const esp_partition_t *part = esp_ota_get_boot_partition(), *factory_part, *ota;
930 esp_image_header_t eih, ota_eih;
931 uint32_t *p_force_factory_magic = (uint32_t *)LWS_MAGIC_REBOOT_TYPE_ADS;
933 /* confirm what we are told is the boot part is sane */
934 spi_flash_read(part->address , &eih, sizeof(eih));
935 factory_part = esp_partition_find_first(ESP_PARTITION_TYPE_APP,
936 ESP_PARTITION_SUBTYPE_APP_FACTORY, NULL);
937 ota = esp_partition_find_first(ESP_PARTITION_TYPE_APP,
938 ESP_PARTITION_SUBTYPE_APP_OTA_0, NULL);
939 spi_flash_read(ota->address , &ota_eih, sizeof(ota_eih));
941 if (eih.spi_mode == 0xff ||
942 *p_force_factory_magic == LWS_MAGIC_REBOOT_TYPE_FORCED_FACTORY ||
943 *p_force_factory_magic == LWS_MAGIC_REBOOT_TYPE_FORCED_FACTORY_BUTTON
946 * we believed we were going to boot OTA, but we fell
947 * back to FACTORY in the bootloader when we saw it
948 * had been erased. esp_ota_get_boot_partition() still
949 * says the OTA partition then even if we are in the
950 * factory partition right now.
955 #ifdef CONFIG_LWS_IS_FACTORY_APPLICATION
957 if (ota_eih.spi_mode != 0xff &&
958 part->address != factory_part->address) {
962 * we are a FACTORY image running in an OTA slot...
963 * it means we were just written and need to copy
964 * ourselves into the FACTORY slot.
966 lwsl_notice("Copying FACTORY update into place 0x%x len 0x%x\n",
967 factory_part->address, factory_part->size);
969 if (spi_flash_erase_range(factory_part->address, factory_part->size) != ESP_OK) {
970 lwsl_err("spi: Failed to erase\n");
974 for (n = 0; n < factory_part->size; n += sizeof(buf)) {
976 spi_flash_read(part->address + n , buf, sizeof(buf));
977 if (spi_flash_write(factory_part->address + n, buf, sizeof(buf)) != ESP_OK) {
978 lwsl_err("spi: Failed to write\n");
983 /* destroy our OTA image header */
984 spi_flash_erase_range(ota->address, 4096);
987 * with no viable OTA image, we will come back up in factory
988 * where the user can reload the OTA image
990 lwsl_notice(" FACTORY copy successful, rebooting\n");
1001 lws_esp32_set_creation_defaults(struct lws_context_creation_info *info)
1003 const esp_partition_t *part;
1005 memset(info, 0, sizeof(*info));
1007 lws_set_log_level(63, lwsl_emit_syslog);
1009 part = lws_esp_ota_get_boot_partition();
1013 info->fd_limit_per_thread = 30;
1014 info->max_http_header_pool = 2;
1015 info->max_http_header_data = 1024;
1016 info->pt_serv_buf_size = 4096;
1017 info->keepalive_timeout = 5;
1018 info->simultaneous_ssl_restriction = 2;
1019 info->options = LWS_SERVER_OPTION_EXPLICIT_VHOSTS |
1020 LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
1022 info->ssl_cert_filepath = "ssl-pub.pem";
1023 info->ssl_private_key_filepath = "ssl-pri.pem";
1027 lws_esp32_get_image_info(const esp_partition_t *part, struct lws_esp32_image *i,
1028 char *json, int json_len)
1030 esp_image_segment_header_t eis;
1031 esp_image_header_t eih;
1034 spi_flash_read(part->address , &eih, sizeof(eih));
1035 hdr = part->address + sizeof(eih);
1037 if (eih.magic != ESP_IMAGE_HEADER_MAGIC)
1041 while (eih.segment_count-- && eis.data_len != 0xffffffff) {
1042 spi_flash_read(hdr, &eis, sizeof(eis));
1043 hdr += sizeof(eis) + eis.data_len;
1045 hdr += (~hdr & 15) + 1;
1048 spi_flash_read(hdr, &i->romfs_len, sizeof(i->romfs_len));
1049 i->json = i->romfs + i->romfs_len + 4;
1050 spi_flash_read(i->json - 4, &i->json_len, sizeof(i->json_len));
1052 if (i->json_len < json_len - 1)
1053 json_len = i->json_len;
1054 spi_flash_read(i->json, json, json_len);
1055 json[json_len] = '\0';
1060 struct lws_context *
1061 lws_esp32_init(struct lws_context_creation_info *info)
1063 const esp_partition_t *part = lws_esp_ota_get_boot_partition();
1064 struct lws_context *context;
1065 struct lws_esp32_image i;
1066 struct lws_vhost *vhost;
1071 ledc_timer_config_t ledc_timer = {
1072 .bit_num = LEDC_TIMER_13_BIT,
1074 .speed_mode = LEDC_HIGH_SPEED_MODE,
1075 .timer_num = LEDC_TIMER_0
1078 ledc_timer_config(&ledc_timer);
1080 /* user code needs to provide lws_esp32_leds_timer_cb */
1082 leds_timer = xTimerCreate("lws_leds", pdMS_TO_TICKS(25), 1, NULL,
1083 (TimerCallbackFunction_t)lws_esp32_leds_timer_cb);
1084 xTimerStart(leds_timer, 0);
1086 ESP_ERROR_CHECK(nvs_open("lws-station", NVS_READWRITE, &nvh));
1089 if (nvs_get_blob(nvh, "ssl-pub.pem", NULL, &s) == ESP_OK)
1092 if (nvs_get_blob(nvh, "ssl-pri.pem", NULL, &s) == ESP_OK)
1097 /* we are not configured for SSL yet... fall back to port 80 / http */
1099 info->options &= ~LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
1100 lwsl_notice("No SSL certs... using port 80\n");
1103 context = lws_create_context(info);
1104 if (context == NULL) {
1105 lwsl_err("Failed to create context\n");
1109 lws_esp32_get_image_info(part, &i, buf, sizeof(buf) - 1);
1111 lws_esp32_romfs = (romfs_t)i.romfs;
1112 if (!romfs_mount_check(lws_esp32_romfs)) {
1113 lwsl_err("Failed to mount ROMFS at %p 0x%x\n", lws_esp32_romfs, i.romfs);
1117 lwsl_notice("ROMFS length %uKiB\n", i.romfs_len >> 10);
1121 /* set the lws vfs to use our romfs */
1123 lws_set_fops(context, &fops);
1125 vhost = lws_create_vhost(context, info);
1127 lwsl_err("Failed to create vhost\n");
1129 lws_init_vhost_client_ssl(info, vhost);
1131 lws_protocol_init(context);
1136 static const uint16_t sineq16[] = {
1137 0x0000, 0x0191, 0x031e, 0x04a4, 0x061e, 0x0789, 0x08e2, 0x0a24,
1138 0x0b4e, 0x0c5c, 0x0d4b, 0x0e1a, 0x0ec6, 0x0f4d, 0x0faf, 0x0fea,
1141 static uint16_t sine_lu(int n)
1143 switch ((n >> 4) & 3) {
1145 return 4096 + sineq16[n & 15];
1147 return 4096 + sineq16[15 - (n & 15)];
1149 return 4096 - sineq16[n & 15];
1151 return 4096 - sineq16[15 - (n & 15)];
1155 /* useful for sine led fade patterns */
1157 uint16_t lws_esp32_sine_interp(int n)
1161 * 4: table entry in quadrant
1164 * total 10 bits / 1024 steps per cycle
1167 return (sine_lu(n >> 4) * (15 - (n & 15)) +
1168 sine_lu((n >> 4) + 1) * (n & 15)) / 15;