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.
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.
Behaviors
Behaviors decide. Each tick, a behavior reads the snapshot and asks the safety layer for commands. It holds no drone and no clock, so a behavior's test builds a snapshot by hand, with no drone, mock or thread.
Safety layer
Apart from two narrow exceptions, a test wrapper and the operator's kill switch (not built yet), the safety layer is the only code that sends commands to the drone. It runs the safety pre-check on every snapshot and answers each command request at once.
Drone interface
The drone interface is the contract every adapter implements. Its commands start an action and return; what happened shows in later snapshots. Only connect() and disconnect() may block.
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.
cflib
Bitcraze's official Python library for the Crazyflie. It runs threads of its own: its receive thread calls the adapter's log callbacks. It has no type hints, so the four adapter modules that use it run the type checker in its basic mode.
Crazyradio
The USB radio dongle the PC uses to talk to the drone. Everything crosses it as CRTP packets. The adapter's default address is radio://0/80/2M/E7E7E7E7E7.
Firmware
Code running on the drone itself: stabilization, estimation and motor control. Its high-level commander plans and flies smooth moves on the drone. If streamed setpoints stop, its supervisor warns after 0.5 s and times out after 2 s, which levels the drone and then cuts its motors.
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()
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.
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
log_blocks.py
The log blocks, and their callbacks, which convert each sample to SI units and write it to the telemetry buffer on cflib's receive thread.
- Owns
- the telemetry buffer; the other parts read it from here on every call
commands.py
Every send: setpoints, high-level moves with their hand-over, the motor stop, arming, the emergency stop, the buzzer and the estimate reset.
- Owns
- the setpoint stream's state: whether one is running, and its vertical speed
link.py
The radio link: opening and closing it with time limits, the parameters and deck checks, the lost link, and the thrust base.
- Owns
- cflib's
SyncCrazyflie; the other parts look up the drone through it on every call
take_off_and_landing.py
The initial climb, the landing approach, the final descent and "may be flying", moved on by one tick at each update. It sends through FlightCommands, a Protocol, so it never imports cflib. Section 5 flies it.
- Owns
- the landing phase and the flight state
time_limit.py
Runs a blocking step of connecting on a helper thread, with a time limit, so the interrupt signal still gets through: cflib's connect waits with no time limit.
- Tested
- alone, without cflib
conversions.py
Conversions between cflib's units and data and the project's SI units, as plain functions: millimeters to meters, millisecond timestamps to seconds, radians to degrees, and the bytes of the level setpoint's packet.
- Tested
- alone, without cflib
touchdown.py
Decides whether a landing has really touched down, from the down range, and when the final descent must be over.
- Tested
- alone, without cflib
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()
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)
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: ...
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.
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.
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.
| Value | From | Age | Limit |
|---|
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.
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.
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
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 time | New stamp | Drone time | Why |
|---|---|---|---|
| 16,777.100 s | 50 | 16,777.266 s | the counter wrapped |
| 16,777.266 s | 16,777,200 | 16,777.200 s | a 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)
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()
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).
Commands
Not written yet.
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.
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).
The initial climb lands
Three things end the climb in a landing that starts the final descent from where the drone is, with no landing approach: no flow at 0.15 m (a fresh velocity uncertainty under 0.03 m/s), 1.5 s since the take-off was sent, or a land request during the climb.
The landing approach's backup
The drone trails its high-level move, so the down range reaching 0.15 m starts the final descent, not the move's end. If the down range never gets there, the final descent starts anyway 1 s after the move should have ended. The backup runs on the clock, so it shares neither the down range nor the estimate.
The final descent's deadline
Set once, when the final descent starts, from the highest recent down range. If that's 0.15 m, the deadline is about 2.5 s later. With no recent reading at all, it's about 22 s later. When it passes without a confirmed touchdown, the drone must be on the floor, so the motors stop.
FormulaThe whole deadline
deadline = start + height / speed + 2 sstart: when the final descent starts.height: the highest down range in the last 1 s, or 2 m without one.speed: 0.3 m/s in the level descent, 0.1 m/s in the slow one without a fresh down range.
No usable down range
A level descent from an unknown height could drift for seconds. So without a fresh down range, the final descent is one slow high-level move straight down at 0.1 m/s, timed to its deadline. Unlike streamed setpoints, it keeps going if the ticks stop.
The transcript test flies this flight against a fake cflib and checks every call, in order. These are its flight's lines.
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
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:
...
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
| Number | Value | Where |
|---|---|---|
| Initial climb speed | 0.4 m/s | bad_flow_zone.py 9 |
| Final descent height | 0.15 m | bad_flow_zone.py 13, ADR-0077 |
| Initial climb's time limit | 1.5 s | bad_flow_zone.py 16, ADR-0077 |
| High-level vertical speed | 0.3 m/s | take_off_and_landing.py 45 |
| Shortest high-level move | 0.5 s | take_off_and_landing.py 49 |
| Hover settle | 1 s | take_off_and_landing.py 47 |
| Approach aims below the final descent height by | 0.05 m | take_off_and_landing.py 36 |
| Approach backup | 1 s | take_off_and_landing.py 38 |
| Final descent speed | 0.3 m/s | bad_flow_zone.py 11, ADR-0072 |
| Down range period | 20 ms | log_blocks.py 41 |
| Touchdown down range | 0.05 m | interface.py 26 |
| Touchdown hold | 0.3 s | touchdown.py 14 |
| Deadline: recent window | 1 s | touchdown.py 17 |
| Deadline: margin | 2 s | touchdown.py 22 |
| Tick rate | 20 Hz | tick_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.
These sections are planned and not written yet.
May Be Flying
Not written yet.
Connect and Disconnect
Not written yet.
Failures
Not written yet.
Testing
Not written yet.