Debian Codegraph @

examples/strategy/bareboxrebootstrategy.py

raw symbols SCIP
1 import enum
2
3 import attr
4
5 from labgrid import target_factory, step
6 from labgrid.driver import BareboxDriver, ShellDriver
7 from labgrid.protocol import PowerProtocol
8 from labgrid.strategy import Strategy, never_retry
9
10
11 @attr.s(eq=False)
12 class StrategyError(Exception):
13 msg = attr.ib(validator=attr.validators.instance_of(str))
14
15
16 class Status(enum.Enum):
17 unknown = 0
18 barebox = 1
19 shell = 2
20
21
22 @target_factory.reg_driver
23 @attr.s(eq=False)
24 class BareboxRebootStrategy(Strategy):
25 """A Strategy to switch to barebox or shell and back via reboot
26
27 In your env.yaml, simply instantiate the strategy without parameters, for example:
28
29 .. code-block:: yaml
30 targets:
31 main:
32 resources:
33 RawSerialPort:
34 port: "/dev/ttyUSB0"
35 drivers:
36 ManualPowerDriver:
37 name: "example"
38 SerialDriver {}
39 BareboxDriver:
40 prompt: 'barebox@[^:]+:[^ ]+ '
41 bootstring: '\[[ .0-9]+\] '
42 ShellDriver:
43 prompt: 'root@\w+:[^ ]+ '
44 login_prompt: ' login: '
45 username: 'root'
46 BareboxRebootStrategy: {}
47 """
48
49 # pull in the according drivers into self.*
50 bindings = {
51 "power": PowerProtocol,
52 "barebox": BareboxDriver,
53 "shell": ShellDriver,
54 }
55
56 status = attr.ib(default=Status.unknown)
57
58 def __attrs_post_init__(self):
59 super().__attrs_post_init__()
60
61 @never_retry
62 @step(args=["new_status"])
63 def transition(self, new_status, *, step):
64 if not isinstance(new_status, Status):
65 new_status = Status[new_status]
66
67 if new_status == Status.unknown:
68 raise StrategyError(f"can not transition to {new_status}")
69
70 elif self.status == new_status:
71 step.skip("nothing to do")
72 return
73
74 elif self.status == Status.unknown:
75 # unknown state after initialization, cycle power
76 self.target.activate(self.power)
77 self.power.cycle()
78
79 # we can then let the according driver do the rest to get us into a barebox or shell:
80 if new_status == Status.barebox:
81 self.target.activate(self.barebox)
82 elif new_status == Status.shell:
83 # (this assumes that barebox will autoboot to the shell after a timeout)
84 self.target.activate(self.shell)
85
86 elif self.status == Status.barebox and new_status == Status.shell:
87 # in barebox: boot the default target and hope it will get us to a shell :->
88 self.barebox.boot("")
89 self.barebox.await_boot()
90 self.target.activate(self.shell)
91
92 elif self.status == Status.shell and new_status == Status.barebox:
93 # in shell: we can simply reboot to get a barebox
94 # make sure run() reads the shell prompt and returns
95 self.shell.run("(sleep 1;reboot)&")
96 self.target.activate(self.barebox)
97
98 else:
99 raise StrategyError(f"no transition found from {self.status} to {new_status}")
100
101 self.status = new_status