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

2024-06-12 14:18

本文主要是介绍AP_HAL 再分析, 以pixhawk-fmuv2为硬件平台,ChibiOS为底层操作系统:,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

AP_HAL.h 分析

#include <stdint.h>#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"
```cINS_Generic.cpp```c++
//
// Simple test for the AP_InertialSensor driver.
//#include <AP_HAL/AP_HAL.h>        --->>> 硬件接口
#include <AP_BoardConfig/AP_BoardConfig.h> 
#include <AP_InertialSensor/AP_InertialSensor.h>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);  --->>> 框架方法loopvoid setup(void)
{// setup any board specific driversBoardConfig.init();hal.console->printf("AP_InertialSensor startup...\n");ins.init(100);// display initial valuesdisplay_offsets_and_scaling();// display number of detected accels/gyroshal.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 inputwhile (!hal.console->available()) {hal.scheduler->delay(20);}// read in user inputwhile (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 resultshal.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 inputwhile (hal.console->available()) {hal.console->read();}// clear out any existing samples from ins 刷新采样值ins.update();      // loop as long as user does not press a keywhile (!hal.console->available()) {// wait until we have a sampleins.wait_for_sample();// read samples from insins.update();// print each accel/gyro result every 50 cyclesif (counter++ % 50 != 0) {continue;}// loop and print each sensorfor (uint8_t ii = 0; ii < ins_count; ii++) {char state;if (ii > accel_count - 1) {// No accel presentstate = '-';} else if (ins.get_accel_health(ii)) {// Healthy accelstate = 'h';} else {// Accel present but not healthystate = '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);  ---> 获取gyroif (ii > gyro_count - 1) {// No gyro presentstate = '-';} else if (ins.get_gyro_health(ii)) {// Healthy gyrostate = 'h';} else {// Gyro present but not healthystate = '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 inputwhile (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_IDsetup_usb_strings();
#endif#ifdef HAL_STDOUT_SERIAL//STDOUT InitialistionSerialConfig stdoutcfg ={HAL_STDOUT_BAUDRATE,0,USART_CR2_STOP1_BITS,0};sdStart((SerialDriver*)&HAL_STDOUT_SERIAL, &stdoutcfg);
#endifassert(callbacks);g_callbacks = callbacks; --->>> static AP_HAL::HAL::Callbacks* g_callbacks;//Takeover main --->>> 接管mainmain_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 bootChibiOS::I2CBus::clear_all();
#endif#if STM32_DMA_ADVANCEDChibiOS::Shared_DMA::init();
#endifperipheral_power_enable();hal.uartA->begin(115200);#ifdef HAL_SPI_CHECK_CLOCK_FREQ// optional test of SPI clock frequenciesChibiOS::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 thesystem, and to allow initial sensor read loops to run*/hal_chibios_set_priority(APM_STARTUP_PRIORITY);if (stm32_was_watchdog_reset()) {// load saved watchdog datastm32_watchdog_load((uint32_t *)&utilInstance.persistent_data, (sizeof(utilInstance.persistent_data)+3)/4);}schedulerInstance.hal_initialized();g_callbacks->setup();                --->>> 回调前述setup框架方法#ifdef IOMCU_FWstm32_watchdog_init();
#elif !defined(HAL_BOOTLOADER_BUILD)// setup watchdog to reset if main loop stopsif (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);}
#endifschedulerInstance.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'tcalled delay_microseconds_boost(), to ensure low prioritydrivers get a chance to run. Callingdelay_microseconds_boost() means we have already given uptime from the main loop, so we don't need to do it againhere*/
#ifndef HAL_DISABLE_LOOP_DELAYif (!schedulerInstance.check_called_boost()) {hal.scheduler->delay_microseconds(50);}
#endifschedulerInstance.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函数启动应用

这篇关于AP_HAL 再分析, 以pixhawk-fmuv2为硬件平台,ChibiOS为底层操作系统:的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1054455

相关文章

C++ STL-string类底层实现过程

《C++STL-string类底层实现过程》本文实现了一个简易的string类,涵盖动态数组存储、深拷贝机制、迭代器支持、容量调整、字符串修改、运算符重载等功能,模拟标准string核心特性,重点强... 目录实现框架一、默认成员函数1.默认构造函数2.构造函数3.拷贝构造函数(重点)4.赋值运算符重载函数

Redis分布式锁中Redission底层实现方式

《Redis分布式锁中Redission底层实现方式》Redission基于Redis原子操作和Lua脚本实现分布式锁,通过SETNX命令、看门狗续期、可重入机制及异常处理,确保锁的可靠性和一致性,是... 目录Redis分布式锁中Redission底层实现一、Redission分布式锁的基本使用二、Red

Android 缓存日志Logcat导出与分析最佳实践

《Android缓存日志Logcat导出与分析最佳实践》本文全面介绍AndroidLogcat缓存日志的导出与分析方法,涵盖按进程、缓冲区类型及日志级别过滤,自动化工具使用,常见问题解决方案和最佳实... 目录android 缓存日志(Logcat)导出与分析全攻略为什么要导出缓存日志?按需过滤导出1. 按

Linux中的HTTPS协议原理分析

《Linux中的HTTPS协议原理分析》文章解释了HTTPS的必要性:HTTP明文传输易被篡改和劫持,HTTPS通过非对称加密协商对称密钥、CA证书认证和混合加密机制,有效防范中间人攻击,保障通信安全... 目录一、什么是加密和解密?二、为什么需要加密?三、常见的加密方式3.1 对称加密3.2非对称加密四、

MySQL中读写分离方案对比分析与选型建议

《MySQL中读写分离方案对比分析与选型建议》MySQL读写分离是提升数据库可用性和性能的常见手段,本文将围绕现实生产环境中常见的几种读写分离模式进行系统对比,希望对大家有所帮助... 目录一、问题背景介绍二、多种解决方案对比2.1 原生mysql主从复制2.2 Proxy层中间件:ProxySQL2.3

python使用Akshare与Streamlit实现股票估值分析教程(图文代码)

《python使用Akshare与Streamlit实现股票估值分析教程(图文代码)》入职测试中的一道题,要求:从Akshare下载某一个股票近十年的财务报表包括,资产负债表,利润表,现金流量表,保存... 目录一、前言二、核心知识点梳理1、Akshare数据获取2、Pandas数据处理3、Matplotl

python panda库从基础到高级操作分析

《pythonpanda库从基础到高级操作分析》本文介绍了Pandas库的核心功能,包括处理结构化数据的Series和DataFrame数据结构,数据读取、清洗、分组聚合、合并、时间序列分析及大数据... 目录1. Pandas 概述2. 基本操作:数据读取与查看3. 索引操作:精准定位数据4. Group

MySQL中EXISTS与IN用法使用与对比分析

《MySQL中EXISTS与IN用法使用与对比分析》在MySQL中,EXISTS和IN都用于子查询中根据另一个查询的结果来过滤主查询的记录,本文将基于工作原理、效率和应用场景进行全面对比... 目录一、基本用法详解1. IN 运算符2. EXISTS 运算符二、EXISTS 与 IN 的选择策略三、性能对比

MySQL 内存使用率常用分析语句

《MySQL内存使用率常用分析语句》用户整理了MySQL内存占用过高的分析方法,涵盖操作系统层确认及数据库层bufferpool、内存模块差值、线程状态、performance_schema性能数据... 目录一、 OS层二、 DB层1. 全局情况2. 内存占js用详情最近连续遇到mysql内存占用过高导致

深度解析Nginx日志分析与499状态码问题解决

《深度解析Nginx日志分析与499状态码问题解决》在Web服务器运维和性能优化过程中,Nginx日志是排查问题的重要依据,本文将围绕Nginx日志分析、499状态码的成因、排查方法及解决方案展开讨论... 目录前言1. Nginx日志基础1.1 Nginx日志存放位置1.2 Nginx日志格式2. 499