|
| 1 | +"""t03 — Passing multiple values via separate ports. |
| 2 | +
|
| 3 | +Extends t02 with a stateful producer (counts ticks before reporting a |
| 4 | +pose) and multiple primitive ports passed to a single consumer. |
| 5 | +
|
| 6 | +A later release adds `register_type` for sending custom Python classes |
| 7 | +through a single port — until then, pass each field as its own primitive |
| 8 | +port (string / int / float / bool). |
| 9 | +
|
| 10 | +Run: python t03_passing_data.py |
| 11 | +Expected output: |
| 12 | + [navigate] heading to (1.5, 2.5) at 0.8 m/s |
| 13 | + final status: SUCCESS |
| 14 | +""" |
| 15 | + |
| 16 | +from __future__ import annotations |
| 17 | + |
| 18 | +import pybt |
| 19 | + |
| 20 | +XML = """ |
| 21 | +<root BTCPP_format="4"> |
| 22 | + <BehaviorTree ID="Main"> |
| 23 | + <Sequence> |
| 24 | + <PlanPose x="{x}" y="{y}" speed="{speed}"/> |
| 25 | + <Navigate x="{x}" y="{y}" speed="{speed}"/> |
| 26 | + </Sequence> |
| 27 | + </BehaviorTree> |
| 28 | +</root> |
| 29 | +""" |
| 30 | + |
| 31 | + |
| 32 | +@pybt.ports(outputs=["x", "y", "speed"]) |
| 33 | +class PlanPose(pybt.SyncActionNode): |
| 34 | + def tick(self) -> pybt.NodeStatus: |
| 35 | + self.set_output("x", 1.5) |
| 36 | + self.set_output("y", 2.5) |
| 37 | + self.set_output("speed", 0.8) |
| 38 | + return pybt.NodeStatus.SUCCESS |
| 39 | + |
| 40 | + |
| 41 | +@pybt.ports(inputs=["x", "y", "speed"]) |
| 42 | +class Navigate(pybt.SyncActionNode): |
| 43 | + def tick(self) -> pybt.NodeStatus: |
| 44 | + x = float(self.get_input("x")) |
| 45 | + y = float(self.get_input("y")) |
| 46 | + speed = float(self.get_input("speed")) |
| 47 | + print(f"[navigate] heading to ({x}, {y}) at {speed} m/s") |
| 48 | + return pybt.NodeStatus.SUCCESS |
| 49 | + |
| 50 | + |
| 51 | +def main() -> int: |
| 52 | + factory = pybt.BehaviorTreeFactory() |
| 53 | + factory.register_node_type(PlanPose, "PlanPose") |
| 54 | + factory.register_node_type(Navigate, "Navigate") |
| 55 | + tree = factory.create_tree_from_text(XML) |
| 56 | + status = tree.tick_while_running() |
| 57 | + print(f"final status: {status.name}") |
| 58 | + return 0 if status == pybt.NodeStatus.SUCCESS else 1 |
| 59 | + |
| 60 | + |
| 61 | +if __name__ == "__main__": |
| 62 | + raise SystemExit(main()) |
0 commit comments