Skip to content

Commit 43936ab

Browse files
committed
Merge branch 'bugfix/mdns_query_failed_after_init' into 'master'
Fixed: mdns query failed after init See merge request idf/esp-idf!3480
2 parents f2de760 + 6309643 commit 43936ab

File tree

5 files changed

+242
-23
lines changed

5 files changed

+242
-23
lines changed

components/mdns/mdns.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3465,7 +3465,7 @@ static mdns_tx_packet_t * _mdns_create_search_packet(mdns_search_once_t * search
34653465
static void _mdns_search_send_pcb(mdns_search_once_t * search, tcpip_adapter_if_t tcpip_if, mdns_ip_protocol_t ip_protocol)
34663466
{
34673467
mdns_tx_packet_t * packet = NULL;
3468-
if (_mdns_server->interfaces[tcpip_if].pcbs[ip_protocol].pcb && _mdns_server->interfaces[tcpip_if].pcbs[ip_protocol].state == PCB_RUNNING) {
3468+
if (_mdns_server->interfaces[tcpip_if].pcbs[ip_protocol].pcb && _mdns_server->interfaces[tcpip_if].pcbs[ip_protocol].state > PCB_INIT) {
34693469
packet = _mdns_create_search_packet(search, tcpip_if, ip_protocol);
34703470
if (!packet) {
34713471
return;

examples/protocols/mdns/README.md

Lines changed: 82 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,88 @@ Shows how to use mDNS to advertise lookup services and hosts
1010
- GPIO0 (BOOT Button) is initialized as pulled-up input that can be monitored for button press
1111
- Example task is started to check if the button is pressed so it can execute the mDNS queries defined
1212

13-
## Running the example
13+
### Configure the project
1414

15-
- Run `make menuconfig` to configure the access point's SSID and Password and the default device mDNS host name and instance name
16-
- Run `make flash monitor` to build and upload the example to your board and connect to it's serial terminal
17-
- Wait for WiFi to connec to your access point
18-
- You can now ping the device at `[hostname].local` and browse for `_http._tcp` on the same network to find the advertised service
19-
- Pressing the BOOT button will start quring the local network for the predefined in `check_button` hosts and services
15+
```
16+
make menuconfig
17+
```
18+
19+
* Set `Default serial port` under `Serial flasher config`.
20+
* Set `WiFi SSID` and `WiFi Password` for the board to connect to AP.
21+
* Set `mDNS Hostname` as host name prefix for the device and its instance name in `mDNS Instance Name`
22+
* Disable `Resolve test services` to prevent the example from querying defined names/services on startup (cause warnings in example logs, as illustrated below)
23+
24+
### Build and Flash
25+
26+
Build the project and flash it to the board, then run monitor tool to view serial output:
27+
28+
```
29+
make -j4 flash monitor
30+
```
31+
- Wait for WiFi to connect to your access point
32+
- You can now ping the device at `[board-hostname].local`, where `[board-hostname]` is a string created from preconfigured hostname (`esp32-mdns` by default) and last 3 bytes from device MAC address. Please check the serial output log for the specific board-hostname (`esp32-mdns_80FFFF` in the log below)
33+
- You can also browse for `_http._tcp` on the same network to find the advertised service
34+
- Pressing the BOOT button will start querying the local network for the predefined in `check_button` hosts and services
35+
36+
37+
(To exit the serial monitor, type ``Ctrl-]``.)
38+
39+
See the Getting Started Guide for full steps to configure and use ESP-IDF to build projects.
40+
41+
## Example Output
42+
```
43+
I (0) cpu_start: Starting scheduler on APP CPU.
44+
I (276) system_api: Base MAC address is not set, read default base MAC address from BLK0 of EFUSE
45+
I (276) mdns-test: mdns hostname set to: [esp32-mdns_80FFFF]
46+
I (286) wifi: wifi driver task: 3ffc2fa4, prio:23, stack:3584, core=0
47+
I (286) wifi: wifi firmware version: a3be639
48+
I (286) wifi: config NVS flash: enabled
49+
I (296) wifi: config nano formating: disabled
50+
I (296) system_api: Base MAC address is not set, read default base MAC address from BLK0 of EFUSE
51+
I (306) system_api: Base MAC address is not set, read default base MAC address from BLK0 of EFUSE
52+
I (336) wifi: Init dynamic tx buffer num: 32
53+
I (336) wifi: Init data frame dynamic rx buffer num: 32
54+
I (336) wifi: Init management frame dynamic rx buffer num: 32
55+
I (346) wifi: Init static rx buffer size: 1600
56+
I (346) wifi: Init static rx buffer num: 10
57+
I (346) wifi: Init dynamic rx buffer num: 32
58+
I (356) mdns-test: Setting WiFi configuration SSID myssid...
59+
I (426) phy: phy_version: 4000, b6198fa, Sep 3 2018, 15:11:06, 0, 0
60+
I (426) wifi: mode : sta (30:ae:a4:80:FF:FF)
61+
I (426) gpio: GPIO[0]| InputEn: 1| OutputEn: 0| OpenDrain: 0| Pullup: 1| Pulldown: 0| Intr:0
62+
I (1756) wifi: n:11 0, o:1 0, ap:255 255, sta:11 0, prof:1
63+
I (2736) wifi: state: init -> auth (b0)
64+
I (2756) wifi: state: auth -> assoc (0)
65+
I (2766) wifi: state: assoc -> run (10)
66+
I (2786) wifi: connected with myssid, channel 11
67+
I (2786) wifi: pm start, type: 1
68+
69+
I (4786) event: sta ip: 192.168.0.139, mask: 255.255.255.0, gw: 192.168.0.2
70+
I (4786) mdns-test: Query A: tinytester.local
71+
W (6876) mdns-test: ESP_ERR_NOT_FOUND: Host was not found!
72+
I (6876) mdns-test: Query PTR: _tiny._tcp.local
73+
W (9976) mdns-test: No results found!
74+
I (21126) mdns-test: Query A: esp32.local
75+
W (23176) mdns-test: ESP_ERR_NOT_FOUND: Host was not found!
76+
I (23176) mdns-test: Query PTR: _arduino._tcp.local
77+
W (26276) mdns-test: No results found!
78+
I (26276) mdns-test: Query PTR: _http._tcp.local
79+
1: Interface: STA, Type: V6
80+
PTR : HP Color LaserJet MFP M277dw (7C2E10)
81+
SRV : NPI7C2E10.local:80
82+
A : 254.128.0.0
83+
2: Interface: STA, Type: V4
84+
PTR : switch4e4919
85+
SRV : switch4e4919.local:80
86+
TXT : [1] path=/config/authentication_page.htm;
87+
A : 192.168.0.118
88+
I (29396) mdns-test: Query PTR: _printer._tcp.local
89+
1: Interface: STA, Type: V6
90+
PTR : HP Color LaserJet MFP M277dw (7C2E10)
91+
SRV : NPI7C2E10.local:515
92+
A : 254.128.0.0
93+
2: Interface: STA, Type: V4
94+
PTR : HP Color LaserJet MFP M277dw (7C2E10)
95+
```
2096

2197
See the README.md file in the upper level 'examples' directory for more information about examples.

examples/protocols/mdns/main/Kconfig.projbuild

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,28 +2,37 @@ menu "Example Configuration"
22

33
config WIFI_SSID
44
string "WiFi SSID"
5-
default "myssid"
6-
help
7-
SSID (network name) for the example to connect to.
5+
default "myssid"
6+
help
7+
SSID (network name) for the example to connect to.
88

99
config WIFI_PASSWORD
1010
string "WiFi Password"
11-
default "mypassword"
12-
help
13-
WiFi password (WPA or WPA2) for the example to use.
11+
default "mypassword"
12+
help
13+
WiFi password (WPA or WPA2) for the example to use.
1414

15-
Can be left blank if the network has no security set.
15+
Can be left blank if the network has no security set.
1616

1717
config MDNS_HOSTNAME
1818
string "mDNS Hostname"
19-
default "esp32-mdns"
20-
help
21-
mDNS Hostname for example to use
19+
default "esp32-mdns"
20+
help
21+
mDNS Hostname for example to use
2222

2323
config MDNS_INSTANCE
2424
string "mDNS Instance Name"
25-
default "ESP32 with mDNS"
26-
help
27-
mDNS Instance Name for example to use
25+
default "ESP32 with mDNS"
26+
help
27+
mDNS Instance Name for example to use
28+
29+
config RESOLVE_TEST_SERVICES
30+
bool "Resolve test services"
31+
default y
32+
help
33+
Enable resolving test services on startup.
34+
These services are advertized and evaluated in automated tests.
35+
When executed locally, these will not be resolved and warnings appear in the log.
36+
Please set to false to disable initial querying to avoid warnings.
2837

2938
endmenu

examples/protocols/mdns/main/mdns_example_main.c

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,12 @@
2929
#define EXAMPLE_WIFI_SSID CONFIG_WIFI_SSID
3030
#define EXAMPLE_WIFI_PASS CONFIG_WIFI_PASSWORD
3131

32-
#define EXAMPLE_MDNS_HOSTNAME CONFIG_MDNS_HOSTNAME
3332
#define EXAMPLE_MDNS_INSTANCE CONFIG_MDNS_INSTANCE
3433

34+
3535
/* FreeRTOS event group to signal when we are connected & ready to make a request */
3636
static EventGroupHandle_t wifi_event_group;
37+
static const char c_config_hostname[] = CONFIG_MDNS_HOSTNAME;
3738

3839
/* The event group allows multiple bits for each event,
3940
but we only care about one event - are we connected
@@ -97,10 +98,20 @@ static void initialise_wifi(void)
9798

9899
static void initialise_mdns(void)
99100
{
101+
_Static_assert(sizeof(c_config_hostname) < CONFIG_MAIN_TASK_STACK_SIZE/2, "Configured mDNS name consumes more than half of the stack. Please select a shorter host name or extend the main stack size please.");
102+
const size_t config_hostname_len = sizeof(c_config_hostname) - 1; // without term char
103+
char hostname[config_hostname_len + 1 + 3*2 + 1]; // adding underscore + 3 digits + term char
104+
uint8_t mac[6];
105+
106+
// adding 3 LSBs from mac addr to setup a board specific name
107+
esp_read_mac(mac, ESP_MAC_WIFI_STA);
108+
snprintf(hostname, sizeof(hostname), "%s_%02x%02X%02X", c_config_hostname, mac[3], mac[4], mac[5]);
109+
100110
//initialize mDNS
101111
ESP_ERROR_CHECK( mdns_init() );
102112
//set mDNS hostname (required if you want to advertise services)
103-
ESP_ERROR_CHECK( mdns_hostname_set(EXAMPLE_MDNS_HOSTNAME) );
113+
ESP_ERROR_CHECK( mdns_hostname_set(hostname) );
114+
ESP_LOGI(TAG, "mdns hostname set to: [%s]", hostname);
104115
//set default mDNS instance name
105116
ESP_ERROR_CHECK( mdns_instance_name_set(EXAMPLE_MDNS_INSTANCE) );
106117

@@ -191,7 +202,7 @@ static void query_mdns_host(const char * host_name)
191202
return;
192203
}
193204

194-
ESP_LOGI(TAG, IPSTR, IP2STR(&addr));
205+
ESP_LOGI(TAG, "Query A: %s.local resolved to: " IPSTR, host_name, IP2STR(&addr));
195206
}
196207

197208
static void initialise_button(void)
@@ -228,6 +239,12 @@ static void mdns_example_task(void *pvParameters)
228239
/* Wait for the callback to set the CONNECTED_BIT in the event group. */
229240
xEventGroupWaitBits(wifi_event_group, IP4_CONNECTED_BIT | IP6_CONNECTED_BIT,
230241
false, true, portMAX_DELAY);
242+
243+
#if CONFIG_RESOLVE_TEST_SERVICES == 1
244+
/* Send initial queries that are started by CI tester */
245+
query_mdns_host("tinytester");
246+
#endif
247+
231248
while(1) {
232249
check_button();
233250
vTaskDelay(50 / portTICK_PERIOD_MS);
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
import re
2+
import os
3+
import sys
4+
import socket
5+
import time
6+
import imp
7+
import struct
8+
import dpkt, dpkt.dns
9+
from threading import Thread
10+
11+
12+
13+
# this is a test case write with tiny-test-fw.
14+
# to run test cases outside tiny-test-fw,
15+
# we need to set environment variable `TEST_FW_PATH`,
16+
# then get and insert `TEST_FW_PATH` to sys path before import FW module
17+
18+
test_fw_path = os.getenv("TEST_FW_PATH")
19+
if test_fw_path and test_fw_path not in sys.path:
20+
sys.path.insert(0, test_fw_path)
21+
22+
import TinyFW
23+
import IDF
24+
25+
g_run_server = True
26+
g_done = False
27+
28+
def mdns_server(esp_host):
29+
global g_run_server
30+
global g_done
31+
UDP_IP="0.0.0.0"
32+
UDP_PORT=5353
33+
MCAST_GRP = '224.0.0.251'
34+
sock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
35+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
36+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
37+
sock.bind( (UDP_IP,UDP_PORT) )
38+
mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)
39+
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
40+
dns = dpkt.dns.DNS(b'\x00\x00\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x01')
41+
# sock.sendto(dns.pack(),(MCAST_GRP,UDP_PORT))
42+
sock.settimeout(30)
43+
resp_dns = dpkt.dns.DNS(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
44+
resp_dns.op = dpkt.dns.DNS_QR | dpkt.dns.DNS_AA
45+
resp_dns.rcode = dpkt.dns.DNS_RCODE_NOERR
46+
arr = dpkt.dns.DNS.RR()
47+
arr.cls = dpkt.dns.DNS_IN
48+
arr.type = dpkt.dns.DNS_A
49+
arr.name = u'tinytester.local'
50+
arr.ip =socket.inet_aton('127.0.0.1')
51+
resp_dns. an.append(arr)
52+
sock.sendto(resp_dns.pack(),(MCAST_GRP,UDP_PORT))
53+
while g_run_server:
54+
try:
55+
m=sock.recvfrom( 1024 );
56+
dns = dpkt.dns.DNS(m[0])
57+
if len(dns.qd)>0 and dns.qd[0].type == dpkt.dns.DNS_A:
58+
if dns.qd[0].name == u'tinytester.local':
59+
print (dns.__repr__(),dns.qd[0].name)
60+
sock.sendto(resp_dns.pack(),(MCAST_GRP,UDP_PORT))
61+
if len(dns.an)>0 and dns.an[0].type == dpkt.dns.DNS_A:
62+
if dns.an[0].name == esp_host + u'.local':
63+
print("Received answer esp32-mdns query")
64+
g_done = True
65+
print (dns.an[0].name)
66+
dns = dpkt.dns.DNS(b'\x00\x00\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x01')
67+
dns.qd[0].name= esp_host + u'.local'
68+
sock.sendto(dns.pack(),(MCAST_GRP,UDP_PORT))
69+
print("Sending esp32-mdns query")
70+
time.sleep(0.5)
71+
except socket.timeout:
72+
break
73+
74+
@IDF.idf_example_test(env_tag="Example_WIFI")
75+
def test_examples_protocol_mdns(env, extra_data):
76+
global g_run_server
77+
global g_done
78+
"""
79+
steps: |
80+
1. join AP + init mdns example
81+
2. get the dut host name (and IP address)
82+
3. check the mdns name is accessible
83+
4. check DUT output if mdns advertized host is resolved
84+
"""
85+
dut1 = env.get_dut("mdns-test", "examples/protocols/mdns")
86+
# check and log bin size
87+
binary_file = os.path.join(dut1.app.binary_path, "mdns-test.bin")
88+
bin_size = os.path.getsize(binary_file)
89+
IDF.log_performance("mdns-test_bin_size", "{}KB".format(bin_size//1024))
90+
IDF.check_performance("mdns-test_bin_size", bin_size//1024)
91+
# 1. start mdns application
92+
dut1.start_app()
93+
# 2. get the dut host name (and IP address)
94+
specific_host = dut1.expect(re.compile(r"mdns hostname set to: \[([^\]]+)\]"), timeout=30)
95+
specific_host = str(specific_host[0])
96+
dut_ip = ""
97+
try:
98+
dut_ip = dut1.expect(re.compile(r" sta ip: ([^,]+),"), timeout=30)
99+
except DUT.ExpectTimeout:
100+
raise ValueError('ENV_TEST_FAILURE: Cannot connect to AP')
101+
# 3. check the mdns name is accessible
102+
thread1 = Thread(target = mdns_server, args = (specific_host,))
103+
thread1.start()
104+
start = time.time()
105+
while (time.time() - start) <= 60:
106+
if g_done:
107+
print("Test passed")
108+
break
109+
g_run_server = False
110+
thread1.join()
111+
if g_done == False:
112+
raise ValueError('Test has failed: did not receive mdns answer within timeout')
113+
# 4. check DUT output if mdns advertized host is resolved
114+
dut1.expect(re.compile(r"mdns-test: Query A: tinytester.local resolved to: 127.0.0.1"), timeout=30)
115+
116+
if __name__ == '__main__':
117+
test_examples_protocol_mdns()

0 commit comments

Comments
 (0)