example_test.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. # Need Python 3 string formatting functions
  2. from __future__ import print_function
  3. import logging
  4. import os
  5. import re
  6. from threading import Thread
  7. import ttfw_idf
  8. LOG_LEVEL = logging.DEBUG
  9. LOGGER_NAME = 'modbus_test'
  10. # Allowed parameter reads
  11. TEST_READ_MIN_COUNT = 10 # Minimum number of correct readings
  12. TEST_READ_MAX_ERR_COUNT = 2 # Maximum allowed read errors during initialization
  13. TEST_THREAD_EXPECT_TIMEOUT = 120 # Test theread expect timeout in seconds
  14. TEST_THREAD_JOIN_TIMEOUT = 180 # Test theread join timeout in seconds
  15. # Test definitions
  16. TEST_MASTER_RTU = 'master_rtu'
  17. TEST_SLAVE_RTU = 'slave_rtu'
  18. TEST_MASTER_ASCII = 'master_ascii'
  19. TEST_SLAVE_ASCII = 'slave_ascii'
  20. # Define tuple of strings to expect for each DUT.
  21. #
  22. master_expect = ('MASTER_TEST: Modbus master stack initialized...', 'MASTER_TEST: Start modbus test...', 'MASTER_TEST: Destroy master...')
  23. slave_expect = ('SLAVE_TEST: Modbus slave stack initialized.', 'SLAVE_TEST: Start modbus test...', 'SLAVE_TEST: Modbus controller destroyed.')
  24. # The dictionary for expected values in listing
  25. expect_dict_master_ok = {'START': (),
  26. 'READ_PAR_OK': (),
  27. 'ALARM_MSG': (u'7',)}
  28. expect_dict_master_err = {'READ_PAR_ERR': (u'263', u'ESP_ERR_TIMEOUT'),
  29. 'READ_STK_ERR': (u'107', u'ESP_ERR_TIMEOUT')}
  30. # The dictionary for regular expression patterns to check in listing
  31. pattern_dict_master_ok = {'START': (r'.*I \([0-9]+\) MASTER_TEST: Start modbus test...'),
  32. 'READ_PAR_OK': (r'.*I\s\([0-9]+\) MASTER_TEST: Characteristic #[0-9]+ [a-zA-Z0-9_]+'
  33. r'\s\([a-zA-Z\%\/]+\) value = [a-zA-Z0-9\.\s]*\(0x[a-zA-Z0-9]+\) read successful.'),
  34. 'ALARM_MSG': (r'.*I \([0-9]*\) MASTER_TEST: Alarm triggered by cid #([0-9]+).')}
  35. pattern_dict_master_err = {'READ_PAR_ERR_TOUT': (r'.*E \([0-9]+\) MASTER_TEST: Characteristic #[0-9]+'
  36. r'\s\([a-zA-Z0-9_]+\) read fail, err = [0-9]+ \([_A-Z]+\).'),
  37. 'READ_STK_ERR_TOUT': (r'.*E \([0-9]+\) MB_CONTROLLER_MASTER: [a-zA-Z0-9_]+\([0-9]+\):\s'
  38. r'SERIAL master get parameter failure error=\(0x([a-zA-Z0-9]+)\) \(([_A-Z]+)\).')}
  39. # The dictionary for expected values in listing
  40. expect_dict_slave_ok = {'START': (),
  41. 'READ_PAR_OK': (),
  42. 'DESTROY': ()}
  43. # The dictionary for regular expression patterns to check in listing
  44. pattern_dict_slave_ok = {'START': (r'.*I \([0-9]+\) SLAVE_TEST: Start modbus test...'),
  45. 'READ_PAR_OK': (r'.*I\s\([0-9]+\) SLAVE_TEST: [A-Z]+ READ \([a-zA-Z0-9_]+ us\),\s'
  46. r'ADDR:[0-9]+, TYPE:[0-9]+, INST_ADDR:0x[a-zA-Z0-9]+, SIZE:[0-9]+'),
  47. 'DESTROY': (r'.*I\s\([0-9]+\) SLAVE_TEST: Modbus controller destroyed.')}
  48. logger = logging.getLogger(LOGGER_NAME)
  49. class DutTestThread(Thread):
  50. def __init__(self, dut=None, name=None, expect=None):
  51. """ Initialize the thread parameters
  52. """
  53. self.tname = name
  54. self.dut = dut
  55. self.expected = expect
  56. self.result = False
  57. self.data = None
  58. super(DutTestThread, self).__init__()
  59. def run(self):
  60. """ The function implements thread functionality
  61. """
  62. # Must reset again as flashing during start_app will reset multiple times, causing unexpected results
  63. self.dut.reset()
  64. # Capture output from the DUT
  65. self.dut.start_capture_raw_data()
  66. # Check expected strings in the listing
  67. for string in self.expected:
  68. self.dut.expect(string, TEST_THREAD_EXPECT_TIMEOUT)
  69. # Check DUT exceptions
  70. dut_exceptions = self.dut.get_exceptions()
  71. if 'Guru Meditation Error:' in dut_exceptions:
  72. raise Exception('%s generated an exception: %s\n' % (str(self.dut), dut_exceptions))
  73. # Mark thread has run to completion without any exceptions
  74. self.data = self.dut.stop_capture_raw_data()
  75. self.result = True
  76. def test_filter_output(data=None, start_pattern=None, end_pattern=None):
  77. """Use patters to filter output
  78. """
  79. start_index = str(data).find(start_pattern)
  80. end_index = str(data).find(end_pattern)
  81. logger.debug('Listing start index= %d, end=%d' % (start_index, end_index))
  82. if start_index == -1 or end_index == -1:
  83. return data
  84. return data[start_index:end_index + len(end_pattern)]
  85. def test_expect_re(data, pattern):
  86. """
  87. Check if re pattern is matched in data cache
  88. :param data: data to process
  89. :param pattern: compiled RegEx pattern
  90. :return: match groups if match succeed otherwise None
  91. """
  92. ret = None
  93. if isinstance(pattern, type(u'')):
  94. pattern = pattern.encode('utf-8')
  95. regex = re.compile(pattern)
  96. if isinstance(data, type(u'')):
  97. data = data.encode('utf-8')
  98. match = regex.search(data)
  99. if match:
  100. ret = tuple(None if x is None else x.decode() for x in match.groups())
  101. index = match.end()
  102. else:
  103. index = None
  104. return ret, index
  105. def test_check_output(data=None, check_dict=None, expect_dict=None):
  106. """ Check output for the test
  107. Check log using regular expressions:
  108. """
  109. global logger
  110. match_count = 0
  111. index = 0
  112. data_lines = data.splitlines()
  113. for key, pattern in check_dict.items():
  114. if key not in expect_dict:
  115. break
  116. # Check pattern in the each line
  117. for line in data_lines:
  118. group, index = test_expect_re(line, pattern)
  119. if index is not None:
  120. logger.debug('Found key{%s}=%s, line: \n%s' % (key, group, line))
  121. if expect_dict[key] == group:
  122. logger.debug('The result is correct for the key:%s, expected:%s == returned:%s' % (key, str(expect_dict[key]), str(group)))
  123. match_count += 1
  124. return match_count
  125. def test_check_mode(dut=None, mode_str=None, value=None):
  126. """ Check communication mode for dut
  127. """
  128. global logger
  129. try:
  130. opt = dut.app.get_sdkconfig()[mode_str]
  131. logger.info('%s {%s} = %s.\n' % (str(dut), mode_str, opt))
  132. return value == opt
  133. except Exception:
  134. logger.info('ENV_TEST_FAILURE: %s: Cannot find option %s in sdkconfig.' % (str(dut), mode_str))
  135. return False
  136. @ttfw_idf.idf_example_test(env_tag='Example_T2_RS485')
  137. def test_modbus_communication(env, comm_mode):
  138. global logger
  139. # Get device under test. "dut1 - master", "dut2 - slave" must be properly connected through RS485 interface driver
  140. dut_master = env.get_dut('modbus_master', 'examples/protocols/modbus/serial/mb_master', dut_class=ttfw_idf.ESP32DUT)
  141. dut_slave = env.get_dut('modbus_slave', 'examples/protocols/modbus/serial/mb_slave', dut_class=ttfw_idf.ESP32DUT)
  142. try:
  143. logger.debug('Environment vars: %s\r\n' % os.environ)
  144. logger.debug('DUT slave sdkconfig: %s\r\n' % dut_slave.app.get_sdkconfig())
  145. logger.debug('DUT master sdkconfig: %s\r\n' % dut_master.app.get_sdkconfig())
  146. # Check Kconfig configuration options for each built example
  147. if test_check_mode(dut_master, 'CONFIG_MB_COMM_MODE_ASCII', 'y') and test_check_mode(dut_slave, 'CONFIG_MB_COMM_MODE_ASCII', 'y'):
  148. logger.info('ENV_TEST_INFO: Modbus ASCII test mode selected in the configuration. \n')
  149. slave_name = TEST_SLAVE_ASCII
  150. master_name = TEST_MASTER_ASCII
  151. elif test_check_mode(dut_master, 'CONFIG_MB_COMM_MODE_RTU', 'y') and test_check_mode(dut_slave, 'CONFIG_MB_COMM_MODE_RTU', 'y'):
  152. logger.info('ENV_TEST_INFO: Modbus RTU test mode selected in the configuration. \n')
  153. slave_name = TEST_SLAVE_RTU
  154. master_name = TEST_MASTER_RTU
  155. else:
  156. logger.error("ENV_TEST_FAILURE: Communication mode in master and slave configuration don't match.\n")
  157. raise Exception("ENV_TEST_FAILURE: Communication mode in master and slave configuration don't match.\n")
  158. # Check if slave address for example application is default one to be able to communicate
  159. if not test_check_mode(dut_slave, 'CONFIG_MB_SLAVE_ADDR', '1'):
  160. logger.error('ENV_TEST_FAILURE: Slave address option is incorrect.\n')
  161. raise Exception('ENV_TEST_FAILURE: Slave address option is incorrect.\n')
  162. # Flash app onto each DUT
  163. dut_master.start_app()
  164. dut_slave.start_app()
  165. # Create thread for each dut
  166. dut_master_thread = DutTestThread(dut=dut_master, name=master_name, expect=master_expect)
  167. dut_slave_thread = DutTestThread(dut=dut_slave, name=slave_name, expect=slave_expect)
  168. # Start each thread
  169. dut_slave_thread.start()
  170. dut_master_thread.start()
  171. # Wait for threads to complete
  172. dut_slave_thread.join(timeout=TEST_THREAD_JOIN_TIMEOUT)
  173. dut_master_thread.join(timeout=TEST_THREAD_JOIN_TIMEOUT)
  174. if dut_slave_thread.isAlive():
  175. logger.error('ENV_TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n' %
  176. (dut_slave_thread.tname, TEST_THREAD_JOIN_TIMEOUT))
  177. raise Exception('ENV_TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n' %
  178. (dut_slave_thread.tname, TEST_THREAD_JOIN_TIMEOUT))
  179. if dut_master_thread.isAlive():
  180. logger.error('ENV_TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n' %
  181. (dut_master_thread.tname, TEST_THREAD_JOIN_TIMEOUT))
  182. raise Exception('ENV_TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n' %
  183. (dut_master_thread.tname, TEST_THREAD_JOIN_TIMEOUT))
  184. finally:
  185. dut_master.close()
  186. dut_slave.close()
  187. # Check if test threads completed successfully and captured data
  188. if not dut_slave_thread.result or dut_slave_thread.data is None:
  189. logger.error('The thread %s was not run successfully.' % dut_slave_thread.tname)
  190. raise Exception('The thread %s was not run successfully.' % dut_slave_thread.tname)
  191. if not dut_master_thread.result or dut_master_thread.data is None:
  192. logger.error('The thread %s was not run successfully.' % dut_slave_thread.tname)
  193. raise Exception('The thread %s was not run successfully.' % dut_master_thread.tname)
  194. # Filter output to get test messages
  195. master_output = test_filter_output(dut_master_thread.data, master_expect[0], master_expect[len(master_expect) - 1])
  196. if master_output is not None:
  197. logger.info('The data for master thread is captured.')
  198. logger.debug(master_output)
  199. slave_output = test_filter_output(dut_slave_thread.data, slave_expect[0], slave_expect[len(slave_expect) - 1])
  200. if slave_output is not None:
  201. logger.info('The data for slave thread is captured.')
  202. logger.debug(slave_output)
  203. # Check if parameters are read correctly by master
  204. match_count = test_check_output(master_output, pattern_dict_master_ok, expect_dict_master_ok)
  205. if match_count < TEST_READ_MIN_COUNT:
  206. logger.error('There are errors reading parameters from %s, %d' % (dut_master_thread.tname, match_count))
  207. raise Exception('There are errors reading parameters from %s, %d' % (dut_master_thread.tname, match_count))
  208. logger.info('OK pattern test for %s, match_count=%d.' % (dut_master_thread.tname, match_count))
  209. # If the test completed successfully (alarm triggered) but there are some errors during reading of parameters
  210. match_count = test_check_output(master_output, pattern_dict_master_err, expect_dict_master_err)
  211. if match_count > TEST_READ_MAX_ERR_COUNT:
  212. logger.error('There are errors reading parameters from %s, %d' % (dut_master_thread.tname, match_count))
  213. raise Exception('There are errors reading parameters from %s, %d' % (dut_master_thread.tname, match_count))
  214. logger.info('ERROR pattern test for %s, match_count=%d.' % (dut_master_thread.tname, match_count))
  215. match_count = test_check_output(slave_output, pattern_dict_slave_ok, expect_dict_slave_ok)
  216. if match_count < TEST_READ_MIN_COUNT:
  217. logger.error('There are errors reading parameters from %s, %d' % (dut_slave_thread.tname, match_count))
  218. raise Exception('There are errors reading parameters from %s, %d' % (dut_slave_thread.tname, match_count))
  219. logger.info('OK pattern test for %s, match_count=%d.' % (dut_slave_thread.tname, match_count))
  220. if __name__ == '__main__':
  221. logger = logging.getLogger(LOGGER_NAME)
  222. # create file handler which logs even debug messages
  223. fh = logging.FileHandler('modbus_test.log')
  224. fh.setLevel(logging.DEBUG)
  225. logger.setLevel(logging.DEBUG)
  226. # create console handler
  227. ch = logging.StreamHandler()
  228. ch.setLevel(logging.INFO)
  229. # set format of output for both handlers
  230. formatter = logging.Formatter('%(levelname)s:%(message)s')
  231. ch.setFormatter(formatter)
  232. fh.setFormatter(formatter)
  233. logger.addHandler(fh)
  234. logger.addHandler(ch)
  235. logger.info('Start script %s.' % os.path.basename(__file__))
  236. print('Logging file name: %s' % logger.handlers[0].baseFilename)
  237. test_modbus_communication()
  238. logging.shutdown()