Making adjustments for coming state changes.  I also rewrote some robot
keywords in python.

Note that the changes for the new "bmc" values are not present yet
since the product code for that is not yet available to me.

Change-Id: I30ea13930512ae1ffcf29000d0e4661352a797d7
Signed-off-by: Michael Walsh <micwalsh@us.ibm.com>
diff --git a/extended/obmc_boot_test.robot b/extended/obmc_boot_test.robot
index c1f5399..8c4714b 100644
--- a/extended/obmc_boot_test.robot
+++ b/extended/obmc_boot_test.robot
@@ -74,13 +74,6 @@
 ${next_boot}                ${EMPTY}
 # State dictionary.  Initializing to a realistic state for testing in
 # test_mode.
-&{default_state}            power=1
-...                         bmc=HOST_BOOTED
-...                         boot_progress=FW Progress, Starting OS
-...                         os_ping=1
-...                         os_login=1
-...                         os_run_cmd=1
-&{state}                    &{default_state}
 
 # Flag variables.
 ${cp_setup_called}          ${0}
@@ -106,7 +99,7 @@
     :For  ${BOOT_COUNT}  IN RANGE  ${max_num_tests}
     \  Test Loop Body  ${BOOT_COUNT}
 
-    Rprint Timen  Completed all requested boot tests.
+    Rqprint Timen  Completed all requested boot tests.
 
 ###############################################################################
 
@@ -115,8 +108,6 @@
 Setup
     [Documentation]  Do general program setup tasks.
 
-    Rprintn
-
     Validate Parms
 
     Rqprint Pgm Header
@@ -145,7 +136,7 @@
     ${temp_state}=  Run Keyword If  '${test_mode}' == '0'  Get State
     ...  ELSE  Create Dictionary  &{default_state}
     Set Global Variable  &{state}  &{temp_state}
-    Rpvars  state
+    Rqpvars  state
 
 ###############################################################################
 
@@ -154,7 +145,7 @@
 Validate Parms
     [Documentation]  Validate all program parameters.
 
-    rprintn
+    Rqprintn
 
     Rvalid Value  AVAIL_BOOTS
     Rvalid Value  openbmc_host
@@ -188,6 +179,10 @@
 
     Set FFDC Dir Path Style
 
+    ${default_state}=  Return Default State
+    Set Global Variable  ${state}  ${default_state}
+    Set Global Variable  ${default_state}  ${default_state}
+
 ###############################################################################
 
 
@@ -226,7 +221,9 @@
     Rqprintn
     Rqprint Timen  Starting boot ${BOOT_COUNT+1} of ${max_num_tests}.
 
-    ${loc_next_boot}=  Select Boot  ${state['power']}
+    Rqpvars  state
+
+    ${loc_next_boot}=  Select Boot  ${state}
     Set Global Variable  ${next_boot}  ${loc_next_boot}
 
     # Clear this file.  Plug-ins may now write to it.
@@ -235,7 +232,7 @@
     ${status}  ${msg}=  Run Keyword And Ignore Error  Run Boot  ${next_boot}
     Run Keyword If  '${status}' == 'FAIL'  rprint  ${msg}
 
-    rprintn
+    Rqprintn
     Run Keyword If  '${BOOT_STATUS}' == 'PASS'  Run Keywords
     ...    Set Global Variable  ${boot_success}  ${1}  AND
     ...    Rqprint Timen  BOOT_SUCCESS: "${next_boot}" succeeded.
@@ -276,60 +273,7 @@
     ...  quiet=${1}
     ...  ELSE  Create Dictionary  &{default_state}
     Set Global Variable  &{state}  &{temp_state}
