example_test.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. # SPDX-FileCopyrightText: 2016-2021 Espressif Systems (Shanghai) CO LTD
  2. # SPDX-License-Identifier: Apache-2.0
  3. import logging
  4. import os
  5. import re
  6. from threading import Thread
  7. import ttfw_idf
  8. from tiny_test_fw import DUT
  9. LOG_LEVEL = logging.DEBUG
  10. LOGGER_NAME = 'modbus_test'
  11. # Allowed options for the test
  12. TEST_READ_MAX_ERR_COUNT = 3 # Maximum allowed read errors during initialization
  13. TEST_THREAD_JOIN_TIMEOUT = 60 # Test theread join timeout in seconds
  14. TEST_EXPECT_STR_TIMEOUT = 30 # Test expect timeout in seconds
  15. TEST_MASTER_TCP = 'mb_tcp_master'
  16. TEST_SLAVE_TCP = 'mb_tcp_slave'
  17. STACK_DEFAULT = 0
  18. STACK_IPV4 = 1
  19. STACK_IPV6 = 2
  20. STACK_INIT = 3
  21. STACK_CONNECT = 4
  22. STACK_START = 5
  23. STACK_PAR_OK = 6
  24. STACK_PAR_FAIL = 7
  25. STACK_DESTROY = 8
  26. pattern_dict_slave = {STACK_IPV4: (r'.*I \([0-9]+\) example_connect: - IPv4 address: ([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}).*'),
  27. STACK_IPV6: (r'.*I \([0-9]+\) example_connect: - IPv6 address: (([A-Fa-f0-9]{1,4}::?){1,7}[A-Fa-f0-9]{1,4}).*'),
  28. STACK_INIT: (r'.*I \(([0-9]+)\) MB_TCP_SLAVE_PORT: (Protocol stack initialized).'),
  29. STACK_CONNECT: (r'.*I\s\(([0-9]+)\) MB_TCP_SLAVE_PORT: Socket \(#[0-9]+\), accept client connection from address: '
  30. r'([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}).*'),
  31. STACK_START: (r'.*I\s\(([0-9]+)\) SLAVE_TEST: (Start modbus test).*'),
  32. STACK_PAR_OK: (r'.*I\s\(([0-9]+)\) SLAVE_TEST: ([A-Z]+ [A-Z]+) \([a-zA-Z0-9_]+ us\),\s'
  33. r'ADDR:([0-9]+), TYPE:[0-9]+, INST_ADDR:0x[a-zA-Z0-9]+, SIZE:[0-9]+'),
  34. STACK_PAR_FAIL: (r'.*E \(([0-9]+)\) SLAVE_TEST: Response time exceeds configured [0-9]+ [ms], ignore packet.*'),
  35. STACK_DESTROY: (r'.*I\s\(([0-9]+)\) SLAVE_TEST: (Modbus controller destroyed).')}
  36. pattern_dict_master = {STACK_IPV4: (r'.*I \([0-9]+\) example_connect: - IPv4 address: ([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}).*'),
  37. STACK_IPV6: (r'.*I \([0-9]+\) example_connect: - IPv6 address: (([A-Fa-f0-9]{1,4}::?){1,7}[A-Fa-f0-9]{1,4}).*'),
  38. STACK_INIT: (r'.*I \(([0-9]+)\) MASTER_TEST: (Modbus master stack initialized).*'),
  39. STACK_CONNECT: (r'.*.*I\s\(([0-9]+)\) MB_TCP_MASTER_PORT: (Connected [0-9]+ slaves), start polling.*'),
  40. STACK_START: (r'.*I \(([0-9]+)\) MASTER_TEST: (Start modbus test).*'),
  41. STACK_PAR_OK: (r'.*I\s\(([0-9]+)\) MASTER_TEST: Characteristic #[0-9]+ ([a-zA-Z0-9_]+)'
  42. r'\s\([a-zA-Z\%\/]+\) value = [a-zA-Z0-9\.]+ \(0x[a-zA-Z0-9]+\) read successful.*'),
  43. STACK_PAR_FAIL: (r'.*E \(([0-9]+)\) MASTER_TEST: Characteristic #[0-9]+\s\(([a-zA-Z0-9_]+)\)\s'
  44. r'read fail, err = [0-9]+ \([_A-Z]+\).*'),
  45. STACK_DESTROY: (r'.*I\s\(([0-9]+)\) MASTER_TEST: (Destroy master).*')}
  46. logger = logging.getLogger(LOGGER_NAME)
  47. class DutTestThread(Thread):
  48. """ Test thread class
  49. """
  50. def __init__(self, dut=None, name=None, ip_addr=None, expect=None):
  51. """ Initialize the thread parameters
  52. """
  53. self.tname = name
  54. self.dut = dut
  55. self.expected = expect
  56. self.data = None
  57. self.ip_addr = ip_addr
  58. self.test_finish = False
  59. self.param_fail_count = 0
  60. self.param_ok_count = 0
  61. self.test_stage = STACK_DEFAULT
  62. super(DutTestThread, self).__init__()
  63. def __enter__(self):
  64. logger.debug('Restart %s.' % self.tname)
  65. # Reset DUT first
  66. self.dut.reset()
  67. # Capture output from the DUT
  68. self.dut.start_capture_raw_data(capture_id=self.dut.name)
  69. return self
  70. def __exit__(self, exc_type, exc_value, traceback):
  71. """ The exit method of context manager
  72. """
  73. if exc_type is not None or exc_value is not None:
  74. logger.info('Thread %s rised an exception type: %s, value: %s' % (self.tname, str(exc_type), str(exc_value)))
  75. def run(self):
  76. """ The function implements thread functionality
  77. """
  78. # Initialize slave IP for master board
  79. if (self.ip_addr is not None):
  80. self.set_ip(0)
  81. # Check expected strings in the listing
  82. self.test_start(TEST_EXPECT_STR_TIMEOUT)
  83. # Check DUT exceptions
  84. dut_exceptions = self.dut.get_exceptions()
  85. if 'Guru Meditation Error:' in dut_exceptions:
  86. raise Exception('%s generated an exception: %s\n' % (str(self.dut), dut_exceptions))
  87. # Mark thread has run to completion without any exceptions
  88. self.data = self.dut.stop_capture_raw_data(capture_id=self.dut.name)
  89. def set_ip(self, index=0):
  90. """ The method to send slave IP to master application
  91. """
  92. message = r'.*Waiting IP([0-9]{1,2}) from stdin.*'
  93. # Read all data from previous restart to get prompt correctly
  94. self.dut.read()
  95. result = self.dut.expect(re.compile(message), TEST_EXPECT_STR_TIMEOUT)
  96. if int(result[0]) != index:
  97. raise Exception('Incorrect index of IP=%d for %s\n' % (int(result[0]), str(self.dut)))
  98. message = 'IP%s=%s' % (result[0], self.ip_addr)
  99. self.dut.write(message, '\r\n', False)
  100. logger.debug('Sent message for %s: %s' % (self.tname, message))
  101. message = r'.*IP\([0-9]+\) = \[([0-9a-zA-Z\.\:]+)\] set from stdin.*'
  102. result = self.dut.expect(re.compile(message), TEST_EXPECT_STR_TIMEOUT)
  103. logger.debug('Thread %s initialized with slave IP (%s).' % (self.tname, result[0]))
  104. def test_start(self, timeout_value):
  105. """ The method to initialize and handle test stages
  106. """
  107. def handle_get_ip4(data):
  108. """ Handle get_ip v4
  109. """
  110. logger.debug('%s[STACK_IPV4]: %s' % (self.tname, str(data)))
  111. self.test_stage = STACK_IPV4
  112. def handle_get_ip6(data):
  113. """ Handle get_ip v6
  114. """
  115. logger.debug('%s[STACK_IPV6]: %s' % (self.tname, str(data)))
  116. self.test_stage = STACK_IPV6
  117. def handle_init(data):
  118. """ Handle init
  119. """
  120. logger.debug('%s[STACK_INIT]: %s' % (self.tname, str(data)))
  121. self.test_stage = STACK_INIT
  122. def handle_connect(data):
  123. """ Handle connect
  124. """
  125. logger.debug('%s[STACK_CONNECT]: %s' % (self.tname, str(data)))
  126. self.test_stage = STACK_CONNECT
  127. def handle_test_start(data):
  128. """ Handle connect
  129. """
  130. logger.debug('%s[STACK_START]: %s' % (self.tname, str(data)))
  131. self.test_stage = STACK_START
  132. def handle_par_ok(data):
  133. """ Handle parameter ok
  134. """
  135. logger.debug('%s[READ_PAR_OK]: %s' % (self.tname, str(data)))
  136. if self.test_stage >= STACK_START:
  137. self.param_ok_count += 1
  138. self.test_stage = STACK_PAR_OK
  139. def handle_par_fail(data):
  140. """ Handle parameter fail
  141. """
  142. logger.debug('%s[READ_PAR_FAIL]: %s' % (self.tname, str(data)))
  143. self.param_fail_count += 1
  144. self.test_stage = STACK_PAR_FAIL
  145. def handle_destroy(data):
  146. """ Handle destroy
  147. """
  148. logger.debug('%s[DESTROY]: %s' % (self.tname, str(data)))
  149. self.test_stage = STACK_DESTROY
  150. self.test_finish = True
  151. while not self.test_finish:
  152. try:
  153. self.dut.expect_any((re.compile(self.expected[STACK_IPV4]), handle_get_ip4),
  154. (re.compile(self.expected[STACK_IPV6]), handle_get_ip6),
  155. (re.compile(self.expected[STACK_INIT]), handle_init),
  156. (re.compile(self.expected[STACK_CONNECT]), handle_connect),
  157. (re.compile(self.expected[STACK_START]), handle_test_start),
  158. (re.compile(self.expected[STACK_PAR_OK]), handle_par_ok),
  159. (re.compile(self.expected[STACK_PAR_FAIL]), handle_par_fail),
  160. (re.compile(self.expected[STACK_DESTROY]), handle_destroy),
  161. timeout=timeout_value)
  162. except DUT.ExpectTimeout:
  163. logger.debug('%s, expect timeout on stage #%d (%s seconds)' % (self.tname, self.test_stage, timeout_value))
  164. self.test_finish = True
  165. def test_check_mode(dut=None, mode_str=None, value=None):
  166. """ Check communication mode for dut
  167. """
  168. global logger
  169. try:
  170. opt = dut.app.get_sdkconfig()[mode_str]
  171. logger.debug('%s {%s} = %s.\n' % (str(dut), mode_str, opt))
  172. return value == opt
  173. except Exception:
  174. logger.error('ENV_TEST_FAILURE: %s: Cannot find option %s in sdkconfig.' % (str(dut), mode_str))
  175. return False
  176. @ttfw_idf.idf_example_test(env_tag='Example_Modbus_TCP', target=['esp32'])
  177. def test_modbus_communication(env, comm_mode):
  178. global logger
  179. rel_project_path = os.path.join('examples', 'protocols', 'modbus', 'tcp')
  180. # Get device under test. Both duts must be able to be connected to WiFi router
  181. dut_master = env.get_dut('modbus_tcp_master', os.path.join(rel_project_path, TEST_MASTER_TCP))
  182. dut_slave = env.get_dut('modbus_tcp_slave', os.path.join(rel_project_path, TEST_SLAVE_TCP))
  183. log_file = os.path.join(env.log_path, 'modbus_tcp_test.log')
  184. print('Logging file name: %s' % log_file)
  185. try:
  186. # create file handler which logs even debug messages
  187. logger.setLevel(logging.DEBUG)
  188. fh = logging.FileHandler(log_file)
  189. fh.setLevel(logging.DEBUG)
  190. # set format of output for both handlers
  191. formatter = logging.Formatter('%(levelname)s:%(message)s')
  192. fh.setFormatter(formatter)
  193. logger.addHandler(fh)
  194. # create console handler
  195. ch = logging.StreamHandler()
  196. ch.setLevel(logging.INFO)
  197. # set format of output for both handlers
  198. formatter = logging.Formatter('%(levelname)s:%(message)s')
  199. ch.setFormatter(formatter)
  200. logger.addHandler(ch)
  201. # Check Kconfig configuration options for each built example
  202. if (test_check_mode(dut_master, 'CONFIG_FMB_COMM_MODE_TCP_EN', 'y') and
  203. test_check_mode(dut_slave, 'CONFIG_FMB_COMM_MODE_TCP_EN', 'y')):
  204. slave_name = TEST_SLAVE_TCP
  205. master_name = TEST_MASTER_TCP
  206. else:
  207. logger.error('ENV_TEST_FAILURE: IP resolver mode do not match in the master and slave implementation.\n')
  208. raise Exception('ENV_TEST_FAILURE: IP resolver mode do not match in the master and slave implementation.\n')
  209. address = None
  210. if test_check_mode(dut_master, 'CONFIG_MB_SLAVE_IP_FROM_STDIN', 'y'):
  211. logger.info('ENV_TEST_INFO: Set slave IP address through STDIN.\n')
  212. # Flash app onto DUT (Todo: Debug case when the slave flashed before master then expect does not work correctly for no reason
  213. dut_slave.start_app()
  214. dut_master.start_app()
  215. if test_check_mode(dut_master, 'CONFIG_EXAMPLE_CONNECT_IPV6', 'y'):
  216. address = dut_slave.expect(re.compile(pattern_dict_slave[STACK_IPV6]), TEST_EXPECT_STR_TIMEOUT)
  217. else:
  218. address = dut_slave.expect(re.compile(pattern_dict_slave[STACK_IPV4]), TEST_EXPECT_STR_TIMEOUT)
  219. if address is not None:
  220. print('Found IP slave address: %s' % address[0])
  221. else:
  222. raise Exception('ENV_TEST_FAILURE: Slave IP address is not found in the output. Check network settings.\n')
  223. else:
  224. raise Exception('ENV_TEST_FAILURE: Slave IP resolver is not configured correctly.\n')
  225. # Create thread for each dut
  226. with DutTestThread(dut=dut_master, name=master_name, ip_addr=address[0], expect=pattern_dict_master) as dut_master_thread:
  227. with DutTestThread(dut=dut_slave, name=slave_name, ip_addr=None, expect=pattern_dict_slave) as dut_slave_thread:
  228. # Start each thread
  229. dut_slave_thread.start()
  230. dut_master_thread.start()
  231. # Wait for threads to complete
  232. dut_slave_thread.join(timeout=TEST_THREAD_JOIN_TIMEOUT)
  233. dut_master_thread.join(timeout=TEST_THREAD_JOIN_TIMEOUT)
  234. if dut_slave_thread.isAlive():
  235. logger.error('ENV_TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n' %
  236. (dut_slave_thread.tname, TEST_THREAD_JOIN_TIMEOUT))
  237. raise Exception('ENV_TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n' %
  238. (dut_slave_thread.tname, TEST_THREAD_JOIN_TIMEOUT))
  239. if dut_master_thread.isAlive():
  240. logger.error('TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n' %
  241. (dut_master_thread.tname, TEST_THREAD_JOIN_TIMEOUT))
  242. raise Exception('TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n' %
  243. (dut_master_thread.tname, TEST_THREAD_JOIN_TIMEOUT))
  244. logger.info('TEST_INFO: %s error count = %d, %s error count = %d.\n' %
  245. (dut_master_thread.tname, dut_master_thread.param_fail_count,
  246. dut_slave_thread.tname, dut_slave_thread.param_fail_count))
  247. logger.info('TEST_INFO: %s ok count = %d, %s ok count = %d.\n' %
  248. (dut_master_thread.tname, dut_master_thread.param_ok_count,
  249. dut_slave_thread.tname, dut_slave_thread.param_ok_count))
  250. if ((dut_master_thread.param_fail_count > TEST_READ_MAX_ERR_COUNT) or
  251. (dut_slave_thread.param_fail_count > TEST_READ_MAX_ERR_COUNT) or
  252. (dut_slave_thread.param_ok_count == 0) or
  253. (dut_master_thread.param_ok_count == 0)):
  254. raise Exception('TEST_FAILURE: %s parameter read error(ok) count = %d(%d), %s parameter read error(ok) count = %d(%d).\n' %
  255. (dut_master_thread.tname, dut_master_thread.param_fail_count, dut_master_thread.param_ok_count,
  256. dut_slave_thread.tname, dut_slave_thread.param_fail_count, dut_slave_thread.param_ok_count))
  257. logger.info('TEST_SUCCESS: The Modbus parameter test is completed successfully.\n')
  258. finally:
  259. dut_master.close()
  260. dut_slave.close()
  261. logging.shutdown()
  262. if __name__ == '__main__':
  263. test_modbus_communication()