40e51f9d116503bd2ac8f4d5227b4195a7f9c53a
[platform/upstream/libwebsockets.git] / lib / lws-plat-esp32.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com>
5  *
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.
10  *
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.
15  *
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,
19  *  MA  02110-1301  USA
20  */
21
22 #include "private-libwebsockets.h"
23 #include "freertos/timers.h"
24 #include <esp_attr.h>
25 #include <esp_system.h>
26
27 /*
28  * included from libwebsockets.c for unix builds
29  */
30
31 unsigned long long time_in_microseconds(void)
32 {
33         struct timeval tv;
34         gettimeofday(&tv, NULL);
35         return ((unsigned long long)tv.tv_sec * 1000000LL) + tv.tv_usec;
36 }
37
38 LWS_VISIBLE int
39 lws_get_random(struct lws_context *context, void *buf, int len)
40 {
41         uint8_t *pb = buf;
42
43         while (len) {
44                 uint32_t r = esp_random();
45                 uint8_t *p = (uint8_t *)&r;
46                 int b = 4;
47
48                 if (len < b)
49                         b = len;
50
51                 len -= b;
52
53                 while (b--)
54                         *pb++ = p[b];
55         }
56
57         return pb - (uint8_t *)buf;
58 }
59
60 LWS_VISIBLE int
61 lws_send_pipe_choked(struct lws *wsi)
62 {
63         fd_set writefds;
64         struct timeval tv = { 0, 0 };
65
66         /* treat the fact we got a truncated send pending as if we're choked */
67         if (wsi->trunc_len)
68                 return 1;
69
70         FD_ZERO(&writefds);
71         FD_SET(wsi->desc.sockfd, &writefds);
72
73         if (select(wsi->desc.sockfd + 1, NULL, &writefds, NULL, &tv) < 1)
74                 return 1;
75
76         return 0;
77 }
78
79 LWS_VISIBLE int
80 lws_poll_listen_fd(struct lws_pollfd *fd)
81 {
82         fd_set readfds;
83         struct timeval tv = { 0, 0 };
84
85         FD_ZERO(&readfds);
86         FD_SET(fd->fd, &readfds);
87
88         return select(fd->fd + 1, &readfds, NULL, NULL, &tv);
89 }
90
91 LWS_VISIBLE void
92 lws_cancel_service_pt(struct lws *wsi)
93 {
94 }
95
96 LWS_VISIBLE void
97 lws_cancel_service(struct lws_context *context)
98 {
99 }
100
101 LWS_VISIBLE void lwsl_emit_syslog(int level, const char *line)
102 {
103         printf("%d: %s", level, line);
104 }
105
106 LWS_VISIBLE LWS_EXTERN int
107 _lws_plat_service_tsi(struct lws_context *context, int timeout_ms, int tsi)
108 {
109         struct lws_context_per_thread *pt;
110         int n = -1, m, c;
111
112         /* stay dead once we are dead */
113
114         if (!context || !context->vhost_list)
115                 return 1;
116
117         pt = &context->pt[tsi];
118         lws_stats_atomic_bump(context, pt, LWSSTATS_C_SERVICE_ENTRY, 1);
119
120         if (timeout_ms < 0)
121                 goto faked_service;
122
123         if (!context->service_tid_detected) {
124                 struct lws _lws;
125
126                 memset(&_lws, 0, sizeof(_lws));
127                 _lws.context = context;
128
129                 context->service_tid_detected =
130                         context->vhost_list->protocols[0].callback(
131                         &_lws, LWS_CALLBACK_GET_THREAD_ID, NULL, NULL, 0);
132         }
133         context->service_tid = context->service_tid_detected;
134
135         /*
136          * is there anybody with pending stuff that needs service forcing?
137          */
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 */
144                         timeout_ms = 0;
145         }
146
147 //      n = poll(pt->fds, pt->fds_count, timeout_ms);
148         {
149                 fd_set readfds, writefds, errfds;
150                 struct timeval tv = { timeout_ms / 1000,
151                                       (timeout_ms % 1000) * 1000 }, *ptv = &tv;
152                 int max_fd = 0;
153                 FD_ZERO(&readfds);
154                 FD_ZERO(&writefds);
155                 FD_ZERO(&errfds);
156
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);
166                 }
167
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;
176                 }
177         }
178
179
180 #ifdef LWS_OPENSSL_SUPPORT
181         if (!pt->rx_draining_ext_list &&
182             !lws_ssl_anybody_has_buffered_read_tsi(context, tsi) && !n) {
183 #else
184         if (!pt->rx_draining_ext_list && !n) /* poll timeout */ {
185 #endif
186                 lws_service_fd_tsi(context, NULL, tsi);
187                 return 0;
188         }
189
190 faked_service:
191         m = lws_service_flag_pending(context, tsi);
192         if (m)
193                 c = -1; /* unknown limit */
194         else
195                 if (n < 0) {
196                         if (LWS_ERRNO != LWS_EINTR)
197                                 return -1;
198                         return 0;
199                 } else
200                         c = n;
201
202         /* any socket with events to service? */
203         for (n = 0; n < pt->fds_count && c; n++) {
204                 if (!pt->fds[n].revents)
205                         continue;
206
207                 c--;
208
209                 m = lws_service_fd_tsi(context, &pt->fds[n], tsi);
210                 if (m < 0)
211                         return -1;
212                 /* if something closed, retry this slot */
213                 if (m)
214                         n--;
215         }
216
217         return 0;
218 }
219
220 LWS_VISIBLE int
221 lws_plat_check_connection_error(struct lws *wsi)
222 {
223         return 0;
224 }
225
226 LWS_VISIBLE int
227 lws_plat_service(struct lws_context *context, int timeout_ms)
228 {
229         return _lws_plat_service_tsi(context, timeout_ms, 0);
230 }
231
232 LWS_VISIBLE int
233 lws_plat_set_socket_options(struct lws_vhost *vhost, int fd)
234 {
235         int optval = 1;
236         socklen_t optlen = sizeof(optval);
237
238 #if defined(__APPLE__) || \
239     defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || \
240     defined(__NetBSD__) || \
241     defined(__OpenBSD__)
242         struct protoent *tcp_proto;
243 #endif
244
245         if (vhost->ka_time) {
246                 /* enable keepalive on this socket */
247                 optval = 1;
248                 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
249                                (const void *)&optval, optlen) < 0)
250                         return 1;
251
252 #if defined(__APPLE__) || \
253     defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || \
254     defined(__NetBSD__) || \
255         defined(__CYGWIN__) || defined(__OpenBSD__) || defined (__sun)
256
257                 /*
258                  * didn't find a way to set these per-socket, need to
259                  * tune kernel systemwide values
260                  */
261 #else
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)
266                         return 1;
267
268                 optval = vhost->ka_interval;
269                 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL,
270                                (const void *)&optval, optlen) < 0)
271                         return 1;
272
273                 optval = vhost->ka_probes;
274                 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT,
275                                (const void *)&optval, optlen) < 0)
276                         return 1;
277 #endif
278         }
279
280         /* Disable Nagle */
281         optval = 1;
282 //      if (setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&optval, optlen) < 0)
283 //              return 1;
284         if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &optval, optlen) < 0)
285                 return 1;
286
287         /* We are nonblocking... */
288         if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
289                 return 1;
290
291         return 0;
292 }
293
294 LWS_VISIBLE void
295 lws_plat_drop_app_privileges(struct lws_context_creation_info *info)
296 {
297 }
298
299 LWS_VISIBLE int
300 lws_plat_context_early_init(void)
301 {
302         //signal(SIGPIPE, SIG_IGN);
303
304 //      signal(SIGABRT, sigabrt_handler);
305
306         return 0;
307 }
308
309 LWS_VISIBLE void
310 lws_plat_context_early_destroy(struct lws_context *context)
311 {
312 }
313
314 LWS_VISIBLE void
315 lws_plat_context_late_destroy(struct lws_context *context)
316 {
317 #ifdef LWS_WITH_PLUGINS
318         if (context->plugin_list)
319                 lws_plat_plugins_destroy(context);
320 #endif
321
322         if (context->lws_lookup)
323                 lws_free(context->lws_lookup);
324 }
325
326 /* cast a struct sockaddr_in6 * into addr for ipv6 */
327
328 LWS_VISIBLE int
329 lws_interface_to_sa(int ipv6, const char *ifname, struct sockaddr_in *addr,
330                     size_t addrlen)
331 {
332 #if 0
333         int rc = -1;
334
335         struct ifaddrs *ifr;
336         struct ifaddrs *ifc;
337 #ifdef LWS_USE_IPV6
338         struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
339 #endif
340
341         getifaddrs(&ifr);
342         for (ifc = ifr; ifc != NULL && rc; ifc = ifc->ifa_next) {
343                 if (!ifc->ifa_addr)
344                         continue;
345
346                 lwsl_info(" interface %s vs %s\n", ifc->ifa_name, ifname);
347
348                 if (strcmp(ifc->ifa_name, ifname))
349                         continue;
350
351                 switch (ifc->ifa_addr->sa_family) {
352                 case AF_INET:
353 #ifdef LWS_USE_IPV6
354                         if (ipv6) {
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));
363                         } else
364 #endif
365                                 memcpy(addr,
366                                         (struct sockaddr_in *)ifc->ifa_addr,
367                                                     sizeof(struct sockaddr_in));
368                         break;
369 #ifdef LWS_USE_IPV6
370                 case AF_INET6:
371                         memcpy(&addr6->sin6_addr,
372                           &((struct sockaddr_in6 *)ifc->ifa_addr)->sin6_addr,
373                                                        sizeof(struct in6_addr));
374                         break;
375 #endif
376                 default:
377                         continue;
378                 }
379                 rc = 0;
380         }
381
382         freeifaddrs(ifr);
383
384         if (rc == -1) {
385                 /* check if bind to IP address */
386 #ifdef LWS_USE_IPV6
387                 if (inet_pton(AF_INET6, ifname, &addr6->sin6_addr) == 1)
388                         rc = 0;
389                 else
390 #endif
391                 if (inet_pton(AF_INET, ifname, &addr->sin_addr) == 1)
392                         rc = 0;
393         }
394
395         return rc;
396 #endif
397
398         return -1;
399 }
400
401 LWS_VISIBLE void
402 lws_plat_insert_socket_into_fds(struct lws_context *context, struct lws *wsi)
403 {
404         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
405
406         pt->fds[pt->fds_count++].revents = 0;
407 }
408
409 LWS_VISIBLE void
410 lws_plat_delete_socket_from_fds(struct lws_context *context,
411                                                 struct lws *wsi, int m)
412 {
413         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
414
415         pt->fds_count--;
416 }
417
418 LWS_VISIBLE void
419 lws_plat_service_periodic(struct lws_context *context)
420 {
421 }
422
423 LWS_VISIBLE int
424 lws_plat_change_pollfd(struct lws_context *context,
425                       struct lws *wsi, struct lws_pollfd *pfd)
426 {
427         return 0;
428 }
429
430 LWS_VISIBLE const char *
431 lws_plat_inet_ntop(int af, const void *src, char *dst, int cnt)
432 {
433         return inet_ntop(af, src, dst, cnt);
434 }
435
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)
439 {
440         struct stat stat_buf;
441         lws_fop_fd_t fop_fd;
442         int ret = open(filename, *flags, 0664);
443
444         if (ret < 0)
445                 return NULL;
446
447         if (fstat(ret, &stat_buf) < 0)
448                 goto bail;
449
450         fop_fd = malloc(sizeof(*fop_fd));
451         if (!fop_fd)
452                 goto bail;
453
454         fop_fd->fops = fops;
455         fop_fd->fd = ret;
456         fop_fd->flags = *flags;
457         fop_fd->filesystem_priv = NULL; /* we don't use it */
458         fop_fd->pos = 0;
459         fop_fd->len = stat_buf.st_size;
460
461         return fop_fd;
462
463 bail:
464         close(ret);
465
466         return NULL;
467 }
468
469 LWS_VISIBLE int IRAM_ATTR
470 _lws_plat_file_close(lws_fop_fd_t *fops_fd)
471 {
472         int fd = (*fops_fd)->fd;
473
474         free(*fops_fd);
475         *fops_fd = NULL;
476
477         return close(fd);
478 }
479
480 LWS_VISIBLE lws_fileofs_t IRAM_ATTR
481 _lws_plat_file_seek_cur(lws_fop_fd_t fops_fd, lws_fileofs_t offset)
482 {
483         return lseek(fops_fd->fd, offset, SEEK_CUR);
484 }
485
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)
489 {
490         long n;
491
492         n = read(fops_fd->fd, buf, len);
493         if (n == -1) {
494                 *amount = 0;
495                 return -1;
496         }
497         fops_fd->pos += n;
498         *amount = n;
499
500         return 0;
501 }
502
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)
506 {
507         long n;
508
509         n = write(fops_fd->fd, buf, len);
510         if (n == -1) {
511                 *amount = 0;
512                 return -1;
513         }
514         fops_fd->pos += n;
515         *amount = n;
516
517         return 0;
518 }
519
520
521 LWS_VISIBLE int
522 lws_plat_init(struct lws_context *context,
523               struct lws_context_creation_info *info)
524 {
525         /* master context has the global fd lookup array */
526         context->lws_lookup = lws_zalloc(sizeof(struct lws *) *
527                                          context->max_fds);
528         if (context->lws_lookup == NULL) {
529                 lwsl_err("OOM on lws_lookup array for %d connections\n",
530                          context->max_fds);
531                 return 1;
532         }
533
534         lwsl_notice(" mem: platform fd map: %5lu bytes\n",
535                     (unsigned long)(sizeof(struct lws *) * context->max_fds));
536
537 #ifdef LWS_WITH_PLUGINS
538         if (info->plugin_dirs)
539                 lws_plat_plugins_init(context, info->plugin_dirs);
540 #endif
541
542         return 0;
543 }
544
545
546 LWS_VISIBLE void esp32_uvtimer_cb(TimerHandle_t t)
547 {
548         struct timer_mapping *p = pvTimerGetTimerID(t);
549
550         p->cb(p->t);
551 }
552
553 void ERR_error_string_n(unsigned long e, char *buf, size_t len)
554 {
555         strncpy(buf, "unknown", len);
556 }
557
558 void ERR_free_strings(void)
559 {
560 }
561
562 char *ERR_error_string(unsigned long e, char *buf)
563 {
564         if (buf)
565                 strcpy(buf, "unknown");
566
567         return "unknown";
568 }
569
570
571 /* helper functionality */
572
573 #include "romfs.h"
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"
580
581 struct lws_esp32 lws_esp32 = {
582         .model = CONFIG_LWS_MODEL_NAME,
583         .serial = "unknown",
584         .region = WIFI_COUNTRY_US, // default to safest option
585 };
586
587 /*
588  * Group AP / Station State
589  */
590
591 enum lws_gapss {
592         LWS_GAPSS_INITIAL,      /* just started up, init and move to LWS_GAPSS_SCAN */
593         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)
598                                  */
599         LWS_GAPSS_AP,           /*
600                                  * Trying to be the group AP... periodically do a scan
601                                  * LWS_GAPSS_AP_SCAN, faster and then slower
602                                  */
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
607                                  * station
608                                  */
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.
615                                  */
616         LWS_GAPSS_STAT_GRP_AP_SCAN,
617                                 /*
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
622                                  */
623         LWS_GAPSS_STAT,         /*
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 
627                                  */
628         LWS_GAPSS_STAT_HAPPY,
629 };
630
631 static const char *gapss_str[] = {
632         "LWS_GAPSS_INITIAL",
633         "LWS_GAPSS_SCAN",
634         "LWS_GAPSS_AP",
635         "LWS_GAPSS_AP_SCAN",
636         "LWS_GAPSS_STAT_GRP_AP",
637         "LWS_GAPSS_STAT_GRP_AP_SCAN",
638         "LWS_GAPSS_STAT",
639         "LWS_GAPSS_STAT_HAPPY",
640 };
641
642 static romfs_t lws_esp32_romfs;
643 static TimerHandle_t leds_timer, scan_timer
644 #if !defined(CONFIG_LWS_IS_FACTORY_APPLICATION)
645 , mdns_timer
646 #endif
647 ;
648 static enum lws_gapss gapss = LWS_GAPSS_INITIAL;
649
650 struct esp32_file {
651         const struct inode *i;
652 };
653
654 static void lws_gapss_to(enum lws_gapss to)
655 {
656         lwsl_notice("gapss from %s to %s\n", gapss_str[gapss], gapss_str[to]);
657         gapss = to;
658 }
659
660 uint32_t lws_esp32_get_reboot_type(void)
661 {
662         uint32_t *p = (uint32_t *)LWS_MAGIC_REBOOT_TYPE_ADS, val = *p;
663         nvs_handle nvh;
664         size_t s = 0;
665         int n = 0;
666
667         ESP_ERROR_CHECK(nvs_open("lws-station", NVS_READWRITE, &nvh));
668         if (nvs_get_blob(nvh, "ssl-pub.pem", NULL, &s) == ESP_OK)
669                 n = 1;
670         if (nvs_get_blob(nvh, "ssl-pri.pem", NULL, &s) == ESP_OK)
671                 n |= 2;
672         nvs_close(nvh);
673
674         /*
675          * in the case the SSL certs are not there, don't require
676          * the button to be down to access all features.
677          */
678         if (n != 3)
679                 val = LWS_MAGIC_REBOOT_TYPE_FORCED_FACTORY_BUTTON;
680
681         return val;
682 }
683
684 static void render_ip(char *dest, int len, uint8_t *ip)
685 {
686         snprintf(dest, len, "%u.%u.%u.%u", ip[0], ip[1], ip[2], ip[3]);
687 }
688
689 void lws_esp32_restart_guided(uint32_t type)
690 {
691         uint32_t *p_force_factory_magic = (uint32_t *)LWS_MAGIC_REBOOT_TYPE_ADS;
692
693         lwsl_notice("%s: %x\n", __func__, type);
694         *p_force_factory_magic = type;
695
696         esp_restart();
697 }
698
699 /*
700  * esp-idf goes crazy with zero length str nvs.  Use this as a workaround
701  * to delete the key in that case.
702  */
703
704 esp_err_t lws_nvs_set_str(nvs_handle handle, const char* key, const char* value)
705 {
706         if (*value)
707                 return nvs_set_str(handle, key, value);
708
709         return nvs_erase_key(handle, key);
710 }
711
712 static wifi_scan_config_t scan_config = {
713         .ssid = 0,
714         .bssid = 0,
715         .channel = 0,
716         .show_hidden = true
717 };
718
719 static char scan_ongoing = 0, scan_timer_exists = 0;
720 static int try_slot = -1;
721
722 static wifi_config_t config = {
723         .ap = {
724             .channel = 6,
725             .authmode = WIFI_AUTH_OPEN,
726             .max_connection = 1,
727         } }, sta_config = {
728         .sta = {
729                 .bssid_set = 0,
730         } };
731
732 static void lws_esp32_scan_timer_cb(TimerHandle_t th)
733 {
734         int n;
735
736         lwsl_notice("%s\n", __func__);
737         scan_ongoing = 0;
738         n = esp_wifi_scan_start(&scan_config, false);
739         if (n != ESP_OK)
740                 lwsl_err("scan start failed %d\n", n);
741 }
742
743 #if !defined(CONFIG_LWS_IS_FACTORY_APPLICATION)
744 static void lws_esp32_mdns_timer_cb(TimerHandle_t th)
745 {
746         uint64_t now = time_in_microseconds(); 
747         struct lws_group_member *p, **p1;
748         const mdns_result_t *r;
749         int n, m;
750
751         if (!lws_esp32.mdns)
752                 return;
753         n = mdns_query_end(lws_esp32.mdns);
754         lwsl_notice("%s: %d results\n", __func__, n);
755
756         for (m = 0; m < n; m++) {
757                 r = mdns_result_get(lws_esp32.mdns, m);
758                 lwsl_notice("found %s / %s / %s\n", r->host, r->instance, r->txt);
759                 p = lws_esp32.first;
760                 while (p) {
761                         if (strcmp(r->host, p->host)) {
762                                 lwsl_notice("%s vs %s\n", r->host, p->host);
763                                 goto next;
764                         }
765                         if (memcmp(&r->addr, &p->addr, sizeof(r->addr))) {
766                                 lwsl_notice("0x%x vs 0x%x\n", *((unsigned int *)&r->addr),
767                                                 *((unsigned int *)&p->addr));
768                                 goto next;
769                         }
770                         lwsl_notice("updating existing group member\n");
771                         p->last_seen = now;
772                         break;
773 next:
774                         p = p->next;
775                 }
776                 if (!p) { /* did not find */
777                         lwsl_notice("creating new group member\n");
778                         p = malloc(sizeof(*p));
779                         if (!p)
780                                 continue;
781                         strncpy(p->host, r->host, sizeof(p->host) - 1);
782                         p->host[sizeof(p->host) - 1] = '\0';
783                         memcpy(&p->addr, &r->addr, sizeof(p->addr));
784                         memcpy(&p->addrv6, &r->addrv6, sizeof(p->addrv6));
785                         p->last_seen = now;
786                         p->next = lws_esp32.first;
787                         lws_esp32.first = p;
788                         lws_esp32.extant_group_members++;
789                 }
790         }
791
792         mdns_result_free(lws_esp32.mdns);
793
794         /* garbage-collect group members not seen for too long */
795         p1 = &lws_esp32.first;
796         while (*p1) {
797                 p = *p1;
798                 if (now - p->last_seen > 60000000) {
799                         lwsl_notice("timing out group member\n");
800                         lws_esp32.extant_group_members--;
801                         *p1 = p->next;
802                         free(p);
803                         continue;
804                 }
805                 p1 = &(*p1)->next;
806         }
807
808         mdns_query(lws_esp32.mdns, "_lwsgrmem", "_tcp", 0);
809         xTimerStart(mdns_timer, 0);
810 }
811 #endif
812
813 static int
814 start_scan()
815 {
816         /* if no APs configured, no point... */
817
818         if (!lws_esp32.ssid[0][0] &&
819             !lws_esp32.ssid[1][0] &&
820             !lws_esp32.ssid[2][0] &&
821             !lws_esp32.ssid[3][0])
822                 return 0;
823
824         if (scan_timer_exists && !scan_ongoing) {
825                 // lwsl_notice("Starting scan timer...\n");
826                 scan_ongoing = 1;
827                 xTimerStart(scan_timer, 0);
828         }
829
830         return 0;
831 }
832
833
834
835 static void
836 end_scan()
837 {
838         wifi_ap_record_t ap_records[10];
839         uint16_t count_ap_records;
840         int n, m;
841
842         count_ap_records = ARRAY_SIZE(ap_records);
843         if (esp_wifi_scan_get_ap_records(&count_ap_records, ap_records) != ESP_OK) {
844                 lwsl_err("%s: failed\n", __func__);
845                 return;
846         }
847
848         if (!count_ap_records)
849                 goto passthru;
850
851         if (gapss != LWS_GAPSS_SCAN) {
852                 lwsl_notice("ignoring scan as gapss %s\n", gapss_str[gapss]);
853                 goto passthru;
854         }
855
856         /* no point if no APs set up */
857         if (!lws_esp32.ssid[0][0] &&
858             !lws_esp32.ssid[1][0] &&
859             !lws_esp32.ssid[2][0] &&
860             !lws_esp32.ssid[3][0])
861                 goto passthru;
862
863         lwsl_notice("checking %d scan records\n", count_ap_records);
864
865         for (n = 0; n < 4; n++) {
866
867                 if (!lws_esp32.ssid[(n + try_slot + 1) & 3][0])
868                         continue;
869
870                 lwsl_notice("looking for %s\n", lws_esp32.ssid[(n + try_slot + 1) & 3]);
871
872                 /* this ssid appears in scan results? */
873
874                 for (m = 0; m < count_ap_records; m++) {
875                         // lwsl_notice("  %s\n", ap_records[m].ssid);
876                         if (strcmp((char *)ap_records[m].ssid, lws_esp32.ssid[(n + try_slot + 1) & 3]) == 0)
877                                 goto hit;
878                 }
879
880                 continue;
881
882 hit:
883                 m = (n + try_slot + 1) & 3;
884                 try_slot = m;
885                 lwsl_notice("Attempting connection with slot %d: %s:\n", m,
886                                 lws_esp32.ssid[m]);
887                 /* set the ssid we last tried to connect to */
888                 strncpy(lws_esp32.active_ssid, lws_esp32.ssid[m],
889                                 sizeof(lws_esp32.active_ssid) - 1);
890                 lws_esp32.active_ssid[sizeof(lws_esp32.active_ssid) - 1] = '\0';
891
892                 strncpy((char *)sta_config.sta.ssid, lws_esp32.ssid[m], sizeof(sta_config.sta.ssid) - 1);
893                 strncpy((char *)sta_config.sta.password, lws_esp32.password[m], sizeof(sta_config.sta.password) - 1);
894
895                 tcpip_adapter_set_hostname(TCPIP_ADAPTER_IF_STA, (const char *)&config.ap.ssid[7]);
896                 lws_gapss_to(LWS_GAPSS_STAT);
897
898                 esp_wifi_set_config(WIFI_IF_STA, &sta_config);
899                 esp_wifi_connect();
900                 break;
901         }
902
903         if (n == 4)
904                 start_scan();
905
906 passthru:
907         if (lws_esp32.scan_consumer)
908                 lws_esp32.scan_consumer(count_ap_records, ap_records, lws_esp32.scan_consumer_arg);
909
910 }       
911
912 esp_err_t lws_esp32_event_passthru(void *ctx, system_event_t *event)
913 {
914         char slot[8];
915         nvs_handle nvh;
916         uint32_t use;
917 #if !defined(CONFIG_LWS_IS_FACTORY_APPLICATION)
918         int n;
919 #endif
920
921         switch(event->event_id) {
922         case SYSTEM_EVENT_STA_START:
923                 //esp_wifi_connect();
924 //              break;
925                 /* fallthru */
926         case SYSTEM_EVENT_STA_DISCONNECTED:
927                 lwsl_notice("SYSTEM_EVENT_STA_DISCONNECTED\n");
928                 lws_esp32.inet = 0;
929                 lws_esp32.sta_ip[0] = '\0';
930                 lws_esp32.sta_mask[0] = '\0';
931                 lws_esp32.sta_gw[0] = '\0';
932                 lws_gapss_to(LWS_GAPSS_SCAN);
933                 if (lws_esp32.mdns)
934                         mdns_service_remove_all(lws_esp32.mdns);
935                 lws_esp32.mdns = NULL;
936                 start_scan();
937                 esp_wifi_connect();
938                 break;
939         case SYSTEM_EVENT_STA_GOT_IP:
940                 lwsl_notice("SYSTEM_EVENT_STA_GOT_IP\n");
941
942                 lws_esp32.inet = 1;
943                 render_ip(lws_esp32.sta_ip, sizeof(lws_esp32.sta_ip) - 1,
944                                 (uint8_t *)&event->event_info.got_ip.ip_info.ip);
945                 render_ip(lws_esp32.sta_mask, sizeof(lws_esp32.sta_mask) - 1,
946                                 (uint8_t *)&event->event_info.got_ip.ip_info.netmask);
947                 render_ip(lws_esp32.sta_gw, sizeof(lws_esp32.sta_gw) - 1,
948                                 (uint8_t *)&event->event_info.got_ip.ip_info.gw);
949
950                 if (!nvs_open("lws-station", NVS_READWRITE, &nvh)) {
951                         lws_snprintf(slot, sizeof(slot) - 1, "%duse", try_slot);
952                         use = 0;
953                         nvs_get_u32(nvh, slot, &use);
954                         nvs_set_u32(nvh, slot, use + 1);
955                         nvs_commit(nvh);
956                         nvs_close(nvh);
957                 }
958
959                 lws_gapss_to(LWS_GAPSS_STAT_HAPPY);
960
961 #if !defined(CONFIG_LWS_IS_FACTORY_APPLICATION)
962                 n = mdns_init(TCPIP_ADAPTER_IF_STA, &lws_esp32.mdns);
963                 if (!n) {
964                         static char *txta[4];
965
966                         mdns_set_hostname(lws_esp32.mdns, lws_esp32.hostname);
967                         mdns_set_instance(lws_esp32.mdns, lws_esp32.group);
968                         mdns_service_add(lws_esp32.mdns, "_lwsgrmem", "_tcp", 443);
969                         if (txta[0])
970                                 free(txta[0]);
971                         txta[0] = malloc(32 * 4);
972                         if (!txta[0]) {
973                                 lwsl_notice("mdns OOM\n");
974                                 break;
975                         }
976                         txta[1] = &txta[0][32];
977                         txta[2] = &txta[1][32];
978                         txta[3] = &txta[2][32];
979
980                         lws_snprintf(txta[0], 31, "model=%s", lws_esp32.model);
981                         lws_snprintf(txta[1], 31, "group=%s", lws_esp32.group);
982                         lws_snprintf(txta[2], 31, "role=%s", lws_esp32.role);
983                         lws_snprintf(txta[3], 31, "role=%s", lws_esp32.role);
984
985                         if (mdns_service_txt_set(lws_esp32.mdns, "_lwsgrmem", "_tcp", 4,
986                                                  (const char **)txta))
987                                 lwsl_notice("txt set failed\n");
988                 } else
989                         lwsl_err("unable to init mdns on STA: %d\n", n);
990
991                 mdns_query(lws_esp32.mdns, "_lwsgrmem", "_tcp", 0);
992                 xTimerStart(mdns_timer, 0);
993 #endif
994
995                 lwsl_notice(" --- Got IP %s\n", lws_esp32.sta_ip);
996                 break;
997
998         case SYSTEM_EVENT_SCAN_DONE:
999                 lwsl_notice("SYSTEM_EVENT_SCAN_DONE\n");
1000                 end_scan();
1001                 break;
1002         default:
1003                 break;
1004         }
1005
1006         return ESP_OK;
1007 }
1008
1009 static lws_fop_fd_t IRAM_ATTR
1010 esp32_lws_fops_open(const struct lws_plat_file_ops *fops, const char *filename,
1011                 const char *vfs_path, lws_fop_flags_t *flags)
1012 {
1013         struct esp32_file *f = malloc(sizeof(*f));
1014         lws_fop_fd_t fop_fd;
1015         size_t len, csum;
1016
1017         lwsl_notice("%s: %s\n", __func__, filename);
1018
1019         if (!f)
1020                 return NULL;
1021         f->i = romfs_get_info(lws_esp32_romfs, filename, &len, &csum);
1022         if (!f->i)
1023                 goto bail;
1024
1025         fop_fd = malloc(sizeof(*fop_fd));
1026         if (!fop_fd)
1027                 goto bail;
1028
1029         fop_fd->fops = fops;
1030         fop_fd->filesystem_priv = f;
1031         fop_fd->mod_time = csum;
1032         *flags |= LWS_FOP_FLAG_MOD_TIME_VALID;
1033         fop_fd->flags = *flags;
1034         
1035         fop_fd->len = len;
1036         fop_fd->pos = 0;
1037
1038         return fop_fd;
1039
1040 bail:
1041         free(f);
1042
1043         return NULL;
1044 }
1045
1046 static int IRAM_ATTR
1047 esp32_lws_fops_close(lws_fop_fd_t *fop_fd)
1048 {
1049         free((*fop_fd)->filesystem_priv);
1050         free(*fop_fd);
1051
1052         *fop_fd = NULL;
1053
1054         return 0;
1055 }
1056 static lws_fileofs_t IRAM_ATTR
1057 esp32_lws_fops_seek_cur(lws_fop_fd_t fop_fd, lws_fileofs_t offset_from_cur_pos)
1058 {
1059         fop_fd->pos += offset_from_cur_pos;
1060         
1061         if (fop_fd->pos > fop_fd->len)
1062                 fop_fd->pos = fop_fd->len;
1063
1064        return 0;
1065 }
1066
1067 static int IRAM_ATTR
1068 esp32_lws_fops_read(lws_fop_fd_t fop_fd, lws_filepos_t *amount, uint8_t *buf,
1069                    lws_filepos_t len)
1070 {
1071        struct esp32_file *f = fop_fd->filesystem_priv;
1072 #if 0
1073        if ((long)buf & 3) {
1074                lwsl_err("misaligned buf\n");
1075
1076                return -1;
1077        }
1078 #endif
1079        if (fop_fd->pos >= fop_fd->len)
1080                return 0;
1081
1082        if (len > fop_fd->len - fop_fd->pos)
1083                len = fop_fd->len - fop_fd->pos;
1084
1085        spi_flash_read((uint32_t)(char *)f->i + fop_fd->pos, buf, len);
1086
1087        *amount = len;
1088        fop_fd->pos += len;
1089
1090        return 0;
1091 }
1092
1093 static const struct lws_plat_file_ops fops = {
1094         .next = &fops_zip,
1095         .LWS_FOP_OPEN = esp32_lws_fops_open,
1096         .LWS_FOP_CLOSE = esp32_lws_fops_close,
1097         .LWS_FOP_READ = esp32_lws_fops_read,
1098         .LWS_FOP_SEEK_CUR = esp32_lws_fops_seek_cur,
1099 };
1100
1101 int
1102 lws_esp32_wlan_nvs_get(int retry)
1103 {
1104         nvs_handle nvh;
1105         char r[2], lws_esp32_force_ap = 0, slot[12];
1106         size_t s;
1107         uint8_t mac[6];
1108         int n;
1109
1110         esp_efuse_mac_get_default(mac);
1111         mac[5] |= 1; /* match the AP MAC */
1112         snprintf(lws_esp32.serial, sizeof(lws_esp32.serial) - 1, "%02X%02X%02X", mac[3], mac[4], mac[5]);
1113
1114         ESP_ERROR_CHECK(nvs_open("lws-station", NVS_READWRITE, &nvh));
1115
1116         config.sta.ssid[0] = '\0';
1117         config.sta.password[0] = '\0';
1118
1119         for (n = 0; n < 4; n++) {
1120                 lws_snprintf(slot, sizeof(slot) - 1, "%dssid", n);
1121                 s = sizeof(lws_esp32.ssid[0]) - 1;
1122                 lws_esp32.ssid[n][0] = '\0';
1123                 nvs_get_str(nvh, slot, lws_esp32.ssid[n], &s);
1124
1125                 lws_snprintf(slot, sizeof(slot) - 1, "%dpassword", n);
1126                 s = sizeof(lws_esp32.password[0]) - 1;
1127                 lws_esp32.password[n][0] = '\0';
1128                 nvs_get_str(nvh, slot, lws_esp32.password[n], &s);
1129         }
1130
1131         s = sizeof(lws_esp32.serial) - 1;
1132         if (nvs_get_str(nvh, "serial", lws_esp32.serial, &s) != ESP_OK)
1133                 lws_esp32_force_ap = 1;
1134         else
1135                 snprintf((char *)config.ap.ssid, sizeof(config.ap.ssid) - 1,
1136                          "config-%s-%s", lws_esp32.model, lws_esp32.serial);
1137         s = sizeof(lws_esp32.opts) - 1;
1138         if (nvs_get_str(nvh, "opts", lws_esp32.opts, &s) != ESP_OK)
1139                 lws_esp32_force_ap = 1;
1140
1141         s = sizeof(r);
1142         if (nvs_get_str(nvh, "region", r, &s) != ESP_OK)
1143                 lws_esp32_force_ap = 1;
1144         else
1145                 lws_esp32.region = atoi(r);
1146         lws_esp32.access_pw[0] = '\0';
1147         nvs_get_str(nvh, "access_pw", lws_esp32.access_pw, &s);
1148
1149         lws_esp32.group[0] = '\0';
1150         s = sizeof(lws_esp32.group);
1151         nvs_get_str(nvh, "group", lws_esp32.group, &s);
1152
1153         lws_esp32.role[0] = '\0';
1154         s = sizeof(lws_esp32.role);
1155         nvs_get_str(nvh, "role", lws_esp32.role, &s);
1156
1157         lws_snprintf(lws_esp32.hostname, sizeof(lws_esp32.hostname) - 1,
1158                         "%s-%s-%s", lws_esp32.model,
1159                         lws_esp32.group,
1160                         lws_esp32.serial);
1161
1162         nvs_close(nvh);
1163
1164         lws_gapss_to(LWS_GAPSS_SCAN);
1165         start_scan();
1166
1167         return lws_esp32_force_ap;
1168 }
1169
1170 void
1171 lws_esp32_wlan_config(void)
1172 {
1173         ledc_timer_config_t ledc_timer = {
1174                 .bit_num = LEDC_TIMER_13_BIT,
1175                 .freq_hz = 5000,
1176                 .speed_mode = LEDC_HIGH_SPEED_MODE,
1177                 .timer_num = LEDC_TIMER_0
1178         };
1179
1180         ledc_timer_config(&ledc_timer);
1181
1182         /* user code needs to provide lws_esp32_leds_timer_cb */
1183
1184         leds_timer = xTimerCreate("lws_leds", pdMS_TO_TICKS(25), 1, NULL,
1185                           (TimerCallbackFunction_t)lws_esp32_leds_timer_cb);
1186         scan_timer = xTimerCreate("lws_scan", pdMS_TO_TICKS(10000), 0, NULL,
1187                           (TimerCallbackFunction_t)lws_esp32_scan_timer_cb);
1188 #if !defined(CONFIG_LWS_IS_FACTORY_APPLICATION)
1189         mdns_timer = xTimerCreate("lws_mdns", pdMS_TO_TICKS(5000), 0, NULL,
1190                           (TimerCallbackFunction_t)lws_esp32_mdns_timer_cb);
1191 #endif
1192         scan_timer_exists = 1;
1193         xTimerStart(leds_timer, 0);
1194
1195
1196         lws_esp32_wlan_nvs_get(0);
1197         tcpip_adapter_init();
1198 }
1199
1200 void
1201 lws_esp32_wlan_start_ap(void)
1202 {
1203         wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
1204
1205         ESP_ERROR_CHECK( esp_wifi_init(&cfg));
1206         ESP_ERROR_CHECK( esp_wifi_set_storage(WIFI_STORAGE_RAM));
1207         esp_wifi_set_country(lws_esp32.region);
1208
1209         ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_APSTA) );
1210         ESP_ERROR_CHECK( esp_wifi_set_config(WIFI_IF_AP, &config) );
1211         ESP_ERROR_CHECK( esp_wifi_set_config(WIFI_IF_STA, &sta_config));
1212         ESP_ERROR_CHECK( esp_wifi_start());
1213
1214         esp_wifi_scan_start(&scan_config, false);
1215
1216         if (sta_config.sta.ssid[0]) {
1217                 tcpip_adapter_set_hostname(TCPIP_ADAPTER_IF_STA, (const char *)&config.ap.ssid[7]);
1218                 esp_wifi_set_auto_connect(1);
1219                 ESP_ERROR_CHECK( esp_wifi_connect());
1220                 ESP_ERROR_CHECK( esp_wifi_set_config(WIFI_IF_STA, &sta_config));
1221                 ESP_ERROR_CHECK( esp_wifi_connect());
1222         }
1223 }
1224
1225 void
1226 lws_esp32_wlan_start_station(void)
1227 {
1228         wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
1229
1230         ESP_ERROR_CHECK( esp_wifi_init(&cfg));
1231         ESP_ERROR_CHECK( esp_wifi_set_storage(WIFI_STORAGE_RAM));
1232         esp_wifi_set_country(lws_esp32.region);
1233
1234         ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_STA));
1235         ESP_ERROR_CHECK( esp_wifi_set_config(WIFI_IF_STA, &sta_config));
1236
1237         ESP_ERROR_CHECK( esp_wifi_start());
1238
1239         tcpip_adapter_set_hostname(TCPIP_ADAPTER_IF_STA, (const char *)&config.ap.ssid[7]);
1240         esp_wifi_set_auto_connect(1);
1241         ESP_ERROR_CHECK( esp_wifi_connect());
1242
1243         lws_esp32_scan_timer_cb(NULL);
1244 }
1245
1246 const esp_partition_t *
1247 lws_esp_ota_get_boot_partition(void)
1248 {
1249         const esp_partition_t *part = esp_ota_get_boot_partition(), *factory_part, *ota;
1250         esp_image_header_t eih, ota_eih;
1251         uint32_t *p_force_factory_magic = (uint32_t *)LWS_MAGIC_REBOOT_TYPE_ADS;
1252
1253         /* confirm what we are told is the boot part is sane */
1254         spi_flash_read(part->address , &eih, sizeof(eih));
1255         factory_part = esp_partition_find_first(ESP_PARTITION_TYPE_APP,
1256                         ESP_PARTITION_SUBTYPE_APP_FACTORY, NULL);
1257         ota = esp_partition_find_first(ESP_PARTITION_TYPE_APP,
1258                         ESP_PARTITION_SUBTYPE_APP_OTA_0, NULL);
1259         spi_flash_read(ota->address , &ota_eih, sizeof(ota_eih));
1260
1261         if (eih.spi_mode == 0xff ||
1262             *p_force_factory_magic == LWS_MAGIC_REBOOT_TYPE_FORCED_FACTORY ||
1263             *p_force_factory_magic == LWS_MAGIC_REBOOT_TYPE_FORCED_FACTORY_BUTTON
1264            ) {
1265                 /*
1266                  * we believed we were going to boot OTA, but we fell
1267                  * back to FACTORY in the bootloader when we saw it
1268                  * had been erased.  esp_ota_get_boot_partition() still
1269                  * says the OTA partition then even if we are in the
1270                  * factory partition right now.
1271                  */
1272                 part = factory_part;
1273         } 
1274         
1275 #ifdef CONFIG_LWS_IS_FACTORY_APPLICATION
1276         else
1277                 if (ota_eih.spi_mode != 0xff &&
1278                     part->address != factory_part->address) {
1279                         uint8_t buf[4096];
1280                         uint32_t n;
1281                         /*
1282                          * we are a FACTORY image running in an OTA slot...
1283                          * it means we were just written and need to copy
1284                          * ourselves into the FACTORY slot.
1285                          */
1286                         lwsl_notice("Copying FACTORY update into place 0x%x len 0x%x\n",
1287                                     factory_part->address, factory_part->size);
1288                         esp_task_wdt_feed();
1289                         if (spi_flash_erase_range(factory_part->address, factory_part->size) != ESP_OK) {
1290                                 lwsl_err("spi: Failed to erase\n");
1291                                 goto retry;
1292                         }
1293
1294                         for (n = 0; n < factory_part->size; n += sizeof(buf)) {
1295                                 esp_task_wdt_feed();
1296                                 spi_flash_read(part->address + n , buf, sizeof(buf));
1297                                 if (spi_flash_write(factory_part->address + n, buf, sizeof(buf)) != ESP_OK) {
1298                                         lwsl_err("spi: Failed to write\n");
1299                                         goto retry;
1300                                 }
1301                         }
1302
1303                         /* destroy our OTA image header */
1304                         spi_flash_erase_range(ota->address, 4096);
1305
1306                         /*
1307                          * with no viable OTA image, we will come back up in factory
1308                          * where the user can reload the OTA image
1309                          */
1310                         lwsl_notice("  FACTORY copy successful, rebooting\n");
1311 retry:
1312                         esp_restart();
1313                 }
1314 #endif
1315
1316         return part;
1317 }
1318
1319
1320 void
1321 lws_esp32_set_creation_defaults(struct lws_context_creation_info *info)
1322 {
1323         const esp_partition_t *part;
1324
1325         memset(info, 0, sizeof(*info));
1326
1327         lws_set_log_level(63, lwsl_emit_syslog);
1328
1329         part = lws_esp_ota_get_boot_partition();
1330         (void)part;
1331
1332         info->port = 443;
1333         info->fd_limit_per_thread = 30;
1334         info->max_http_header_pool = 3;
1335         info->max_http_header_data = 1024;
1336         info->pt_serv_buf_size = 4096;
1337         info->keepalive_timeout = 30;
1338         info->timeout_secs = 30;
1339         info->simultaneous_ssl_restriction = 3;
1340         info->options = LWS_SERVER_OPTION_EXPLICIT_VHOSTS |
1341                        LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
1342
1343         info->ssl_cert_filepath = "ssl-pub.pem";
1344         info->ssl_private_key_filepath = "ssl-pri.pem";
1345 }
1346
1347 int
1348 lws_esp32_get_image_info(const esp_partition_t *part, struct lws_esp32_image *i,
1349                          char *json, int json_len)
1350 {
1351         esp_image_segment_header_t eis;
1352         esp_image_header_t eih;
1353         uint32_t hdr;
1354
1355         spi_flash_read(part->address , &eih, sizeof(eih));
1356         hdr = part->address + sizeof(eih);
1357
1358         if (eih.magic != ESP_IMAGE_HEADER_MAGIC)
1359                 return 1;
1360
1361         eis.data_len = 0;
1362         while (eih.segment_count-- && eis.data_len != 0xffffffff) {
1363                 spi_flash_read(hdr, &eis, sizeof(eis));
1364                 hdr += sizeof(eis) + eis.data_len;
1365         }
1366         hdr += (~hdr & 15) + 1;
1367
1368         i->romfs = hdr + 4;
1369         spi_flash_read(hdr, &i->romfs_len, sizeof(i->romfs_len));
1370         i->json = i->romfs + i->romfs_len + 4;
1371         spi_flash_read(i->json - 4, &i->json_len, sizeof(i->json_len));
1372
1373         if (i->json_len < json_len - 1)
1374                 json_len = i->json_len;
1375         spi_flash_read(i->json, json, json_len);
1376         json[json_len] = '\0';
1377
1378         return 0;
1379 }
1380
1381 struct lws_context *
1382 lws_esp32_init(struct lws_context_creation_info *info)
1383 {
1384         const esp_partition_t *part = lws_esp_ota_get_boot_partition();
1385         struct lws_context *context;
1386         struct lws_esp32_image i;
1387         struct lws_vhost *vhost;
1388         nvs_handle nvh;
1389         char buf[512];
1390         size_t s;
1391         int n;
1392
1393         ESP_ERROR_CHECK(nvs_open("lws-station", NVS_READWRITE, &nvh));
1394         n = 0;
1395         s = 1;
1396         if (nvs_get_blob(nvh, "ssl-pub.pem", NULL, &s) == ESP_OK)
1397                 n = 1;
1398         s = 1;
1399         if (nvs_get_blob(nvh, "ssl-pri.pem", NULL, &s) == ESP_OK)
1400                 n |= 2;
1401         nvs_close(nvh);
1402
1403         if (n != 3) {
1404                 /* we are not configured for SSL yet... fall back to port 80 / http */
1405                 info->port = 80;
1406                 info->options &= ~LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
1407                 lwsl_notice("No SSL certs... using port 80\n");
1408         }
1409
1410         context = lws_create_context(info);
1411         if (context == NULL) {
1412                 lwsl_err("Failed to create context\n");
1413                 return NULL;
1414         }
1415
1416         lws_esp32_get_image_info(part, &i, buf, sizeof(buf) - 1);
1417         
1418         lws_esp32_romfs = (romfs_t)i.romfs;
1419         if (!romfs_mount_check(lws_esp32_romfs)) {
1420                 lwsl_err("Failed to mount ROMFS at %p 0x%x\n", lws_esp32_romfs, i.romfs);
1421                 return NULL;
1422         }
1423
1424         lwsl_notice("ROMFS length %uKiB\n", i.romfs_len >> 10);
1425
1426         puts(buf);
1427
1428         /* set the lws vfs to use our romfs */
1429
1430         lws_set_fops(context, &fops);
1431
1432         vhost = lws_create_vhost(context, info);
1433         if (!vhost)
1434                 lwsl_err("Failed to create vhost\n");
1435         else
1436                 lws_init_vhost_client_ssl(info, vhost); 
1437
1438         lws_protocol_init(context);
1439
1440         return context;
1441 }
1442
1443 static const uint16_t sineq16[] = {
1444         0x0000, 0x0191, 0x031e, 0x04a4, 0x061e, 0x0789, 0x08e2, 0x0a24,
1445         0x0b4e, 0x0c5c, 0x0d4b, 0x0e1a, 0x0ec6, 0x0f4d, 0x0faf, 0x0fea,
1446 };
1447
1448 static uint16_t sine_lu(int n)
1449 {
1450         switch ((n >> 4) & 3) {
1451         case 0:
1452                 return 4096 + sineq16[n & 15];
1453         case 1:
1454                 return 4096 + sineq16[15 - (n & 15)];
1455         case 2:
1456                 return 4096 - sineq16[n & 15];
1457         default:
1458                 return  4096 - sineq16[15 - (n & 15)];
1459         }
1460 }
1461
1462 /* useful for sine led fade patterns */
1463
1464 uint16_t lws_esp32_sine_interp(int n)
1465 {
1466         /*
1467          * 2: quadrant
1468          * 4: table entry in quadrant
1469          * 4: interp (LSB)
1470          *
1471          * total 10 bits / 1024 steps per cycle
1472          */
1473
1474         return (sine_lu(n >> 4) * (15 - (n & 15)) +
1475                 sine_lu((n >> 4) + 1) * (n & 15)) / 15;
1476 }
1477