example_test.py 15 KB

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