esp32: make button debounce also available in factory
[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 int
437 lws_plat_inet_pton(int af, const char *src, void *dst)
438 {
439         return 1; //  inet_pton(af, src, dst);
440 }
441
442 LWS_VISIBLE lws_fop_fd_t IRAM_ATTR
443 _lws_plat_file_open(const struct lws_plat_file_ops *fops, const char *filename,
444                     const char *vpath, lws_fop_flags_t *flags)
445 {
446         struct stat stat_buf;
447         lws_fop_fd_t fop_fd;
448         int ret = open(filename, *flags, 0664);
449
450         if (ret < 0)
451                 return NULL;
452
453         if (fstat(ret, &stat_buf) < 0)
454                 goto bail;
455
456         fop_fd = malloc(sizeof(*fop_fd));
457         if (!fop_fd)
458                 goto bail;
459
460         fop_fd->fops = fops;
461         fop_fd->fd = ret;
462         fop_fd->flags = *flags;
463         fop_fd->filesystem_priv = NULL; /* we don't use it */
464         fop_fd->pos = 0;
465         fop_fd->len = stat_buf.st_size;
466
467         return fop_fd;
468
469 bail:
470         close(ret);
471
472         return NULL;
473 }
474
475 LWS_VISIBLE int IRAM_ATTR
476 _lws_plat_file_close(lws_fop_fd_t *fops_fd)
477 {
478         int fd = (*fops_fd)->fd;
479
480         free(*fops_fd);
481         *fops_fd = NULL;
482
483         return close(fd);
484 }
485
486 LWS_VISIBLE lws_fileofs_t IRAM_ATTR
487 _lws_plat_file_seek_cur(lws_fop_fd_t fops_fd, lws_fileofs_t offset)
488 {
489         return lseek(fops_fd->fd, offset, SEEK_CUR);
490 }
491
492 LWS_VISIBLE int IRAM_ATTR
493 _lws_plat_file_read(lws_fop_fd_t fops_fd, lws_filepos_t *amount,
494                     uint8_t *buf, lws_filepos_t len)
495 {
496         long n;
497
498         n = read(fops_fd->fd, buf, len);
499         if (n == -1) {
500                 *amount = 0;
501                 return -1;
502         }
503         fops_fd->pos += n;
504         *amount = n;
505
506         return 0;
507 }
508
509 LWS_VISIBLE int IRAM_ATTR
510 _lws_plat_file_write(lws_fop_fd_t fops_fd, lws_filepos_t *amount,
511                      uint8_t *buf, lws_filepos_t len)
512 {
513         long n;
514
515         n = write(fops_fd->fd, buf, len);
516         if (n == -1) {
517                 *amount = 0;
518                 return -1;
519         }
520         fops_fd->pos += n;
521         *amount = n;
522
523         return 0;
524 }
525
526
527 LWS_VISIBLE int
528 lws_plat_init(struct lws_context *context,
529               struct lws_context_creation_info *info)
530 {
531         /* master context has the global fd lookup array */
532         context->lws_lookup = lws_zalloc(sizeof(struct lws *) *
533                                          context->max_fds);
534         if (context->lws_lookup == NULL) {
535                 lwsl_err("OOM on lws_lookup array for %d connections\n",
536                          context->max_fds);
537                 return 1;
538         }
539
540         lwsl_notice(" mem: platform fd map: %5lu bytes\n",
541                     (unsigned long)(sizeof(struct lws *) * context->max_fds));
542
543 #ifdef LWS_WITH_PLUGINS
544         if (info->plugin_dirs)
545                 lws_plat_plugins_init(context, info->plugin_dirs);
546 #endif
547
548         return 0;
549 }
550
551
552 LWS_VISIBLE void esp32_uvtimer_cb(TimerHandle_t t)
553 {
554         struct timer_mapping *p = pvTimerGetTimerID(t);
555
556         p->cb(p->t);
557 }
558
559 void ERR_error_string_n(unsigned long e, char *buf, size_t len)
560 {
561         strncpy(buf, "unknown", len);
562 }
563
564 void ERR_free_strings(void)
565 {
566 }
567
568 char *ERR_error_string(unsigned long e, char *buf)
569 {
570         if (buf)
571                 strcpy(buf, "unknown");
572
573         return "unknown";
574 }
575
576
577 /* helper functionality */
578
579 #include "romfs.h"
580 #include <esp_ota_ops.h>
581 #include <tcpip_adapter.h>
582 #include <esp_image_format.h>
583 #include <esp_task_wdt.h>
584 #include "soc/ledc_reg.h"
585 #include "driver/ledc.h"
586
587 struct lws_esp32 lws_esp32 = {
588         .model = CONFIG_LWS_MODEL_NAME,
589         .serial = "unknown",
590         .region = WIFI_COUNTRY_US, // default to safest option
591 };
592
593 /*
594  * Group AP / Station State
595  */
596
597 enum lws_gapss {
598         LWS_GAPSS_INITIAL,      /* just started up, init and move to LWS_GAPSS_SCAN */
599         LWS_GAPSS_SCAN,         /*
600                                  * Unconnected, scanning: AP known in one of the config
601                                  * slots -> configure it, start timeout + LWS_GAPSS_STAT,
602                                  * if no AP already up in same group with lower MAC,
603                                  * after a random period start up our AP (LWS_GAPSS_AP)
604                                  */
605         LWS_GAPSS_AP,           /*
606                                  * Trying to be the group AP... periodically do a scan
607                                  * LWS_GAPSS_AP_SCAN, faster and then slower
608                                  */
609         LWS_GAPSS_AP_SCAN,      /*
610                                  * doing a scan while trying to be the group AP... if
611                                  * we see a lower MAC being the AP for the same group
612                                  * AP, abandon being an AP and join that AP as a
613                                  * station
614                                  */
615         LWS_GAPSS_STAT_GRP_AP,  /*
616                                  * We have decided to join another group member who is
617                                  * being the AP, as its MAC is lower than ours.  This
618                                  * is a stable state, but we still do periodic scans
619                                  * (LWS_GAPSS_STAT_GRP_AP_SCAN) and will always prefer
620                                  * an AP configured in a slot.
621                                  */
622         LWS_GAPSS_STAT_GRP_AP_SCAN,
623                                 /*
624                                  * We have joined a group member who is doing the AP
625                                  * job... we want to check every now and then if a
626                                  * configured AP has appeared that we should better
627                                  * use instead.  Otherwise stay in LWS_GAPSS_STAT_GRP_AP
628                                  */
629         LWS_GAPSS_STAT,         /*
630                                  * trying to connect to another non-group AP.  If we
631                                  * don't get an IP within a timeout and retries,
632                                  * blacklist it and go back 
633                                  */
634         LWS_GAPSS_STAT_HAPPY,
635 };
636
637 static const char *gapss_str[] = {
638         "LWS_GAPSS_INITIAL",
639         "LWS_GAPSS_SCAN",
640         "LWS_GAPSS_AP",
641         "LWS_GAPSS_AP_SCAN",
642         "LWS_GAPSS_STAT_GRP_AP",
643         "LWS_GAPSS_STAT_GRP_AP_SCAN",
644         "LWS_GAPSS_STAT",
645         "LWS_GAPSS_STAT_HAPPY",
646 };
647
648 static romfs_t lws_esp32_romfs;
649 static TimerHandle_t leds_timer, scan_timer, debounce_timer
650 #if !defined(CONFIG_LWS_IS_FACTORY_APPLICATION)
651 , mdns_timer
652 #endif
653 ;
654 static enum lws_gapss gapss = LWS_GAPSS_INITIAL;
655 static char bdown;
656
657 #define GPIO_SW 14
658
659 struct esp32_file {
660         const struct inode *i;
661 };
662
663 static void lws_gapss_to(enum lws_gapss to)
664 {
665         lwsl_notice("gapss from %s to %s\n", gapss_str[gapss], gapss_str[to]);
666         gapss = to;
667 }
668
669 uint32_t lws_esp32_get_reboot_type(void)
670 {
671         uint32_t *p = (uint32_t *)LWS_MAGIC_REBOOT_TYPE_ADS, val = *p;
672         nvs_handle nvh;
673         size_t s = 0;
674         int n = 0;
675
676         ESP_ERROR_CHECK(nvs_open("lws-station", NVS_READWRITE, &nvh));
677         if (nvs_get_blob(nvh, "ssl-pub.pem", NULL, &s) == ESP_OK)
678                 n = 1;
679         if (nvs_get_blob(nvh, "ssl-pri.pem", NULL, &s) == ESP_OK)
680                 n |= 2;
681         nvs_close(nvh);
682
683         /*
684          * in the case the SSL certs are not there, don't require
685          * the button to be down to access all features.
686          */
687         if (n != 3)
688                 val = LWS_MAGIC_REBOOT_TYPE_FORCED_FACTORY_BUTTON;
689
690         return val;
691 }
692
693 static void render_ip(char *dest, int len, uint8_t *ip)
694 {
695         snprintf(dest, len, "%u.%u.%u.%u", ip[0], ip[1], ip[2], ip[3]);
696 }
697
698 void lws_esp32_restart_guided(uint32_t type)
699 {
700         uint32_t *p_force_factory_magic = (uint32_t *)LWS_MAGIC_REBOOT_TYPE_ADS;
701
702         lwsl_notice("%s: %x\n", __func__, type);
703         *p_force_factory_magic = type;
704
705         esp_restart();
706 }
707
708 /*
709  * esp-idf goes crazy with zero length str nvs.  Use this as a workaround
710  * to delete the key in that case.
711  */
712
713 esp_err_t lws_nvs_set_str(nvs_handle handle, const char* key, const char* value)
714 {
715         if (*value)
716                 return nvs_set_str(handle, key, value);
717
718         return nvs_erase_key(handle, key);
719 }
720
721 static wifi_scan_config_t scan_config = {
722         .ssid = 0,
723         .bssid = 0,
724         .channel = 0,
725         .show_hidden = true
726 };
727
728 static char scan_ongoing = 0, scan_timer_exists = 0;
729 static int try_slot = -1;
730
731 static wifi_config_t config = {
732         .ap = {
733             .channel = 6,
734             .authmode = WIFI_AUTH_OPEN,
735             .max_connection = 1,
736         } }, sta_config = {
737         .sta = {
738                 .bssid_set = 0,
739         } };
740
741 static void lws_esp32_scan_timer_cb(TimerHandle_t th)
742 {
743         int n;
744
745         lwsl_notice("%s\n", __func__);
746         scan_ongoing = 0;
747         n = esp_wifi_scan_start(&scan_config, false);
748         if (n != ESP_OK)
749                 lwsl_err("scan start failed %d\n", n);
750 }
751
752 #if !defined(CONFIG_LWS_IS_FACTORY_APPLICATION)
753
754 void __attribute__(( weak ))
755 lws_group_member_event(int e, void *p)
756 {
757 }
758
759 void __attribute__(( weak ))
760 lws_get_iframe_size(int *w, int *h)
761 {
762         *w = 320;
763         *h = 160;
764 }
765
766 void lws_group_member_event_call(int e, void *p)
767 {
768         lws_group_member_event(e, p);
769 }
770
771 static int
772 get_txt_param(const char *txt, const char *param, char *result, int len)
773 {
774         const char *p;
775
776 again:
777         p = strstr(txt, param);
778         if (!p) {
779                 *result = '\0';
780                 return 1;
781         }
782
783         p += strlen(param);
784         if (*p != '=') {
785                 txt = p;
786                 goto again;
787         }
788         p++;
789         while (*p && *p != '&' && --len)
790                 *result++ = *p++;
791
792         *result = '\0';
793
794         return 0;
795 }
796
797 static void lws_esp32_mdns_timer_cb(TimerHandle_t th)
798 {
799         uint64_t now = time_in_microseconds(); 
800         struct lws_group_member *p, **p1;
801         const mdns_result_t *r;
802         int n, m;
803
804         if (!lws_esp32.mdns)
805                 return;
806         n = mdns_query_end(lws_esp32.mdns);
807
808         for (m = 0; m < n; m++) {
809                 char ch = 0, group[16];
810
811                 r = mdns_result_get(lws_esp32.mdns, m);
812
813                 get_txt_param(r->txt, "group", group, sizeof(group));
814                 if (strcmp(group, lws_esp32.group)) /* not our group */ {
815                         lwsl_notice("group %s vs %s  %s\n",
816                                         group, lws_esp32.group, r->txt);
817                         continue;
818                 }
819
820                 p = lws_esp32.first;
821                 while (p) {
822                         if (strcmp(r->host, p->host))
823                                 goto next;
824                         if (memcmp(&r->addr, &p->addr, sizeof(r->addr)))
825                                 goto next;
826
827                         p->last_seen = now;
828                         break;
829 next:
830                         p = p->next;
831                 }
832                 if (!p) { /* did not find */
833                         char temp[8];
834                         p = malloc(sizeof(*p));
835                         if (!p)
836                                 continue;
837                         strncpy(p->host, r->host, sizeof(p->host) - 1);
838                         p->host[sizeof(p->host) - 1] = '\0';
839
840                         get_txt_param(r->txt, "model", p->model, sizeof(p->model));
841                         get_txt_param(r->txt, "role", p->role, sizeof(p->role));
842                         get_txt_param(r->txt, "mac", p->mac, sizeof(p->mac));
843                         get_txt_param(r->txt, "width", temp, sizeof(temp));
844                         p->width = atoi(temp);
845                         get_txt_param(r->txt, "height", temp, sizeof(temp));
846                         p->height = atoi(temp);
847
848                         memcpy(&p->addr, &r->addr, sizeof(p->addr));
849                         memcpy(&p->addrv6, &r->addrv6, sizeof(p->addrv6));
850                         p->last_seen = now;
851                         p->flags = 0;
852                         p->next = lws_esp32.first;
853                         lws_esp32.first = p;
854                         lws_esp32.extant_group_members++;
855
856                         lws_group_member_event_call(LWS_SYSTEM_GROUP_MEMBER_ADD, p);
857                 } else {
858                         if (memcmp(&p->addr, &r->addr, sizeof(p->addr))) {
859                                 memcpy(&p->addr, &r->addr, sizeof(p->addr));
860                                 ch = 1;
861                         }
862                         if (memcmp(&p->addrv6, &r->addrv6, sizeof(p->addrv6))) {
863                                 memcpy(&p->addrv6, &r->addrv6, sizeof(p->addrv6));
864                                 ch = 1;
865                         }
866                         if (ch)
867                                 lws_group_member_event_call(LWS_SYSTEM_GROUP_MEMBER_CHANGE, p);
868                 }
869         }
870
871         mdns_result_free(lws_esp32.mdns);
872
873         /* garbage-collect group members not seen for too long */
874         p1 = &lws_esp32.first;
875         while (*p1) {
876                 p = *p1;
877                 if (!(p->flags & LWS_GROUP_FLAG_SELF) &&
878                                 now - p->last_seen > 60000000) {
879                         lws_esp32.extant_group_members--;
880                         *p1 = p->next;
881
882                         lws_group_member_event_call(LWS_SYSTEM_GROUP_MEMBER_REMOVE, p);
883                         free(p);
884                         continue;
885                 }
886                 p1 = &(*p1)->next;
887         }
888
889         mdns_query(lws_esp32.mdns, "_lwsgrmem", "_tcp", 0);
890         xTimerStart(mdns_timer, 0);
891 }
892 #endif
893
894 void __attribute__(( weak ))
895 lws_esp32_button(int down)
896 {
897 }
898
899 void IRAM_ATTR
900 gpio_irq(void *arg)
901 {
902         bdown ^= 1;
903         gpio_set_intr_type(GPIO_SW, GPIO_INTR_DISABLE);
904         xTimerStart(debounce_timer, 0);
905
906         lws_esp32_button(bdown);
907 }
908
909 static void lws_esp32_debounce_timer_cb(TimerHandle_t th)
910 {
911         if (bdown)
912                 gpio_set_intr_type(GPIO_SW, GPIO_INTR_POSEDGE);
913         else
914                 gpio_set_intr_type(GPIO_SW, GPIO_INTR_NEGEDGE);
915 }
916
917
918 static int
919 start_scan()
920 {
921         /* if no APs configured, no point... */
922
923         if (!lws_esp32.ssid[0][0] &&
924             !lws_esp32.ssid[1][0] &&
925             !lws_esp32.ssid[2][0] &&
926             !lws_esp32.ssid[3][0])
927                 return 0;
928
929         if (scan_timer_exists && !scan_ongoing) {
930                 // lwsl_notice("Starting scan timer...\n");
931                 scan_ongoing = 1;
932                 xTimerStart(scan_timer, 0);
933         }
934
935         return 0;
936 }
937
938
939
940 static void
941 end_scan()
942 {
943         wifi_ap_record_t ap_records[10];
944         uint16_t count_ap_records;
945         int n, m;
946
947         count_ap_records = ARRAY_SIZE(ap_records);
948         if (esp_wifi_scan_get_ap_records(&count_ap_records, ap_records) != ESP_OK) {
949                 lwsl_err("%s: failed\n", __func__);
950                 return;
951         }
952
953         if (!count_ap_records)
954                 goto passthru;
955
956         if (gapss != LWS_GAPSS_SCAN) {
957                 lwsl_notice("ignoring scan as gapss %s\n", gapss_str[gapss]);
958                 goto passthru;
959         }
960
961         /* no point if no APs set up */
962         if (!lws_esp32.ssid[0][0] &&
963             !lws_esp32.ssid[1][0] &&
964             !lws_esp32.ssid[2][0] &&
965             !lws_esp32.ssid[3][0])
966                 goto passthru;
967
968         lwsl_notice("checking %d scan records\n", count_ap_records);
969
970         for (n = 0; n < 4; n++) {
971
972                 if (!lws_esp32.ssid[(n + try_slot + 1) & 3][0])
973                         continue;
974
975                 lwsl_notice("looking for %s\n", lws_esp32.ssid[(n + try_slot + 1) & 3]);
976
977                 /* this ssid appears in scan results? */
978
979                 for (m = 0; m < count_ap_records; m++) {
980                         // lwsl_notice("  %s\n", ap_records[m].ssid);
981                         if (strcmp((char *)ap_records[m].ssid, lws_esp32.ssid[(n + try_slot + 1) & 3]) == 0)
982                                 goto hit;
983                 }
984
985                 continue;
986
987 hit:
988                 m = (n + try_slot + 1) & 3;
989                 try_slot = m;
990                 lwsl_notice("Attempting connection with slot %d: %s:\n", m,
991                                 lws_esp32.ssid[m]);
992                 /* set the ssid we last tried to connect to */
993                 strncpy(lws_esp32.active_ssid, lws_esp32.ssid[m],
994                                 sizeof(lws_esp32.active_ssid) - 1);
995                 lws_esp32.active_ssid[sizeof(lws_esp32.active_ssid) - 1] = '\0';
996
997                 strncpy((char *)sta_config.sta.ssid, lws_esp32.ssid[m], sizeof(sta_config.sta.ssid) - 1);
998                 strncpy((char *)sta_config.sta.password, lws_esp32.password[m], sizeof(sta_config.sta.password) - 1);
999
1000                 tcpip_adapter_set_hostname(TCPIP_ADAPTER_IF_STA, (const char *)&config.ap.ssid[7]);
1001                 lws_gapss_to(LWS_GAPSS_STAT);
1002
1003                 esp_wifi_set_config(WIFI_IF_STA, &sta_config);
1004                 esp_wifi_connect();
1005                 break;
1006         }
1007
1008         if (n == 4)
1009                 start_scan();
1010
1011 passthru:
1012         if (lws_esp32.scan_consumer)
1013                 lws_esp32.scan_consumer(count_ap_records, ap_records, lws_esp32.scan_consumer_arg);
1014
1015 }
1016
1017 static void
1018 lws_set_genled(int n)
1019 {
1020         lws_esp32.genled_t = time_in_microseconds();
1021         lws_esp32.genled = n;
1022 }
1023
1024 int
1025 lws_esp32_leds_network_indication(void)
1026 {
1027         uint64_t us, r;
1028         int n, fadein = 100, speed = 1199, div = 1, base = 0;
1029
1030         r = time_in_microseconds();
1031         us = r - lws_esp32.genled_t;
1032
1033         switch (lws_esp32.genled) {
1034         case LWSESP32_GENLED__INIT:
1035                 lws_esp32.genled = LWSESP32_GENLED__LOST_NETWORK;
1036                 /* fallthru */
1037         case LWSESP32_GENLED__LOST_NETWORK:
1038                 fadein = us / 10000; /* 100 steps in 1s */
1039                 if (fadein > 100) {
1040                         fadein = 100;
1041                         lws_esp32.genled = LWSESP32_GENLED__NO_NETWORK;
1042                 }
1043                 /* fallthru */
1044         case LWSESP32_GENLED__NO_NETWORK:
1045                 break;
1046         case LWSESP32_GENLED__CONN_AP:
1047                 base = 4096;
1048                 speed = 933;
1049                 div = 2;
1050                 break;
1051         case LWSESP32_GENLED__GOT_IP:
1052                 fadein = us / 10000; /* 100 steps in 1s */
1053                 if (fadein > 100) {
1054                         fadein = 100;
1055                         lws_esp32.genled = LWSESP32_GENLED__OK;
1056                 }
1057                 fadein = 100 - fadein; /* we are fading out */
1058                 /* fallthru */
1059         case LWSESP32_GENLED__OK:
1060                 if (lws_esp32.genled == LWSESP32_GENLED__OK)
1061                         return 0;
1062
1063                 base = 4096;
1064                 speed = 766;
1065                 div = 3;
1066                 break;
1067         }
1068
1069         n = base + (lws_esp32_sine_interp(r / speed) / div);
1070         return (n * fadein) / 100;
1071 }
1072
1073 esp_err_t lws_esp32_event_passthru(void *ctx, system_event_t *event)
1074 {
1075 #if !defined(CONFIG_LWS_IS_FACTORY_APPLICATION)
1076         struct lws_group_member *mem;
1077         int n;
1078 #endif
1079         char slot[8];
1080         nvs_handle nvh;
1081         uint32_t use;
1082
1083         switch((int)event->event_id) {
1084         case SYSTEM_EVENT_STA_START:
1085                 //esp_wifi_connect();
1086 //              break;
1087                 /* fallthru */
1088         case SYSTEM_EVENT_STA_DISCONNECTED:
1089                 lwsl_notice("SYSTEM_EVENT_STA_DISCONNECTED\n");
1090                 lws_esp32.conn_ap = 0;
1091                 lws_esp32.inet = 0;
1092                 lws_esp32.sta_ip[0] = '\0';
1093                 lws_esp32.sta_mask[0] = '\0';
1094                 lws_esp32.sta_gw[0] = '\0';
1095                 lws_gapss_to(LWS_GAPSS_SCAN);
1096                 if (lws_esp32.mdns)
1097                         mdns_service_remove_all(lws_esp32.mdns);
1098                 mdns_free(lws_esp32.mdns);
1099                 lws_esp32.mdns = NULL;
1100                 lws_set_genled(LWSESP32_GENLED__LOST_NETWORK);
1101                 start_scan();
1102                 esp_wifi_connect();
1103                 break;
1104
1105         case SYSTEM_EVENT_STA_CONNECTED:
1106                 lws_esp32.conn_ap = 1;
1107                 lws_set_genled(LWSESP32_GENLED__CONN_AP);
1108                 break;
1109
1110         case SYSTEM_EVENT_STA_GOT_IP:
1111                 lwsl_notice("SYSTEM_EVENT_STA_GOT_IP\n");
1112
1113                 lws_esp32.inet = 1;
1114                 lws_set_genled(LWSESP32_GENLED__GOT_IP);
1115
1116                 render_ip(lws_esp32.sta_ip, sizeof(lws_esp32.sta_ip) - 1,
1117                                 (uint8_t *)&event->event_info.got_ip.ip_info.ip);
1118                 render_ip(lws_esp32.sta_mask, sizeof(lws_esp32.sta_mask) - 1,
1119                                 (uint8_t *)&event->event_info.got_ip.ip_info.netmask);
1120                 render_ip(lws_esp32.sta_gw, sizeof(lws_esp32.sta_gw) - 1,
1121                                 (uint8_t *)&event->event_info.got_ip.ip_info.gw);
1122
1123                 if (!nvs_open("lws-station", NVS_READWRITE, &nvh)) {
1124                         lws_snprintf(slot, sizeof(slot) - 1, "%duse", try_slot);
1125                         use = 0;
1126                         nvs_get_u32(nvh, slot, &use);
1127                         nvs_set_u32(nvh, slot, use + 1);
1128                         nvs_commit(nvh);
1129                         nvs_close(nvh);
1130                 }
1131
1132                 lws_gapss_to(LWS_GAPSS_STAT_HAPPY);
1133
1134 #if !defined(CONFIG_LWS_IS_FACTORY_APPLICATION)
1135                 n = mdns_init(TCPIP_ADAPTER_IF_STA, &lws_esp32.mdns);
1136                 if (!n) {
1137                         static char *txta[6];
1138                         int w, h;
1139
1140                         mdns_set_hostname(lws_esp32.mdns, lws_esp32.hostname);
1141                         mdns_set_instance(lws_esp32.mdns, lws_esp32.group);
1142                         mdns_service_add(lws_esp32.mdns, "_lwsgrmem", "_tcp", 443);
1143                         if (txta[0])
1144                                 free(txta[0]);
1145                         txta[0] = malloc(32 * ARRAY_SIZE(txta));
1146                         if (!txta[0]) {
1147                                 lwsl_notice("mdns OOM\n");
1148                                 break;
1149                         }
1150                         txta[1] = &txta[0][32];
1151                         txta[2] = &txta[1][32];
1152                         txta[3] = &txta[2][32];
1153                         txta[4] = &txta[3][32];
1154                         txta[5] = &txta[4][32];
1155
1156                         lws_get_iframe_size(&w, &h);
1157
1158                         lws_snprintf(txta[0], 31, "model=%s", lws_esp32.model);
1159                         lws_snprintf(txta[1], 31, "group=%s", lws_esp32.group);
1160                         lws_snprintf(txta[2], 31, "role=%s", lws_esp32.role);
1161                         lws_snprintf(txta[3], 31, "mac=%s", lws_esp32.mac);
1162                         lws_snprintf(txta[4], 31, "width=%d", w);
1163                         lws_snprintf(txta[5], 31, "height=%d", h);
1164
1165                         mem = lws_esp32.first;
1166                         while (mem) {
1167                                 if (mem->flags & 1)
1168                                         break;
1169                                 mem = mem->next;
1170                         }
1171
1172                         if (!mem) {
1173                                 struct lws_group_member *mem = malloc(sizeof(*mem));
1174                                 if (mem) {
1175                                         mem->last_seen = ~(uint64_t)0;
1176                                         strcpy(mem->model, lws_esp32.model);
1177                                         strcpy(mem->role, lws_esp32.role);
1178                                         strcpy(mem->host, lws_esp32.hostname);
1179                                         strcpy(mem->mac, lws_esp32.mac);
1180                                         mem->flags = LWS_GROUP_FLAG_SELF;
1181                                         lws_get_iframe_size(&mem->width, &mem->height);
1182                                         memcpy(&mem->addr, &event->event_info.got_ip.ip_info.ip,
1183                                                         sizeof(mem->addr));
1184                                         memcpy(&mem->addrv6, &event->event_info.got_ip6.ip6_info.ip,
1185                                                         sizeof(mem->addrv6));
1186                                         mem->next = lws_esp32.first;
1187                                         lws_esp32.first = mem;
1188                                         lws_esp32.extant_group_members++;
1189
1190                                         lws_group_member_event_call(LWS_SYSTEM_GROUP_MEMBER_ADD, mem);
1191                                 }
1192                         } else { /* update our IP */
1193                                         memcpy(&mem->addr, &event->event_info.got_ip.ip_info.ip,
1194                                                         sizeof(mem->addr));
1195                                         memcpy(&mem->addrv6, &event->event_info.got_ip6.ip6_info.ip,
1196                                                         sizeof(mem->addrv6));
1197                                         lws_group_member_event_call(LWS_SYSTEM_GROUP_MEMBER_CHANGE, mem);
1198                         }
1199
1200
1201                         if (mdns_service_txt_set(lws_esp32.mdns, "_lwsgrmem", "_tcp", ARRAY_SIZE(txta),
1202                                                  (const char **)txta))
1203                                 lwsl_notice("txt set failed\n");
1204                 } else
1205                         lwsl_err("unable to init mdns on STA: %d\n", n);
1206
1207                 mdns_query(lws_esp32.mdns, "_lwsgrmem", "_tcp", 0);
1208                 xTimerStart(mdns_timer, 0);
1209 #endif
1210
1211                 lwsl_notice(" --- Got IP %s\n", lws_esp32.sta_ip);
1212                 break;
1213
1214         case SYSTEM_EVENT_SCAN_DONE:
1215                 lwsl_notice("SYSTEM_EVENT_SCAN_DONE\n");
1216                 end_scan();
1217                 break;
1218
1219         default:
1220                 break;
1221         }
1222
1223         return ESP_OK;
1224 }
1225
1226 static lws_fop_fd_t IRAM_ATTR
1227 esp32_lws_fops_open(const struct lws_plat_file_ops *fops, const char *filename,
1228                 const char *vfs_path, lws_fop_flags_t *flags)
1229 {
1230         struct esp32_file *f = malloc(sizeof(*f));
1231         lws_fop_fd_t fop_fd;
1232         size_t len, csum;
1233
1234         lwsl_notice("%s: %s\n", __func__, filename);
1235
1236         if (!f)
1237                 return NULL;
1238         f->i = romfs_get_info(lws_esp32_romfs, filename, &len, &csum);
1239         if (!f->i)
1240                 goto bail;
1241
1242         fop_fd = malloc(sizeof(*fop_fd));
1243         if (!fop_fd)
1244                 goto bail;
1245
1246         fop_fd->fops = fops;
1247         fop_fd->filesystem_priv = f;
1248         fop_fd->mod_time = csum;
1249         *flags |= LWS_FOP_FLAG_MOD_TIME_VALID;
1250         fop_fd->flags = *flags;
1251         
1252         fop_fd->len = len;
1253         fop_fd->pos = 0;
1254
1255         return fop_fd;
1256
1257 bail:
1258         free(f);
1259
1260         return NULL;
1261 }
1262
1263 static int IRAM_ATTR
1264 esp32_lws_fops_close(lws_fop_fd_t *fop_fd)
1265 {
1266         free((*fop_fd)->filesystem_priv);
1267         free(*fop_fd);
1268
1269         *fop_fd = NULL;
1270
1271         return 0;
1272 }
1273 static lws_fileofs_t IRAM_ATTR
1274 esp32_lws_fops_seek_cur(lws_fop_fd_t fop_fd, lws_fileofs_t offset_from_cur_pos)
1275 {
1276         fop_fd->pos += offset_from_cur_pos;
1277         
1278         if (fop_fd->pos > fop_fd->len)
1279                 fop_fd->pos = fop_fd->len;
1280
1281        return 0;
1282 }
1283
1284 static int IRAM_ATTR
1285 esp32_lws_fops_read(lws_fop_fd_t fop_fd, lws_filepos_t *amount, uint8_t *buf,
1286                    lws_filepos_t len)
1287 {
1288        struct esp32_file *f = fop_fd->filesystem_priv;
1289 #if 0
1290        if ((long)buf & 3) {
1291                lwsl_err("misaligned buf\n");
1292
1293                return -1;
1294        }
1295 #endif
1296        if (fop_fd->pos >= fop_fd->len)
1297                return 0;
1298
1299        if (len > fop_fd->len - fop_fd->pos)
1300                len = fop_fd->len - fop_fd->pos;
1301
1302        spi_flash_read((uint32_t)(char *)f->i + fop_fd->pos, buf, len);
1303
1304        *amount = len;
1305        fop_fd->pos += len;
1306
1307        return 0;
1308 }
1309
1310 static const struct lws_plat_file_ops fops = {
1311         .next = &fops_zip,
1312         .LWS_FOP_OPEN = esp32_lws_fops_open,
1313         .LWS_FOP_CLOSE = esp32_lws_fops_close,
1314         .LWS_FOP_READ = esp32_lws_fops_read,
1315         .LWS_FOP_SEEK_CUR = esp32_lws_fops_seek_cur,
1316 };
1317
1318 int
1319 lws_esp32_wlan_nvs_get(int retry)
1320 {
1321         nvs_handle nvh;
1322         char r[2], lws_esp32_force_ap = 0, slot[12];
1323         size_t s;
1324         uint8_t mac[6];
1325         int n;
1326
1327         esp_efuse_mac_get_default(mac);
1328         mac[5] |= 1; /* match the AP MAC */
1329         snprintf(lws_esp32.serial, sizeof(lws_esp32.serial) - 1, "%02X%02X%02X", mac[3], mac[4], mac[5]);
1330         snprintf(lws_esp32.mac, sizeof(lws_esp32.mac) - 1, "%02X%02X%02X%02X%02X%02X", mac[0],
1331                         mac[1], mac[2], mac[3], mac[4], mac[5]);
1332
1333         ESP_ERROR_CHECK(nvs_open("lws-station", NVS_READWRITE, &nvh));
1334
1335         config.sta.ssid[0] = '\0';
1336         config.sta.password[0] = '\0';
1337
1338         for (n = 0; n < 4; n++) {
1339                 lws_snprintf(slot, sizeof(slot) - 1, "%dssid", n);
1340                 s = sizeof(lws_esp32.ssid[0]) - 1;
1341                 lws_esp32.ssid[n][0] = '\0';
1342                 nvs_get_str(nvh, slot, lws_esp32.ssid[n], &s);
1343
1344                 lws_snprintf(slot, sizeof(slot) - 1, "%dpassword", n);
1345                 s = sizeof(lws_esp32.password[0]) - 1;
1346                 lws_esp32.password[n][0] = '\0';
1347                 nvs_get_str(nvh, slot, lws_esp32.password[n], &s);
1348         }
1349
1350         s = sizeof(lws_esp32.serial) - 1;
1351         if (nvs_get_str(nvh, "serial", lws_esp32.serial, &s) != ESP_OK)
1352                 lws_esp32_force_ap = 1;
1353         else
1354                 snprintf((char *)config.ap.ssid, sizeof(config.ap.ssid) - 1,
1355                          "config-%s-%s", lws_esp32.model, lws_esp32.serial);
1356         s = sizeof(lws_esp32.opts) - 1;
1357         if (nvs_get_str(nvh, "opts", lws_esp32.opts, &s) != ESP_OK)
1358                 lws_esp32_force_ap = 1;
1359
1360         s = sizeof(r);
1361         if (nvs_get_str(nvh, "region", r, &s) != ESP_OK)
1362                 lws_esp32_force_ap = 1;
1363         else
1364                 lws_esp32.region = atoi(r);
1365         lws_esp32.access_pw[0] = '\0';
1366         nvs_get_str(nvh, "access_pw", lws_esp32.access_pw, &s);
1367
1368         lws_esp32.group[0] = '\0';
1369         s = sizeof(lws_esp32.group);
1370         nvs_get_str(nvh, "group", lws_esp32.group, &s);
1371
1372         lws_esp32.role[0] = '\0';
1373         s = sizeof(lws_esp32.role);
1374         nvs_get_str(nvh, "role", lws_esp32.role, &s);
1375
1376         /* if group and role defined: group-role */
1377         if (lws_esp32.group[0] && lws_esp32.role[0])
1378                 lws_snprintf(lws_esp32.hostname, sizeof(lws_esp32.hostname) - 1,
1379                                 "%s-%s", lws_esp32.group, lws_esp32.role);
1380         else /* otherwise model-serial */
1381                 lws_snprintf(lws_esp32.hostname, sizeof(lws_esp32.hostname) - 1,
1382                                 "%s-%s", lws_esp32.model, lws_esp32.serial);
1383
1384         nvs_close(nvh);
1385
1386         lws_gapss_to(LWS_GAPSS_SCAN);
1387         start_scan();
1388
1389         return lws_esp32_force_ap;
1390 }
1391
1392
1393 void
1394 lws_esp32_wlan_config(void)
1395 {
1396         ledc_timer_config_t ledc_timer = {
1397                 .bit_num = LEDC_TIMER_13_BIT,
1398                 .freq_hz = 5000,
1399                 .speed_mode = LEDC_HIGH_SPEED_MODE,
1400                 .timer_num = LEDC_TIMER_0
1401         };
1402         int n;
1403
1404         ledc_timer_config(&ledc_timer);
1405
1406         lws_set_genled(LWSESP32_GENLED__INIT);
1407
1408         /* user code needs to provide lws_esp32_leds_timer_cb */
1409
1410         leds_timer = xTimerCreate("lws_leds", pdMS_TO_TICKS(25), 1, NULL,
1411                           (TimerCallbackFunction_t)lws_esp32_leds_timer_cb);
1412         scan_timer = xTimerCreate("lws_scan", pdMS_TO_TICKS(10000), 0, NULL,
1413                           (TimerCallbackFunction_t)lws_esp32_scan_timer_cb);
1414         debounce_timer = xTimerCreate("lws_db", pdMS_TO_TICKS(100), 0, NULL,
1415                           (TimerCallbackFunction_t)lws_esp32_debounce_timer_cb);
1416
1417 #if !defined(CONFIG_LWS_IS_FACTORY_APPLICATION)
1418         mdns_timer = xTimerCreate("lws_mdns", pdMS_TO_TICKS(5000), 0, NULL,
1419                           (TimerCallbackFunction_t)lws_esp32_mdns_timer_cb);
1420 #endif
1421         scan_timer_exists = 1;
1422         xTimerStart(leds_timer, 0);
1423
1424         *(volatile uint32_t *)PERIPHS_IO_MUX_MTMS_U = FUNC_MTMS_GPIO14;
1425
1426         gpio_output_set(0, 0, 0, (1 << GPIO_SW));
1427
1428         n = gpio_install_isr_service(0);
1429         if (!n) {
1430                 gpio_config_t c;
1431
1432                 c.intr_type = GPIO_INTR_NEGEDGE;
1433                 c.mode = GPIO_MODE_INPUT;
1434                 c.pin_bit_mask = 1 << GPIO_SW;
1435                 c.pull_down_en = 0;
1436                 c.pull_up_en = 0;
1437                 gpio_config(&c);
1438
1439                 if (gpio_isr_handler_add(GPIO_SW, gpio_irq, NULL))
1440                         lwsl_notice("isr handler add for 14 failed\n");
1441         } else
1442                 lwsl_notice("failed to install gpio isr service: %d\n", n);
1443
1444         lws_esp32_wlan_nvs_get(0);
1445         tcpip_adapter_init();
1446 }
1447
1448 void
1449 lws_esp32_wlan_start_ap(void)
1450 {
1451         wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
1452
1453         ESP_ERROR_CHECK( esp_wifi_init(&cfg));
1454         ESP_ERROR_CHECK( esp_wifi_set_storage(WIFI_STORAGE_RAM));
1455         esp_wifi_set_country(lws_esp32.region);
1456
1457         ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_APSTA) );
1458         ESP_ERROR_CHECK( esp_wifi_set_config(WIFI_IF_AP, &config) );
1459         ESP_ERROR_CHECK( esp_wifi_set_config(WIFI_IF_STA, &sta_config));
1460         ESP_ERROR_CHECK( esp_wifi_start());
1461
1462         esp_wifi_scan_start(&scan_config, false);
1463
1464         if (sta_config.sta.ssid[0]) {
1465                 tcpip_adapter_set_hostname(TCPIP_ADAPTER_IF_STA, (const char *)&config.ap.ssid[7]);
1466                 esp_wifi_set_auto_connect(1);
1467                 ESP_ERROR_CHECK( esp_wifi_connect());
1468                 ESP_ERROR_CHECK( esp_wifi_set_config(WIFI_IF_STA, &sta_config));
1469                 ESP_ERROR_CHECK( esp_wifi_connect());
1470         }
1471 }
1472
1473 void
1474 lws_esp32_wlan_start_station(void)
1475 {
1476         wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
1477
1478         ESP_ERROR_CHECK( esp_wifi_init(&cfg));
1479         ESP_ERROR_CHECK( esp_wifi_set_storage(WIFI_STORAGE_RAM));
1480         esp_wifi_set_country(lws_esp32.region);
1481
1482         ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_STA));
1483         ESP_ERROR_CHECK( esp_wifi_set_config(WIFI_IF_STA, &sta_config));
1484
1485         ESP_ERROR_CHECK( esp_wifi_start());
1486
1487         tcpip_adapter_set_hostname(TCPIP_ADAPTER_IF_STA, (const char *)&config.ap.ssid[7]);
1488         esp_wifi_set_auto_connect(1);
1489         ESP_ERROR_CHECK( esp_wifi_connect());
1490
1491         lws_esp32_scan_timer_cb(NULL);
1492 }
1493
1494 const esp_partition_t *
1495 lws_esp_ota_get_boot_partition(void)
1496 {
1497         const esp_partition_t *part = esp_ota_get_boot_partition(), *factory_part, *ota;
1498         esp_image_header_t eih, ota_eih;
1499         uint32_t *p_force_factory_magic = (uint32_t *)LWS_MAGIC_REBOOT_TYPE_ADS;
1500
1501         /* confirm what we are told is the boot part is sane */
1502         spi_flash_read(part->address , &eih, sizeof(eih));
1503         factory_part = esp_partition_find_first(ESP_PARTITION_TYPE_APP,
1504                         ESP_PARTITION_SUBTYPE_APP_FACTORY, NULL);
1505         ota = esp_partition_find_first(ESP_PARTITION_TYPE_APP,
1506                         ESP_PARTITION_SUBTYPE_APP_OTA_0, NULL);
1507         spi_flash_read(ota->address , &ota_eih, sizeof(ota_eih));
1508
1509         if (eih.spi_mode == 0xff ||
1510             *p_force_factory_magic == LWS_MAGIC_REBOOT_TYPE_FORCED_FACTORY ||
1511             *p_force_factory_magic == LWS_MAGIC_REBOOT_TYPE_FORCED_FACTORY_BUTTON
1512            ) {
1513                 /*
1514                  * we believed we were going to boot OTA, but we fell
1515                  * back to FACTORY in the bootloader when we saw it
1516                  * had been erased.  esp_ota_get_boot_partition() still
1517                  * says the OTA partition then even if we are in the
1518                  * factory partition right now.
1519                  */
1520                 part = factory_part;
1521         } 
1522         
1523 #ifdef CONFIG_LWS_IS_FACTORY_APPLICATION
1524         else
1525                 if (ota_eih.spi_mode != 0xff &&
1526                     part->address != factory_part->address) {
1527                         uint8_t buf[4096];
1528                         uint32_t n;
1529                         /*
1530                          * we are a FACTORY image running in an OTA slot...
1531                          * it means we were just written and need to copy
1532                          * ourselves into the FACTORY slot.
1533                          */
1534                         lwsl_notice("Copying FACTORY update into place 0x%x len 0x%x\n",
1535                                     factory_part->address, factory_part->size);
1536                         esp_task_wdt_feed();
1537                         if (spi_flash_erase_range(factory_part->address, factory_part->size) != ESP_OK) {
1538                                 lwsl_err("spi: Failed to erase\n");
1539                                 goto retry;
1540                         }
1541
1542                         for (n = 0; n < factory_part->size; n += sizeof(buf)) {
1543                                 esp_task_wdt_feed();
1544                                 spi_flash_read(part->address + n , buf, sizeof(buf));
1545                                 if (spi_flash_write(factory_part->address + n, buf, sizeof(buf)) != ESP_OK) {
1546                                         lwsl_err("spi: Failed to write\n");
1547                                         goto retry;
1548                                 }
1549                         }
1550
1551                         /* destroy our OTA image header */
1552                         spi_flash_erase_range(ota->address, 4096);
1553
1554                         /*
1555                          * with no viable OTA image, we will come back up in factory
1556                          * where the user can reload the OTA image
1557                          */
1558                         lwsl_notice("  FACTORY copy successful, rebooting\n");
1559 retry:
1560                         esp_restart();
1561                 }
1562 #endif
1563
1564         return part;
1565 }
1566
1567
1568 void
1569 lws_esp32_set_creation_defaults(struct lws_context_creation_info *info)
1570 {
1571         const esp_partition_t *part;
1572
1573         memset(info, 0, sizeof(*info));
1574
1575         lws_set_log_level(63, lwsl_emit_syslog);
1576
1577         part = lws_esp_ota_get_boot_partition();
1578         (void)part;
1579
1580         info->port = 443;
1581         info->fd_limit_per_thread = 30;
1582         info->max_http_header_pool = 3;
1583         info->max_http_header_data = 1024;
1584         info->pt_serv_buf_size = 4096;
1585         info->keepalive_timeout = 30;
1586         info->timeout_secs = 30;
1587         info->simultaneous_ssl_restriction = 3;
1588         info->options = LWS_SERVER_OPTION_EXPLICIT_VHOSTS |
1589                        LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
1590
1591         info->ssl_cert_filepath = "ssl-pub.pem";
1592         info->ssl_private_key_filepath = "ssl-pri.pem";
1593 }
1594
1595 int
1596 lws_esp32_get_image_info(const esp_partition_t *part, struct lws_esp32_image *i,
1597                          char *json, int json_len)
1598 {
1599         esp_image_segment_header_t eis;
1600         esp_image_header_t eih;
1601         uint32_t hdr;
1602
1603         spi_flash_read(part->address , &eih, sizeof(eih));
1604         hdr = part->address + sizeof(eih);
1605
1606         if (eih.magic != ESP_IMAGE_HEADER_MAGIC)
1607                 return 1;
1608
1609         eis.data_len = 0;
1610         while (eih.segment_count-- && eis.data_len != 0xffffffff) {
1611                 spi_flash_read(hdr, &eis, sizeof(eis));
1612                 hdr += sizeof(eis) + eis.data_len;
1613         }
1614         hdr += (~hdr & 15) + 1;
1615
1616         i->romfs = hdr + 4;
1617         spi_flash_read(hdr, &i->romfs_len, sizeof(i->romfs_len));
1618         i->json = i->romfs + i->romfs_len + 4;
1619         spi_flash_read(i->json - 4, &i->json_len, sizeof(i->json_len));
1620
1621         if (i->json_len < json_len - 1)
1622                 json_len = i->json_len;
1623         spi_flash_read(i->json, json, json_len);
1624         json[json_len] = '\0';
1625
1626         return 0;
1627 }
1628
1629 struct lws_context *
1630 lws_esp32_init(struct lws_context_creation_info *info)
1631 {
1632         const esp_partition_t *part = lws_esp_ota_get_boot_partition();
1633         struct lws_context *context;
1634         struct lws_esp32_image i;
1635         struct lws_vhost *vhost;
1636         nvs_handle nvh;
1637         char buf[512];
1638         size_t s;
1639         int n;
1640
1641         ESP_ERROR_CHECK(nvs_open("lws-station", NVS_READWRITE, &nvh));
1642         n = 0;
1643         s = 1;
1644         if (nvs_get_blob(nvh, "ssl-pub.pem", NULL, &s) == ESP_OK)
1645                 n = 1;
1646         s = 1;
1647         if (nvs_get_blob(nvh, "ssl-pri.pem", NULL, &s) == ESP_OK)
1648                 n |= 2;
1649         nvs_close(nvh);
1650
1651         if (n != 3) {
1652                 /* we are not configured for SSL yet... fall back to port 80 / http */
1653                 info->port = 80;
1654                 info->options &= ~LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
1655                 lwsl_notice("No SSL certs... using port 80\n");
1656         }
1657
1658         context = lws_create_context(info);
1659         if (context == NULL) {
1660                 lwsl_err("Failed to create context\n");
1661                 return NULL;
1662         }
1663
1664         lws_esp32_get_image_info(part, &i, buf, sizeof(buf) - 1);
1665         
1666         lws_esp32_romfs = (romfs_t)i.romfs;
1667         if (!romfs_mount_check(lws_esp32_romfs)) {
1668                 lwsl_err("Failed to mount ROMFS at %p 0x%x\n", lws_esp32_romfs, i.romfs);
1669                 return NULL;
1670         }
1671
1672         lwsl_notice("ROMFS length %uKiB\n", i.romfs_len >> 10);
1673
1674         puts(buf);
1675
1676         /* set the lws vfs to use our romfs */
1677
1678         lws_set_fops(context, &fops);
1679
1680         vhost = lws_create_vhost(context, info);
1681         if (!vhost)
1682                 lwsl_err("Failed to create vhost\n");
1683         else
1684                 lws_init_vhost_client_ssl(info, vhost); 
1685
1686         lws_protocol_init(context);
1687
1688         return context;
1689 }
1690
1691 static const uint16_t sineq16[] = {
1692         0x0000, 0x0191, 0x031e, 0x04a4, 0x061e, 0x0789, 0x08e2, 0x0a24,
1693         0x0b4e, 0x0c5c, 0x0d4b, 0x0e1a, 0x0ec6, 0x0f4d, 0x0faf, 0x0fea,
1694 };
1695
1696 static uint16_t sine_lu(int n)
1697 {
1698         switch ((n >> 4) & 3) {
1699         case 1:
1700                 return 4096 + sineq16[n & 15];
1701         case 2:
1702                 return 4096 + sineq16[15 - (n & 15)];
1703         case 3:
1704                 return 4096 - sineq16[n & 15];
1705         default:
1706                 return  4096 - sineq16[15 - (n & 15)];
1707         }
1708 }
1709
1710 /* useful for sine led fade patterns */
1711
1712 uint16_t lws_esp32_sine_interp(int n)
1713 {
1714         /*
1715          * 2: quadrant
1716          * 4: table entry in quadrant
1717          * 4: interp (LSB)
1718          *
1719          * total 10 bits / 1024 steps per cycle
1720          *
1721          * +   0: 0
1722          * + 256: 4096
1723          * + 512: 8192
1724          * + 768: 4096
1725          * +1023: 0
1726          */
1727
1728         return (sine_lu(n >> 4) * (15 - (n & 15)) +
1729                 sine_lu((n >> 4) + 1) * (n & 15)) / 15;
1730 }
1731