wss_server_example_test.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. #!/usr/bin/env python
  2. #
  3. # SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD
  4. # SPDX-License-Identifier: Apache-2.0
  5. from __future__ import division, print_function, unicode_literals
  6. import os
  7. import re
  8. import threading
  9. import time
  10. from types import TracebackType
  11. from typing import Any, Optional
  12. import tiny_test_fw
  13. import ttfw_idf
  14. import websocket
  15. from tiny_test_fw import Utility
  16. OPCODE_TEXT = 0x1
  17. OPCODE_BIN = 0x2
  18. OPCODE_PING = 0x9
  19. OPCODE_PONG = 0xa
  20. CORRECT_ASYNC_DATA = 'Hello client'
  21. class WsClient:
  22. def __init__(self, ip, port, ca_file): # type: (str, int, str) -> None
  23. self.port = port
  24. self.ip = ip
  25. sslopt = {'ca_certs':ca_file, 'check_hostname': False}
  26. self.ws = websocket.WebSocket(sslopt=sslopt)
  27. # Set timeout to 10 seconds to avoid conection failure at the time of handshake
  28. self.ws.settimeout(10)
  29. def __enter__(self): # type: ignore
  30. self.ws.connect('wss://{}:{}/ws'.format(self.ip, self.port))
  31. return self
  32. def __exit__(self, exc_type, exc_value, traceback): # type: (type, RuntimeError, TracebackType) -> None
  33. self.ws.close()
  34. def read(self): # type: () -> Any
  35. return self.ws.recv_data(control_frame=True)
  36. def write(self, data, opcode=OPCODE_TEXT): # type: (str, int) -> Any
  37. if opcode == OPCODE_PING:
  38. return self.ws.ping(data)
  39. if opcode == OPCODE_PONG:
  40. return self.ws.pong(data)
  41. return self.ws.send(data)
  42. class wss_client_thread(threading.Thread):
  43. def __init__(self, ip, port, ca_file): # type: (str, int, str) -> None
  44. threading.Thread.__init__(self)
  45. self.ip = ip
  46. self.port = port
  47. self.ca_file = ca_file
  48. self.start_time = time.time()
  49. self.exc = None
  50. self.data = 'Espressif'
  51. self.async_response = False
  52. def run(self): # type: () -> None
  53. with WsClient(self.ip, self.port, self.ca_file) as ws:
  54. while True:
  55. try:
  56. opcode, data = ws.read()
  57. data = data.decode('UTF-8')
  58. if opcode == OPCODE_PING:
  59. ws.write(data=self.data, opcode=OPCODE_PONG)
  60. if opcode == OPCODE_TEXT:
  61. if data == CORRECT_ASYNC_DATA:
  62. self.async_response = True
  63. Utility.console_log('Thread {} obtained correct async message'.format(self.name))
  64. # Keep sending pong to update the keepalive in the server
  65. if (time.time() - self.start_time) > 20:
  66. break
  67. except Exception as e:
  68. Utility.console_log('Failed to connect to the client and read async data')
  69. self.exc = e # type: ignore
  70. if self.async_response is not True:
  71. self.exc = RuntimeError('Failed to obtain correct async data') # type: ignore
  72. def join(self, timeout=0): # type:(Optional[float]) -> None
  73. threading.Thread.join(self)
  74. if self.exc:
  75. raise self.exc
  76. def test_multiple_client_keep_alive_and_async_response(ip, port, ca_file): # type: (str, int, str) -> None
  77. threads = []
  78. for _ in range(3):
  79. try:
  80. thread = wss_client_thread(ip, port, ca_file)
  81. thread.start()
  82. threads.append(thread)
  83. except OSError:
  84. Utility.console_log('Error: unable to start thread')
  85. # keep delay of 5 seconds between two connections to avoid handshake timeout
  86. time.sleep(5)
  87. for t in threads:
  88. t.join()
  89. @ttfw_idf.idf_example_test(env_tag='Example_WIFI_Protocols')
  90. def test_examples_protocol_https_wss_server(env, extra_data): # type: (tiny_test_fw.Env.Env, None) -> None # pylint: disable=unused-argument
  91. # Acquire DUT
  92. dut1 = env.get_dut('https_server', 'examples/protocols/https_server/wss_server', dut_class=ttfw_idf.ESP32DUT)
  93. # Get binary file
  94. binary_file = os.path.join(dut1.app.binary_path, 'wss_server.bin')
  95. bin_size = os.path.getsize(binary_file)
  96. ttfw_idf.log_performance('https_wss_server_bin_size', '{}KB'.format(bin_size // 1024))
  97. # Upload binary and start testing
  98. Utility.console_log('Starting wss_server test app')
  99. dut1.start_app()
  100. # Parse IP address of STA
  101. got_port = dut1.expect(re.compile(r'Server listening on port (\d+)'), timeout=60)[0]
  102. Utility.console_log('Waiting to connect with AP')
  103. got_ip = dut1.expect(re.compile(r'IPv4 address: (\d+\.\d+\.\d+\.\d+)'), timeout=60)[0]
  104. Utility.console_log('Got IP : ' + got_ip)
  105. Utility.console_log('Got Port : ' + got_port)
  106. ca_file = os.path.join(os.path.dirname(__file__), 'main', 'certs', 'servercert.pem')
  107. # Start ws server test
  108. with WsClient(got_ip, int(got_port), ca_file) as ws:
  109. # Check for echo
  110. DATA = 'Espressif'
  111. dut1.expect('performing session handshake')
  112. client_fd = dut1.expect(re.compile(r'New client connected (\d+)'), timeout=20)[0]
  113. ws.write(data=DATA, opcode=OPCODE_TEXT)
  114. dut1.expect(re.compile(r'Received packet with message: {}'.format(DATA)))
  115. opcode, data = ws.read()
  116. data = data.decode('UTF-8')
  117. if data != DATA:
  118. raise RuntimeError('Failed to receive the correct echo response')
  119. Utility.console_log('Correct echo response obtained from the wss server')
  120. # Test for keepalive
  121. Utility.console_log('Testing for keep alive (approx time = 20s)')
  122. start_time = time.time()
  123. while True:
  124. try:
  125. opcode, data = ws.read()
  126. if opcode == OPCODE_PING:
  127. ws.write(data='Espressif', opcode=OPCODE_PONG)
  128. Utility.console_log('Received PING, replying PONG (to update the keepalive)')
  129. # Keep sending pong to update the keepalive in the server
  130. if (time.time() - start_time) > 20:
  131. break
  132. except Exception:
  133. Utility.console_log('Failed the test for keep alive,\nthe client got abruptly disconnected')
  134. raise
  135. # keepalive timeout is 10 seconds so do not respond for (10 + 1) senconds
  136. Utility.console_log('Testing if client is disconnected if it does not respond for 10s i.e. keep_alive timeout (approx time = 11s)')
  137. try:
  138. dut1.expect('Client not alive, closing fd {}'.format(client_fd), timeout=20)
  139. dut1.expect('Client disconnected {}'.format(client_fd))
  140. except Exception:
  141. Utility.console_log('ENV_ERROR:Failed the test for keep alive,\nthe connection was not closed after timeout')
  142. time.sleep(11)
  143. Utility.console_log('Passed the test for keep alive')
  144. # Test keep alive and async response for multiple simultaneous client connections
  145. Utility.console_log('Testing for multiple simultaneous client connections (approx time = 30s)')
  146. test_multiple_client_keep_alive_and_async_response(got_ip, int(got_port), ca_file)
  147. Utility.console_log('Passed the test for multiple simultaneous client connections')
  148. if __name__ == '__main__':
  149. test_examples_protocol_https_wss_server() # pylint: disable=no-value-for-parameter