3 Copyright (c) 2011-2013 ARM Limited
5 Licensed under the Apache License, Version 2.0 (the "License");
6 you may not use this file except in compliance with the License.
7 You may obtain a copy of the License at
9 http://www.apache.org/licenses/LICENSE-2.0
11 Unless required by applicable law or agreed to in writing, software
12 distributed under the License is distributed on an "AS IS" BASIS,
13 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 See the License for the specific language governing permissions and
15 limitations under the License.
18 # Check if 'serial' module is installed
20 from serial import Serial
21 except ImportError, e:
22 print "Error: Can't import 'serial' module: %s"% e
28 from sys import stdout
29 from time import sleep, time
30 from optparse import OptionParser
32 import host_tests_plugins
34 # This is a little tricky. We need to add upper directory to path so
35 # we can find packages we want from the same level as other files do
37 sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')))
41 """ Base class for a host driven test
44 parser = OptionParser()
46 parser.add_option("-m", "--micro",
48 help="The target microcontroller",
51 parser.add_option("-p", "--port",
53 help="The serial port of the target mbed",
56 parser.add_option("-d", "--disk",
58 help="The target disk path",
61 parser.add_option("-f", "--image-path",
63 help="Path with target's image",
66 parser.add_option("-c", "--copy",
68 help="Copy method selector",
69 metavar="COPY_METHOD")
71 parser.add_option("-C", "--program_cycle_s",
72 dest="program_cycle_s",
73 help="Program cycle sleep. Define how many seconds you want wait after copying bianry onto target",
75 metavar="COPY_METHOD")
77 parser.add_option("-t", "--timeout",
82 parser.add_option("-r", "--reset",
83 dest="forced_reset_type",
84 help="Forces different type of reset")
86 parser.add_option("-R", "--reset-timeout",
87 dest="forced_reset_timeout",
90 help="When forcing a reset using option -r you can set up after reset timeout in seconds")
92 (self.options, _) = parser.parse_args()
94 self.DEFAULT_RESET_TOUT = 0
95 self.DEFAULT_TOUT = 10
97 if self.options.port is None:
98 raise Exception("The serial port of the target mbed have to be provided as command line arguments")
100 # Options related to copy / reset mbed device
101 self.port = self.options.port
102 self.disk = self.options.disk
103 self.image_path = self.options.image_path.strip('"')
104 self.copy_method = self.options.copy_method
105 self.program_cycle_s = float(self.options.program_cycle_s)
108 self.serial_baud = 9600
109 self.serial_timeout = 1
111 self.timeout = self.DEFAULT_TOUT if self.options.timeout is None else self.options.timeout
112 print 'MBED: Instrumentation: "%s" and disk: "%s"' % (self.port, self.disk)
114 def init_serial_params(self, serial_baud=9600, serial_timeout=1):
115 """ Initialize port parameters.
116 This parameters will be used by self.init_serial() function to open serial port
118 self.serial_baud = serial_baud
119 self.serial_timeout = serial_timeout
121 def init_serial(self, serial_baud=None, serial_timeout=None):
122 """ Initialize serial port.
123 Function will return error is port can't be opened or initialized
125 # Overload serial port configuration from default to parameters' values if they are specified
126 serial_baud = serial_baud if serial_baud is not None else self.serial_baud
127 serial_timeout = serial_timeout if serial_timeout is not None else self.serial_timeout
134 # We will pool for serial to be re-mounted if it was unmounted after device reset
135 result = self.pool_for_serial_init(serial_baud, serial_timeout) # Blocking
142 def pool_for_serial_init(self, serial_baud, serial_timeout, pooling_loops=40, init_delay=0.5, loop_delay=0.25):
143 """ Functions pools for serial port readiness
147 # This loop is used to check for serial port availability due to
148 # some delays and remounting when devices are being flashed with new software.
149 for i in range(pooling_loops):
150 sleep(loop_delay if i else init_delay)
152 self.serial = Serial(self.port, baudrate=serial_baud, timeout=serial_timeout)
153 except Exception as e:
155 last_error = "MBED: %s"% str(e)
159 print "...port ready!"
162 if not result and last_error:
166 def set_serial_timeout(self, timeout):
167 """ Wraps self.mbed.serial object timeout property
171 self.serial.timeout = timeout
175 def serial_read(self, count=1):
176 """ Wraps self.mbed.serial object read method
181 result = self.serial.read(count)
186 def serial_readline(self, timeout=5):
187 """ Wraps self.mbed.serial object read method to read one line from serial port
191 while (time() - start) < timeout:
194 c = self.serial.read(1)
196 except Exception as e:
197 print "MBED: %s"% str(e)
204 def serial_write(self, write_buffer):
205 """ Wraps self.mbed.serial object write method
210 result = self.serial.write(write_buffer)
215 def reset_timeout(self, timeout):
216 """ Timeout executed just after reset command is issued
218 for n in range(0, timeout):
222 """ Calls proper reset plugin to do the job.
223 Please refer to host_test_plugins functionality
225 # Flush serials to get only input after reset
227 if self.options.forced_reset_type:
228 result = host_tests_plugins.call_plugin('ResetMethod', self.options.forced_reset_type, disk=self.disk)
230 result = host_tests_plugins.call_plugin('ResetMethod', 'default', serial=self.serial)
231 # Give time to wait for the image loading
232 reset_tout_s = self.options.forced_reset_timeout if self.options.forced_reset_timeout is not None else self.DEFAULT_RESET_TOUT
233 self.reset_timeout(reset_tout_s)
236 def copy_image(self, image_path=None, disk=None, copy_method=None):
237 """ Closure for copy_image_raw() method.
238 Method which is actually copying image to mbed
240 # Set closure environment
241 image_path = image_path if image_path is not None else self.image_path
242 disk = disk if disk is not None else self.disk
243 copy_method = copy_method if copy_method is not None else self.copy_method
244 # Call proper copy method
245 result = self.copy_image_raw(image_path, disk, copy_method)
246 sleep(self.program_cycle_s)
249 def copy_image_raw(self, image_path=None, disk=None, copy_method=None):
250 """ Copy file depending on method you want to use. Handles exception
251 and return code from shell copy commands.
253 if copy_method is not None:
254 # image_path - Where is binary with target's firmware
255 result = host_tests_plugins.call_plugin('CopyMethod', copy_method, image_path=image_path, destination_disk=disk)
257 copy_method = 'default'
258 result = host_tests_plugins.call_plugin('CopyMethod', copy_method, image_path=image_path, destination_disk=disk)
262 """ Flush serial ports
266 self.serial.flushInput()
267 self.serial.flushOutput()
272 class HostTestResults:
273 """ Test results set by host tests
276 self.RESULT_SUCCESS = 'success'
277 self.RESULT_FAILURE = 'failure'
278 self.RESULT_ERROR = 'error'
279 self.RESULT_IO_SERIAL = 'ioerr_serial'
280 self.RESULT_NO_IMAGE = 'no_image'
281 self.RESULT_IOERR_COPY = "ioerr_copy"
282 self.RESULT_PASSIVE = "passive"
283 self.RESULT_NOT_DETECTED = "not_detected"
284 self.RESULT_MBED_ASSERT = "mbed_assert"
287 import workspace_tools.host_tests as host_tests
290 class Test(HostTestResults):
291 """ Base class for host test's test runner
293 # Select default host_test supervision (replaced after autodetection)
294 test_supervisor = host_tests.get_host_test("default")
299 def detect_test_config(self, verbose=False):
300 """ Detects test case configuration
304 line = self.mbed.serial_readline()
305 if "{start}" in line:
306 self.notify("HOST: Start test...")
309 # Detect if this is property from TEST_ENV print
310 m = re.search('{([\w_]+);([\w\d\+ ]+)}}', line[:-1])
311 if m and len(m.groups()) == 2:
312 # This is most likely auto-detection property
313 result[m.group(1)] = m.group(2)
315 self.notify("HOST: Property '%s' = '%s'"% (m.group(1), m.group(2)))
317 # We can check if this is TArget Id in mbed specific format
318 m2 = re.search('^([\$]+)([a-fA-F0-9]+)', line[:-1])
319 if m2 and len(m2.groups()) == 2:
321 target_id = m2.group(1) + m2.group(2)
322 self.notify("HOST: TargetID '%s'"% target_id)
323 self.notify(line[len(target_id):-1])
325 self.notify("HOST: Unknown property: %s"% line.strip())
329 """ Test runner for host test. This function will start executing
330 test and forward test result via serial port to test suite
332 # Copy image to device
333 self.notify("HOST: Copy image onto target...")
334 result = self.mbed.copy_image()
336 self.print_result(self.RESULT_IOERR_COPY)
338 # Initialize and open target's serial port (console)
339 self.notify("HOST: Initialize serial port...")
340 result = self.mbed.init_serial()
342 self.print_result(self.RESULT_IO_SERIAL)
345 self.notify("HOST: Reset target...")
346 result = self.mbed.reset()
348 self.print_result(self.RESULT_IO_SERIAL)
352 CONFIG = self.detect_test_config(verbose=True) # print CONFIG
354 if "host_test_name" in CONFIG:
355 if host_tests.is_host_test(CONFIG["host_test_name"]):
356 self.test_supervisor = host_tests.get_host_test(CONFIG["host_test_name"])
357 result = self.test_supervisor.test(self) #result = self.test()
359 if result is not None:
360 self.print_result(result)
362 self.notify("HOST: Passive mode...")
365 self.print_result(self.RESULT_ERROR)
368 """ Setup and check if configuration for test is
369 correct. E.g. if serial port can be opened.
372 if not self.mbed.serial:
374 self.print_result(self.RESULT_IO_SERIAL)
377 def notify(self, message):
378 """ On screen notification function
383 def print_result(self, result):
384 """ Test result unified printing function
386 self.notify("\r\n{{%s}}\r\n{{end}}" % result)
389 class DefaultTestSelector(Test):
390 """ Test class with serial port initialization
393 HostTestResults.__init__(self)
396 if __name__ == '__main__':
397 DefaultTestSelector().run()