AP_HAL 再分析, 以pixhawk-fmuv2为硬件平台,ChibiOS为底层操作系统:

AP_HAL.h 分析

#include 

#include "AP_HAL_Namespace.h"
#include "AP_HAL_Boards.h"     --->>> 板子选择比如 HAL_BOARD_CHIBIOS
#include "AP_HAL_Macros.h"
#include "AP_HAL_Main.h"

/**< hal 模块的类集合,所有的类都是纯虚类<接口类>,
 * 也就是应用层不依赖于具体的底层类,而是依赖于抽象
 * 即:面向接口编程
 */
/* HAL Module Classes (all pure virtual) */ 
#include "UARTDriver.h" /* --->>> Pure virtual UARTDriver class 纯虚UARTDriver类, 只定义接口, 在具体的四大系统软硬件平台中进行实现 */
#include "AnalogIn.h"   /* --->>> 代表模拟输入器件,比如声纳等,fanout一定范围内的电压值, 只定义接口,在具体的四大系统软硬件平台中进行实现 */
#include "Storage.h"    /* --->>> 储存类块设备, 比如sd等, 只定义接口,在具体的四大系统软硬件平台中进行实现 */
#include "GPIO.h"       /* --->>> GPIO, 及其对应的中断触发方式, 只定义接口,在具体的四大系统软硬件平台中进行实现 */
#include "RCInput.h"    /* --->>> 接收机输入, 只定义接口,在具体的四大系统软硬件平台中进行实现 */
#include "RCOutput.h"   /* --->>> 接收机输出, 只定义接口,在具体的四大系统软硬件平台中进行实现 */
#include "Scheduler.h"  /* --->>> 调度器, 提供线程创建等功能 只定义接口,在具体的四大系统软硬件平台中进行实现 */*/
#include "Semaphores.h" /* --->>> 信号量相关操作, 只定义接口,在具体的四大系统软硬件平台中进行实现 */
#include "Util.h"       /* --->>> 一些辅助性,配置性,工具 比如log存储位置,snprintf等 只定义接口,在具体的四大系统软硬件平台中进行实现 */
#include "OpticalFlow.h"/* --->>> 光流,chibios、linux都平台没有实现 */
#include "Flash.h"      /* --->>> flash 页、块操作相关接口 只定义接口,在具体的四大系统软硬件平台中进行实现 */

#if HAL_WITH_UAVCAN
#include "CAN.h"        /* --->>> 定义can总线协议需要实现的相关接口 只定义接口,在具体的四大系统软硬件平台中进行实现 */*/
#endif

#include "utility/BetterStream.h" /* --->>> 流操作相关接口printf,write,read..., UARTDriver继承了此接口类 */

/* HAL Class definition */
/**< --->>> 包含了当前目录下的HAL.h, 主要定义了 AP_HAL::HAL 接口类,聚合了系统硬件的几乎所有接口,比如
 * uart, spi, i2c, scheduler等, 该类在四大系统软硬件平台中进行实现 
 */
#include "HAL.h"        
#include "system.h"
```c

INS_Generic.cpp

```c++
//
// Simple test for the AP_InertialSensor driver.
//

#include         --->>> 硬件接口
#include  
#include 

const AP_HAL::HAL &hal = AP_HAL::get_HAL(); --->>> 在四大系统软硬件平台中实现,如HAL_ChibiOS中

	const AP_HAL::HAL& AP_HAL::get_HAL() {
		static const HAL_ChibiOS hal_chibios; --->>> 定义一个静态HAL_ChibiOS对象,并返回其引用,依然是面向接口
		return hal_chibios;
	}

static AP_InertialSensor ins;    --->>> 静态对象

static void display_offsets_and_scaling();
static void run_test();

// board specific config
static AP_BoardConfig BoardConfig;  --->>> 静态对象

void setup(void); --->>> 框架方法setup
void loop(void);  --->>> 框架方法loop

