1# This example code is in the Public Domain (or CC0 licensed, at your option.)
2
3# Unless required by applicable law or agreed to in writing, this
4# software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
5# CONDITIONS OF ANY KIND, either express or implied.
6
7# -*- coding: utf-8 -*-
8
9from __future__ import print_function, unicode_literals
10
11import os
12import re
13import socket
14import sys
15from builtins import input
16from threading import Event, Thread
17
18import netifaces
19import ttfw_idf
20
21# -----------  Config  ----------
22PORT = 3333
23INTERFACE = 'eth0'
24# -------------------------------
25
26
27def get_my_ip(type):
28    for i in netifaces.ifaddresses(INTERFACE)[type]:
29        return i['addr'].replace('%{}'.format(INTERFACE), '')
30
31
32class UdpServer:
33
34    def __init__(self, port, family_addr, persist=False):
35        self.port = port
36        self.family_addr = family_addr
37        self.socket = socket.socket(family_addr, socket.SOCK_DGRAM)
38        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
39        self.socket.settimeout(60.0)
40        self.shutdown = Event()
41        self.persist = persist
42
43    def __enter__(self):
44        try:
45            self.socket.bind(('', self.port))
46        except socket.error as e:
47            print('Bind failed:{}'.format(e))
48            raise
49
50        print('Starting server on port={} family_addr={}'.format(self.port, self.family_addr))
51        self.server_thread = Thread(target=self.run_server)
52        self.server_thread.start()
53        return self
54
55    def __exit__(self, exc_type, exc_value, traceback):
56        if self.persist:
57            sock = socket.socket(self.family_addr, socket.SOCK_DGRAM)
58            sock.sendto(b'Stop', ('localhost', self.port))
59            sock.close()
60            self.shutdown.set()
61        self.server_thread.join()
62        self.socket.close()
63
64    def run_server(self):
65        while not self.shutdown.is_set():
66            try:
67                data, addr = self.socket.recvfrom(1024)
68                if not data:
69                    return
70                data = data.decode()
71                print('Reply[' + addr[0] + ':' + str(addr[1]) + '] - ' + data)
72                reply = 'OK: ' + data
73                self.socket.sendto(reply.encode(), addr)
74            except socket.error as e:
75                print('Running server failed:{}'.format(e))
76                raise
77            if not self.persist:
78                break
79
80
81@ttfw_idf.idf_example_test(env_tag='Example_WIFI_Protocols')
82def test_examples_protocol_socket_udpclient(env, extra_data):
83    """
84    steps:
85      1. join AP
86      2. have the board connect to the server
87      3. send and receive data
88    """
89    dut1 = env.get_dut('udp_client', 'examples/protocols/sockets/udp_client', dut_class=ttfw_idf.ESP32DUT)
90    # check and log bin size
91    binary_file = os.path.join(dut1.app.binary_path, 'udp_client.bin')
92    bin_size = os.path.getsize(binary_file)
93    ttfw_idf.log_performance('udp_client_bin_size', '{}KB'.format(bin_size // 1024))
94
95    # start test
96    dut1.start_app()
97
98    ipv4 = dut1.expect(re.compile(r' IPv4 address: ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)'), timeout=30)[0]
99    ipv6_r = r':'.join((r'[0-9a-fA-F]{4}',) * 8)    # expect all 8 octets from IPv6 (assumes it's printed in the long form)
100    ipv6 = dut1.expect(re.compile(r' IPv6 address: ({})'.format(ipv6_r)), timeout=30)[0]
101    print('Connected with IPv4={} and IPv6={}'.format(ipv4, ipv6))
102
103    # test IPv4
104    with UdpServer(PORT, socket.AF_INET):
105        server_ip = get_my_ip(netifaces.AF_INET)
106        print('Connect udp client to server IP={}'.format(server_ip))
107        dut1.write(server_ip)
108        dut1.expect(re.compile(r'OK: Message from ESP32'))
109    # test IPv6
110    with UdpServer(PORT, socket.AF_INET6):
111        server_ip = get_my_ip(netifaces.AF_INET6)
112        print('Connect udp client to server IP={}'.format(server_ip))
113        dut1.write(server_ip)
114        dut1.expect(re.compile(r'OK: Message from ESP32'))
115
116
117if __name__ == '__main__':
118    if sys.argv[1:] and sys.argv[1].startswith('IPv'):     # if additional arguments provided:
119        # Usage: example_test.py <IPv4|IPv6>
120        family_addr = socket.AF_INET6 if sys.argv[1] == 'IPv6' else socket.AF_INET
121        with UdpServer(PORT, family_addr, persist=True) as s:
122            print(input('Press Enter stop the server...'))
123    else:
124        test_examples_protocol_socket_udpclient()
125