RT-Thread 內核學習筆記 - 內核對象rt_objecthtml
RT-Thread 內核學習筆記 - 內核對象操做API學習
RT-Thread 內核學習筆記 - 內核對象初始化鏈表組織方式url
RT-Thread 內核學習筆記 - 內核對象鏈表結構深刻理解spa
RT-Thread 內核學習筆記 - 設備模型rt_device的理解.net
RT-Thread 內核學習筆記 - 理解defunct殭屍線程線程
前言
- 最近在看內核源碼,暫時避開費腦力的任務調度、內存管理等較複雜的實現方法,發現rt_device設備框架實現很簡單。
- rt_device,設備管理的框架(模型),提供標準的設備操做接口API,一些外設,能夠抽象成設備,進行統一的管理操做,如LCD、Touch、Sensor等。
rt_device的結構
- rt_device,是內核對象派生出來的,所以,有些操做,就是在操做內核對象。上幾篇筆記研究內核對象的管理,如今發現,看device.c文件,很容易能看懂。
rt_device的使用
- RT-Thread 的PIN、CAN、Serial、I2C、SPI、PM等,都抽象成一種設備模型。這些設備模型,派生於rt_device便可。
pin設備模型:結構以下:指針
/* pin device and operations for RT-Thread */ struct rt_device_pin { struct rt_device parent; /* 派生於rt_device */ const struct rt_pin_ops *ops; /* 設備特有的操做接口,還能夠根據須要增長其餘成員 */ };
- 因此用戶能夠派生本身想要的設備框架,增長特定設備的操做接口:ops,特定屬性:結構體成員。
- 須要把具體的設備,註冊到內核容器上,這裏調用rt_device的註冊接口。
如:code
/* 使用時,須要把設備名稱、操做接口等,傳入 */ int rt_device_pin_register(const char *name, const struct rt_pin_ops *ops, void *user_data) { _hw_pin.parent.type = RT_Device_Class_Miscellaneous; /* 設備類型,爲了區分設備種類 */ _hw_pin.parent.rx_indicate = RT_NULL; /* 接收回調,串口、CAN通常會有 */ _hw_pin.parent.tx_complete = RT_NULL; /* 發送回調,串口、CAN通常會有 */ #ifdef RT_USING_DEVICE_OPS _hw_pin.parent.ops = &pin_ops; #else _hw_pin.parent.init = RT_NULL; /* 如下標準的rt_device設備操做接口,根據須要實現 */ _hw_pin.parent.open = RT_NULL; _hw_pin.parent.close = RT_NULL; _hw_pin.parent.read = _pin_read; _hw_pin.parent.write = _pin_write; _hw_pin.parent.control = _pin_control; #endif _hw_pin.ops = ops; /* 操做接口,設備的特有操做接口 */ _hw_pin.parent.user_data = user_data; /* 不是必要的用戶數據 */ /* register a character device */ rt_device_register(&_hw_pin.parent, name, RT_DEVICE_FLAG_RDWR); /* 設備註冊接口:註冊爲具體設備 */ return 0; }
- 具體設備對接設備框架
/* 具體設備的OPS 實現 */ const static struct rt_pin_ops _stm32_pin_ops = { stm32_pin_mode, stm32_pin_write, stm32_pin_read, stm32_pin_attach_irq, stm32_pin_dettach_irq, stm32_pin_irq_enable, }; /* 實際設備的註冊方法 */ rt_device_pin_register("pin", &_stm32_pin_ops, RT_NULL);
- 設備註冊後,能夠經過:list_device查看
其餘
- rt_device_read rt_device_write等操做前,須要:rt_device_open
- rt_device_open rt_device_close 操做最好成對出現,緣由是rt_device內部有引用計數,如你open兩次,close一次,計數爲1,沒有真正的close。
- 通常經過rt_device_find,經過設備名稱,查找設備,獲取設備的操做句柄,也就是設備結構體指針,從而能夠進一步進行操做設備的操做接口ops或經過設備的標準操做接口操做設備。
- RT-Thread 的設備類型不少,能夠派生各類設備模型(框架),從而能夠註冊掛載不少設備上去,能夠方便的實現讀寫控制等操做,如控制硬件、傳感器等。
總結
- 設備派生於內核對象:rt_object,熟悉內核對象,有利於熟悉rt_device的操做
- 繼續研究RT-Thread內核,不斷學習,收穫不少。