The Crazyflie adapter · project tour, chapter 1
Project tour, chapter 1

The Crazyflie adapter

The one place where this project's Python code talks to a real drone. It has two jobs: turn the project's own types into calls to Bitcraze's library, and never drop a flying drone.

A nano drone, the Crazyflie 2.1+, flown by a PC over a USB radio Every link opens the code at commit 5050718 Sections 1, 2, 3 and 5 are ready; the rest are coming
Start simpleEach section opens with a short summary. That's the 15-minute tour.
Go deeperOpen any drop-down, or press Everything at the top to open them all.
Words and numbers with dotsHover or tap one. A word shows its definition from the project's glossary, and a number shows where it comes from in the code.
01

The Adapter

Above the Crazyflie adapter, the code uses the project's own types and generic words: range readings, a position estimate, take off, land. Below it is Bitcraze's world: cflib, the Crazyradio and the drone's firmware. The adapter is the only code in src/ that imports cflib, and a fitness function fails continuous integration if anything else does.

This project'sPython code Bitcraze'slibrary, radioand firmware Behaviorsdecide Safety layerjudges and sends Drone interfacethe contract Crazyflie adapterthis chapter cflibBitcraze's Python library CrazyradioUSB radio dongle Firmwareon the drone command requests snapshot commands snapshot commands that don't block take_snapshot() cflib calls log callbacks CRTP packets CRTP packets setpoints, moves log blocks over the air ◀ the only layerthat imports cflib Crazyflie-only wordsstay below this line
Layer · this chapter

Crazyflie adapter

Implements the drone interface on a real Crazyflie. It converts between the project's SI units and cflib's millimeters, degrees and millisecond timestamps, in one place. Crazyflie-only ideas, such as decks, log blocks and radio addresses, stop here.

Click a layer. Commands flow down and telemetry flows up, one step at a time, and nothing skips a step (ARCHITECTURE.md, data flow).
Why it's built this wayWhy an adapter at all?

The project started before the drone was bought. Behaviors had to run and be tested with no hardware, then run unchanged on the real drone. If behaviors called cflib directly, nothing would run without a drone, and cflib's threading and blocking quirks would leak into every behavior.

So behaviors talk only to the drone interface, and adapters implement it: a mock adapter for tests and development, and the Crazyflie adapter for flights. cflib's quirks are solved once, in one place.

Why it's built this wayWhy Crazyflie-focused, and not generic?

