Skip to content

Crazyflie Interface Documentation

Introduction

Overview: Implements foundational object management and control interfaces for single and swarm drone operations within the RflySim simulation environment, supporting time scheduling, single-drone state management, and full-swarm command broadcasting.

This module serves as the core底层 (底层 = foundational/low-level) interface module for RflySim’s Crazyflie swarm drone simulation development. It caters to the development needs of swarm drone simulation tasks: it enables individual drone state and control management via the Crazyflie class, and unified command broadcasting and object management across the entire swarm via the CrazyflieServer class. Additionally, the TimeHelper class provides unified time management capabilities essential for swarm simulations, ensuring temporal consistency in multi-drone scheduling.

This module is suitable for scenarios such as swarm drone cooperative task development, multi-drone formation control algorithm validation, and swarm path planning simulation, forming the foundational object support layer for upper-layer swarm task application development.

Quick Start

Minimal working example; copy and modify minimal configuration to run.

from RflySimSDK.swarm import Crazyflie
import time

# 1. Initialize a single drone with ID=0, initially positioned on the ground at the origin
drone = Crazyflie(
    id=0,
    initialPosition=[0, 0, 0.01], # Initial position; z set to small height to avoid ground collision
    tf=None, # No custom coordinate transform; default world frame used
    mode=None # Use default control mode
)

# 2. Assign drone to group, join group 0 (bit 0 set to 1)
drone.setGroupMask(0b00000001)

# 3. Enter main loop to sustain drone state updates
drone.loop()

# Custom task logic (e.g., takeoff, waypoint following) can be added here
time.sleep(3) # Example: maintain for 3 seconds before exiting

Environment & Dependencies

  • Python Environment: >= 3.8.10
  • Dependencies: ctrl, numpy, threading, time
  • Prerequisites: Before invoking this interface, ensure RflySimSDK is imported and the swarm simulation environment is correctly configured.

Core Interface Description

The module crazyflie.py includes configuration variables, helper functions, and core business classes.

Global Constants and Enumerations

This section lists all globally accessible constants and enumerations directly referenceable within the module.

Standalone Constants

None


Global/Standalone Functions

None


TimeHelper Class

Contains all time-related functionality. This class supports using the same script for real hardware and variable-rate simulation: on real hardware, it uses ROS time functions; in simulation mode, it operates independently of ROS, freeing scripts from needing to detect the current runtime environment. Class attributes include a no-op visualizer object, conforming to the visualization API specifications required by simulation scripts.

__init__()

Function Description: Initializes a TimeHelper instance
Parameters (Args):
None
Returns:

  • TimeHelper instance object

Exceptions (Raises):
None


time()

Function Description: Retrieves the current time in seconds
Parameters (Args):
None
Returns:

  • float: Current time in seconds

Exceptions (Raises):
None

Example:

from RflySimSDK.swarm.crazyflie import TimeHelper
time_helper = TimeHelper()
current_t = time_helper.time()

sleep(duration)

Function Description: Suspends execution for a specified duration in seconds
Parameters (Args):

Parameter Name Type Required Default Description
duration float Yes Duration to sleep, in seconds

Returns:

  • None

Exceptions (Raises):
None

Example:

from RflySimSDK.swarm.crazyflie import TimeHelper
time_helper = TimeHelper()
# Sleep for 2 seconds
time_helper.sleep(2)

sleepForRate(rateHz)

Function Description: When called within a loop, this method allows the loop to run at a specified frequency by sleeping for the remaining time in each cycle.

Arguments (Args):

Parameter Name Type Required Default Value Description
rateHz float Yes - Target loop frequency in Hertz

Returns:

  • None

Raises: - None


isShutdown()

Function Description: Determines whether the script should terminate (e.g., upon receiving a Ctrl+C interrupt signal).

Arguments (Args): - None

Returns:

  • bool: Returns True if the script should terminate; otherwise, returns False.

Raises: - None


Crazyflie Class

Represents an object for a single Crazyflie drone. Most functionality of this module is encapsulated within this class.

__init__(id, initialPosition, tf, mode)

Function Description: Initializes a single Crazyflie drone object.

Arguments (Args):

