使用 AirSim 的 C++ API#

如果您还没有阅读,请先阅读通用 API 文档。本文档描述了 C++ 示例以及其他 C++ 特定的详细信息。

快速入门#

最快的入门方法是在 Visual Studio 2019 中打开 AirSim.sln。您将在解决方案中看到 Hello CarHello Drone 示例。这些示例将向您展示在 VC++ 项目中需要设置的包含路径和库路径。如果您使用的是 Linux,那么您将在 cmake 文件或编译器命令行中指定这些路径。

包含和库文件夹#

  • 包含文件夹:$(ProjectDir)..\AirLib\deps\rpclib\include;include;$(ProjectDir)..\AirLib\deps\eigen3;$(ProjectDir)..\AirLib\include
  • 依赖项:rpc.lib
  • 库文件夹:$(ProjectDir)\..\AirLib\deps\MavLinkCom\lib\$(Platform)\$(Configuration);$(ProjectDir)\..\AirLib\deps\rpclib\lib\$(Platform)\$(Configuration);$(ProjectDir)\..\AirLib\lib\$(Platform)\$(Configuration)
  • 引用:将 AirLib 和 MavLinkCom 引用到项目引用。(右键单击您的项目,然后转到引用添加引用...,然后选择 AirLib 和 MavLinkCom)

Hello Car#

以下是如何使用 AirSim API 通过 C++ 控制模拟汽车(另请参见Python 示例


// ready to run example: https://github.com/Microsoft/AirSim/blob/main/HelloCar/main.cpp

#include <iostream>
#include "vehicles/car/api/CarRpcLibClient.hpp"

int main()
{
    msr::airlib::CarRpcLibClient client;
    client.enableApiControl(true); //this disables manual control
    CarControllerBase::CarControls controls;

    std::cout << "Press enter to drive forward" << std::endl; std::cin.get();
    controls.throttle = 1;
    client.setCarControls(controls);

    std::cout << "Press Enter to activate handbrake" << std::endl; std::cin.get();
    controls.handbrake = true;
    client.setCarControls(controls);

    std::cout << "Press Enter to take turn and drive backward" << std::endl; std::cin.get();
    controls.handbrake = false;
    controls.throttle = -1;
    controls.steering = 1;
    client.setCarControls(controls);

    std::cout << "Press Enter to stop" << std::endl; std::cin.get();
    client.setCarControls(CarControllerBase::CarControls());

    return 0;
}

Hello Drone#

以下是如何使用 AirSim API 通过 C++ 控制模拟四旋翼无人机(另请参见Python 示例


// ready to run example: https://github.com/Microsoft/AirSim/blob/main/HelloDrone/main.cpp

#include <iostream>
#include "vehicles/multirotor/api/MultirotorRpcLibClient.hpp"

int main()
{
    msr::airlib::MultirotorRpcLibClient client;

    std::cout << "Press Enter to enable API control\n"; std::cin.get();
    client.enableApiControl(true);

    std::cout << "Press Enter to arm the drone\n"; std::cin.get();
    client.armDisarm(true);

    std::cout << "Press Enter to takeoff\n"; std::cin.get();
    client.takeoffAsync(5)->waitOnLastTask();

    std::cout << "Press Enter to move 5 meters in x direction with 1 m/s velocity\n"; std::cin.get();
    auto position = client.getMultirotorState().getPosition(); // from current location
    client.moveToPositionAsync(position.x() + 5, position.y(), position.z(), 1)->waitOnLastTask();

    std::cout << "Press Enter to land\n"; std::cin.get();
    client.landAsync()->waitOnLastTask();

    return 0;
}

另请参阅#

  • 示例展示了如何在您的其他项目中使用 AirSim 的内部基础设施
  • DroneShell 应用程序展示了如何使用 C++ API 创建简单的界面来控制无人机
  • HelloSpawnedDrones 应用程序展示了如何即时创建额外的载具
  • Python API