void setup(void)
{
    // setup any board specific drivers
    BoardConfig.init();

    hal.console->printf("AP_InertialSensor startup...\n");

    ins.init(100);

    // display initial values
    display_offsets_and_scaling();

    // display number of detected accels/gyros
    hal.console->printf("\n");
    hal.console->printf("Number of detected accels : %u\n", ins.get_accel_count());
    hal.console->printf("Number of detected gyros  : %u\n\n", ins.get_gyro_count());

    hal.console->printf("Complete. Reading:\n");
}

void loop(void) --->>> 读取用户输入,并且响应,这里脉络是很清晰的,我们暂不进入具体函数的实现细节
{
    int16_t user_input;

    hal.console->printf("\n");
    hal.console->printf("%s\n",
    "Menu:\n"
    "    d) display offsets and scaling\n"
    "    l) level (capture offsets from level)\n"
    "    t) test\n"
    "    r) reboot");

    // wait for user input
    while (!hal.console->available()) {
        hal.scheduler->delay(20);
    }

    // read in user input
    while (hal.console->available()) {
        user_input = hal.console->read();

        if (user_input == 'd' || user_input == 'D') {
            display_offsets_and_scaling();
        }

        if (user_input == 't' || user_input == 'T') { ---> 测试方法
            run_test();
        }

        if (user_input == 'r' || user_input == 'R') {
            hal.scheduler->reboot(false);
        }
    }
}

static void display_offsets_and_scaling()
{
    const Vector3f &accel_offsets = ins.get_accel_offsets();
    const Vector3f &accel_scale = ins.get_accel_scale();
    const Vector3f &gyro_offsets = ins.get_gyro_offsets();

    // display results
    hal.console->printf("\nAccel Offsets X:%10.8f \t Y:%10.8f \t Z:%10.8f\n",
                        (double)accel_offsets.x,
                        (double)accel_offsets.y,
                        (double)accel_offsets.z);
    hal.console->printf("Accel Scale X:%10.8f \t Y:%10.8f \t Z:%10.8f\n",
                        (double)accel_scale.x,
                        (double)accel_scale.y,
                        (double)accel_scale.z);
    hal.console->printf("Gyro Offsets X:%10.8f \t Y:%10.8f \t Z:%10.8f\n",
                        (double)gyro_offsets.x,
                        (double)gyro_offsets.y,
                        (double)gyro_offsets.z);
}

static void run_test()
{
    Vector3f accel;
    Vector3f gyro;
    uint8_t counter = 0;
    static uint8_t accel_count = ins.get_accel_count(); ---> 获取acc和gyro轴数
    static uint8_t gyro_count = ins.get_gyro_count();
    static uint8_t ins_count = MAX(accel_count, gyro_count);

    // flush any user input
    while (hal.console->available()) {
        hal.console->read();
    }

    // clear out any existing samples from ins 刷新采样值
    ins.update();      

    // loop as long as user does not press a key
    while (!hal.console->available()) {
        // wait until we have a sample
        ins.wait_for_sample();

        // read samples from ins
        ins.update();

        // print each accel/gyro result every 50 cycles
        if (counter++ % 50 != 0) {
            continue;
        }

        // loop and print each sensor
        for (uint8_t ii = 0; ii < ins_count; ii++) {
            char state;

            if (ii > accel_count - 1) {
                // No accel present
                state = '-';
            } else if (ins.get_accel_health(ii)) {
                // Healthy accel
                state = 'h';
            } else {
                // Accel present but not healthy
                state = 'u';
            }

            accel = ins.get_accel(ii); ---> 获取acc 

            hal.console->printf("%u - Accel (%c) : X:%6.2f Y:%6.2f Z:%6.2f norm:%5.2f",
                                ii, state, (double)accel.x, (double)accel.y, (double)accel.z,
                                (double)accel.length());

            gyro = ins.get_gyro(ii);  ---> 获取gyro

            if (ii > gyro_count - 1) {
                // No gyro present
                state = '-';
            } else if (ins.get_gyro_health(ii)) {
                // Healthy gyro
                state = 'h';
            } else {
                // Gyro present but not healthy
                state = 'u';
            }

            hal.console->printf("   Gyro (%c) : X:%6.2f Y:%6.2f Z:%6.2f\n",
                                state, (double)gyro.x, (double)gyro.y, (double)gyro.z);
            auto temp = ins.get_temperature(ii);
            hal.console->printf("   t:%6.2f\n", (double)temp);
        }
    }

    // clear user input
    while (hal.console->available()) {
        hal.console->read();
    }
}