Parameter Name Type Description
id int Integer ID of the drone, ranging from [0, 255], corresponding to the last byte of the drone’s communication address.
initialPosition iterable of float Initial position of the drone in the format [x, y, z]; typically placed on the ground of the experiment area, with z = 0.0.
tf tf.TransformListener ROS transform listener, used to query the current state of the drone.
mode None Drone operating mode parameter.

Returns: None
Raises: None


loop()

Function Description: No additional description provided.

Arguments (Args): - None

Returns: None
Raises: None


setGroupMask(groupMask)

Function Description: Sets the group mask bit for the current drone. Grouping allows actions (e.g., executing a pre-uploaded trajectory) to be triggered only for a subset of drones by sending a single wireless packet, which is crucial for achieving tightly synchronized formation maneuvers. Up to 8 groups are supported, with each group corresponding to one bit in the groupMask byte. When a broadcast command with a groupMask parameter is issued on a CrazyflieServer object, the command affects only those drones whose own groupMask, when bitwise ANDed with the command’s groupMask, yields a non-zero result. Commands with groupMask = 0 apply to all drones, regardless of group membership. Some single-drone (non-broadcast) commands also support groupMask, though it serves no special purpose in such cases.

Arguments (Args):

Parameter Name Type Required Default Value Description
groupMask int Yes None An 8-bit integer indicating the membership status of the current drone in up to 8 possible groups.

Returns: None
Raises: None


enableCollisionAvoidance(others, ellipsoidRadii)

Function Description: Enables onboard collision avoidance for the drone. Once enabled, the drone uses the Buffered Voronoi Cells method to avoid collisions with other Crazyflie drones, with all computations performed onboard. This collision avoidance method accounts for downwash effects: the high-speed airflow generated by the rotors necessitates a significantly larger safe clearance when passing beneath another drone compared to passing alongside it; therefore, the collision detection boundary is modeled as an ellipsoid.

Arguments (Args):

Parameter Name Type Required Default Value Description
others List[Crazyflie] Yes None List of other Crazyflie objects. In simulation, collision avoidance is performed only with drones in this list; in real hardware, this list is ignored, and collision avoidance is performed with all other Crazyflies on the same wireless channel.
ellipsoidRadii array-like of float[3] Yes None Radii of the collision volume ellipsoid in meters; the three elements correspond to the semi-axes along the x, y, and z coordinate directions, respectively.

Returns: None
Raises: None


disableCollisionAvoidance()

Function Description: Disables onboard collision avoidance functionality.

Arguments (Args): - None

Returns: None
Raises: None


takeoff(targetHeight, duration, groupMask=0)

Function Description: Executes a takeoff maneuver: the drone ascends vertically to the target height and then hovers indefinitely. This is an asynchronous command and returns immediately.

Arguments (Args):

Parameter Name Type Required Default Value Description
targetHeight float Yes None z-coordinate of the hover target height in meters.
duration float Yes None Time required to reach the target height in seconds.
groupMask int No 0 Group mask bit; refer to the description of the setGroupMask() method.

Returns: None
Raises: None


land(targetHeight, duration, groupMask=0)

Function Description: Executes a landing maneuver: the drone descends vertically to the target height. After landing, the user must cut motor power. This is an asynchronous command and returns immediately. Typically, the target height should be set slightly above the initial position (e.g., a few centimeters higher) to prevent the controller from attempting to fly into the ground due to inaccuracies in the motion capture coordinate origin.

Arguments (Args):

Parameter Name Type Required Default Value Description
targetHeight float Yes None z-coordinate of the landing target height in meters.
duration float Yes None Time required to reach the target height in seconds.
groupMask int No 0 Group mask bit; refer to the description of the setGroupMask() method.

Returns: No return value
Raises: None


stop(groupMask=0)

Function Description: Disables motor power in low-level command mode. This method is suitable for non-emergency scenarios, such as landing followed by a subsequent takeoff; subsequent low-level or high-level commands will restart the motors. Arguments (Args):

Parameter Name Type Required Default Value Description
groupMask int No 0 Group mask bit; refer to the description of the setGroupMask() method

Returns: No return value
Raises: None


