2013-05-22 11:11:09 -04:00
|
|
|
from migen.fhdl.std import *
|
2012-01-09 10:28:48 -05:00
|
|
|
|
|
|
|
class FSM:
|
2012-03-17 19:09:40 -04:00
|
|
|
def __init__(self, *states, delayed_enters=[]):
|
|
|
|
nstates = len(states) + sum([d[2] for d in delayed_enters])
|
|
|
|
|
2012-11-29 15:22:38 -05:00
|
|
|
self._state = Signal(max=nstates)
|
|
|
|
self._next_state = Signal(max=nstates)
|
2012-02-02 15:12:37 -05:00
|
|
|
for n, state in enumerate(states):
|
2012-11-28 17:18:43 -05:00
|
|
|
setattr(self, state, n)
|
2012-01-09 10:28:48 -05:00
|
|
|
self.actions = [[] for i in range(len(states))]
|
2012-03-17 19:09:40 -04:00
|
|
|
|
|
|
|
for name, target, delay in delayed_enters:
|
|
|
|
target_state = getattr(self, target)
|
|
|
|
if delay:
|
|
|
|
name_state = len(self.actions)
|
2012-11-28 17:18:43 -05:00
|
|
|
setattr(self, name, name_state)
|
2012-03-17 19:09:40 -04:00
|
|
|
for i in range(delay-1):
|
2012-11-28 17:18:43 -05:00
|
|
|
self.actions.append([self.next_state(name_state+i+1)])
|
2012-03-17 19:09:40 -04:00
|
|
|
self.actions.append([self.next_state(target_state)])
|
|
|
|
else:
|
|
|
|
# alias
|
2013-06-10 16:49:05 -04:00
|
|
|
setattr(self, name, target_state)
|
2012-01-09 10:28:48 -05:00
|
|
|
|
|
|
|
def reset_state(self, state):
|
|
|
|
self._state.reset = state
|
|
|
|
|
|
|
|
def next_state(self, state):
|
|
|
|
return self._next_state.eq(state)
|
|
|
|
|
|
|
|
def act(self, state, *statements):
|
2012-11-28 17:18:43 -05:00
|
|
|
self.actions[state] += statements
|
2012-01-09 10:28:48 -05:00
|
|
|
|
|
|
|
def get_fragment(self):
|
2012-11-28 19:11:15 -05:00
|
|
|
cases = dict((s, a) for s, a in enumerate(self.actions) if a)
|
2012-01-09 10:28:48 -05:00
|
|
|
comb = [
|
|
|
|
self._next_state.eq(self._state),
|
2012-11-28 19:11:15 -05:00
|
|
|
Case(self._state, cases)
|
2012-01-09 10:28:48 -05:00
|
|
|
]
|
|
|
|
sync = [self._state.eq(self._next_state)]
|
|
|
|
return Fragment(comb, sync)
|