1 /*
2  * Copyright (c) 2019 Tobias Svehagen
3  * Copyright (c) 2020 Grinn
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #define DT_DRV_COMPAT espressif_esp_at
9 
10 #undef _POSIX_C_SOURCE
11 #define _POSIX_C_SOURCE 200809L
12 
13 #include <zephyr/logging/log.h>
14 LOG_MODULE_REGISTER(wifi_esp_at, CONFIG_WIFI_LOG_LEVEL);
15 
16 #include <zephyr/kernel.h>
17 #include <ctype.h>
18 #include <errno.h>
19 #include <zephyr/device.h>
20 #include <zephyr/init.h>
21 #include <stdlib.h>
22 #include <string.h>
23 
24 #include <zephyr/drivers/gpio.h>
25 #include <zephyr/drivers/uart.h>
26 
27 #include <zephyr/net/dns_resolve.h>
28 #include <zephyr/net/net_if.h>
29 #include <zephyr/net/net_ip.h>
30 #include <zephyr/net/net_offload.h>
31 #include <zephyr/net/wifi_mgmt.h>
32 #include <zephyr/net/conn_mgr/connectivity_wifi_mgmt.h>
33 
34 #include "esp.h"
35 
36 struct esp_config {
37 #if DT_INST_NODE_HAS_PROP(0, power_gpios)
38 	const struct gpio_dt_spec power;
39 #endif
40 #if DT_INST_NODE_HAS_PROP(0, reset_gpios)
41 	const struct gpio_dt_spec reset;
42 #endif
43 };
44 
45 NET_BUF_POOL_DEFINE(mdm_recv_pool, MDM_RECV_MAX_BUF, MDM_RECV_BUF_SIZE,
46 		    0, NULL);
47 
48 /* RX thread structures */
49 K_KERNEL_STACK_DEFINE(esp_rx_stack,
50 		      CONFIG_WIFI_ESP_AT_RX_STACK_SIZE);
51 struct k_thread esp_rx_thread;
52 
53 /* RX thread work queue */
54 K_KERNEL_STACK_DEFINE(esp_workq_stack,
55 		      CONFIG_WIFI_ESP_AT_WORKQ_STACK_SIZE);
56 
57 static const struct esp_config esp_driver_config = {
58 #if DT_INST_NODE_HAS_PROP(0, power_gpios)
59 	.power = GPIO_DT_SPEC_INST_GET(0, power_gpios),
60 #endif
61 #if DT_INST_NODE_HAS_PROP(0, reset_gpios)
62 	.reset = GPIO_DT_SPEC_INST_GET(0, reset_gpios),
63 #endif
64 };
65 struct esp_data esp_driver_data;
66 
esp_configure_hostname(struct esp_data * data)67 static void esp_configure_hostname(struct esp_data *data)
68 {
69 #if defined(CONFIG_NET_HOSTNAME_ENABLE)
70 	char cmd[sizeof("AT+CWHOSTNAME=\"\"") + NET_HOSTNAME_MAX_LEN];
71 
72 	snprintk(cmd, sizeof(cmd), "AT+CWHOSTNAME=\"%s\"", net_hostname_get());
73 	cmd[sizeof(cmd) - 1] = '\0';
74 
75 	esp_cmd_send(data, NULL, 0, cmd, ESP_CMD_TIMEOUT);
76 #else
77 	ARG_UNUSED(data);
78 #endif
79 }
80 
esp_mode_from_flags(struct esp_data * data)81 static inline uint8_t esp_mode_from_flags(struct esp_data *data)
82 {
83 	uint8_t flags = data->flags;
84 	uint8_t mode = 0;
85 
86 	if (flags & (EDF_STA_CONNECTED | EDF_STA_LOCK)) {
87 		mode |= ESP_MODE_STA;
88 	}
89 
90 	if (flags & EDF_AP_ENABLED) {
91 		mode |= ESP_MODE_AP;
92 	}
93 
94 	/*
95 	 * ESP AT 1.7 does not allow to disable radio, so enter STA mode
96 	 * instead.
97 	 */
98 	if (IS_ENABLED(CONFIG_WIFI_ESP_AT_VERSION_1_7) &&
99 	    mode == ESP_MODE_NONE) {
100 		mode = ESP_MODE_STA;
101 	}
102 
103 	return mode;
104 }
105 
esp_mode_switch(struct esp_data * data,uint8_t mode)106 static int esp_mode_switch(struct esp_data *data, uint8_t mode)
107 {
108 	char cmd[] = "AT+"_CWMODE"=X";
109 	int err;
110 
111 	cmd[sizeof(cmd) - 2] = ('0' + mode);
112 	LOG_DBG("Switch to mode %hhu", mode);
113 
114 	err = esp_cmd_send(data, NULL, 0, cmd, ESP_CMD_TIMEOUT);
115 	if (err) {
116 		LOG_WRN("Failed to switch to mode %d: %d", (int) mode, err);
117 	}
118 
119 	return err;
120 }
121 
esp_mode_switch_if_needed(struct esp_data * data)122 static int esp_mode_switch_if_needed(struct esp_data *data)
123 {
124 	uint8_t new_mode = esp_mode_from_flags(data);
125 	uint8_t old_mode = data->mode;
126 	int err;
127 
128 	if (old_mode == new_mode) {
129 		return 0;
130 	}
131 
132 	data->mode = new_mode;
133 
134 	err = esp_mode_switch(data, new_mode);
135 	if (err) {
136 		return err;
137 	}
138 
139 	if (!(old_mode & ESP_MODE_STA) && (new_mode & ESP_MODE_STA)) {
140 		/*
141 		 * Hostname change is applied only when STA is enabled.
142 		 */
143 		esp_configure_hostname(data);
144 	}
145 
146 	return 0;
147 }
148 
esp_mode_switch_submit_if_needed(struct esp_data * data)149 static void esp_mode_switch_submit_if_needed(struct esp_data *data)
150 {
151 	if (data->mode != esp_mode_from_flags(data)) {
152 		k_work_submit_to_queue(&data->workq, &data->mode_switch_work);
153 	}
154 }
155 
esp_mode_switch_work(struct k_work * work)156 static void esp_mode_switch_work(struct k_work *work)
157 {
158 	struct esp_data *data =
159 		CONTAINER_OF(work, struct esp_data, mode_switch_work);
160 
161 	(void)esp_mode_switch_if_needed(data);
162 }
163 
esp_mode_flags_set(struct esp_data * data,uint8_t flags)164 static inline int esp_mode_flags_set(struct esp_data *data, uint8_t flags)
165 {
166 	esp_flags_set(data, flags);
167 
168 	return esp_mode_switch_if_needed(data);
169 }
170 
esp_mode_flags_clear(struct esp_data * data,uint8_t flags)171 static inline int esp_mode_flags_clear(struct esp_data *data, uint8_t flags)
172 {
173 	esp_flags_clear(data, flags);
174 
175 	return esp_mode_switch_if_needed(data);
176 }
177 
178 /*
179  * Modem Response Command Handlers
180  */
181 
182 /* Handler: OK */
MODEM_CMD_DEFINE(on_cmd_ok)183 MODEM_CMD_DEFINE(on_cmd_ok)
184 {
185 	struct esp_data *dev = CONTAINER_OF(data, struct esp_data,
186 					    cmd_handler_data);
187 
188 	modem_cmd_handler_set_error(data, 0);
189 	k_sem_give(&dev->sem_response);
190 
191 	return 0;
192 }
193 
194 /* Handler: ERROR */
MODEM_CMD_DEFINE(on_cmd_error)195 MODEM_CMD_DEFINE(on_cmd_error)
196 {
197 	struct esp_data *dev = CONTAINER_OF(data, struct esp_data,
198 					    cmd_handler_data);
199 
200 	modem_cmd_handler_set_error(data, -EIO);
201 	k_sem_give(&dev->sem_response);
202 
203 	return 0;
204 }
205 
206 /* RX thread */
esp_rx(void * p1,void * p2,void * p3)207 static void esp_rx(void *p1, void *p2, void *p3)
208 {
209 	ARG_UNUSED(p2);
210 	ARG_UNUSED(p3);
211 
212 	struct esp_data *data = p1;
213 
214 	while (true) {
215 		/* wait for incoming data */
216 		modem_iface_uart_rx_wait(&data->mctx.iface, K_FOREVER);
217 
218 		modem_cmd_handler_process(&data->mctx.cmd_handler, &data->mctx.iface);
219 
220 		/* give up time if we have a solid stream of data */
221 		k_yield();
222 	}
223 }
224 
str_unquote(char * str)225 static char *str_unquote(char *str)
226 {
227 	char *end;
228 
229 	if (str[0] != '"') {
230 		return str;
231 	}
232 
233 	str++;
234 
235 	end = strrchr(str, '"');
236 	if (end != NULL) {
237 		*end = 0;
238 	}
239 
240 	return str;
241 }
242 
243 /* +CIPSTAMAC:"xx:xx:xx:xx:xx:xx" */
MODEM_CMD_DEFINE(on_cmd_cipstamac)244 MODEM_CMD_DEFINE(on_cmd_cipstamac)
245 {
246 	struct esp_data *dev = CONTAINER_OF(data, struct esp_data,
247 					    cmd_handler_data);
248 	char *mac;
249 	int err;
250 
251 	mac = str_unquote(argv[0]);
252 	err = net_bytes_from_str(dev->mac_addr, sizeof(dev->mac_addr), mac);
253 	if (err) {
254 		LOG_ERR("Failed to parse MAC address");
255 	}
256 
257 	return 0;
258 }
259 
esp_pull_quoted(char ** str,char * str_end,char ** unquoted)260 static int esp_pull_quoted(char **str, char *str_end, char **unquoted)
261 {
262 	if (**str != '"') {
263 		return -EAGAIN;
264 	}
265 
266 	(*str)++;
267 
268 	*unquoted = *str;
269 
270 	while (*str < str_end) {
271 		if (**str == '"') {
272 			**str = '\0';
273 			(*str)++;
274 
275 			if (**str == ',') {
276 				(*str)++;
277 			}
278 
279 			return 0;
280 		}
281 
282 		(*str)++;
283 	}
284 
285 	return -EAGAIN;
286 }
287 
esp_pull(char ** str,char * str_end)288 static int esp_pull(char **str, char *str_end)
289 {
290 	while (*str < str_end) {
291 		if (**str == ',' || **str == ':' || **str == '\r' || **str == '\n') {
292 			char last_c = **str;
293 
294 			**str = '\0';
295 
296 			if (last_c == ',' || last_c == ':') {
297 				(*str)++;
298 			}
299 
300 			return 0;
301 		}
302 
303 		(*str)++;
304 	}
305 
306 	return -EAGAIN;
307 }
308 
esp_pull_raw(char ** str,char * str_end,char ** raw)309 static int esp_pull_raw(char **str, char *str_end, char **raw)
310 {
311 	*raw = *str;
312 
313 	return esp_pull(str, str_end);
314 }
315 
esp_pull_long(char ** str,char * str_end,long * value)316 static int esp_pull_long(char **str, char *str_end, long *value)
317 {
318 	char *str_begin = *str;
319 	int err;
320 	char *endptr;
321 
322 	err = esp_pull(str, str_end);
323 	if (err) {
324 		return err;
325 	}
326 
327 	*value = strtol(str_begin, &endptr, 10);
328 	if (endptr == str_begin) {
329 		LOG_ERR("endptr == str_begin");
330 		return -EBADMSG;
331 	}
332 
333 	return 0;
334 }
335 
336 /* +CWLAP:(sec,ssid,rssi,channel) */
337 /* with: CONFIG_WIFI_ESP_AT_SCAN_MAC_ADDRESS: +CWLAP:<ecn>,<ssid>,<rssi>,<mac>,<ch>*/
MODEM_CMD_DIRECT_DEFINE(on_cmd_cwlap)338 MODEM_CMD_DIRECT_DEFINE(on_cmd_cwlap)
339 {
340 	struct esp_data *dev = CONTAINER_OF(data, struct esp_data,
341 					    cmd_handler_data);
342 	struct wifi_scan_result res = { 0 };
343 	char cwlap_buf[sizeof("\"0\",\"\",-100,\"xx:xx:xx:xx:xx:xx\",12") +
344 		       WIFI_SSID_MAX_LEN * 2 + 1];
345 	char *ecn;
346 	char *ssid;
347 	char *mac;
348 	char *channel;
349 	long rssi;
350 	long ecn_id;
351 	int err;
352 
353 	len = net_buf_linearize(cwlap_buf, sizeof(cwlap_buf) - 1,
354 				data->rx_buf, 0, sizeof(cwlap_buf) - 1);
355 	cwlap_buf[len] = '\0';
356 
357 	char *str = &cwlap_buf[sizeof("+CWJAP:(") - 1];
358 	char *str_end = cwlap_buf + len;
359 
360 	err = esp_pull_raw(&str, str_end, &ecn);
361 	if (err) {
362 		return err;
363 	}
364 
365 	ecn_id = strtol(ecn, NULL, 10);
366 	if (ecn_id == 0) {
367 		res.security = WIFI_SECURITY_TYPE_NONE;
368 	} else {
369 		res.security = WIFI_SECURITY_TYPE_PSK;
370 	}
371 
372 	err = esp_pull_quoted(&str, str_end, &ssid);
373 	if (err) {
374 		return err;
375 	}
376 
377 	err = esp_pull_long(&str, str_end, &rssi);
378 	if (err) {
379 		return err;
380 	}
381 
382 	if (strlen(ssid) > WIFI_SSID_MAX_LEN) {
383 		return -EBADMSG;
384 	}
385 
386 	res.ssid_length = MIN(sizeof(res.ssid), strlen(ssid));
387 	memcpy(res.ssid, ssid, res.ssid_length);
388 
389 	res.rssi = rssi;
390 
391 	if (IS_ENABLED(CONFIG_WIFI_ESP_AT_SCAN_MAC_ADDRESS)) {
392 		err = esp_pull_quoted(&str, str_end, &mac);
393 		if (err) {
394 			return err;
395 		}
396 
397 		res.mac_length = WIFI_MAC_ADDR_LEN;
398 		if (net_bytes_from_str(res.mac, sizeof(res.mac), mac) < 0) {
399 			LOG_ERR("Invalid MAC address");
400 			res.mac_length = 0;
401 		}
402 	}
403 
404 	err = esp_pull_raw(&str, str_end, &channel);
405 	if (err) {
406 		return err;
407 	}
408 
409 	res.channel = strtol(channel, NULL, 10);
410 
411 	if (dev->scan_cb) {
412 		dev->scan_cb(dev->net_iface, 0, &res);
413 	}
414 
415 	return str - cwlap_buf;
416 }
417 
418 /* +CWJAP:(ssid,bssid,channel,rssi) */
MODEM_CMD_DIRECT_DEFINE(on_cmd_cwjap)419 MODEM_CMD_DIRECT_DEFINE(on_cmd_cwjap)
420 {
421 	struct esp_data *dev = CONTAINER_OF(data, struct esp_data,
422 					    cmd_handler_data);
423 	struct wifi_iface_status *status = dev->wifi_status;
424 	char cwjap_buf[sizeof("\"\",\"xx:xx:xx:xx:xx:xx\",12,-100") +
425 		       WIFI_SSID_MAX_LEN * 2 + 1];
426 	uint8_t flags = dev->flags;
427 	char *ssid;
428 	char *bssid;
429 	char *channel;
430 	char *rssi;
431 	int err;
432 
433 	len = net_buf_linearize(cwjap_buf, sizeof(cwjap_buf) - 1,
434 				data->rx_buf, 0, sizeof(cwjap_buf) - 1);
435 	cwjap_buf[len] = '\0';
436 
437 	char *str = &cwjap_buf[sizeof("+CWJAP:") - 1];
438 	char *str_end = cwjap_buf + len;
439 
440 	status->band = WIFI_FREQ_BAND_2_4_GHZ;
441 	status->iface_mode = WIFI_MODE_INFRA;
442 
443 	if (flags & EDF_STA_CONNECTED) {
444 		status->state = WIFI_STATE_COMPLETED;
445 	} else if (flags & EDF_STA_CONNECTING) {
446 		status->state = WIFI_STATE_SCANNING;
447 	} else {
448 		status->state = WIFI_STATE_DISCONNECTED;
449 	}
450 
451 	err = esp_pull_quoted(&str, str_end, &ssid);
452 	if (err) {
453 		return err;
454 	}
455 
456 	err = esp_pull_quoted(&str, str_end, &bssid);
457 	if (err) {
458 		return err;
459 	}
460 
461 	err = esp_pull_raw(&str, str_end, &channel);
462 	if (err) {
463 		return err;
464 	}
465 
466 	err = esp_pull_raw(&str, str_end, &rssi);
467 	if (err) {
468 		return err;
469 	}
470 
471 	strncpy(status->ssid, ssid, sizeof(status->ssid));
472 	status->ssid_len = strnlen(status->ssid, sizeof(status->ssid));
473 
474 	err = net_bytes_from_str(status->bssid, sizeof(status->bssid), bssid);
475 	if (err) {
476 		LOG_WRN("Invalid MAC address");
477 		memset(status->bssid, 0x0, sizeof(status->bssid));
478 	}
479 
480 	status->channel = strtol(channel, NULL, 10);
481 	status->rssi = strtol(rssi, NULL, 10);
482 
483 	return str - cwjap_buf;
484 }
485 
esp_dns_work(struct k_work * work)486 static void esp_dns_work(struct k_work *work)
487 {
488 #if defined(ESP_MAX_DNS)
489 	struct esp_data *data = CONTAINER_OF(work, struct esp_data, dns_work);
490 	struct dns_resolve_context *dnsctx;
491 	struct sockaddr_in *addrs = data->dns_addresses;
492 	const struct sockaddr *dns_servers[ESP_MAX_DNS + 1] = {};
493 	size_t i;
494 	int err;
495 
496 	for (i = 0; i < ESP_MAX_DNS; i++) {
497 		if (!addrs[i].sin_addr.s_addr) {
498 			break;
499 		}
500 		dns_servers[i] = (struct sockaddr *) &addrs[i];
501 	}
502 
503 	dnsctx = dns_resolve_get_default();
504 	err = dns_resolve_reconfigure(dnsctx, NULL, dns_servers);
505 	if (err) {
506 		LOG_ERR("Could not set DNS servers: %d", err);
507 	}
508 
509 	LOG_DBG("DNS resolver reconfigured");
510 #endif
511 }
512 
513 /* +CIPDNS:enable[,"DNS IP1"[,"DNS IP2"[,"DNS IP3"]]] */
MODEM_CMD_DEFINE(on_cmd_cipdns)514 MODEM_CMD_DEFINE(on_cmd_cipdns)
515 {
516 #if defined(ESP_MAX_DNS)
517 	struct esp_data *dev = CONTAINER_OF(data, struct esp_data,
518 					    cmd_handler_data);
519 	struct sockaddr_in *addrs = dev->dns_addresses;
520 	char **servers = (char **)argv + 1;
521 	size_t num_servers = argc - 1;
522 	size_t valid_servers = 0;
523 	size_t i;
524 	int err;
525 
526 	for (i = 0; i < ESP_MAX_DNS; i++) {
527 		if (i >= num_servers) {
528 			addrs[i].sin_addr.s_addr = 0;
529 			break;
530 		}
531 
532 		servers[i] = str_unquote(servers[i]);
533 		LOG_DBG("DNS[%zu]: %s", i, servers[i]);
534 
535 		err = net_addr_pton(AF_INET, servers[i], &addrs[i].sin_addr);
536 		if (err) {
537 			LOG_ERR("Invalid DNS address: %s",
538 				servers[i]);
539 			addrs[i].sin_addr.s_addr = 0;
540 			break;
541 		}
542 
543 		addrs[i].sin_family = AF_INET;
544 		addrs[i].sin_port = htons(53);
545 
546 		valid_servers++;
547 	}
548 
549 	if (valid_servers) {
550 		k_work_submit(&dev->dns_work);
551 	}
552 #endif
553 
554 	return 0;
555 }
556 
557 static const struct modem_cmd response_cmds[] = {
558 	MODEM_CMD("OK", on_cmd_ok, 0U, ""), /* 3GPP */
559 	MODEM_CMD("ERROR", on_cmd_error, 0U, ""), /* 3GPP */
560 };
561 
MODEM_CMD_DEFINE(on_cmd_wifi_connected)562 MODEM_CMD_DEFINE(on_cmd_wifi_connected)
563 {
564 	struct esp_data *dev = CONTAINER_OF(data, struct esp_data,
565 					    cmd_handler_data);
566 
567 	if (esp_flags_are_set(dev, EDF_STA_CONNECTED)) {
568 		return 0;
569 	}
570 
571 	esp_flags_set(dev, EDF_STA_CONNECTED);
572 	wifi_mgmt_raise_connect_result_event(dev->net_iface, 0);
573 	net_if_dormant_off(dev->net_iface);
574 
575 	return 0;
576 }
577 
esp_mgmt_disconnect_work(struct k_work * work)578 static void esp_mgmt_disconnect_work(struct k_work *work)
579 {
580 	struct esp_socket *sock;
581 	struct esp_data *dev;
582 
583 	dev = CONTAINER_OF(work, struct esp_data, disconnect_work);
584 
585 	/* Cleanup any sockets that weren't closed */
586 	for (int i = 0; i < ARRAY_SIZE(dev->sockets); i++) {
587 		sock = &dev->sockets[i];
588 		if (esp_socket_connected(sock)) {
589 			LOG_WRN("Socket %d left open, manually closing", i);
590 			esp_socket_close(sock);
591 		}
592 	}
593 
594 	esp_flags_clear(dev, EDF_STA_CONNECTED);
595 	esp_mode_switch_submit_if_needed(dev);
596 
597 #if defined(CONFIG_NET_NATIVE_IPV4)
598 	net_if_ipv4_addr_rm(dev->net_iface, &dev->ip);
599 #endif
600 	if (!esp_flags_are_set(dev, EDF_AP_ENABLED)) {
601 		net_if_dormant_on(dev->net_iface);
602 	}
603 	wifi_mgmt_raise_disconnect_result_event(dev->net_iface, 0);
604 }
605 
MODEM_CMD_DEFINE(on_cmd_wifi_disconnected)606 MODEM_CMD_DEFINE(on_cmd_wifi_disconnected)
607 {
608 	struct esp_data *dev = CONTAINER_OF(data, struct esp_data,
609 					    cmd_handler_data);
610 
611 	if (esp_flags_are_set(dev, EDF_STA_CONNECTED)) {
612 		k_work_submit_to_queue(&dev->workq, &dev->disconnect_work);
613 	}
614 
615 	return 0;
616 }
617 
618 /*
619  * +CIPSTA:ip:"<ip>"
620  * +CIPSTA:gateway:"<ip>"
621  * +CIPSTA:netmask:"<ip>"
622  */
MODEM_CMD_DEFINE(on_cmd_cipsta)623 MODEM_CMD_DEFINE(on_cmd_cipsta)
624 {
625 	struct esp_data *dev = CONTAINER_OF(data, struct esp_data,
626 					    cmd_handler_data);
627 	char *ip;
628 
629 	ip = str_unquote(argv[1]);
630 
631 	if (!strcmp(argv[0], "ip")) {
632 		net_addr_pton(AF_INET, ip, &dev->ip);
633 	} else if (!strcmp(argv[0], "gateway")) {
634 		net_addr_pton(AF_INET, ip, &dev->gw);
635 	} else if (!strcmp(argv[0], "netmask")) {
636 		net_addr_pton(AF_INET, ip, &dev->nm);
637 	} else {
638 		LOG_WRN("Unknown IP type %s", argv[0]);
639 	}
640 
641 	return 0;
642 }
643 
esp_ip_addr_work(struct k_work * work)644 static void esp_ip_addr_work(struct k_work *work)
645 {
646 	struct k_work_delayable *dwork = k_work_delayable_from_work(work);
647 	struct esp_data *dev = CONTAINER_OF(dwork, struct esp_data,
648 					    ip_addr_work);
649 	int ret;
650 
651 	static const struct modem_cmd cmds[] = {
652 		MODEM_CMD("+"_CIPSTA":", on_cmd_cipsta, 2U, ":"),
653 	};
654 	static const struct modem_cmd dns_cmds[] = {
655 		MODEM_CMD_ARGS_MAX("+CIPDNS:", on_cmd_cipdns, 1U, 3U, ","),
656 	};
657 
658 	ret = esp_cmd_send(dev, cmds, ARRAY_SIZE(cmds), "AT+"_CIPSTA"?",
659 			   ESP_CMD_TIMEOUT);
660 	if (ret < 0) {
661 		LOG_WRN("Failed to query IP settings: ret %d", ret);
662 		k_work_reschedule_for_queue(&dev->workq, &dev->ip_addr_work,
663 					    K_SECONDS(5));
664 		return;
665 	}
666 
667 #if defined(CONFIG_NET_NATIVE_IPV4)
668 	/* update interface addresses */
669 #if defined(CONFIG_WIFI_ESP_AT_IP_STATIC)
670 	net_if_ipv4_addr_add(dev->net_iface, &dev->ip, NET_ADDR_MANUAL, 0);
671 #else
672 	net_if_ipv4_addr_add(dev->net_iface, &dev->ip, NET_ADDR_DHCP, 0);
673 #endif
674 	net_if_ipv4_set_gw(dev->net_iface, &dev->gw);
675 	net_if_ipv4_set_netmask_by_addr(dev->net_iface, &dev->ip, &dev->nm);
676 #endif
677 
678 	if (IS_ENABLED(CONFIG_WIFI_ESP_AT_DNS_USE)) {
679 		ret = esp_cmd_send(dev, dns_cmds, ARRAY_SIZE(dns_cmds),
680 				   "AT+CIPDNS?", ESP_CMD_TIMEOUT);
681 		if (ret) {
682 			LOG_WRN("DNS fetch failed: %d", ret);
683 		}
684 	}
685 }
686 
MODEM_CMD_DEFINE(on_cmd_got_ip)687 MODEM_CMD_DEFINE(on_cmd_got_ip)
688 {
689 	struct esp_data *dev = CONTAINER_OF(data, struct esp_data,
690 					    cmd_handler_data);
691 
692 	k_work_reschedule_for_queue(&dev->workq, &dev->ip_addr_work,
693 				    K_SECONDS(1));
694 
695 	return 0;
696 }
697 
MODEM_CMD_DEFINE(on_cmd_connect)698 MODEM_CMD_DEFINE(on_cmd_connect)
699 {
700 	struct esp_socket *sock;
701 	struct esp_data *dev;
702 	uint8_t link_id;
703 
704 	link_id = data->match_buf[0] - '0';
705 
706 	dev = CONTAINER_OF(data, struct esp_data, cmd_handler_data);
707 	sock = esp_socket_ref_from_link_id(dev, link_id);
708 	if (!sock) {
709 		LOG_ERR("No socket for link %d", link_id);
710 		return 0;
711 	}
712 
713 	esp_socket_unref(sock);
714 
715 	return 0;
716 }
717 
MODEM_CMD_DEFINE(on_cmd_closed)718 MODEM_CMD_DEFINE(on_cmd_closed)
719 {
720 	struct esp_socket *sock;
721 	struct esp_data *dev;
722 	uint8_t link_id;
723 	atomic_val_t old_flags;
724 
725 	link_id = data->match_buf[0] - '0';
726 
727 	LOG_DBG("Link %d closed", link_id);
728 
729 	dev = CONTAINER_OF(data, struct esp_data, cmd_handler_data);
730 	sock = esp_socket_ref_from_link_id(dev, link_id);
731 	if (!sock) {
732 		LOG_ERR("No socket for link %d", link_id);
733 		return 0;
734 	}
735 
736 	old_flags = esp_socket_flags_clear_and_set(sock,
737 				ESP_SOCK_CONNECTED, ESP_SOCK_CLOSE_PENDING);
738 
739 	if (!(old_flags & ESP_SOCK_CONNECTED)) {
740 		LOG_DBG("Link %d already closed", link_id);
741 		goto socket_unref;
742 	}
743 
744 	if (!(old_flags & ESP_SOCK_CLOSE_PENDING)) {
745 		esp_socket_work_submit(sock, &sock->close_work);
746 	}
747 
748 socket_unref:
749 	esp_socket_unref(sock);
750 
751 	return 0;
752 }
753 
754 /*
755  * Passive mode: "+IPD,<id>,<len>\r\n"
756  * Other:        "+IPD,<id>,<len>:<data>"
757  */
758 #define MIN_IPD_LEN (sizeof("+IPD,I,0E") - 1)
759 #define MAX_IPD_LEN (sizeof("+IPD,I,4294967295,\"\",65535E") - 1) + NET_IPV4_ADDR_LEN
760 
cmd_ipd_parse_hdr(struct esp_data * dev,struct esp_socket ** sock,struct net_buf * buf,uint16_t len,int * data_offset,long * data_len)761 static int cmd_ipd_parse_hdr(struct esp_data *dev,
762 			     struct esp_socket **sock,
763 			     struct net_buf *buf, uint16_t len,
764 			     int *data_offset, long *data_len)
765 {
766 	char ipd_buf[MAX_IPD_LEN + 1];
767 	char *str;
768 	char *str_end;
769 	long link_id;
770 	size_t frags_len;
771 	size_t match_len;
772 	int err;
773 
774 	frags_len = net_buf_frags_len(buf);
775 
776 	/* Wait until minimum cmd length is available */
777 	if (frags_len < MIN_IPD_LEN) {
778 		return -EAGAIN;
779 	}
780 
781 	match_len = net_buf_linearize(ipd_buf, MAX_IPD_LEN,
782 				      buf, 0, MAX_IPD_LEN);
783 
784 	ipd_buf[match_len] = 0;
785 	if (ipd_buf[len] != ',' || ipd_buf[len + 2] != ',') {
786 		LOG_ERR("Invalid IPD: %s", ipd_buf);
787 		return -EBADMSG;
788 	}
789 
790 	str = &ipd_buf[len + 1];
791 	str_end = &ipd_buf[match_len];
792 
793 	err = esp_pull_long(&str, str_end, &link_id);
794 	if (err) {
795 		if (err == -EAGAIN && match_len >= MAX_IPD_LEN) {
796 			LOG_ERR("Failed to pull %s", "link_id");
797 			return -EBADMSG;
798 		}
799 
800 		return err;
801 	}
802 
803 	err = esp_pull_long(&str, str_end, data_len);
804 	if (err) {
805 		if (err == -EAGAIN && match_len >= MAX_IPD_LEN) {
806 			LOG_ERR("Failed to pull %s", "data_len");
807 			return -EBADMSG;
808 		}
809 
810 		return err;
811 	}
812 
813 	*sock = esp_socket_ref_from_link_id(dev, link_id);
814 	if (!sock) {
815 		LOG_ERR("No socket for link %ld", link_id);
816 		return str - ipd_buf;
817 	}
818 
819 	if (!ESP_PROTO_PASSIVE(esp_socket_ip_proto(*sock)) &&
820 	    IS_ENABLED(CONFIG_WIFI_ESP_AT_CIPDINFO_USE)) {
821 		struct sockaddr_in *recv_addr =
822 			(struct sockaddr_in *) &(*sock)->context->remote;
823 		char *remote_ip;
824 		long port;
825 
826 		err = esp_pull_quoted(&str, str_end, &remote_ip);
827 		if (err) {
828 			LOG_ERR("Failed to pull remote_ip");
829 			goto socket_unref;
830 		}
831 
832 		err = esp_pull_long(&str, str_end, &port);
833 		if (err) {
834 			LOG_ERR("Failed to pull port");
835 			goto socket_unref;
836 		}
837 
838 		err = net_addr_pton(AF_INET, remote_ip, &recv_addr->sin_addr);
839 		if (err) {
840 			LOG_ERR("Invalid IP address");
841 			err = -EBADMSG;
842 			goto socket_unref;
843 		}
844 
845 		recv_addr->sin_family = AF_INET;
846 		recv_addr->sin_port = htons(port);
847 	}
848 
849 	*data_offset = (str - ipd_buf);
850 
851 	return 0;
852 
853 socket_unref:
854 	esp_socket_unref(*sock);
855 
856 	return err;
857 }
858 
MODEM_CMD_DIRECT_DEFINE(on_cmd_ipd)859 MODEM_CMD_DIRECT_DEFINE(on_cmd_ipd)
860 {
861 	struct esp_data *dev = CONTAINER_OF(data, struct esp_data,
862 					    cmd_handler_data);
863 	struct esp_socket *sock;
864 	int data_offset;
865 	long data_len;
866 	int err;
867 	int ret;
868 
869 	err = cmd_ipd_parse_hdr(dev, &sock, data->rx_buf, len,
870 				&data_offset, &data_len);
871 	if (err) {
872 		if (err == -EAGAIN) {
873 			return -EAGAIN;
874 		}
875 
876 		return len;
877 	}
878 
879 	/*
880 	 * When using passive TCP, the data itself is not included in the +IPD
881 	 * command but must be polled with AT+CIPRECVDATA.
882 	 */
883 	if (ESP_PROTO_PASSIVE(esp_socket_ip_proto(sock))) {
884 		esp_socket_work_submit(sock, &sock->recvdata_work);
885 		ret = data_offset;
886 		goto socket_unref;
887 	}
888 
889 	/* Do we have the whole message? */
890 	if (data_offset + data_len > net_buf_frags_len(data->rx_buf)) {
891 		ret = -EAGAIN;
892 		goto socket_unref;
893 	}
894 
895 	esp_socket_rx(sock, data->rx_buf, data_offset, data_len);
896 
897 	ret = data_offset + data_len;
898 
899 socket_unref:
900 	esp_socket_unref(sock);
901 
902 	return ret;
903 }
904 
MODEM_CMD_DEFINE(on_cmd_busy_sending)905 MODEM_CMD_DEFINE(on_cmd_busy_sending)
906 {
907 	LOG_WRN("Busy sending");
908 	return 0;
909 }
910 
MODEM_CMD_DEFINE(on_cmd_busy_processing)911 MODEM_CMD_DEFINE(on_cmd_busy_processing)
912 {
913 	LOG_WRN("Busy processing");
914 	return 0;
915 }
916 
917 /*
918  * The 'ready' command is sent when device has booted and is ready to receive
919  * commands. It is only expected after a reset of the device.
920  */
MODEM_CMD_DEFINE(on_cmd_ready)921 MODEM_CMD_DEFINE(on_cmd_ready)
922 {
923 	struct esp_data *dev = CONTAINER_OF(data, struct esp_data,
924 					    cmd_handler_data);
925 	k_sem_give(&dev->sem_if_ready);
926 
927 
928 	if (net_if_is_carrier_ok(dev->net_iface)) {
929 		net_if_dormant_on(dev->net_iface);
930 		net_if_carrier_off(dev->net_iface);
931 		LOG_ERR("Unexpected reset");
932 	}
933 
934 	if (esp_flags_are_set(dev, EDF_STA_CONNECTING)) {
935 		wifi_mgmt_raise_connect_result_event(dev->net_iface, -1);
936 	} else if (esp_flags_are_set(dev, EDF_STA_CONNECTED)) {
937 		wifi_mgmt_raise_disconnect_result_event(dev->net_iface, 0);
938 	}
939 
940 	dev->flags = 0;
941 	dev->mode = 0;
942 
943 #if defined(CONFIG_NET_NATIVE_IPV4)
944 	net_if_ipv4_addr_rm(dev->net_iface, &dev->ip);
945 #endif
946 	k_work_submit_to_queue(&dev->workq, &dev->init_work);
947 
948 	return 0;
949 }
950 
951 #if defined(CONFIG_WIFI_ESP_AT_FETCH_VERSION)
952 
cmd_version_log(struct modem_cmd_handler_data * data,const char * type,const char * version)953 static int cmd_version_log(struct modem_cmd_handler_data *data,
954 			   const char *type, const char *version)
955 {
956 	LOG_INF("%s: %s", type, version);
957 
958 	return 0;
959 }
960 
MODEM_CMD_DEFINE(on_cmd_at_version)961 MODEM_CMD_DEFINE(on_cmd_at_version)
962 {
963 	return cmd_version_log(data, "AT version", argv[0]);
964 }
965 
MODEM_CMD_DEFINE(on_cmd_sdk_version)966 MODEM_CMD_DEFINE(on_cmd_sdk_version)
967 {
968 	return cmd_version_log(data, "SDK version", argv[0]);
969 }
970 
MODEM_CMD_DEFINE(on_cmd_compile_time)971 MODEM_CMD_DEFINE(on_cmd_compile_time)
972 {
973 	return cmd_version_log(data, "compile time", argv[0]);
974 }
975 
MODEM_CMD_DEFINE(on_cmd_bin_version)976 MODEM_CMD_DEFINE(on_cmd_bin_version)
977 {
978 	return cmd_version_log(data, "Bin version", argv[0]);
979 }
980 
981 #endif /* CONFIG_WIFI_ESP_AT_FETCH_VERSION */
982 
983 static const struct modem_cmd unsol_cmds[] = {
984 	MODEM_CMD("WIFI CONNECTED", on_cmd_wifi_connected, 0U, ""),
985 	MODEM_CMD("WIFI DISCONNECT", on_cmd_wifi_disconnected, 0U, ""),
986 	MODEM_CMD("WIFI GOT IP", on_cmd_got_ip, 0U, ""),
987 	MODEM_CMD("0,CONNECT", on_cmd_connect, 0U, ""),
988 	MODEM_CMD("1,CONNECT", on_cmd_connect, 0U, ""),
989 	MODEM_CMD("2,CONNECT", on_cmd_connect, 0U, ""),
990 	MODEM_CMD("3,CONNECT", on_cmd_connect, 0U, ""),
991 	MODEM_CMD("4,CONNECT", on_cmd_connect, 0U, ""),
992 	MODEM_CMD("0,CLOSED", on_cmd_closed, 0U, ""),
993 	MODEM_CMD("1,CLOSED", on_cmd_closed, 0U, ""),
994 	MODEM_CMD("2,CLOSED", on_cmd_closed, 0U, ""),
995 	MODEM_CMD("3,CLOSED", on_cmd_closed, 0U, ""),
996 	MODEM_CMD("4,CLOSED", on_cmd_closed, 0U, ""),
997 	MODEM_CMD("busy s...", on_cmd_busy_sending, 0U, ""),
998 	MODEM_CMD("busy p...", on_cmd_busy_processing, 0U, ""),
999 	MODEM_CMD("ready", on_cmd_ready, 0U, ""),
1000 #if defined(CONFIG_WIFI_ESP_AT_FETCH_VERSION)
1001 	MODEM_CMD("AT version:", on_cmd_at_version, 1U, ""),
1002 	MODEM_CMD("SDK version:", on_cmd_sdk_version, 1U, ""),
1003 	MODEM_CMD("Compile time", on_cmd_compile_time, 1U, ""),
1004 	MODEM_CMD("Bin version:", on_cmd_bin_version, 1U, ""),
1005 #endif
1006 	MODEM_CMD_DIRECT("+IPD", on_cmd_ipd),
1007 };
1008 
esp_mgmt_iface_status_work(struct k_work * work)1009 static void esp_mgmt_iface_status_work(struct k_work *work)
1010 {
1011 	struct esp_data *data = CONTAINER_OF(work, struct esp_data, iface_status_work);
1012 	struct wifi_iface_status *status = data->wifi_status;
1013 	int ret;
1014 	static const struct modem_cmd cmds[] = {
1015 		MODEM_CMD_DIRECT("+CWJAP:", on_cmd_cwjap),
1016 	};
1017 
1018 	ret = esp_cmd_send(data, cmds, ARRAY_SIZE(cmds), "AT+CWJAP?",
1019 			   ESP_IFACE_STATUS_TIMEOUT);
1020 	if (ret < 0) {
1021 		LOG_WRN("Failed to request STA status: ret %d", ret);
1022 		status->state = WIFI_STATE_UNKNOWN;
1023 	}
1024 
1025 	k_sem_give(&data->wifi_status_sem);
1026 }
1027 
esp_mgmt_iface_status(const struct device * dev,struct wifi_iface_status * status)1028 static int esp_mgmt_iface_status(const struct device *dev,
1029 				 struct wifi_iface_status *status)
1030 {
1031 	struct esp_data *data = dev->data;
1032 
1033 	memset(status, 0x0, sizeof(*status));
1034 
1035 	status->state = WIFI_STATE_UNKNOWN;
1036 	status->band = WIFI_FREQ_BAND_UNKNOWN;
1037 	status->iface_mode = WIFI_MODE_UNKNOWN;
1038 	status->link_mode = WIFI_LINK_MODE_UNKNOWN;
1039 	status->security = WIFI_SECURITY_TYPE_UNKNOWN;
1040 	status->mfp = WIFI_MFP_UNKNOWN;
1041 
1042 	if (!net_if_is_carrier_ok(data->net_iface)) {
1043 		status->state = WIFI_STATE_INTERFACE_DISABLED;
1044 		return 0;
1045 	}
1046 
1047 	data->wifi_status = status;
1048 	k_sem_init(&data->wifi_status_sem, 0, 1);
1049 
1050 	k_work_submit_to_queue(&data->workq, &data->iface_status_work);
1051 
1052 	k_sem_take(&data->wifi_status_sem, K_FOREVER);
1053 
1054 	return 0;
1055 }
1056 
esp_mgmt_scan_work(struct k_work * work)1057 static void esp_mgmt_scan_work(struct k_work *work)
1058 {
1059 	struct esp_data *dev;
1060 	int ret;
1061 	static const struct modem_cmd cmds[] = {
1062 		MODEM_CMD_DIRECT("+CWLAP:", on_cmd_cwlap),
1063 	};
1064 
1065 	dev = CONTAINER_OF(work, struct esp_data, scan_work);
1066 
1067 	ret = esp_mode_flags_set(dev, EDF_STA_LOCK);
1068 	if (ret < 0) {
1069 		goto out;
1070 	}
1071 	ret = esp_cmd_send(dev,
1072 			   cmds, ARRAY_SIZE(cmds),
1073 			   ESP_CMD_CWLAP,
1074 			   ESP_SCAN_TIMEOUT);
1075 	esp_mode_flags_clear(dev, EDF_STA_LOCK);
1076 	LOG_DBG("ESP Wi-Fi scan: cmd = %s", ESP_CMD_CWLAP);
1077 
1078 	if (ret < 0) {
1079 		LOG_ERR("Failed to scan: ret %d", ret);
1080 	}
1081 
1082 out:
1083 	dev->scan_cb(dev->net_iface, 0, NULL);
1084 	dev->scan_cb = NULL;
1085 }
1086 
esp_mgmt_scan(const struct device * dev,struct wifi_scan_params * params,scan_result_cb_t cb)1087 static int esp_mgmt_scan(const struct device *dev,
1088 			 struct wifi_scan_params *params,
1089 			 scan_result_cb_t cb)
1090 {
1091 	struct esp_data *data = dev->data;
1092 
1093 	ARG_UNUSED(params);
1094 
1095 	if (data->scan_cb != NULL) {
1096 		return -EINPROGRESS;
1097 	}
1098 
1099 	if (!net_if_is_carrier_ok(data->net_iface)) {
1100 		return -EIO;
1101 	}
1102 
1103 	data->scan_cb = cb;
1104 
1105 	k_work_submit_to_queue(&data->workq, &data->scan_work);
1106 
1107 	return 0;
1108 };
1109 
MODEM_CMD_DEFINE(on_cmd_fail)1110 MODEM_CMD_DEFINE(on_cmd_fail)
1111 {
1112 	struct esp_data *dev = CONTAINER_OF(data, struct esp_data,
1113 					    cmd_handler_data);
1114 
1115 	modem_cmd_handler_set_error(data, -EIO);
1116 	k_sem_give(&dev->sem_response);
1117 
1118 	return 0;
1119 }
1120 
esp_mgmt_connect_work(struct k_work * work)1121 static void esp_mgmt_connect_work(struct k_work *work)
1122 {
1123 	struct esp_data *dev;
1124 	int ret;
1125 	static const struct modem_cmd cmds[] = {
1126 		MODEM_CMD("FAIL", on_cmd_fail, 0U, ""),
1127 	};
1128 
1129 	dev = CONTAINER_OF(work, struct esp_data, connect_work);
1130 
1131 	ret = esp_mode_flags_set(dev, EDF_STA_LOCK);
1132 	if (ret < 0) {
1133 		goto out;
1134 	}
1135 
1136 	ret = esp_cmd_send(dev, cmds, ARRAY_SIZE(cmds), dev->conn_cmd,
1137 			   ESP_CONNECT_TIMEOUT);
1138 
1139 	memset(dev->conn_cmd, 0, sizeof(dev->conn_cmd));
1140 
1141 	if (ret < 0) {
1142 		net_if_dormant_on(dev->net_iface);
1143 		if (esp_flags_are_set(dev, EDF_STA_CONNECTED)) {
1144 			esp_flags_clear(dev, EDF_STA_CONNECTED);
1145 			wifi_mgmt_raise_disconnect_result_event(dev->net_iface,
1146 								0);
1147 		} else {
1148 			wifi_mgmt_raise_connect_result_event(dev->net_iface,
1149 							     ret);
1150 		}
1151 	} else if (!esp_flags_are_set(dev, EDF_STA_CONNECTED)) {
1152 		esp_flags_set(dev, EDF_STA_CONNECTED);
1153 		wifi_mgmt_raise_connect_result_event(dev->net_iface, 0);
1154 		net_if_dormant_off(dev->net_iface);
1155 	}
1156 
1157 	esp_mode_flags_clear(dev, EDF_STA_LOCK);
1158 
1159 out:
1160 	esp_flags_clear(dev, EDF_STA_CONNECTING);
1161 }
1162 
esp_conn_cmd_append(struct esp_data * data,size_t * off,const char * chunk,size_t chunk_len)1163 static int esp_conn_cmd_append(struct esp_data *data, size_t *off,
1164 			       const char *chunk, size_t chunk_len)
1165 {
1166 	char *str_end = &data->conn_cmd[sizeof(data->conn_cmd)];
1167 	char *str = &data->conn_cmd[*off];
1168 	const char *chunk_end = chunk + chunk_len;
1169 
1170 	for (; chunk < chunk_end; chunk++) {
1171 		if (str_end - str < 1) {
1172 			return -ENOSPC;
1173 		}
1174 
1175 		*str = *chunk;
1176 		str++;
1177 	}
1178 
1179 	*off = str - data->conn_cmd;
1180 
1181 	return 0;
1182 }
1183 
1184 #define esp_conn_cmd_append_literal(data, off, chunk)			\
1185 	esp_conn_cmd_append(data, off, chunk, sizeof(chunk) - 1)
1186 
esp_conn_cmd_escape_and_append(struct esp_data * data,size_t * off,const char * chunk,size_t chunk_len)1187 static int esp_conn_cmd_escape_and_append(struct esp_data *data, size_t *off,
1188 					  const char *chunk, size_t chunk_len)
1189 {
1190 	char *str_end = &data->conn_cmd[sizeof(data->conn_cmd)];
1191 	char *str = &data->conn_cmd[*off];
1192 	const char *chunk_end = chunk + chunk_len;
1193 
1194 	for (; chunk < chunk_end; chunk++) {
1195 		switch (*chunk) {
1196 		case ',':
1197 		case '\\':
1198 		case '"':
1199 			if (str_end - str < 2) {
1200 				return -ENOSPC;
1201 			}
1202 
1203 			*str = '\\';
1204 			str++;
1205 
1206 			break;
1207 		}
1208 
1209 		if (str_end - str < 1) {
1210 			return -ENOSPC;
1211 		}
1212 
1213 		*str = *chunk;
1214 		str++;
1215 	}
1216 
1217 	*off = str - data->conn_cmd;
1218 
1219 	return 0;
1220 }
1221 
esp_mgmt_connect(const struct device * dev,struct wifi_connect_req_params * params)1222 static int esp_mgmt_connect(const struct device *dev,
1223 			    struct wifi_connect_req_params *params)
1224 {
1225 	struct esp_data *data = dev->data;
1226 	size_t off = 0;
1227 	int err;
1228 
1229 	if (!net_if_is_carrier_ok(data->net_iface) ||
1230 	    !net_if_is_admin_up(data->net_iface)) {
1231 		return -EIO;
1232 	}
1233 
1234 	if (esp_flags_are_set(data, EDF_STA_CONNECTED | EDF_STA_CONNECTING)) {
1235 		return -EALREADY;
1236 	}
1237 
1238 	esp_flags_set(data, EDF_STA_CONNECTING);
1239 
1240 	err = esp_conn_cmd_append_literal(data, &off, "AT+"_CWJAP"=\"");
1241 	if (err) {
1242 		return err;
1243 	}
1244 
1245 	err = esp_conn_cmd_escape_and_append(data, &off,
1246 					     params->ssid, params->ssid_length);
1247 	if (err) {
1248 		return err;
1249 	}
1250 
1251 	err = esp_conn_cmd_append_literal(data, &off, "\",\"");
1252 	if (err) {
1253 		return err;
1254 	}
1255 
1256 	if (params->security == WIFI_SECURITY_TYPE_PSK) {
1257 		err = esp_conn_cmd_escape_and_append(data, &off,
1258 						     params->psk, params->psk_length);
1259 		if (err) {
1260 			return err;
1261 		}
1262 	}
1263 
1264 	err = esp_conn_cmd_append_literal(data, &off, "\"");
1265 	if (err) {
1266 		return err;
1267 	}
1268 
1269 	k_work_submit_to_queue(&data->workq, &data->connect_work);
1270 
1271 	return 0;
1272 }
1273 
esp_mgmt_disconnect(const struct device * dev)1274 static int esp_mgmt_disconnect(const struct device *dev)
1275 {
1276 	struct esp_data *data = dev->data;
1277 	int ret;
1278 
1279 	ret = esp_cmd_send(data, NULL, 0, "AT+CWQAP", ESP_CMD_TIMEOUT);
1280 
1281 	return ret;
1282 }
1283 
esp_mgmt_ap_enable(const struct device * dev,struct wifi_connect_req_params * params)1284 static int esp_mgmt_ap_enable(const struct device *dev,
1285 			      struct wifi_connect_req_params *params)
1286 {
1287 	char cmd[sizeof("AT+"_CWSAP"=\"\",\"\",xx,x") + WIFI_SSID_MAX_LEN +
1288 		 WIFI_PSK_MAX_LEN];
1289 	struct esp_data *data = dev->data;
1290 	int ecn = 0, len, ret;
1291 
1292 	ret = esp_mode_flags_set(data, EDF_AP_ENABLED);
1293 	if (ret < 0) {
1294 		LOG_ERR("Failed to enable AP mode, ret %d", ret);
1295 		return ret;
1296 	}
1297 
1298 	len = snprintk(cmd, sizeof(cmd), "AT+"_CWSAP"=\"");
1299 	memcpy(&cmd[len], params->ssid, params->ssid_length);
1300 	len += params->ssid_length;
1301 
1302 	if (params->security == WIFI_SECURITY_TYPE_PSK) {
1303 		len += snprintk(&cmd[len], sizeof(cmd) - len, "\",\"");
1304 		memcpy(&cmd[len], params->psk, params->psk_length);
1305 		len += params->psk_length;
1306 		ecn = 3;
1307 	} else {
1308 		len += snprintk(&cmd[len], sizeof(cmd) - len, "\",\"");
1309 	}
1310 
1311 	snprintk(&cmd[len], sizeof(cmd) - len, "\",%d,%d", params->channel,
1312 		 ecn);
1313 
1314 	ret = esp_cmd_send(data, NULL, 0, cmd, ESP_CMD_TIMEOUT);
1315 
1316 	net_if_dormant_off(data->net_iface);
1317 
1318 	return ret;
1319 }
1320 
esp_mgmt_ap_disable(const struct device * dev)1321 static int esp_mgmt_ap_disable(const struct device *dev)
1322 {
1323 	struct esp_data *data = dev->data;
1324 
1325 	if (!esp_flags_are_set(data, EDF_STA_CONNECTED)) {
1326 		net_if_dormant_on(data->net_iface);
1327 	}
1328 
1329 	return esp_mode_flags_clear(data, EDF_AP_ENABLED);
1330 }
1331 
esp_init_work(struct k_work * work)1332 static void esp_init_work(struct k_work *work)
1333 {
1334 	struct esp_data *dev;
1335 	int ret;
1336 	static const struct setup_cmd setup_cmds[] = {
1337 		SETUP_CMD_NOHANDLE("AT"),
1338 		/* turn off echo */
1339 		SETUP_CMD_NOHANDLE("ATE0"),
1340 		SETUP_CMD_NOHANDLE("AT+UART_CUR="_UART_CUR),
1341 #if DT_INST_NODE_HAS_PROP(0, target_speed)
1342 	};
1343 	static const struct setup_cmd setup_cmds_target_baudrate[] = {
1344 		SETUP_CMD_NOHANDLE("AT"),
1345 #endif
1346 #if defined(CONFIG_WIFI_ESP_AT_FETCH_VERSION)
1347 		SETUP_CMD_NOHANDLE("AT+GMR"),
1348 #endif
1349 #if defined(CONFIG_WIFI_ESP_AT_VERSION_1_7)
1350 		SETUP_CMD_NOHANDLE(ESP_CMD_CWMODE(STA)),
1351 #endif
1352 #if defined(CONFIG_WIFI_ESP_AT_IP_STATIC)
1353 		/* enable Static IP Config */
1354 		SETUP_CMD_NOHANDLE(ESP_CMD_DHCP_ENABLE(STATION, 0)),
1355 		SETUP_CMD_NOHANDLE(ESP_CMD_SET_IP(CONFIG_WIFI_ESP_AT_IP_ADDRESS,
1356 						  CONFIG_WIFI_ESP_AT_IP_GATEWAY,
1357 						  CONFIG_WIFI_ESP_AT_IP_MASK)),
1358 #else
1359 		/* enable DHCP */
1360 		SETUP_CMD_NOHANDLE(ESP_CMD_DHCP_ENABLE(STATION, 1)),
1361 #endif
1362 		/* enable multiple socket support */
1363 		SETUP_CMD_NOHANDLE("AT+CIPMUX=1"),
1364 
1365 		SETUP_CMD_NOHANDLE(
1366 			ESP_CMD_CWLAPOPT(ESP_CMD_CWLAPOPT_ORDERED, ESP_CMD_CWLAPOPT_MASK)),
1367 
1368 #if !defined(CONFIG_WIFI_ESP_AT_VERSION_1_7)
1369 		SETUP_CMD_NOHANDLE(ESP_CMD_CWMODE(STA)),
1370 		SETUP_CMD_NOHANDLE("AT+CWAUTOCONN=0"),
1371 		SETUP_CMD_NOHANDLE(ESP_CMD_CWMODE(NONE)),
1372 #endif
1373 #if defined(CONFIG_WIFI_ESP_AT_PASSIVE_MODE)
1374 		SETUP_CMD_NOHANDLE("AT+CIPRECVMODE=1"),
1375 #endif
1376 #if defined(CONFIG_WIFI_ESP_AT_CIPDINFO_USE)
1377 		SETUP_CMD_NOHANDLE("AT+CIPDINFO=1"),
1378 #endif
1379 		SETUP_CMD("AT+"_CIPSTAMAC"?", "+"_CIPSTAMAC":",
1380 			  on_cmd_cipstamac, 1U, ""),
1381 	};
1382 
1383 	dev = CONTAINER_OF(work, struct esp_data, init_work);
1384 
1385 	ret = modem_cmd_handler_setup_cmds(&dev->mctx.iface,
1386 					   &dev->mctx.cmd_handler, setup_cmds,
1387 					   ARRAY_SIZE(setup_cmds),
1388 					   &dev->sem_response,
1389 					   ESP_INIT_TIMEOUT);
1390 	if (ret < 0) {
1391 		LOG_ERR("Init failed %d", ret);
1392 		return;
1393 	}
1394 
1395 #if DT_INST_NODE_HAS_PROP(0, target_speed)
1396 	static const struct uart_config uart_config = {
1397 		.baudrate = DT_INST_PROP(0, target_speed),
1398 		.parity = UART_CFG_PARITY_NONE,
1399 		.stop_bits = UART_CFG_STOP_BITS_1,
1400 		.data_bits = UART_CFG_DATA_BITS_8,
1401 		.flow_ctrl = DT_PROP(ESP_BUS, hw_flow_control) ?
1402 			UART_CFG_FLOW_CTRL_RTS_CTS : UART_CFG_FLOW_CTRL_NONE,
1403 	};
1404 
1405 	ret = uart_configure(DEVICE_DT_GET(DT_INST_BUS(0)), &uart_config);
1406 	if (ret < 0) {
1407 		LOG_ERR("Baudrate change failed %d", ret);
1408 		return;
1409 	}
1410 
1411 	/* arbitrary sleep period to give ESP enough time to reconfigure */
1412 	k_sleep(K_MSEC(100));
1413 
1414 	ret = modem_cmd_handler_setup_cmds(&dev->mctx.iface,
1415 				&dev->mctx.cmd_handler,
1416 				setup_cmds_target_baudrate,
1417 				ARRAY_SIZE(setup_cmds_target_baudrate),
1418 				&dev->sem_response,
1419 				ESP_INIT_TIMEOUT);
1420 	if (ret < 0) {
1421 		LOG_ERR("Init failed %d", ret);
1422 		return;
1423 	}
1424 #endif
1425 
1426 	net_if_set_link_addr(dev->net_iface, dev->mac_addr,
1427 			     sizeof(dev->mac_addr), NET_LINK_ETHERNET);
1428 
1429 	if (IS_ENABLED(CONFIG_WIFI_ESP_AT_VERSION_1_7)) {
1430 		/* This is the mode entered in above setup commands */
1431 		dev->mode = ESP_MODE_STA;
1432 
1433 		/*
1434 		 * In case of ESP 1.7 this is the first time CWMODE is entered
1435 		 * STA mode, so request hostname change now.
1436 		 */
1437 		esp_configure_hostname(dev);
1438 	}
1439 
1440 	LOG_INF("ESP Wi-Fi ready");
1441 
1442 	/* L1 network layer (physical layer) is up */
1443 	net_if_carrier_on(dev->net_iface);
1444 
1445 	k_sem_give(&dev->sem_if_up);
1446 }
1447 
esp_reset(const struct device * dev)1448 static int esp_reset(const struct device *dev)
1449 {
1450 	struct esp_data *data = dev->data;
1451 	int ret = -EAGAIN;
1452 
1453 	if (net_if_is_carrier_ok(data->net_iface)) {
1454 		net_if_carrier_off(data->net_iface);
1455 	}
1456 
1457 #if DT_INST_NODE_HAS_PROP(0, power_gpios)
1458 	const struct esp_config *config = dev->config;
1459 
1460 	gpio_pin_set_dt(&config->power, 0);
1461 	k_sleep(K_MSEC(100));
1462 	gpio_pin_set_dt(&config->power, 1);
1463 #elif DT_INST_NODE_HAS_PROP(0, reset_gpios)
1464 	const struct esp_config *config = dev->config;
1465 
1466 	gpio_pin_set_dt(&config->reset, 1);
1467 	k_sleep(K_MSEC(100));
1468 	gpio_pin_set_dt(&config->reset, 0);
1469 #else
1470 #if DT_INST_NODE_HAS_PROP(0, external_reset)
1471 	/* Wait to see if the interface comes up by itself */
1472 	ret = k_sem_take(&data->sem_if_ready, K_MSEC(CONFIG_WIFI_ESP_AT_RESET_TIMEOUT));
1473 #endif
1474 	int retries = 3;
1475 
1476 	/* Don't need to run this if the interface came up by itself */
1477 	while ((ret != 0) && retries--) {
1478 		ret = modem_cmd_send(&data->mctx.iface, &data->mctx.cmd_handler,
1479 				     NULL, 0, "AT+RST", &data->sem_if_ready,
1480 				     K_MSEC(CONFIG_WIFI_ESP_AT_RESET_TIMEOUT));
1481 		if (ret == 0 || ret != -ETIMEDOUT) {
1482 			break;
1483 		}
1484 	}
1485 
1486 	if (ret < 0) {
1487 		LOG_ERR("Failed to reset device: %d", ret);
1488 		return -EAGAIN;
1489 	}
1490 #endif
1491 	LOG_INF("Waiting for interface to come up");
1492 
1493 	ret = k_sem_take(&data->sem_if_up, ESP_INIT_TIMEOUT);
1494 	if (ret == -EAGAIN) {
1495 		LOG_ERR("Timeout waiting for interface");
1496 	}
1497 
1498 	return ret;
1499 }
1500 
esp_iface_init(struct net_if * iface)1501 static void esp_iface_init(struct net_if *iface)
1502 {
1503 	esp_offload_init(iface);
1504 
1505 	/* Not currently connected to a network */
1506 	net_if_dormant_on(iface);
1507 }
1508 
esp_offload_get_type(void)1509 static enum offloaded_net_if_types esp_offload_get_type(void)
1510 {
1511 	return L2_OFFLOADED_NET_IF_TYPE_WIFI;
1512 }
1513 
1514 static const struct wifi_mgmt_ops esp_mgmt_ops = {
1515 	.scan		   = esp_mgmt_scan,
1516 	.connect	   = esp_mgmt_connect,
1517 	.disconnect	   = esp_mgmt_disconnect,
1518 	.ap_enable	   = esp_mgmt_ap_enable,
1519 	.ap_disable	   = esp_mgmt_ap_disable,
1520 	.iface_status	   = esp_mgmt_iface_status,
1521 };
1522 
1523 static const struct net_wifi_mgmt_offload esp_api = {
1524 	.wifi_iface.iface_api.init = esp_iface_init,
1525 	.wifi_iface.get_type = esp_offload_get_type,
1526 	.wifi_mgmt_api = &esp_mgmt_ops,
1527 };
1528 
1529 static int esp_init(const struct device *dev);
1530 
1531 /* The network device must be instantiated above the init function in order
1532  * for the struct net_if that the macro declares to be visible inside the
1533  * function. An `extern` declaration does not work as the struct is static.
1534  */
1535 NET_DEVICE_DT_INST_OFFLOAD_DEFINE(0, esp_init, NULL,
1536 				  &esp_driver_data, &esp_driver_config,
1537 				  CONFIG_WIFI_INIT_PRIORITY, &esp_api,
1538 				  ESP_MTU);
1539 
1540 CONNECTIVITY_WIFI_MGMT_BIND(Z_DEVICE_DT_DEV_ID(DT_DRV_INST(0)));
1541 
esp_init(const struct device * dev)1542 static int esp_init(const struct device *dev)
1543 {
1544 #if DT_INST_NODE_HAS_PROP(0, power_gpios) || DT_INST_NODE_HAS_PROP(0, reset_gpios)
1545 	const struct esp_config *config = dev->config;
1546 #endif
1547 	struct esp_data *data = dev->data;
1548 	int ret = 0;
1549 
1550 	k_sem_init(&data->sem_tx_ready, 0, 1);
1551 	k_sem_init(&data->sem_response, 0, 1);
1552 	k_sem_init(&data->sem_if_ready, 0, 1);
1553 	k_sem_init(&data->sem_if_up, 0, 1);
1554 
1555 	k_work_init(&data->init_work, esp_init_work);
1556 	k_work_init_delayable(&data->ip_addr_work, esp_ip_addr_work);
1557 	k_work_init(&data->scan_work, esp_mgmt_scan_work);
1558 	k_work_init(&data->connect_work, esp_mgmt_connect_work);
1559 	k_work_init(&data->disconnect_work, esp_mgmt_disconnect_work);
1560 	k_work_init(&data->iface_status_work, esp_mgmt_iface_status_work);
1561 	k_work_init(&data->mode_switch_work, esp_mode_switch_work);
1562 	if (IS_ENABLED(CONFIG_WIFI_ESP_AT_DNS_USE)) {
1563 		k_work_init(&data->dns_work, esp_dns_work);
1564 	}
1565 
1566 	esp_socket_init(data);
1567 
1568 	/* initialize the work queue */
1569 	k_work_queue_start(&data->workq, esp_workq_stack,
1570 			   K_KERNEL_STACK_SIZEOF(esp_workq_stack),
1571 			   K_PRIO_COOP(CONFIG_WIFI_ESP_AT_WORKQ_THREAD_PRIORITY),
1572 			   NULL);
1573 	k_thread_name_set(&data->workq.thread, "esp_workq");
1574 
1575 	/* cmd handler */
1576 	const struct modem_cmd_handler_config cmd_handler_config = {
1577 		.match_buf = &data->cmd_match_buf[0],
1578 		.match_buf_len = sizeof(data->cmd_match_buf),
1579 		.buf_pool = &mdm_recv_pool,
1580 		.alloc_timeout = K_NO_WAIT,
1581 		.eol = "\r\n",
1582 		.user_data = NULL,
1583 		.response_cmds = response_cmds,
1584 		.response_cmds_len = ARRAY_SIZE(response_cmds),
1585 		.unsol_cmds = unsol_cmds,
1586 		.unsol_cmds_len = ARRAY_SIZE(unsol_cmds),
1587 	};
1588 
1589 	ret = modem_cmd_handler_init(&data->mctx.cmd_handler, &data->cmd_handler_data,
1590 				     &cmd_handler_config);
1591 	if (ret < 0) {
1592 		goto error;
1593 	}
1594 
1595 	/* modem interface */
1596 	const struct modem_iface_uart_config uart_config = {
1597 		.rx_rb_buf = &data->iface_rb_buf[0],
1598 		.rx_rb_buf_len = sizeof(data->iface_rb_buf),
1599 		.dev = DEVICE_DT_GET(DT_INST_BUS(0)),
1600 		.hw_flow_control = DT_PROP(ESP_BUS, hw_flow_control),
1601 	};
1602 
1603 	ret = modem_iface_uart_init(&data->mctx.iface, &data->iface_data, &uart_config);
1604 	if (ret < 0) {
1605 		goto error;
1606 	}
1607 
1608 	/* pin setup */
1609 #if DT_INST_NODE_HAS_PROP(0, power_gpios)
1610 	ret = gpio_pin_configure_dt(&config->power, GPIO_OUTPUT_INACTIVE);
1611 	if (ret < 0) {
1612 		LOG_ERR("Failed to configure %s pin", "power");
1613 		goto error;
1614 	}
1615 #endif
1616 #if DT_INST_NODE_HAS_PROP(0, reset_gpios)
1617 	ret = gpio_pin_configure_dt(&config->reset, GPIO_OUTPUT_INACTIVE);
1618 	if (ret < 0) {
1619 		LOG_ERR("Failed to configure %s pin", "reset");
1620 		goto error;
1621 	}
1622 #endif
1623 
1624 	data->mctx.driver_data = data;
1625 
1626 	ret = modem_context_register(&data->mctx);
1627 	if (ret < 0) {
1628 		LOG_ERR("Error registering modem context: %d", ret);
1629 		goto error;
1630 	}
1631 
1632 	/* start RX thread */
1633 	k_thread_create(&esp_rx_thread, esp_rx_stack,
1634 			K_KERNEL_STACK_SIZEOF(esp_rx_stack),
1635 			esp_rx,
1636 			data, NULL, NULL,
1637 			K_PRIO_COOP(CONFIG_WIFI_ESP_AT_RX_THREAD_PRIORITY), 0,
1638 			K_NO_WAIT);
1639 	k_thread_name_set(&esp_rx_thread, "esp_rx");
1640 
1641 	/* Retrieve associated network interface so asynchronous messages can be processed early */
1642 	data->net_iface = NET_IF_GET(Z_DEVICE_DT_DEV_ID(DT_DRV_INST(0)), 0);
1643 
1644 	/* Reset the modem */
1645 	ret = esp_reset(dev);
1646 
1647 error:
1648 	return ret;
1649 }
1650