goTo(goal, yaw, duration, relative=False, groupMask=0)

Function Description: Smoothly moves to the target position and then hovers indefinitely. This command is asynchronous and returns immediately. The method plans a smooth trajectory using a 7th-order polynomial that satisfies initial position/velocity/acceleration constraints, zero final velocity and acceleration at the goal, and zero jerk at boundaries. If the drone is currently hovering, the planned trajectory is a straight line; if the current velocity is non-zero, the trajectory is a smooth curve. ⚠️ Note: Frequently calling goTo or using durations that are too short (significantly less than 1 second) may cause system instability; in such cases, cmdPosition() is recommended instead. Arguments (Args):

Parameter Name Type Required Default Value Description
goal iterable of 3 floats Yes N/A Target position, in meters
yaw float Yes N/A Target yaw angle (heading), in radians
duration float Yes N/A Time required to reach the target position, in seconds
relative bool No False If True, the target position is interpreted as an offset relative to the current position; otherwise, it is an absolute coordinate in the global reference frame
groupMask int No 0 Group mask bit; refer to the description of the setGroupMask() method

Returns: No return value
Raises: None


uploadTrajectory(trajectoryId, pieceOffset, trajectory)

Function Description: Uploads a piecewise polynomial trajectory for subsequent execution. Arguments (Args):

Parameter Name Type Required Default Value Description
trajectoryId int Yes N/A ID number assigned to this trajectory; multiple trajectories can be uploaded simultaneously
pieceOffset int Yes N/A Piece offset index
trajectory pycrazyswarm.uav_trajectory.Trajectory Yes N/A Trajectory object

Returns: No return value
Raises: None


startTrajectory(trajectoryId, timescale=1.0, reverse=False, relative=True, groupMask=0)

Function Description: Begins executing a previously uploaded trajectory. This command is asynchronous and returns immediately. Arguments (Args):

Parameter Name Type Required Default Value Description
trajectoryId int Yes N/A ID number used when uploading the trajectory
timescale float No 1.0 Trajectory duration scaling factor; e.g., timescale=2.0 doubles the execution time relative to the nominal duration
reverse bool No False If True, executes the trajectory in reverse time order
relative bool No True If True (default), the trajectory’s starting point is offset to the current setpoint position; this is the typical desired behavior
groupMask int No 0 Group mask bit; refer to the description of the setGroupMask() method

Returns: No return value
Raises: None


notifySetpointsStop(remainValidMillisecs=100, groupMask=0)

Function Description: Notifies the drone that streaming low-level setpoint packets are about to cease. Commands such as cmdVelocityWorld and cmdFullState are streaming setpoint commands. For safety reasons, these commands default to overriding onboard high-level commands (e.g., goTo). After being overridden, the Crazyflie only reverts to onboard high-level commands or other onboard planning logic after a prolonged period without receiving low-level setpoints. This command allows the user to specify a shorter waiting time. It should be called after sending the last low-level setpoint and before sending a high-level command. A common use case is invoking this before sending a landing command after streaming setpoints. Arguments (Args):

Parameter Name Type Required Default Value Description
remainValidMillisecs int No 100 Milliseconds for which the last streaming setpoint remains valid before reverting to onboard behavior; a larger value may be appropriate when wirelessly controlling multiple drones
groupMask int No 0 Group mask bit; refer to the description of the setGroupMask() method

Returns: No return value
Raises: None


position()

Function Description: Returns the latest true position measurement from the motion capture system. If at least one position measurement has been received since startup, it returns the most recent measurement directly. If no position measurements have been received yet, this method blocks until the first measurement arrives and then returns it. Arguments (Args):
No arguments
Returns: np.array[3], current position, in meters
Raises: None


getParam(name)

Function Description: Returns the current value of the onboard parameter with the specified name. Parameters are named primitive-type values that control onboard firmware behavior. They are read via radio upon system startup and cached; parameter values can also be set via ROS launch files at startup, and subsequent setParam() calls update the cached values. If a parameter changes for other reasons, the cache may become outdated, though this is uncommon. Arguments (Args):

Parameter Name Type Required Default Description
name str Yes None Parameter name

Returns: Any, the value of the parameter
Raises: None