-    rpvars  state
-
-###############################################################################
-
-
-###############################################################################
-Select Boot
-    [Documentation]  Select a boot test to be run based on our current state.
-    ...  Return the chosen boot type.
-    [Arguments]  ${power}
-
-    # power      The power state of the machine, either zero or one.
-
-    ${boot}=  Run Keyword If  ${power} == ${0}  Select Power On
-    ...  ELSE  Run Keyword If  ${power} == ${1}  Select Power Off
-    ...  ELSE  Run Keywords  Log to Console
-    ...  **ERROR** BMC not in state to power on or off: "${power}"  AND
-    ...  Fatal Error
-
-    [return]  ${boot}
-
-###############################################################################
-
-
-###############################################################################
-Select Power On
-    [Documentation]  Randomly chooses a boot from the list of Power On boots.
-
-    @{power_on_choices}=  Intersect Lists  ${VALID_POWER_ON}  ${AVAIL_BOOTS}
-
-    ${length}=  Get Length  ${power_on_choices}
-
-    # Currently selects the first boot in the list of options, rather than
-    # selecting randomly.
-    ${chosen}=  Set Variable  @{power_on_choices}[0]
-
-    [return]  ${chosen}
-
-###############################################################################
-
-
-###############################################################################
-Select Power Off
-    [Documentation]  Randomly chooses an boot from the list of Power Off boots.
-
-    @{power_off_choices}=  Intersect Lists  ${VALID_POWER_OFF}  ${AVAIL_BOOTS}
-
-    ${length}=  Get Length  ${power_off_choices}
-
-    # Currently selects the first boot in the list of options, rather than
-    # selecting randomly.
-    ${chosen}=  Set Variable  @{power_off_choices}[0]
-
-    [return]  ${chosen}
+    Rqpvars  state
 
 ###############################################################################
 
@@ -362,75 +306,3 @@
 ###############################################################################
 
 
-###############################################################################
-Print Test Start Message
-    [Documentation]  Print a message indicating what boot test is about to run.
-    [Arguments]  ${boot_keyword}
-
-    ${doing_msg}=  Sprint Timen  Doing "${boot_keyword}".
-    rqprint  ${doing_msg}
-
-    Append to List  ${LAST_TEN}  ${doing_msg}
-    ${length}=  Get Length  ${LAST_TEN}
-
-    Run Keyword If  '${length}' > '${10}'  Remove From List  ${LAST_TEN}  0
-
-###############################################################################
-
-
-###############################################################################
-Print Defect Report
-    [Documentation]  Print a defect report.
-
-    Rqprintn
-    # indent=0, width=90, linefeed=1, char="="
-    Rqprint Dashes  ${0}  ${90}  ${1}  =
-    Rqprintn  Copy this data to the defect:
-    Rqprintn
-
-    Rqpvars  @{parm_list}
-    Print Last Ten Boots
-    Rqprintn
-    Rqpvars  state
-
-    # At some point I'd like to have the 'Call FFDC Methods' return a list
-    # of files it has collected.  In that case, the following "ls" command
-    # would no longer be needed.  For now, however, ls shows the files
-    # named in FFDC_LIST_FILE_PATH so I will refrain from printing those
-    # out (so we don't see duplicates in the list).
-
-    ${rc}  ${output}=  Run and return RC and Output  ls ${LOG_PREFIX}*
-
-    Run Keyword If  '${rc}' != '${0}' and '${rc}' != 'None'  rqpvars  rc
-    ${status}  ${ffdc_list}=  Run Keyword and Ignore Error
-    ...  OperatingSystem.Get File  ${FFDC_LIST_FILE_PATH}
-
-    Rqprintn
-    Rqprintn  FFDC data files:
-    Run Keyword If  '${status_file_path}' != '${EMPTY}'
-    ...  Rqprintn  ${status_file_path}
-    Rqprintn  ${output}
-    # Run Keyword If  '${status}' == 'PASS'  Rqprintn  ${ffdc_list}
-    Rqprintn
-
-    Rqprint Dashes  ${0}  ${90}  ${1}  =
-
-###############################################################################
-
-
-###############################################################################
-Print Last Ten Boots
-    [Documentation]  Logs the last ten boots that were performed with their
-    ...  starting time stamp.
-
-    # indent 0, 90 chars wide, linefeed, char is "="
-    Rqprint Dashes  ${0}  ${90}
-    Rqprintn  Last 10 boots:
-    Rqprintn
-    :FOR  ${boot_entry}  IN  @{LAST_TEN}
-    \  rqprint  ${boot_entry}
-    Rqprint Dashes  ${0}  ${90}
-
-###############################################################################
-
-
diff --git a/lib/boot/poweroffs.py b/lib/boot/poweroffs.py
index b6d8959..e776bfb 100755
--- a/lib/boot/poweroffs.py
+++ b/lib/boot/poweroffs.py
@@ -10,8 +10,13 @@
 
 from robot.libraries.BuiltIn import BuiltIn
 
