Writing a RateControlNode
Overview
This tutorial demonstrates the careBT RateControlNode
. Therefore the SimpleRateControl
node
is implemented which has one child, the AddTwoNumbersMultiTickAction
. The SimpleRateControl
node
throttles the tick rate of the AddTwoNumbersMultiTickAction
node to 1000 ms.
Create the SimpleRateControl node
Create a file named ratecontrol.py
with following content.
Or use the provided file: ratecontrol.py
1from carebt import RateControlNode
2from carebt.examples.longrun_actions import AddTwoNumbersMultiTickAction
3
4
5class SimpleRateControl(RateControlNode):
6 """The `SimpleRateControl` example node.
7
8 The `SimpleRateControl` has one child. In this example this is the
9 `AddTwoNumbersMultiTickAction`. This node has no throttling. Due to
10 the `RateControlNode` such a throttling can be implemented without
11 changing the original source code of the node. Here, this throttling
12 rate is set to 1000 ms.
13
14 Input Parameters
15 ----------------
16 ?ticks : int
17 The number of ticks the calculation takes
18 ?a : int
19 The first value
20 ?b : int
21 The second value
22
23 """
24
25 def __init__(self, bt_runner):
26 super().__init__(bt_runner, 1000, '?ticks ?a ?b')
27
28 def on_init(self) -> None:
29 self.set_child(AddTwoNumbersMultiTickAction, '?ticks ?a ?b => ?result')
The code explained
The constructor (__init__
) of the SimpleRateControl
node needs to call the constructor (super().__init__
)
of the RateControlNode
and passes the bt_runner, the throttling rate in ms and the signature as arguments.
def __init__(self, bt_runner):
super().__init__(bt_runner, 1000, '?ticks ?a ?b')
In the on_init
function the child node is added.
def on_init(self) -> None:
self.set_child(AddTwoNumbersMultiTickAction, '?ticks ?a ?b => ?result')
Run the example
Start the Python interpreter and run the SimpleRateControl
node:
>>> import carebt
>>> from carebt.examples.ratecontrol import SimpleRateControl
>>> bt_runner = carebt.BehaviorTreeRunner()
>>> bt_runner.run(SimpleRateControl, '5 2 3 => ?result')
AddTwoNumbersMultiTickAction: (tick_count = 1/5)
AddTwoNumbersMultiTickAction: (tick_count = 2/5)
AddTwoNumbersMultiTickAction: (tick_count = 3/5)
AddTwoNumbersMultiTickAction: (tick_count = 4/5)
AddTwoNumbersMultiTickAction: DONE 2 + 3 = 5
The AddTwoNumbersMultiTickAction
node is executed until the fifth tick completes
the execution of the node. The time between the ticks is 1000 ms.