example_test.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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 sys
  12. import netifaces
  13. import socket
  14. from threading import Thread, Event
  15. import ttfw_idf
  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 TcpServer:
  24. def __init__(self, port, family_addr, persist=False):
  25. self.port = port
  26. self.socket = socket.socket(family_addr, socket.SOCK_STREAM)
  27. self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  28. self.socket.settimeout(10.0)
  29. self.shutdown = Event()
  30. self.persist = persist
  31. self.family_addr = family_addr
  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.socket.listen(1)
  39. self.server_thread = Thread(target=self.run_server)
  40. self.server_thread.start()
  41. return self
  42. def __exit__(self, exc_type, exc_value, traceback):
  43. if self.persist:
  44. sock = socket.socket(self.family_addr, socket.SOCK_STREAM)
  45. sock.connect(('localhost', self.port))
  46. sock.sendall(b'Stop', )
  47. sock.close()
  48. self.shutdown.set()
  49. self.shutdown.set()
  50. self.server_thread.join()
  51. self.socket.close()
  52. def run_server(self):
  53. while not self.shutdown.is_set():
  54. try:
  55. conn, address = self.socket.accept() # accept new connection
  56. print("Connection from: {}".format(address))
  57. conn.setblocking(1)
  58. data = conn.recv(1024)
  59. if not data:
  60. return
  61. data = data.decode()
  62. print('Received data: ' + data)
  63. reply = 'OK: ' + data
  64. conn.send(reply.encode())
  65. conn.close()
  66. except socket.error as e:
  67. print("Running server failed:{}".format(e))
  68. raise
  69. if not self.persist:
  70. break
  71. @ttfw_idf.idf_example_test(env_tag="Example_WIFI")
  72. def test_examples_protocol_socket(env, extra_data):
  73. """
  74. steps:
  75. 1. join AP
  76. 2. have the board connect to the server
  77. 3. send and receive data
  78. """
  79. dut1 = env.get_dut("tcp_client", "examples/protocols/sockets/tcp_client", dut_class=ttfw_idf.ESP32DUT)
  80. # check and log bin size
  81. binary_file = os.path.join(dut1.app.binary_path, "tcp_client.bin")
  82. bin_size = os.path.getsize(binary_file)
  83. ttfw_idf.log_performance("tcp_client_bin_size", "{}KB".format(bin_size // 1024))
  84. ttfw_idf.check_performance("tcp_client_bin_size", bin_size // 1024, dut1.TARGET)
  85. # start test
  86. dut1.start_app()
  87. data = dut1.expect(re.compile(r" IPv4 address: ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)"), timeout=30)
  88. print("Connected with IPv4: {}".format(data[0]))
  89. # test IPv4
  90. with TcpServer(PORT, socket.AF_INET):
  91. dut1.write(get_my_ip(netifaces.AF_INET))
  92. dut1.expect(re.compile(r"OK: Message from ESP32"))
  93. # test IPv6
  94. with TcpServer(PORT, socket.AF_INET6):
  95. dut1.write(get_my_ip(netifaces.AF_INET6))
  96. dut1.expect(re.compile(r"OK: Message from ESP32"))
  97. if __name__ == '__main__':
  98. if sys.argv[1:] and sys.argv[1].startswith("IPv"): # if additional arguments provided:
  99. # Usage: example_test.py <IPv4|IPv6>
  100. family_addr = socket.AF_INET6 if sys.argv[1] == "IPv6" else socket.AF_INET
  101. with TcpServer(PORT, family_addr, persist=True) as s:
  102. print(input("Press Enter stop the server..."))
  103. else:
  104. test_examples_protocol_socket()