+# We don't want global variable getting changed when an import is done
+# so we'll save it and restore it.
+quiet = int(BuiltIn().get_variable_value("${quiet}"))
+
 # We need utils.robot to get keyword "Initiate Power Off".
 BuiltIn().import_resource("utils.robot")
+BuiltIn().set_global_variable("${quiet}", quiet)
 
 
 ###############################################################################
@@ -39,8 +44,13 @@
     state_mod.wait_state(match_state, wait_time=state_change_timeout,
                          interval="3 seconds", invert=1)
 
-    cmd_buf = ["Create Dictionary", "power=${0}",
-               "bmc=HOST_POWERED_OFF", "boot_progress=Off"]
+    if state_mod.OBMC_STATES_VERSION == 0:
+        cmd_buf = ["Create Dictionary", "power=${0}",
+                   "bmc=HOST_POWERED_OFF", "boot_progress=Off"]
+    else:
+        cmd_buf = ["Create Dictionary", "chassis=Off",
+                   "bmc=HOST_POWERED_OFF", "boot_progress=Off",
+                   "host=Off"]
     grp.rdpissuing_keyword(cmd_buf)
     final_state = BuiltIn().run_keyword(*cmd_buf)
 
diff --git a/lib/boot/powerons.py b/lib/boot/powerons.py
index a861d57..e8b921b 100755
--- a/lib/boot/powerons.py
+++ b/lib/boot/powerons.py
@@ -10,9 +10,15 @@
 
 from robot.libraries.BuiltIn import BuiltIn
 
+# We don't want global variable getting changed when an import is done
+# so we'll save it and restore it.
+quiet = int(BuiltIn().get_variable_value("${quiet}"))
+
 # We need utils.robot to get keyword "Initiate Power On".
 BuiltIn().import_resource("utils.robot")
 
+BuiltIn().set_global_variable("${quiet}", quiet)
+
 
 ###############################################################################
 def bmc_power_on():
@@ -39,9 +45,15 @@
     state_mod.wait_state(match_state, wait_time=state_change_timeout,
                          interval="3 seconds", invert=1)
 
-    cmd_buf = ["Create Dictionary", "power=${1}",
-               "bmc=HOST_BOOTED",
-               "boot_progress=FW Progress, Starting OS"]
+    if state_mod.OBMC_STATES_VERSION == 0:
+        cmd_buf = ["Create Dictionary", "power=${1}",
+                   "bmc=HOST_BOOTED",
+                   "boot_progress=FW Progress, Starting OS"]
+    else:
+        cmd_buf = ["Create Dictionary", "chassis=On",
+                   "bmc=HOST_BOOTED",
+                   "boot_progress=FW Progress, Starting OS",
+                   "host=Running"]
     grp.rdpissuing_keyword(cmd_buf)
     final_state = BuiltIn().run_keyword(*cmd_buf)
 
diff --git a/lib/obmc_boot_test.py b/lib/obmc_boot_test.py
index eb379a4..653dde1 100755
--- a/lib/obmc_boot_test.py
+++ b/lib/obmc_boot_test.py
@@ -12,6 +12,7 @@
 import os
 import time
 import subprocess
+import glob
 
 from robot.utils import DotDict
 from robot.libraries.BuiltIn import BuiltIn