setParam(name, value)

Function Description: Modifies the value of a specified parameter. For an overview of the parameter system, refer to the documentation of the getParam() method.
Arguments (Args):

Parameter Name Type Required Default Description
name str Yes None Parameter name
value Any Yes None New value for the parameter

Returns: None
Raises: None


setParams(params)

Function Description: Modifies multiple parameters’ values in a single call. For an overview of the parameter system, refer to the documentation of the getParam() method.
Arguments (Args):

Parameter Name Type Required Default Description
params Dict[str, Any] Yes None Dictionary mapping parameter names to their values

Returns: None
Raises: None


cmdFullState(pos, vel, acc, yaw, omega)

Function Description: Sends a streaming full-state controller setpoint command. Full-state setpoints are ideal for highly agile maneuvers that require acceleration and angular velocity feedforward inputs to achieve good tracking performance. Full-state setpoints can be derived from any trajectory parameterization that is at least three times differentiable (e.g., piecewise polynomials). Sending any type of streaming setpoint forces a switch from high-level command mode to low-level command mode; currently, switching back is unsupported, meaning methods such as land() or goTo() cannot be used after sending a streaming setpoint.
Arguments (Args):

Parameter Name Type Required Default Description
pos array-like of float[3] Yes None Position, in meters
vel array-like of float[3] Yes None Velocity, in meters/second
acc array-like of float[3] Yes None Acceleration, in meters/second²
yaw float Yes None Yaw angle, in radians
omega array-like of float[3] Yes None Angular velocity in body-fixed frame, in radians/second

Returns: None
Raises: None


cmdVelocityWorld(vel, yawRate)

Function Description: Sends a streaming velocity controller setpoint command in the world coordinate frame. In this mode, the ground station specifies the desired velocity vector and yaw rate, and the onboard controller attempts to track them. Note: The default Mellinger controller is not tuned for this mode; to use it, set firmwareParams.stabilizer.controller to 1 in the startup configuration to switch to the PID controller. Sending any type of streaming setpoint forces a switch from high-level command mode to low-level command mode; currently, switching back is unsupported, meaning methods such as land() or goTo() cannot be used after sending a streaming setpoint.
Arguments (Args):

Parameter Name Type Required Default Description
vel array-like of float[3] Yes None Velocity, in meters/second
yawRate float Yes None Yaw rate, in degrees/second

Returns: None
Raises: None


cmdStop()

Function Description: Interrupts all high-level commands, stops the motors, and cuts power. Suitable for non-emergency scenarios, such as after landing when a subsequent takeoff is planned. Sending a new low-level or high-level command afterward will restart the motors, equivalent to calling the stop() method in high-level mode.
Arguments (Args): None
Returns: None
Raises: None


cmdVel(roll, pitch, yawrate, thrust)

Function Description: Sends a streaming command for manual control input in "simple mode". This command uses absolute roll and pitch angles, yaw rate, and thrust as inputs, typically suitable for novice recreational flying, in contrast to "acro mode", which controls roll and pitch rates. This mode restricts available maneuvers—for instance, flips are impossible, as the controller requires stick inputs to rotate 360 degrees. Note: In this command, angles and angular rates are in degrees, whereas cmdFullState() uses radians. For more information on streaming setpoint commands, refer to the cmdFullState() documentation.
Arguments (Args):

Parameter Name Type Required Default Description
roll float Yes None Roll angle, in degrees; positive indicates right roll
pitch float Yes None Pitch angle, in degrees; positive indicates forward/downward pitch
yawrate float Yes None Yaw rate, in degrees/second; positive indicates counter-clockwise rotation
thrust float Yes None Thrust magnitude, unitless value in range [0, 2^16), where the maximum corresponds to maximum thrust

Returns: None
Raises: None


cmdPosition(pos, yaw=0)

Function Description: Sends a streaming command for an absolute position and yaw setpoint. Suitable for slow maneuvers where a high-level planner has already computed the desired position, and the onboard controller handles the remaining control. As a streaming setpoint, this method requires multiple commands per second (conservatively, at least 10 Hz); if the application generates target positions infrequently and with large separations, the goTo() method is more appropriate. For more information on streaming setpoint commands, refer to the cmdFullState() documentation.
Arguments (Args):

