example_test.py 3.9 KB

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