state_machine.py revision c7f1593f9af3ea1b9264b37628c36f3a70e1749a
1#!/usr/bin/python
2# -*- coding: utf-8 -*-
3#
4# Copyright 2011 Google Inc. All Rights Reserved.
5#
6
7__author__ = 'kbaclawski@google.com (Krystian Baclawski)'
8
9from automation.common import events
10
11
12class BasicStateMachine(object):
13  """Generic class for constructing state machines.
14
15  Keeps all states and possible transition of a state machine. Ensures that
16  transition between two states is always valid. Also stores transition events
17  in a timeline object.
18  """
19  state_machine = {}
20  final_states = []
21
22  def __init__(self, initial_state):
23    assert initial_state in self.state_machine,\
24           'Initial state does not belong to this state machine'
25
26    self._state = initial_state
27
28    self.timeline = events.EventHistory()
29    self.timeline.AddEvent(self._state)
30
31  def __str__(self):
32    return self._state
33
34  def __eq__(self, value):
35    if isinstance(value, BasicStateMachine):
36      value = str(value)
37
38    return self._state == value
39
40  def __ne__(self, value):
41    return not self == value
42
43  def _TransitionAllowed(self, to_state):
44    return to_state in self.state_machine.get(self._state, [])
45
46  def Change(self, new_state):
47    assert self._TransitionAllowed(new_state),\
48           'Transition from %s to %s not possible' % (self._state, new_state)
49
50    self._state = new_state
51
52    self.timeline.AddEvent(self._state)
53
54    if self._state in self.final_states:
55      self.timeline.last.Finish()
56