Parameter Name Type Required Default Description
pos array-like of float[3] Yes None Position, in meters
yaw float No 0 Yaw angle, in radians

Return Value (Returns): No return value
Exceptions (Raises): None


setLEDColor(r, g, b)

Function Description: Sets the color of the LED ring deck. This method facilitates frequent color changes during flight for status indication. To take effect, the parameter ring/effect must be set to 7 (solid color mode); by default, the LED ring color indicates wireless connection quality. This is a blocking command and may cause stability issues when used in large-scale swarms or at high frequencies. Arguments (Args):

Parameter Type Required Default Description
r float Yes None Red component, range [0, 1]
g float Yes None Green component, range [0, 1]
b float Yes None Blue component, range [0, 1]

Return Value (Returns): No return value
Exceptions (Raises): None


readmsg()

Function Description: Reads feedback messages from the drone
Arguments (Args): No arguments
Return Value (Returns): No return value
Exceptions (Raises): None


getMotionPos()

Function Description: Gets the current position of the drone
Arguments (Args): No arguments
Return Value (Returns): A list of length 3, representing the x/y/z position in meters
Exceptions (Raises): None


getMotionVel()

Function Description: Gets the current velocity of the drone
Arguments (Args): No arguments
Return Value (Returns): A list of length 3, representing the x/y/z velocity in meters per second
Exceptions (Raises): None


getMotionAcc()

Function Description: Gets the current acceleration of the drone
Arguments (Args): No arguments
Return Value (Returns): A list of length 3, representing the x/y/z acceleration in meters per second²
Exceptions (Raises): None


Translation Class

This class performs coordinate translation transformations and serves as a tool for coordinate transformations within drone swarms, typically used to adjust the overall positional offset of a drone swarm.

__init__()

Function Description: Initializes an instance of the Translation class
Arguments (Args): None
Return Value (Returns):

  • Translation instance object

Exceptions (Raises): None


Transform Class

A coordinate transformation utility class for spatial coordinate transformations in drone swarm scenarios.

__init__()

Function Description: Initializes an instance of the Transform class
Arguments (Args): None

Return Value (Returns):

  • Transform instance object

Exceptions (Raises): None


Msgg Class

No functional description documentation is provided for this class; its specific purpose and usage scenarios are currently unclear.

__init__()

Function Description: Initializes an instance of the Msgg class
Arguments (Args): No arguments
Return Value (Returns):

  • Msgg instance object

Exceptions (Raises): None


CrazyflieServer Class

Used to broadcast control commands simultaneously to all drones in a swarm and serves as a container for individual Crazyflie instances, enabling synchronized control of multi-drone swarms.

Attributes:

  • crazyfliesById (Dict[int, Crazyflie]): Maps drone IDs (the last byte of the wireless address) to corresponding Crazyflie objects.

__init__(crazyflies_yaml="../launch/crazyflies.yaml", num="1", ids=None, mode="7")

Function Description: Initializes the server and waits until all ROS services are ready before returning.
Arguments (Args):

Parameter Type Required Default Description
crazyflies_yaml str No ../launch/crazyflies.yaml If ending with .yaml, treated as a file path to load configuration; otherwise, parsed directly as a YAML string
num str No "1" Number of drones to connect
ids list No None List of specified drone IDs; if None, default numbering is used
mode str No "7" Simulation mode parameter

Return Value (Returns):

  • CrazyflieServer instance object

Exceptions (Raises):

  • None

init_poses()

Function Description: Initializes drone poses (positions)
Arguments (Args): No arguments
Return Value (Returns):

  • None

Exceptions (Raises):

  • None

emergency()

Function Description: Executes an emergency stop, cutting motor power and ignoring all subsequent control commands. This method should be invoked for safety when a control script contains errors that could damage the drone if execution continues. After an emergency stop, firmware recovery requires either a physical hard reset or an nRF51 restart command.
Arguments (Args): No arguments
Return Value (Returns):

  • None

Exceptions (Raises):

  • None

takeoff(targetHeight, duration, groupMask=0)