The Crazyflie is the only drone, and no other can be tested. So the interface is designed for it alone, but uses a generic name wherever most drones share the idea: range readings, position estimate, arm, take off, land. Crazyflie-only ideas (decks, log blocks, radio addresses, cflib's units) stay inside the adapter.

The accepted risk: some shapes are still Crazyflie-shaped, such as five fixed range directions. Another drone would likely become a separate project.

Python noteAn abstract class, and with for a guaranteed landing

DroneInterface is an abstract base class: a method marked @abstractmethod is like a pure virtual function in C++, and Python refuses to create an object of a class that leaves one unwritten.

It also defines __enter__ and __exit__, so a program writes with drone:. Python calls __exit__ when the block ends, even when it ends with an error, much like a C++ destructor in RAII. Here that means disconnect() always runs, and it lands a drone that may be flying.

def __enter__(self) -> Self:
    self.connect()
    return self

def __exit__(...) -> None:
    # Runs even when the code inside the `with` block raises, so the
    # drone always ends up on the ground.
    self.disconnect()
interface.py 42-54, parameters shortened
02

The Parts

The adapter is nine modules. Four import cflib and run pyright, Python's type checker, in its basic mode. The other five don't import cflib, and all five are type-checked strictly. Four of those are tested without cflib. Take-off and landing is still tested through the adapter, with cflib's objects mocked, until backlog #158.

Import cflib · pyright basic
No cflib · pyright strict
imports cflib · 656 lines

adapter.py

Implements the drone interface. It builds the four parts, runs the steps of connect() and disconnect() in order, does the waiting, and forwards each command to a part in a line or two. About 110 of its lines are test-only forwards to the parts, marked to go with backlog #158.

Owns
the parts; the waits; whether the drone's state is unknown while connecting
Click a module. The bar is its length in lines at the pinned commit. Only the four on the left may import cflib, and a fitness function checks the list (test_import_rules.py 220-225).
MoreWhy connect() builds every part afresh

A new link learns what the drone is doing from the drone: nothing carries over from an earlier one. So connect() starts by calling the same builder as __init__, which makes new parts. Before the split, connect() reset 18 fields by hand. Now no part can carry state from an earlier link, because every part is new.

The order inside the builder matters: take-off and landing keeps the commands object it's given, so it's built right after the commands.

def connect(self) -> None:
    self._is_drone_state_unknown = True
    # A new link learns what the drone is doing from the drone: nothing carries over from an earlier one.
    self._build_parts()
adapter.py 167-173, docstring left out · the builder: adapter.py 140-163
Python noteWhy the parts get lambda: self._link.crazyflie

A lambda is a small unnamed function. lambda: self._link.crazyflie reads self._link each time it's called, not when it's made, like a C++ lambda that captures this rather than a copy of the pointer.

That matters because connect() replaces the telemetry buffer twice, the second time after the estimate reset. A part that kept its own reference would read a dead buffer, and a high-level move would aim at an old position. So every part looks up the drone and the buffer on every call and keeps neither. It also lets the builder make the commands before the link exists.

self._commands = CrazyflieCommands(lambda: self._link.crazyflie, lambda: self._log_blocks.telemetry)
adapter.py 143 · where the buffer is replaced: adapter.py 553-557 · commands.py 49-60
Python noteA Protocol: how take-off and landing sends without cflib

A Protocol describes the methods a type must have, and a class fits it just by having them, with no inheritance. It's close to a C++20 concept. The commands part never names FlightCommands, yet pyright checks that it fits wherever it's passed in.

class FlightCommands(Protocol):
    """The sends take-off and landing makes. The adapter's `CrazyflieCommands` satisfies it (ADR-0093)."""

    def send_level_setpoint(self, vertical_speed: float) -> None: ...
    def go_to(self, position: Vector3, duration: float) -> None: ...
    def go_to_relative(self, offset: Vector3, duration: float, *, linear: bool = False) -> None: ...
    def stop_motors(self) -> None: ...
    def emergency_stop(self) -> None: ...
take_off_and_landing.py 71-82, blank lines left out
Python noteStrict and basic type checking

Python doesn't check types when it runs. Pyright reads the type hints and checks them before the code runs. The project sets its strict mode for all its Python, tests included, and a file can turn it down only with a comment. cflib has no type hints, so the four modules that use it switch to basic mode with one comment on their first line. Everything they hand to the rest of the project is fully typed.

# pyright: basic
# Basic mode because cflib has no type hints (ADR-0004). Everything this module
# exposes is fully typed; the looseness stays inside this file.
adapter.py 1-3 · the project's setting: pyproject.toml
MoreHow the rules are enforced: four fitness functions

Fitness functions read the code instead of running it, and fail continuous integration when a rule breaks. Their import scanner, import follower and comment scanner each have tests of their own.

  • Only the Crazyflie adapter imports cflib. 209-217
  • Inside it, only the four named modules do. A module that starts or stops importing cflib changes the list, so the change shows in review. 220-225
  • Take-off and landing reaches no cflib, not even through another module. 228-233
  • Nothing turns pyright's strict mode down for take-off and landing. 236-242
Why it's built this wayWhy split the adapter, and why here?

The adapter was once one class of 1,421 lines. Size alone is no reason to split a module: parts that share state, dependencies and reasons to change belong together. The project splits a part out only when one of five tests is true of it: it needs fewer dependencies than the file, another module needs it, it runs on a different thread, it has its own state and invariants, or it changes for a different reason.

Take-off and landing passes four of the five tests (1, 2 once the mock adapter runs it, 4 and 5). The log blocks and the link pass 3 and 5. The commands pass 4 and 5.

03

Two Threads

Telemetry arrives on cflib's receive thread, whenever the radio delivers it. Decisions run on the tick's thread, 20 times a second. The two meet in one place: the telemetry buffer, guarded by the only lock in the data path. Each tick copies it into a snapshot, and every value carries the time it arrived, so any reader can tell how old it is.

Click a tick to see each value's age.
Ages at tick 12
ValueFromAgeLimit

Reading the ages

Age is the time since a value arrived on the PC, measured at the snapshot. A value older than its limit is stale: STALE_AFTER, 0.25 s, for everything but the battery, which streams every 1 s and gets 3 s.

The safety pre-check checks the age of four values: the position estimate, the drone status, the down range and the battery voltage. While the drone may be flying, outside the initial climb, it also checks the velocity uncertainty. The table shows a flying drone, so it tags five. One stale value fails the pre-check, and the drone lands. It doesn't check the velocity estimate's age or the Multi-ranger's.

Packets drawn at their log periods (log_blocks.py 39-45) and ticks at 20 Hz (tick_loop.py 20, ADR-0023). Where each stream starts is chosen for the drawing, and real packets arrive late and unevenly.
MoreThe state block's 26 bytes

A log block carries at most 26 bytes of variables. The state block fills all 26: the position and velocity estimates as six 4-byte floats, and the drone status as a 2-byte bitfield. Because the three share one packet, they always come from the same moment, and a lost packet loses all three together, so they go stale together.

xxxxyyyyzzzzvx vxvxvxvyvyvyvyvzvzvzvzinfoinfo

Blue: stateEstimate.x to .vz, the estimates. Amber: supervisor.info, the status bitfield.

MoreStamped values: two clocks on every reading

Every value in a snapshot is a stamped value. Staleness uses the arrival time, on the PC's clock. The drone's own timestamp is kept for measuring latency, for recording and for replay.

@dataclass(frozen=True, slots=True)
class Stamped[T]:
    value: T
    arrival_time: float
    drone_time: float | None

    def age(self, now: float) -> float:
        return now - self.arrival_time
snapshot.py 17-37, docstrings left out · test

Python note. @dataclass writes the constructor and comparisons for you. frozen=True makes every field read-only after construction, and slots=True stops new fields being added. Stamped[T] is a generic class, like a C++ template.

MoreThe drone's clock wraps every 4.7 hours

The drone stamps each packet, and cflib unpacks the stamp as 24 bits, so it restarts at zero every 16,777,216 counts. The code reads the counts as milliseconds since the drone booted, which makes that about 4.7 hours of drone uptime. That unit is marked to verify at the bench.

So the adapter keeps counting up across the wrap, using the previous drone time as the reference. A jump of more than half the range is a wrap. Anything smaller is an ordinary out-of-order packet.

Previous drone timeNew stampDrone timeWhy
16,777.100 s5016,777.266 sthe counter wrapped
16,777.266 s16,777,20016,777.200 sa late packet from before the wrap

Both rows computed with drone_time_from_timestamp at the pinned commit.

MoreA broken estimate goes stale on purpose

If the drone sends a position estimate that isn't a finite number (NaN or infinity), the callback drops it and warns once per streak. The last finite one stays in the buffer and goes stale within 0.25 s, so the safety pre-check fails on it and the drone lands. Its landing then aims at that last finite position, not at NaN. A velocity estimate that isn't finite is dropped the same way, but the pre-check doesn't check the velocity estimate's age, so a dropped one alone doesn't fail it.

if position.is_finite():
    self._telemetry.write_position_estimate(position, drone_time)
if velocity.is_finite():
    self._telemetry.write_velocity_estimate(velocity, drone_time)
self._telemetry.write_drone_status(status, drone_time)
log_blocks.py 281-302, shortened · test · ADR-0030
MoreThe snapshot's time is read after the copy

The buffer copies every value, then reads its clock, all under the lock. Every value was stamped before it was stored, so no value in a snapshot is newer than the snapshot's time, and no age is ever negative.

with self._lock:
    position_estimate = self._position_estimate
    velocity_estimate = self._velocity_estimate
    # ... every other value ...
    drone_status = self._drone_status
    time = self._clock.now()
telemetry_buffer.py 149-157, shortened · test · ADR-0046

Python note. with self._lock: takes the lock at the start of the block and releases it at the end, even when the block raises, like std::lock_guard in C++. The buffer's tests hold the lock themselves to prove that every read and write waits for it (test).

Why it's built this wayWhy a snapshot per tick?

If behaviors read shared values as they changed, one tick could see a mix of old and new values, and locks would spread through behavior code. A read-only snapshot per tick keeps every behavior in a tick on the same picture and confines thread safety to one hand-off: the copy at the start of the tick. It's also easy to build by hand in a test, and to replay from a recording.

Values that arrive together are written together, so no snapshot mixes two samples (test).

04

Commands

Not written yet.

05

The Bad-Flow Zone

Near the floor, the Flow deck's flow can't be trusted, so the estimated horizontal speed and position go wrong: the bad-flow zone. So take-off and landing cross it level. The adapter streams level setpoints, which hold roll and pitch at zero and set only a vertical speed, and hands over to the drone's own planner only once it's 0.15 m up, with flow. In a landing, the motors stop only when the down range confirms touchdown, or when the final descent's deadline says the drone must be on the floor.

0.00 s
level setpoints, streamed every tick the drone's high-level commander at least the bad-flow zone
The state machine · click an amber branch
take-off flow at0.15 m land() down range≤ 0.15 m touchdownconfirmed off On the floor Initial climblevel, +0.4 m/s Flyinghigh-level moves Landing approachgo_to aimed at 0.1 m Final descentlevel, −0.3 m/s Motor stopthen release no flow1.5 s limitland() backup time deadline no down range?

The highlighted state follows the animation. Hover, move-to, set-velocity and take-off are ignored during the two level parts, logged once per streak (232-247, ADR-0056).

What the adapter sends

The transcript test flies this flight against a fake cflib and checks every call, in order. These are its flight's lines.

75send_packet(…04 … cdcccc3e) level, +0.4 m/s
77send_packet(…04 … cdcccc3e) one each tick
⋮…
84send_packet(…04 … cdcccc3e) the last setpoint
85high_level_commander.go_to(0.0, 0.0, 0.5, 0.0, 1.133…)
86commander.send_notify_setpoint_stop() the release
88high_level_commander.go_to(0.0, 0.0, 0.5, 0.0, 1.0) hover
89high_level_commander.go_to(0.0, 0.0, 0.0999…, 0.0, 1.333…)
90send_packet(…04 … 9a9999be) level, −0.3 m/s
⋮… one each tick
101send_packet(…04 … 9a9999be)
102commander.send_stop_setpoint()
103high_level_commander.stop()
104commander.send_notify_setpoint_stop() the release, last
A model drawn from the code's numbers, not a recorded flight: here the drone follows each command at once and every reading is exact. A real drone trails its high-level moves (ADR-0068), and its readings are noisy. The take-off target is 0.5 m, as in the transcript, and the hover's length is the model's.
Why it's built this wayWhy cross the zone level?

A high-level move holds position by the horizontal speed estimate. In the zone that estimate is wrong, so the controller chases a speed that isn't there and slides the drone sideways. A level setpoint ignores the horizontal estimate: the drone moves only vertically, so it doesn't need the flow there.

The risk accepted with it: while level there is no position hold, so a small tilt error pushes the drone sideways. Ending the level part at a fixed 0.15 m keeps that drift small.

MoreThe hand-over at 0.15 m, in three sends

The climb ends at the first fresh down range at or above the final descent height, 0.15 m. With flow there, a hand-over gives the drone to its high-level commander. The order is the point: a streamed setpoint stops the high-level commander, and a stopped high-level commander turns the motors off once the stream is released. So the release must come after the move.

@contextmanager
def _handing_over_to_high_level(self) -> Iterator[None]:
    if self._level_vertical_speed is not None:
        self.send_level_setpoint(self._level_vertical_speed)   # 1. the last setpoint
    yield                                                      # 2. the high-level move
    if self._is_streaming:
        self._current_crazyflie().commander.send_notify_setpoint_stop()   # 3. the release
        self._is_streaming = False
        self._level_vertical_speed = None
commands.py 110-125, docstring left out, numbered comments added · test: the order

Python note. @contextmanager turns a generator into something a with block can use: the code before yield runs when the block starts, and the code after it when the block ends. go_to wraps its one high-level call in it, so no high-level move can skip the hand-over (commands.py 91-95).

Flow means a fresh velocity uncertainty under 0.03 m/s. Missing, stale, negative or not finite counts as no flow (bad_flow_zone.py 20-31, test).

MoreLanding: an approach, then the final descent

The landing approach is a high-level move straight down, aimed 5 cm below the final descent height. It isn't the firmware's own landing, which switches the motors off when it ends, even above the floor. The final descent then streams one level setpoint down each tick until touchdown is confirmed.

match self._landing_phase:
    case _LandingPhase.LANDING_APPROACH:
        down = fresh_down_distance(snapshot, now)
        if down is not None and down.value <= FINAL_DESCENT_HEIGHT:
            self._start_final_descent(down)
        elif now >= self._landing_approach_ends_at:
            self._start_final_descent(down)   # the backup, with a warning
    case _LandingPhase.FINAL_DESCENT:
        ...
take_off_and_landing.py 354-377, shortened

Python note. match and case compare a value against patterns, here the members of an Enum. It reads like a C++ switch on an enum class, with no fall-through between cases.

MoreWhere noisy readings are handled
  • The touchdown hold. The down range must stay at or below 0.05 m for 0.3 s. A higher, missing or stale reading starts the touchdown hold over, so one noisy reading can't confirm touchdown. touchdown.py 64-79 test: one low reading test: the hold restarts
  • The deadline. It comes from the highest down range in the last 1 s, so a short low outlier can't shorten it. test test
  • The height estimate never decides. On this drone the estimate's height comes mostly from the same down sensor, so it can't back that sensor up. Drift can't stop the motors in mid-air either. test ADR-0019 ADR-0012
MoreThe motor stop, and the release after it

Every motor stop sends three things in order: the stop setpoint while a stream runs, the high-level stop, then the release of the setpoint priority. Without the release, the drone refuses the stopped high-level commander's motors-off setpoints, and a drone that still counts as flying locks once its setpoint is 2 s old.

MoreEvery number the animation takes from the code
NumberValueWhere
Initial climb speed0.4 m/sbad_flow_zone.py 9
Final descent height0.15 mbad_flow_zone.py 13, ADR-0077
Initial climb's time limit1.5 sbad_flow_zone.py 16, ADR-0077
High-level vertical speed0.3 m/stake_off_and_landing.py 45
Shortest high-level move0.5 stake_off_and_landing.py 49
Hover settle1 stake_off_and_landing.py 47
Approach aims below the final descent height by0.05 mtake_off_and_landing.py 36
Approach backup1 stake_off_and_landing.py 38
Final descent speed0.3 m/sbad_flow_zone.py 11, ADR-0072
Down range period20 mslog_blocks.py 41
Touchdown down range0.05 minterface.py 26
Touchdown hold0.3 stouchdown.py 14
Deadline: recent window1 stouchdown.py 17
Deadline: margin2 stouchdown.py 22
Tick rate20 Hztick_loop.py 20, ADR-0023
MoreHow this is tested without a drone

The transcript test runs this whole flight on a sim clock against a fake cflib that records every call the adapter makes, then compares the list, in order, with the stored transcript. A change that reorders or alters one send fails it, which matters because the setpoint priority depends on the order. Unit tests cover the rules and each failure branch above, on a sim clock, with no radio.

Coming next

These sections are planned and not written yet.

06

May Be Flying

Not written yet.

07

Connect and Disconnect

Not written yet.

08

Failures

Not written yet.

09

Testing

Not written yet.