hftest.py: Run 'exit' command after running all tests

So as to automate running tests on Android boards, hftest.py should call
the 'exit' command when it's finished running tests in the current test
suite. The board will boot into the Android bootloader and will be ready
to accept the next initrd.

Change-Id: I520931f11368e31aa188a4b94f5cb914b13d3b84
diff --git a/test/hftest/hftest.py b/test/hftest/hftest.py
index a10f932..46bbccd 100755
--- a/test/hftest/hftest.py
+++ b/test/hftest/hftest.py
@@ -235,6 +235,10 @@
 
         return self.finish_run(run_state)
 
+    def finish(self):
+        """Clean up after running tests."""
+        pass
+
 
 class FvpDriver(Driver):
     """Driver which runs tests in Arm FVP emulator."""
@@ -343,6 +347,10 @@
         append_file(run_state.log_path, read_file(uart0_log_path))
         return self.finish_run(run_state)
 
+    def finish(self):
+        """Clean up after running tests."""
+        pass
+
 
 class SerialDriver(Driver):
     """Driver which communicates with a device over the serial port."""
@@ -381,6 +389,20 @@
                         break
         return self.finish_run(run_state)
 
+    def finish(self):
+        """Clean up after running tests."""
+        with serial.Serial(self.tty_file, self.baudrate, timeout=10) as ser:
+            while True:
+                line = ser.readline().decode('utf-8')
+                if len(line) == 0:
+                    input("Timeout. Press ENTER and then reset the device...")
+                elif HFTEST_CTRL_GET_COMMAND_LINE in line:
+                    # Device is waiting for a command. Instruct it to exit
+                    # the test environment.
+                    ser.write("exit".encode('ascii'))
+                    ser.write(b'\r')
+                    break
+
 
 # Tuple used to return information about the results of running a set of tests.
 TestRunnerResult = collections.namedtuple("TestRunnerResult", [
@@ -535,6 +557,9 @@
         elif result.tests_run > 0:
             print("    PASS: all", result.tests_run, "tests passed")
 
+        # Let the driver clean up.
+        self.driver.finish()
+
         return result