Function Description: Broadcasts a synchronized takeoff command. All drones matching the group mask simultaneously ascend vertically to the target height and hover. This is an asynchronous command that returns immediately upon invocation, designed for synchronized multi-drone takeoffs.
Arguments (Args):

Parameter Type Required Default Description
targetHeight float Yes Target z-coordinate height for hovering after takeoff, in meters
duration float Yes Time required to reach the target height, in seconds
groupMask int No 0 Group mask bit; only drones matching the mask execute the command

Return Value (Returns):

  • None

Exceptions (Raises):

  • None

land(targetHeight, duration, groupMask=0)

Function Description: Broadcasts a synchronized landing command, causing all drones matching the group mask to simultaneously descend linearly to the target altitude. This is an asynchronous command that returns immediately upon invocation, designed for synchronized multi-drone landing. After landing, power must be manually cut.

Parameters (Args):

Parameter Name Type Required Default Value Description
targetHeight float Yes - Z-coordinate height of the landing target, in meters; typically set slightly higher (e.g., a few centimeters) than the initial position to avoid ground penetration due to origin errors
duration float Yes - Time required to reach the target height, in seconds
groupMask int No 0 Group mask bit; only drones matching the mask will execute this command

Returns:

  • None

Raises:

  • None

goTo(goal, yaw, duration, groupMask=0)

Function Description: Broadcasts a synchronized movement command, causing all drones matching the group mask to simultaneously and smoothly move to the target position and hover. This is an asynchronous command that returns immediately upon invocation, designed for synchronized multi-drone motion. Only relative coordinate offsets are supported to ensure collision-free swarm motion.

Parameters (Args):

Parameter Name Type Required Default Value Description
goal iterable of 3 floats Yes - Target position offset, formatted as (x, y, z), in meters
yaw float Yes - Target yaw angle (heading), in radians
duration float Yes - Time required to reach the target position, in seconds
groupMask int No 0 Group mask bit; only drones matching the mask will execute this command

Returns:

  • None

Raises:

  • None

startTrajectory(trajectoryId, timescale=1.0, reverse=False, relative=True, groupMask=0)

Function Description: Broadcasts a command to start executing a pre-uploaded trajectory. All drones matching the group mask simultaneously begin executing the uploaded trajectory. This is an asynchronous command that returns immediately upon invocation.

Parameters (Args):

Parameter Name Type Required Default Value Description
trajectoryId int Yes - Trajectory ID, specified during trajectory upload via Crazyflie.uploadTrajectory()
timescale float No 1.0 Trajectory duration scaling factor; e.g., a value of 2.0 doubles the nominal execution time
reverse bool No False If True, executes the trajectory in reverse
relative bool No True If True, offsets the trajectory’s starting point to the current setpoint position
groupMask int No 0 Group mask bit; only drones matching the mask will execute this command

Returns:

  • None

Raises:

  • None

setParam(name, value)

Function Description: Broadcasts a batch parameter-setting command. See Crazyflie.setParam() for detailed documentation.

Parameters (Args):

Parameter Name Type Required Default Value Description
name Yes - Parameter name
value Yes - Parameter value

Returns:

  • None

Raises:

  • None

readmsg()

Function Description: Reads a message.

Parameters (Args):

  • None

Returns:

  • None

Raises:

  • None

singleGetpos(id)

Function Description: Retrieves the position of a single drone.

Parameters (Args):

Parameter Name Type Required Default Value Description
id Yes - Target drone ID

Returns:

  • None

Raises:

  • None

Getpos(id)

Function Description: This implementation is not applicable to this class.

Parameters (Args):

Parameter Name Type Required Default Value Description
id Yes - Target drone ID

Returns:

  • None

Raises:

  • None

Getvel(id)

Function Description: This implementation is not applicable to this class.

Parameters (Args):

Parameter Name Type Required Default Value Description
id Yes - Target drone ID

Returns:

  • None

Raises:

  • None

Getacc(id)

Function Description: This implementation is not applicable to this class.

Parameters (Args):

Parameter Name Type Required Default Value Description
id Yes - Target drone ID

Returns:

  • None

Raises:

  • None

Example:

from RflySimSDK.swarm import CrazyflieServer