AP_HAL_MAIN(); --->>> 位于 /libraries/AP_HAL/AP_HAL_Main.h

#include "HAL.h"

#ifndef AP_MAIN
#define AP_MAIN main
#endif

#define AP_HAL_MAIN() \
    AP_HAL::HAL::FunCallbacks callbacks(setup, loop); \ --->>> class HAL 中定义的嵌套类,
    只是承载setup和loop这两个函数指针
    extern "C" {                               \
    int AP_MAIN(int argc, char* const argv[]); \ --->>> main 函数声明 和 实现
    int AP_MAIN(int argc, char* const argv[]) { \ 
        hal.run(argc, argv, &callbacks); \       --->>> run方法多态到四大平台的具体实现,如HAL_ChibiOS,后面分析
        return 0; \
    } \
    }

#define AP_HAL_MAIN_CALLBACKS(CALLBACKS) extern "C" { \
    int AP_MAIN(int argc, char* const argv[]); \
    int AP_MAIN(int argc, char* const argv[]) { \
        hal.run(argc, argv, CALLBACKS); \
        return 0; \
    } \
    }

void HAL_ChibiOS::run(int argc, char * const argv[], Callbacks* callbacks) const
{
    /*
     * System initializations.
     * - ChibiOS HAL initialization, this also initializes the configured device drivers
     *   and performs the board-specific initializations.
     * - Kernel initialization, the main() function becomes a thread and the
     *   RTOS is active.
     */

#ifdef HAL_USB_PRODUCT_ID
  setup_usb_strings();
#endif
    
#ifdef HAL_STDOUT_SERIAL
    //STDOUT Initialistion
    SerialConfig stdoutcfg =
    {
      HAL_STDOUT_BAUDRATE,
      0,
      USART_CR2_STOP1_BITS,
      0
    };
    sdStart((SerialDriver*)&HAL_STDOUT_SERIAL, &stdoutcfg);
#endif

    assert(callbacks);
    g_callbacks = callbacks; --->>> static AP_HAL::HAL::Callbacks* g_callbacks;


    //Takeover main --->>> 接管main
    main_loop();
}