@@ -193,9 +194,38 @@
     Print the formatted boot_resuls_table to the console.
     """
 
-    grp.rprint(header_footer)
-    grp.rprint(boot_results.sprint_report())
-    grp.rprint(header_footer)
+    grp.rqprint(header_footer)
+    grp.rqprint(boot_results.sprint_report())
+    grp.rqprint(header_footer)
+
+###############################################################################
+
+
+###############################################################################
+def select_boot(state):
+
+    r"""
+    Select a boot test to be run based on our current state and return the
+    chosen boot type.
+
+    Description of arguments:
+    state  The state of the machine, which will include the power state..
+    """
+
+    if 'chassis' in state:
+        # New style state.
+        if state['chassis'] == 'Off':
+            boot = 'BMC Power On'
+        else:
+            boot = 'BMC Power Off'
+    else:
+        # Old style state.
+        if state['power'] == 0:
+            boot = 'BMC Power On'
+        else:
+            boot = 'BMC Power Off'
+
+    return boot
 
 ###############################################################################
 
@@ -231,3 +261,102 @@
     BuiltIn().run_keyword(*cmd_buf)
 
 ###############################################################################
+
+
+###############################################################################
+def print_last_boots():
+
+    r"""
+    Print the last ten boots done with their time stamps.
+    """
+
+    # indent 0, 90 chars wide, linefeed, char is "="
+    grp.rqprint_dashes(0, 90)
+    grp.rqprintn("Last 10 boots:\n")
+    last_ten = BuiltIn().get_variable_value("${LAST_TEN}")
+
+    for boot_entry in last_ten:
+        grp.rqprint(boot_entry)
+    grp.rqprint_dashes(0, 90)
+
+###############################################################################
+
+
+###############################################################################
+def print_test_start_message(boot_keyword):
+
+    r"""
+    Print a message indicating what boot test is about to run.
+
+    Description of arguments:
+    boot_keyword  The name of the boot which is to be run
+                  (e.g. "BMC Power On").
+    """
+
+    doing_msg = gp.sprint_timen("Doing \"" + boot_keyword + "\".")
+    grp.rqprint(doing_msg)
+
+    last_ten = BuiltIn().get_variable_value("${LAST_TEN}")
+    last_ten.append(doing_msg)
+
+    if len(last_ten) > 10:
+        del last_ten[0]
+
+###############################################################################
+
+
+###############################################################################
+def print_defect_report():
+
+    r"""
+    Print a defect report.
+    """
+
+    grp.rqprintn()
+    # indent=0, width=90, linefeed=1, char="="
+    grp.rqprint_dashes(0, 90, 1, "=")
+    grp.rqprintn("Copy this data to the defect:\n")
+
+    parm_list = BuiltIn().get_variable_value("${parm_list}")
+
+    grp.rqpvars(*parm_list)
+
+    grp.rqprintn()
+
+    print_last_boots()
+    grp.rqprintn()
+    state = BuiltIn().get_variable_value("${state}")
+    grp.rqpvar(state)
+
+    # At some point I'd like to have the 'Call FFDC Methods' return a list
+    # of files it has collected.  In that case, the following "ls" command
+    # would no longer be needed.  For now, however, glob shows the files
+    # named in FFDC_LIST_FILE_PATH so I will refrain from printing those
+    # out (so we don't see duplicates in the list).
+
+    LOG_PREFIX = BuiltIn().get_variable_value("${LOG_PREFIX}")
+
+    output = '\n'.join(glob.glob(LOG_PREFIX + '*'))
+
+    FFDC_LIST_FILE_PATH = \
+        BuiltIn().get_variable_value("${FFDC_LIST_FILE_PATH}")
+
+    try:
+        ffdc_list = open(FFDC_LIST_FILE_PATH, 'r')
+    except IOError:
+        ffdc_list = ""
+
+    status_file_path = BuiltIn().get_variable_value("${status_file_path}")
+
+    grp.rqprintn()
+    grp.rqprintn("FFDC data files:")
+    if status_file_path != "":
+        grp.rqprintn(status_file_path)
+
+    grp.rqprintn(output)
+    # grp.rqprintn(ffdc_list)
+    grp.rqprintn()
+
+    grp.rqprint_dashes(0, 90, 1, "=")
+
+###############################################################################
diff --git a/lib/state.py b/lib/state.py
index f84cd3f..67b8d2b 100755
--- a/lib/state.py
+++ b/lib/state.py
@@ -8,13 +8,13 @@
 in this module define state as an ordered dictionary.  Here is an example of
 some test output showing machine state:
 
-state:
-  state[power]:                                   1
-  state[bmc]:                                     HOST_BOOTED
-  state[boot_progress]:                           FW Progress, Starting OS
-  state[os_ping]:                                 1
-  state[os_login]:                                1
-  state[os_run_cmd]:                              1
+default_state:
+  default_state[power]:                           1
+  default_state[bmc]:                             HOST_BOOTED
+  default_state[boot_progress]:                   FW Progress, Starting OS
+  default_state[os_ping]:                         1
+  default_state[os_login]:                        1
+  default_state[os_run_cmd]:                      1
 
 Different users may very well have different needs when inquiring about
 state.  In the future, we can add code to allow a user to specify which
@@ -33,12 +33,67 @@
 
 import commands
 from robot.libraries.BuiltIn import BuiltIn
+from robot.utils import DotDict
 
 import re
+import os
 
+# We don't want global variable getting changed when an import is done
+# so we'll save it and restore it.
+quiet = int(BuiltIn().get_variable_value("${quiet}"))
 # We need utils.robot to get keywords like "Get Power State".
 BuiltIn().import_resource("utils.robot")
 
+###############################################################################
+# The BMC code is about to be changed as far as what states are defined and
+# what the state values can be.  I am creating a means of processing both the
+# old style state (i.e. OBMC_STATES_VERSION = 0) and the new style (i.e.
+# OBMC_STATES_VERSION >= 1.
+# The caller can set environment variable OBMC_STATES_VERSION to dictate
+# whether we're processing old or new style states.  If OBMC_STATES_VERSION is
+# not set it will default to 0.
+DEFAULT_OBMC_STATES_VERSION = 0
+try:
+    BuiltIn().import_resource("state_manager.robot")
+except RuntimeError:
+    pass
+
+try:
+    OBMC_STATES_VERSION = int(os.environ.get('OBMC_STATES_VERSION',
+                              DEFAULT_OBMC_STATES_VERSION))
+except ValueError:
+    OBMC_STATES_VERSION = DEFAULT_OBMC_STATES_VERSION
+BuiltIn().set_global_variable("${quiet}", quiet)
+quiet = int(BuiltIn().get_variable_value("${quiet}"))
+
+if OBMC_STATES_VERSION == 0:
+    default_state = DotDict([('power', '1'),
+                             ('bmc', 'HOST_BOOTED'),
+                             ('boot_progress', 'FW Progress, Starting OS'),
+                             ('os_ping', '1'),
+                             ('os_login', '1'),
+                             ('os_run_cmd', '1')])
+else:
+    default_state = DotDict([('chassis', 'On'),
+                             ('bmc', 'HOST_BOOTED'),
+                             ('boot_progress', 'FW Progress, Starting OS'),
+                             ('host', 'Ready'),
+                             ('os_ping', '1'),
+                             ('os_login', '1'),
+                             ('os_run_cmd', '1')])
+
+
+###############################################################################
+def return_default_state():
+
+    r"""
+    Return default state dictionary.
+    """
+
+    return default_state
+
+###############################################################################
+
 
 ###############################################################################
 def anchor_state(state):
@@ -273,9 +328,16 @@
             os_password = ""
 
     # Get the component states.
-    cmd_buf = ["Get Power State", "quiet=${" + str(quiet) + "}"]
-    grp.rdpissuing_keyword(cmd_buf)
-    power = BuiltIn().run_keyword(*cmd_buf)
+    if OBMC_STATES_VERSION== 0:
+        cmd_buf = ["Get Power State", "quiet=${" + str(quiet) + "}"]
+        grp.rdpissuing_keyword(cmd_buf)
+        power = BuiltIn().run_keyword(*cmd_buf)
+    else:
+        cmd_buf = ["Get Chassis Power State", "quiet=${" + str(quiet) + "}"]
+        grp.rdpissuing_keyword(cmd_buf)
+        chassis = BuiltIn().run_keyword(*cmd_buf)
+        # Strip everything up to the final period.
+        chassis = re.sub(r'.*\.', "", chassis)
 
     cmd_buf = ["Get BMC State", "quiet=${" + str(quiet) + "}"]
     grp.rdpissuing_keyword(cmd_buf)
@@ -285,17 +347,36 @@
     grp.rdpissuing_keyword(cmd_buf)
     boot_progress = BuiltIn().run_keyword(*cmd_buf)
 
+    if OBMC_STATES_VERSION > 0:
+        cmd_buf = ["Get Host State", "quiet=${" + str(quiet) + "}"]
+        grp.rdpissuing_keyword(cmd_buf)
+        host = BuiltIn().run_keyword(*cmd_buf)
+        # Strip everything up to the final period.
+        host = re.sub(r'.*\.', "", host)
+
     # Create composite state dictionary.
-    cmd_buf = ["Create Dictionary", "power=${" + str(power) + "}",
-               "bmc=" + bmc, "boot_progress=" + boot_progress]
+    if OBMC_STATES_VERSION == 0:
+        cmd_buf = ["Create Dictionary", "power=${" + str(power) + "}",
+                   "bmc=" + bmc, "boot_progress=" + boot_progress]
+    else:
+        cmd_buf = ["Create Dictionary", "chassis=" + str(chassis),
+                   "bmc=" + bmc, "boot_progress=" + boot_progress,
+                   "host=" + host]
+
     grp.rdpissuing_keyword(cmd_buf)
     state = BuiltIn().run_keyword(*cmd_buf)
 
     if os_host != "":
         # Create an os_up_match dictionary to test whether we are booted enough
         # to get operating system info.
-        cmd_buf = ["Create Dictionary", "power=^${1}$", "bmc=^HOST_BOOTED$",
-                   "boot_progress=^FW Progress, Starting OS$"]
+        if OBMC_STATES_VERSION == 0:
+            cmd_buf = ["Create Dictionary", "power=^${1}$",
+                       "bmc=^HOST_BOOTED$",
+                       "boot_progress=^FW Progress, Starting OS$"]
+        else:
+            cmd_buf = ["Create Dictionary", "chassis=^On$",
+                       "bmc=^HOST_BOOTED$",
+                       "boot_progress=^FW Progress, Starting OS$"]
         grp.rdpissuing_keyword(cmd_buf)
         os_up_match = BuiltIn().run_keyword(*cmd_buf)
         os_up = compare_states(state, os_up_match)
@@ -338,8 +419,8 @@
     match_state       A dictionary whose key/value pairs are "state field"/
                       "state value".  The state value is interpreted as a
                       regular expression.  Example call from robot:
-                      ${match_state}=  Create Dictionary  power=^1$
-                      ...  bmc=^HOST_BOOTED$
+                      ${match_state}=  Create Dictionary  chassis=^On$
+                      ...  bmc=^Ready$
                       ...  boot_progress=^FW Progress, Starting OS$
                       ${state}=  Check State  &{match_state}
     invert            If this flag is set, this function will succeed if the
@@ -454,9 +535,9 @@
         grp.rprint_var(match_state)
 
     if quiet:
-        print_string=""
+        print_string = ""
     else:
-        print_string="#"
+        print_string = "#"
     cmd_buf = ["Check State", match_state, "invert=${" + str(invert) + "}",
                "print_string=" + print_string, "openbmc_host=" + openbmc_host,
                "openbmc_username=" + openbmc_username,