# Initialize a 3-drone swarm server
cf_server = CrazyflieServer(num=3)

# Synchronously take off to 0.8 m height over 2 seconds
cf_server.takeoff(targetHeight=0.8, duration=2.0)

# All drones move forward 1 meter, taking 3 seconds, with yaw kept at 0 radians  
cf_server.goTo(goal=(1.0, 0, 0), yaw=0, duration=3.0)

# Synchronized landing to a height of 0.1 meters, taking 2 seconds  
cf_server.land(targetHeight=0.1, duration=2.0)

Advanced Usage Examples

Demonstrates complex composite scenarios (e.g., multi-class collaboration, asynchronous control, batch operations)

import RflySimSDK.swarm.crazyflie as cf_sdk
from RflySimSDK.swarm.crazyflie import TimeHelper, Crazyflie, CrazyflieServer

# Initialize the swarm server and drone objects
cf_server = CrazyflieServer()
cf_list = [Crazyflie(i) for i in range(5) for _ in range(5)]
time_helper = TimeHelper()

# Batch initialization for takeoff, enabling collision avoidance, and executing heterogeneous tasks in groups
cf_server.init_poses([(0, 1, 0) for i in range(5)])
for idx, cf in enumerate(cf_list):
    if idx < 3:
        cf.setGroupMask(0b01)
        cf.enableCollisionAvoidance()
    else:
        cf.setGroupMask(0b10)
        cf.disableCollisionAvoidance()
cf_server.takeoff(height=0.8, duration=2)
time_helper.sleep(2)

# Upload and start heterogeneous trajectories for asynchronous collaborative flight
for cf in cf_list:
    if cf.group_mask == 0b01:
        traj = [[0.5 * x/20, 0, 0.8, 0.5] for x in range(20)]
    else:
        traj = [[0, 0.5 * x/20, 0.8, 0.5] for x in range(20)]
    cf.uploadTrajectory(traj_id=1, traj=traj)
    cf.startTrajectory(traj_id=1, timescale=1, reversed=False, relative=False)

# Periodically fetch positions at a fixed frequency to monitor swarm status
while not time_helper.isShutdown():
    all_pos = cf_server.Getpos()
    for idx, pos in enumerate(all_pos):
        print(f"Drone {idx} current position:", pos)
    if not time_helper.sleepForRate(10):
        break

# Batch landing after mission completion
cf_server.land(height=0, duration=2)
time_helper.sleep(3)

Notes and Pitfall Avoidance Guide

  • Scope of Group Mask Effectiveness: The setGroupMask method applies only to a single Crazyflie object. To batch modify group attributes for multiple drones, you must iterate through all target drone objects and invoke the method individually on each; invoking only the batch methods on CrazyflieServer will not automatically synchronize group settings.
  • Collision Avoidance Toggle Timing: After toggling the collision avoidance feature, at least one control cycle must elapse before the change takes effect. Executing movement commands immediately after calling enableCollisionAvoidance or disableCollisionAvoidance may result in the toggle not taking effect. It is recommended to use TimeHelper.sleep to allow sufficient waiting time.
  • Trajectory Upload Parameter Requirements: When calling uploadTrajectory, each trajectory point must include both position information and a time interval. Passing only a position array will cause trajectory parsing to fail; ensure the point sequence format for each trajectory segment conforms to the interface specification.
  • Fixed-Frequency Loop Control: When using sleepForRate to maintain a fixed control frequency, if the processing time for a single loop exceeds the period corresponding to the set frequency, the function will automatically skip the current sleep interval to maintain the target frequency. Avoid adding overly time-consuming custom computations or print statements within the loop, as this may cause noticeable deviations in the overall control cycle.
  • Emergency State Handling: During flight, if position anomalies or loss of control occur, immediately invoke CrazyflieServer.emergency to terminate power output to all drones. Do not directly terminate the process, as this may cause abnormal stalling in the simulation.

Changelog

  • 2024-12-10: fix: Update API documentation page
  • 2024-12-10: fix: Update swarm control interface comments
  • 2024-07-18: fix: Update API homepage index
  • 2024-02-23: feat: Support Crazyflie simulation