static void main_loop()
{
    daemon_task = chThdGetSelfX();

    /*
      switch to high priority for main loop
     */
    chThdSetPriority(APM_MAIN_PRIORITY);

#ifdef HAL_I2C_CLEAR_BUS
    // Clear all I2C Buses. This can be needed on some boards which
    // can get a stuck I2C peripheral on boot
    ChibiOS::I2CBus::clear_all();
#endif

#if STM32_DMA_ADVANCED
    ChibiOS::Shared_DMA::init();
#endif
    peripheral_power_enable();
        
    hal.uartA->begin(115200);

#ifdef HAL_SPI_CHECK_CLOCK_FREQ
    // optional test of SPI clock frequencies
    ChibiOS::SPIDevice::test_clock_freq();
#endif 

    hal.uartB->begin(38400);
    hal.uartC->begin(57600);
    hal.analogin->init();
    hal.scheduler->init();

    /*
      run setup() at low priority to ensure CLI doesn't hang the
      system, and to allow initial sensor read loops to run
     */
    hal_chibios_set_priority(APM_STARTUP_PRIORITY);

    if (stm32_was_watchdog_reset()) {
        // load saved watchdog data
        stm32_watchdog_load((uint32_t *)&utilInstance.persistent_data, (sizeof(utilInstance.persistent_data)+3)/4);
    }

    schedulerInstance.hal_initialized();

    g_callbacks->setup();                --->>> 回调前述setup框架方法

#ifdef IOMCU_FW
    stm32_watchdog_init();
#elif !defined(HAL_BOOTLOADER_BUILD)
    // setup watchdog to reset if main loop stops
    if (AP_BoardConfig::watchdog_enabled()) {
        stm32_watchdog_init();
    }

    if (hal.util->was_watchdog_reset()) {
        AP::internalerror().error(AP_InternalError::error_t::watchdog_reset);
        const AP_HAL::Util::PersistentData &pd = hal.util->persistent_data;
        AP::logger().WriteCritical("WDOG", "TimeUS,Task,IErr,IErrCnt,MavMsg,MavCmd,SemLine", "QbIIHHH",
                                   AP_HAL::micros64(),
                                   pd.scheduler_task,
                                   pd.internal_errors,
                                   pd.internal_error_count,
                                   pd.last_mavlink_msgid,
                                   pd.last_mavlink_cmd,
                                   pd.semaphore_line);
    }
#endif

    schedulerInstance.watchdog_pat();

    hal.scheduler->system_initialized();

    thread_running = true;
    chRegSetThreadName(SKETCHNAME);
    
    /*
      switch to high priority for main loop
     */
    chThdSetPriority(APM_MAIN_PRIORITY);

    while (true) {
        g_callbacks->loop();      --->>> 回调前述loop框架方法

        /*
          give up 50 microseconds of time if the INS loop hasn't
          called delay_microseconds_boost(), to ensure low priority
          drivers get a chance to run. Calling
          delay_microseconds_boost() means we have already given up
          time from the main loop, so we don't need to do it again
          here
         */
#ifndef HAL_DISABLE_LOOP_DELAY
        if (!schedulerInstance.check_called_boost()) {
            hal.scheduler->delay_microseconds(50);
        }
#endif
        schedulerInstance.watchdog_pat();
    }
    thread_running = false;
}
 

战略层次的总结:

  1. 系统平台和硬件由 class HAL 提供接口抽象, 四大系统软硬件平台分别进行了实现:HAL_ChibiOS, HAL_Linux, HAL_Empty, HAL_SITL,这样,将具体应用和底层系统硬件进行了解耦,具体应用只需操作HAL 接口类提供的硬件抽象接口,而当应用部署到具体的系统硬件平台时,具体系统硬件平台将实现该抽象接口,从而多态到具体的硬件,如此,我们可以将应用部署到真实系统硬件平台,或者部署到模拟的系统硬件平台来实现应用仿真;

  2. class HAL 提供run的接口,用来启动应用,同时给系统平台提供封装了setup方法和loop方法的FunCallbacks接口类,系统平台实现run方法,并且在run方法中回调setup和loop;

  3. 应用的入口由AP_HAL_Main中的 AP_HAL_MAIN系列的宏函数提供,其使用应用实现的setup和loop方法,多态到具体系统软硬件平台实现run方法,也就是上面第二点;

  4. 应用比如大的:AntennaTracker, APMRover2, ArduCopter, ArduPlane, 等都提供setup和loop两个框架方法的实现, 并调用AP_HAL_MAIN入口来启动,小到一个传感器的测试用例比如AP_Compass_test也是如此;也就是应用层均使用面向接口编程,而这里的接口主要有以setup和loop为代表的启动运行接口,以及系统硬件平台的HAL接口。来看看具体的比如APMRover2: 其脉络非常清晰

class Rover : public AP_HAL::HAL::Callbacks --->>> 1.直接从封装接口框架setup和loop的抽象类CallBack进行派生,实现了setup和loop方法
const AP_HAL::HAL& hal = AP_HAL::get_HAL(); --->>> 2.获取具体的系统硬件平台实例, 比如在board pixhawk2.6+ChibiOS系统硬件平台上运行
Rover rover;                                --->>> 3.实例化一个rover
AP_HAL_MAIN_CALLBACKS(&rover);              --->>> 4.调用入口宏main函数启动应用

你可能感兴趣的:(Ardupilot,源码剖析,ardupilot)