Compare commits

...

19 Commits

Author SHA1 Message Date
227158870a feat: 添加CDC协议通信模块支持
- 集成nanopb库用于protobuf序列化
- 创建cdc_wrapper_module.c实现帧解析功能
- 实现protocol_module.c处理协议编解码
- 定义device_comm.proto通信协议
- 修改CMakeLists.txt添加protobuf源文件
- 更新配置启用NANOPB支持
- 移除usb_cdc_module中基于行的处理逻辑
2026-04-11 18:21:18 +08:00
39c6a1fe84 feat(usb_device_module): 添加电源管理限制功能
- 引入power_manager_event.h头文件
- 实现update_power_manager_restriction函数来控制电源管理级别
- 在VBUS就绪时设置为ALIVE级别,在VUSB移除时设置为SUSPENDED级别
- 模块初始化时默认设置为SUSPENDED级别
2026-04-11 17:57:00 +08:00
33fb416cfa feat(usb): 添加USB CDC功能模块支持
- 在CMakeLists.txt中添加usb_cdc_module、usb_cdc_test_module和
  usb_device_module源文件
- 添加usb_cdc_rx_event、usb_cdc_tx_event、usb_device_state_event、
  usb_function_ready_event和usb_prepare_event事件定义
- 实现USB CDC串口通信功能,包括接收和发送数据处理
- 添加USB设备状态管理,支持连接、断开、激活等状态变化
- 配置设备树中的USB端点数量以支持CDC ACM功能
- 创建USB设备模块用于管理USB堆栈初始化和状态监控
- 添加USB功能就绪事件以协调不同USB功能的准备状态
2026-04-11 17:15:11 +08:00
c40fc709d5 feat(display): 添加显示模块功能支持电池状态和模式切换
- 配置文件中启用USB CDC ACM类、UART相关配置和LVGL显示库
- 添加对bat_state_event、hid_led_event和mode_switch_event事件的订阅
- 实现UI模型结构体ui_main_model用于管理显示状态
- 添加refresh_ui函数用于刷新UI界面
- 集成电池电量显示、充电状态指示和模式切换状态更新

fix(ui): 重构主UI界面添加动态数据更新功能

- 重写ui_main.c实现完整的UI组件创建和刷新逻辑
- 添加状态栏芯片显示USB、BLE、NumLock、CapsLock状态
- 实现电池图标、电量百分比和充电状态的动态更新
- 添加日期时间显示区域和整体UI刷新功能
- 创建ui_main_model数据结构管理UI状态数据

chore(config): 更新项目配置启用串口和显示相关功能

- 启用串口和UART中断驱动配置
- 添加USB CDC ACM类和HID支持
- 增加LVGL工作队列栈大小到16KB
- 添加蒙特赛拉特32号字体支持
2026-04-11 16:40:54 +08:00
2f6126da96 feat(display): 集成LVGL图形库并重构显示模块
- 将display_test_module重命名为display_module
- 集成LVGL配置到prj.conf中,包括颜色深度、双缓冲等设置
- 添加UI主界面实现(ui_main.c),包含标题和副标题显示
- 实现背光控制功能替代原有的测试图案绘制
- 调整LCD配置参数(mdac从0x70改为0xA0)
- 修改日志级别从DEBUG降至ERROR以优化性能
- 在CMakeLists.txt中添加UI模块源文件引用
2026-04-11 14:28:34 +08:00
76adb3584c feat(board): 添加显示屏和PWM背光支持
- 在CMakeLists.txt中添加display_test_module.c源文件
- 在设备树配置中添加SPI3和PWM0引脚控制定义
- 配置MIPI DBI显示屏驱动,支持ST7789V控制器
- 添加PWM LED背光控制功能
- 启用GPIO复位功能并添加点击检测器配置
- 实现显示测试模块,支持彩色测试图案渲染
2026-04-11 13:41:35 +08:00
39d2962258 feat(keyboard): 添加蓝牙HID支持和电池状态事件
- 添加BLE相关模块:ble_adv_ctrl_module、ble_adv_uuid16、ble_bas_module、
  ble_hid_module
- 新增电池状态事件(bat_state_event)用于监控电池电量、充电状态
- 在多个事件中添加HID_TRANSPORT_BLE支持,包括hid_led_event、
  set_protocol_event等
- 更新配置文件prj.conf以启用蓝牙功能、HID服务和设置系统
- 修改电池模块以计算并报告电池SOC百分比
- 集成CAF设置加载器以管理蓝牙配对信息
2026-04-10 19:28:20 +08:00
b9b7d342f5 feat(bootloader): 添加MCUBoot配置文件和系统构建配置
新增pm_static.yml文件定义内存分区布局,包括mcuboot、app、
mcuboot_primary等分区的地址和大小配置。同时添加sysbuild.conf
文件启用MCUBoot引导加载器和单应用模式配置。
2026-04-10 14:57:27 +08:00
70381192d9 feat: 添加HID流控制模块和相关事件处理
- 添加hid_flowctrl_module.c实现HID报告流控制功能,包括FIFO队列管理和
  报告发送控制
- 新增hid_report_sent_event、hid_transport_state_event和
  hid_tx_report_event事件类型及其对应的头文件和实现
- 在CMakeLists.txt中注册新模块和事件源文件
- 修改keyboard_core_module.c以支持队列策略,并添加编码器事件处理逻辑
- 更新usb_hid_module.c将直接的键盘HID报告事件改为通过
  hid_tx_report_event进行传输,并添加状态报告事件
- 在keyboard_hid_report_event中增加queue_policy字段以支持不同
  队列策略
2026-04-10 13:46:50 +08:00
e97bd47e36 fix(keyboard): 修复数字键盘回车键映射问题
由于数字键盘回车键映射位置错误,导致该按键功能无法正常使用。
此修复将数字键盘回车键映射重新添加到正确的位置,
确保按键能够正常工作。
2026-04-10 11:42:19 +08:00
e226338565 feat(encoder): 添加编码器模块支持
- 在CMakeLists.txt中添加encoder_module.c和encoder_event.c源文件
- 配置设备树pinctrl设置编码器引脚(QDEC_A和QDEC_B)
- 在设备树中启用qdec外设并配置相关参数
- 添加atguigu厂商前缀到vendor-prefixes.txt
- 创建encoder_event.h事件头文件定义编码器事件结构
- 在prj.conf中启用NRFX_QDEC和PINCTRL_DYNAMIC配置
- 实现encoder_module.c包含完整的编码器驱动逻辑
- 实现encoder_event.c处理编码器事件的发布和记录
2026-04-10 10:40:28 +08:00
b9bb326e8b feat(usb): 添加USB HID模块支持键盘和消费设备
- 添加USB HID模块实现键盘和消费控制设备功能
- 在CMakeLists.txt中添加usb_hid_module.c和相关事件文件
- 添加HID LED事件和设置协议事件定义及实现
- 配置设备树添加HID键盘和消费者设备节点
- 启用USB设备堆栈配置选项
- 修改键盘核心模块以处理协议切换事件
- 修复键映射中keypad enter的位置错误
- 注释掉电池模块中的调试日志输出
2026-04-10 09:06:18 +08:00
0da731e59d feat(keyboard): 添加键盘核心模块和HID报告事件支持
- 添加keyboard_core_module.c实现键盘核心功能,包括按键映射、
  报告构建和状态管理
- 添加keyboard_hid_report_event相关文件,实现键盘HID报告事件
  的定义和处理
- 在CMakeLists.txt中注册新的源文件
- 定义键盘协议模式(BOOT/REPORT)和报告类型枚举
- 实现按键事件处理、模式切换响应和电源管理功能
- 支持多媒体控制键和标准键盘按键的不同处理逻辑
2026-04-08 16:32:13 +08:00
6610b3471d feat: 添加模式切换模块支持USB/2.4G/BLE模式检测
- 在CMakeLists.txt中添加新的包含目录inc/events和源文件
  mode_switch_module.c、mode_switch_event.c
- 在设备树文件中添加模式切换ADC配置节点和通道设置
- 新增mode_switch_event.h头文件定义模式切换事件结构
- 实现mode_switch_event.c事件处理和日志记录功能
- 创建mode_switch_module.c核心模块实现ADC采样、
  模式检测和事件发布逻辑
- 支持三种模式:USB、2.4G、BLE的电压阈值判断
- 集成CAF事件系统,支持电源管理和状态转换
2026-04-08 14:28:05 +08:00
e4c824d657 feat(drivers/pmic): 添加IP5306硬件看门狗功能支持
为IP5306 PMIC驱动添加了硬件看门狗脉冲生成功能,通过RTC2、GPIOTE和PPI外设实现硬
件级的唤醒脉冲生成。当配置keepalive-hardware属性时,系统将使用硬件方式而非软件
定时器来产生看门狗脉冲。

在设备树中新增keepalive-hardware布尔属性,用于启用硬件看门狗功能,并相应更新了
驱动程序以支持软硬件两种看门狗模式的选择。

相关的DTS文件和配置也进行了相应调整,包括添加必要的nRF52硬件抽象层依赖以及
RTC2和GPIOTE相关配置选项。
2026-04-08 13:42:04 +08:00
cfcefbf28a feat(drivers): 添加IP5306 PMIC驱动支持
- 添加IP5306 PMIC驱动实现,包括I2C通信和GPIO唤醒功能
- 实现电源管理芯片的状态读取接口(充电状态、满电状态)
- 集成Wakeup保持脉冲功能,支持可配置的脉冲宽度和间隔时间
- 添加设备树绑定文件和Kconfig配置选项

refactor(blinky): 集成IP5306电源管理芯片到电池模块

- 在电池模块中集成IP5306 PMIC状态监控功能
- 修改日志输出格式,显示电池电压及充电/满电状态
- 增加设备初始化检查和错误处理机制
- 配置电源管理限制级别为暂停模式

build: 配置CMakeLists.txt以包含驱动子目录

- 更新主CMakeLists.txt文件添加drivers子目录
- 配置驱动程序的构建层次结构(pmic -> ip5306)
- 设置条件编译目标源文件

docs: 添加设备树和板级配置支持

- 添加mini_keyboard板的I2C引脚控制配置
- 配置IP5306设备节点和相关GPIO引脚定义
- 启用I2C配置选项以支持PMIC通信
2026-04-08 11:01:01 +08:00
42aee4c511 feat(blinky): 添加电池模块支持
- 在CMakeLists.txt中添加battery_module.c源文件
- 在设备树中添加电压分压器配置和ADC通道设置
- 添加传感器和ADC相关的Kconfig配置
- 实现电池模块功能,包括电压采样、电源管理事件处理
- 支持电池电压定期采样和日志输出
2026-04-07 16:58:10 +08:00
528b486090 feat(prj.conf): 添加重启和电源管理配置
添加了系统重启功能配置和电源管理模块配置,包括默认超时设置
和可选的常驻电源模式配置项。
2026-04-07 15:29:17 +08:00
2c421b23b6 feat(mini_keyboard): 添加CAF按钮模块支持并完善项目配置
- 添加external目录到.gitignore排除列表
- 在CMakeLists.txt中添加inc目录包含路径
- 更新DTS文件启用gpio0状态
- 创建CAF按钮定义头文件buttons_def.h,配置4x6矩阵键盘引脚
- 在prj.conf中启用CAF按钮模块及相关配置
- 添加详细的CAF官方模块清单文档caf_stock_modules_guide.md
- 添加nRF Desktop架构说明文档nrf_desktop_architecture.md,为后续
  键盘功能开发提供架构参考
2026-04-07 14:26:59 +08:00
74 changed files with 8632 additions and 8 deletions

1
.gitignore vendored
View File

@@ -4,3 +4,4 @@
# build
/build*/
/external/

View File

@@ -4,4 +4,49 @@ cmake_minimum_required(VERSION 3.20.0)
find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})
project(blinky)
target_sources(app PRIVATE src/main.c)
list(APPEND CMAKE_MODULE_PATH ${ZEPHYR_BASE}/modules/nanopb)
include(nanopb)
zephyr_include_directories(
inc
inc/events
)
add_subdirectory(drivers)
zephyr_nanopb_sources(app
proto/device_comm.proto
)
target_sources(app PRIVATE
src/main.c
src/battery_module.c
src/ble_adv_ctrl_module.c
src/ble_adv_uuid16.c
src/ble_bas_module.c
src/ble_hid_module.c
src/display_module.c
src/encoder_module.c
src/hid_flowctrl_module.c
src/keyboard_core_module.c
src/ui/ui_main.c
src/cdc_wrapper_module.c
src/protocol_module.c
src/usb_cdc_module.c
src/usb_device_module.c
src/usb_hid_module.c
src/events/bat_state_event.c
src/events/encoder_event.c
src/events/hid_led_event.c
src/events/hid_report_sent_event.c
src/events/hid_transport_state_event.c
src/events/hid_tx_report_event.c
src/mode_switch_module.c
src/events/keyboard_hid_report_event.c
src/events/mode_switch_event.c
src/events/set_protocol_event.c
src/events/usb_cdc_rx_event.c
src/events/usb_cdc_tx_event.c
src/events/usb_device_state_event.c
src/events/usb_function_ready_event.c
src/events/usb_prepare_event.c
)

7
Kconfig Normal file
View File

@@ -0,0 +1,7 @@
mainmenu "blinky"
source "Kconfig.zephyr"
menu "Application Drivers"
rsource "drivers/Kconfig"
endmenu

View File

@@ -1,2 +1,61 @@
&pinctrl {
i2c0_default: i2c0_default {
group1 {
psels = <NRF_PSEL(TWIM_SDA, 1, 0)>,
<NRF_PSEL(TWIM_SCL, 0, 24)>;
};
};
i2c0_sleep: i2c0_sleep {
group1 {
psels = <NRF_PSEL(TWIM_SDA, 1, 0)>,
<NRF_PSEL(TWIM_SCL, 0, 24)>;
low-power-enable;
};
};
encoder_default: encoder_default {
group1 {
psels = <NRF_PSEL(QDEC_A, 0, 10)>,
<NRF_PSEL(QDEC_B, 1, 6)>;
bias-pull-up;
};
};
encoder_sleep: encoder_sleep {
group1 {
psels = <NRF_PSEL(QDEC_A, 0, 10)>,
<NRF_PSEL(QDEC_B, 1, 6)>;
low-power-enable;
bias-pull-up;
};
};
spi3_default: spi3_default {
group1 {
psels = <NRF_PSEL(SPIM_SCK, 1, 13)>,
<NRF_PSEL(SPIM_MOSI, 0, 28)>;
};
};
spi3_sleep: spi3_sleep {
group1 {
psels = <NRF_PSEL(SPIM_SCK, 1, 13)>,
<NRF_PSEL(SPIM_MOSI, 0, 28)>;
low-power-enable;
};
};
pwm0_default: pwm0_default {
group1 {
psels = <NRF_PSEL(PWM_OUT0, 1, 11)>;
};
};
pwm0_sleep: pwm0_sleep {
group1 {
psels = <NRF_PSEL(PWM_OUT0, 1, 11)>;
low-power-enable;
};
};
};

View File

@@ -1,6 +1,9 @@
/dts-v1/;
#include <nordic/nrf52840_qiaa.dtsi>
#include "mini_keyboard-pinctrl.dtsi"
#include <zephyr/dt-bindings/adc/adc.h>
#include <zephyr/dt-bindings/mipi_dbi/mipi_dbi.h>
#include <zephyr/dt-bindings/pwm/pwm.h>
/ {
model = "Mini keyboard";
@@ -10,10 +13,31 @@
zephyr,sram = &sram0;
zephyr,flash = &flash0;
zephyr,code-partition = &slot0_partition;
zephyr,display = &screen_lcd;
};
aliases {
led0 = &myled0;
qdec0 = &qdec;
backlight = &backlight;
};
hid_kbd: hid_kbd {
compatible = "zephyr,hid-device";
label = "HID_KBD";
protocol-code = "keyboard";
in-report-size = <29>;
out-report-size = <1>;
in-polling-period-us = <1000>;
out-polling-period-us = <1000>;
};
hid_consumer: hid_consumer {
compatible = "zephyr,hid-device";
label = "HID_CONSUMER";
protocol-code = "none";
in-report-size = <2>;
in-polling-period-us = <1000>;
};
leds {
@@ -22,6 +46,67 @@
gpios = <&gpio1 2 GPIO_ACTIVE_LOW>;
};
};
pwm_leds {
compatible = "pwm-leds";
status = "okay";
backlight: pwm_led_0 {
pwms = <&pwm0 0 PWM_MSEC(10) PWM_POLARITY_INVERTED>;
};
};
mipi_dbi_screen: mipi_dbi_screen {
compatible = "zephyr,mipi-dbi-spi";
spi-dev = <&spi3>;
dc-gpios = <&gpio0 3 GPIO_ACTIVE_HIGH>;
reset-gpios = <&gpio1 10 GPIO_ACTIVE_LOW>;
write-only;
#address-cells = <1>;
#size-cells = <0>;
screen_lcd: st7789v@0 {
compatible = "sitronix,st7789v";
status = "okay";
reg = <0>;
mipi-max-frequency = <32000000>;
width = <320>;
height = <172>;
x-offset = <0>;
y-offset = <34>;
vcom = <0x34>;
gctrl = <0x00>;
mdac = <0xA0>;
gamma = <0x01>;
colmod = <0x05>;
lcm = <0x2c>;
porch-param = [ 0c 0c 00 33 33 ];
cmd2en-param = [ 5a 69 02 01 ];
pwctrl1-param = [ a4 a1 ];
pvgam-param = [ f0 04 08 0a 0a 05 25 33 3c 24 0e 0f 27 2f ];
nvgam-param = [ f0 02 06 06 04 22 25 32 3b 3a 15 17 2d 37 ];
ram-param = [ 00 f0 ];
rgb-param = [ cd 08 14 ];
ready-time-ms = <120>;
mipi-mode = "MIPI_DBI_MODE_SPI_4WIRE";
};
};
vbatt: vbatt {
compatible = "voltage-divider";
io-channels = <&adc 7>;
output-ohms = <100000>;
full-ohms = <200000>;
power-gpios = <&gpio0 9 GPIO_ACTIVE_HIGH>;
power-on-sample-delay-us = <200>;
};
mode_switch_adc: mode-switch-adc {
compatible = "voltage-divider";
io-channels = <&adc 5>;
output-ohms = <1>;
full-ohms = <1>;
};
};
&flash0 {
@@ -52,6 +137,59 @@
};
};
&uicr {
nfct-pins-as-gpios;
gpio-as-nreset;
};
&adc {
status = "okay";
#address-cells = <1>;
#size-cells = <0>;
channel@5 {
reg = <5>;
zephyr,gain = "ADC_GAIN_1_6";
zephyr,reference = "ADC_REF_INTERNAL";
zephyr,acquisition-time = <ADC_ACQ_TIME(ADC_ACQ_TIME_MICROSECONDS, 40)>;
zephyr,input-positive = <NRF_SAADC_AIN5>;
zephyr,resolution = <12>;
zephyr,oversampling = <4>;
};
channel@7 {
reg = <7>;
zephyr,gain = "ADC_GAIN_1_4";
zephyr,reference = "ADC_REF_INTERNAL";
zephyr,acquisition-time = <ADC_ACQ_TIME(ADC_ACQ_TIME_MICROSECONDS, 40)>;
zephyr,input-positive = <NRF_SAADC_AIN7>;
zephyr,resolution = <14>;
zephyr,oversampling = <4>;
};
};
&i2c0 {
status = "okay";
pinctrl-0 = <&i2c0_default>;
pinctrl-1 = <&i2c0_sleep>;
pinctrl-names = "default", "sleep";
clock-frequency = <400000>;
ip5306: pmic@75 {
compatible = "injoinic,ip5306";
reg = <0x75>;
wakeup-gpios = <&gpio0 22 GPIO_ACTIVE_LOW>;
keepalive-interval-ms = <8000>;
keepalive-pulse-width-ms = <500>;
keepalive-hardware;
status = "okay";
};
};
&gpio0 {
status = "okay";
};
&gpio1 {
status = "okay";
};
@@ -59,3 +197,42 @@
&gpiote {
status = "okay";
};
&spi3 {
status = "okay";
pinctrl-0 = <&spi3_default>;
pinctrl-1 = <&spi3_sleep>;
pinctrl-names = "default", "sleep";
cs-gpios = <&gpio0 2 GPIO_ACTIVE_LOW>;
};
&pwm0 {
status = "okay";
pinctrl-0 = <&pwm0_default>;
pinctrl-1 = <&pwm0_sleep>;
pinctrl-names = "default", "sleep";
};
&qdec {
status = "okay";
pinctrl-0 = <&encoder_default>;
pinctrl-1 = <&encoder_sleep>;
pinctrl-names = "default", "sleep";
led-pre = <0>;
steps = <80>;
nordic,period = "SAMPLEPER_1024US";
};
&usbd {
status = "okay";
num-bidir-endpoints = <1>;
num-in-endpoints = <7>;
num-out-endpoints = <7>;
num-isoin-endpoints = <0>;
num-isoout-endpoints = <0>;
cdc_acm_uart0: cdc_acm_uart0 {
compatible = "zephyr,cdc-acm-uart";
label = "CDC_ACM_0";
};
};

View File

@@ -0,0 +1,782 @@
# CAF 官方现成模块清单与使用方法
本文基于本地 `NCS v3.2.3` 的官方源码与文档整理,范围以以下目录为准:
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf`
- `C:\ncs\v3.2.3\nrf\subsys\caf\modules`
目标是回答两个问题:
1. CAF 官方现成提供了哪些模块可以直接用。
2. 这些模块最小要怎么启用、怎么接入。
## 1. CAF 是什么
CAF, Common Application Framework是 Nordic 基于 `app_event_manager` 封装的一组现成模块和事件。
它的基本模式是:
- 你启用某个 CAF 模块
- 模块监听 CAF 事件或应用自定义事件
- 模块自己和别的模块通过事件解耦通信
因此 CAF 更像一套“事件驱动应用积木”,而不是单个库函数。
## 2. 使用 CAF 的最小前提
在使用任何 CAF 模块前,建议先完成这 3 件事。
### 2.1 打开 CAF
`prj.conf` 中至少启用:
```conf
CONFIG_CAF=y
```
### 2.2 启用并初始化 Application Event Manager
你的应用需要正常使用 `app_event_manager`
### 2.3 在 `main()` 中发出第一条 `module_state_event`
CAF 模块在收到 `main` 模块的 `MODULE_STATE_READY` 后才会继续初始化。
典型写法:
```c
#include <app_event_manager.h>
#define MODULE main
#include <caf/events/module_state_event.h>
int main(void)
{
if (app_event_manager_init()) {
return 0;
}
module_set_state(MODULE_STATE_READY);
return 0;
}
```
可以参考:
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\caf_overview.rst`
- `C:\ncs\v3.2.3\nrf\applications\nrf_desktop\src\main.c`
## 3. CAF 官方现成模块列表
`C:\ncs\v3.2.3\nrf\subsys\caf\modules\Kconfig`NCS 3.2.3 中 CAF 官方模块包括:
1. `CAF_BLE_ADV`
2. `CAF_BLE_BOND`
3. `CAF_BLE_SMP`
4. `CAF_BLE_STATE`
5. `CAF_BLE_STATE_PM`
6. `CAF_BUTTONS`
7. `CAF_BUTTONS_PM_KEEP_ALIVE`
8. `CAF_CLICK_DETECTOR`
9. `CAF_FACTORY_RESET_REQUEST`
10. `CAF_LEDS`
11. `CAF_NET_STATE`
12. `CAF_POWER_MANAGER`
13. `CAF_SENSOR_DATA_AGGREGATOR`
14. `CAF_SENSOR_MANAGER`
15. `CAF_SETTINGS_LOADER`
16. `CAF_SHELL`
## 4. 模块总览表
| 模块 | 主要作用 | 典型输入 | 典型输出 | 最小启用点 |
| --- | --- | --- | --- | --- |
| `CAF_BUTTONS` | 扫描按键/矩阵键盘 GPIO | GPIO 变化 | `button_event` | `CONFIG_CAF_BUTTONS=y` |
| `CAF_BUTTONS_PM_KEEP_ALIVE` | 按键活动保持系统唤醒 | `button_event` | `keep_alive_event` | `CONFIG_CAF_BUTTONS_PM_KEEP_ALIVE=y` |
| `CAF_CLICK_DETECTOR` | 将按键动作识别为短按/长按/双击 | `button_event` | `click_event` | `CONFIG_CAF_CLICK_DETECTOR=y` |
| `CAF_LEDS` | 根据 LED effect 控制 LED | `led_event` | LED 状态变化 | `CONFIG_CAF_LEDS=y` |
| `CAF_POWER_MANAGER` | 管理挂起/唤醒/关机 | keep-alive、restriction、error | `power_down_event``wake_up_event``power_off_event` | `CONFIG_CAF_POWER_MANAGER=y` |
| `CAF_BLE_STATE` | 打开 BLE、管理连接回调 | 蓝牙栈回调 | `ble_peer_event``ble_peer_conn_params_event` | `CONFIG_CAF_BLE_STATE=y` |
| `CAF_BLE_STATE_PM` | BLE 连接存在时限制省电级别 | `ble_peer_event` | power restriction | `CONFIG_CAF_BLE_STATE_PM=y` |
| `CAF_BLE_ADV` | Peripheral 侧广播控制 | BLE 状态、advertising provider 数据 | 广播行为、`force_power_down_event` | `CONFIG_CAF_BLE_ADV=y` |
| `CAF_BLE_BOND` | 默认 BLE bond 管理 | `click_event`、settings | bond erase 行为 | `CONFIG_CAF_BLE_BOND=y` |
| `CAF_BLE_SMP` | BLE 上 MCUmgr DFU | MCUmgr 传输 | `ble_smp_transfer_event` | `CONFIG_CAF_BLE_SMP=y` |
| `CAF_SETTINGS_LOADER` | 在合适时机调用 `settings_load()` | `module_state_event` | settings 已装载 | `CONFIG_CAF_SETTINGS_LOADER=y` |
| `CAF_NET_STATE` | 上报网络连接状态 | LTE / OpenThread backend | `net_state_event` | `CONFIG_CAF_NET_STATE=y` |
| `CAF_SENSOR_MANAGER` | 周期采样传感器 | sensor driver | `sensor_event``sensor_state_event` | `CONFIG_CAF_SENSOR_MANAGER=y` |
| `CAF_SENSOR_DATA_AGGREGATOR` | 聚合 sensor_event 数据块 | `sensor_event` | `sensor_data_aggregator_event` | `CONFIG_CAF_SENSOR_DATA_AGGREGATOR=y` |
| `CAF_FACTORY_RESET_REQUEST` | 上电窗口内按键触发恢复出厂请求 | `button_event` | `factory_reset_event` | `CONFIG_CAF_FACTORY_RESET_REQUEST=y` |
| `CAF_SHELL` | 通过 shell 手动发 CAF 事件 | shell 命令 | `button_event` 等 | `CONFIG_CAF_SHELL=y` |
## 5. 各模块使用方法
下面按“用途、最小接入方法、何时使用”来总结。
### 5.1 `CAF_BUTTONS`
**用途**
- 读取独立按键或矩阵键盘
- 统一生成 `button_event`
**最小接入**
1.`prj.conf` 打开:
```conf
CONFIG_CAF_BUTTONS=y
CONFIG_GPIO=y
```
2. 新建按钮定义头文件,例如 `buttons_def.h`,定义:
- `row[]`
- `col[]`
3.`CONFIG_CAF_BUTTONS_DEF_PATH` 指向这个配置文件。
例如:
```conf
CONFIG_CAF_BUTTONS_DEF_PATH="buttons_def.h"
```
**何时使用**
- 你要做按键输入,基本都会先用它
- 对键盘项目最常用
**补充**
- 支持矩阵键盘和直接 GPIO 按键
- 支持去抖、扫描周期、按键极性配置
- 可选支持 PM 事件和唤醒
参考:
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\buttons.rst`
### 5.2 `CAF_BUTTONS_PM_KEEP_ALIVE`
**用途**
- 按键按下时自动发 `keep_alive_event`
- 常配合 `CAF_POWER_MANAGER`
**最小接入**
```conf
CONFIG_CAF_BUTTONS=y
CONFIG_CAF_POWER_MANAGER=y
CONFIG_CAF_BUTTONS_PM_KEEP_ALIVE=y
```
**何时使用**
- 设备需要超时休眠
- 但用户按键活动应重置休眠计时
参考:
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\buttons_pm_keep_alive.rst`
### 5.3 `CAF_CLICK_DETECTOR`
**用途**
-`button_event` 识别短按、长按、双击
- 生成 `click_event`
**最小接入**
1. 打开:
```conf
CONFIG_CAF_CLICK_DETECTOR=y
```
2. 新建 click 配置头文件,定义 `click_detector_config[]`
至少要给出:
- `key_id`
- `consume_button_event`
3.`CONFIG_CAF_CLICK_DETECTOR_DEF_PATH` 指向该文件。
**何时使用**
- 一个键要复用多个动作
- 如长按进入配对、双击切层、长按恢复出厂
参考:
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\click_detector.rst`
### 5.4 `CAF_LEDS`
**用途**
- 接收 `led_event`
- 用 PWM 或 GPIO 驱动 LED
- 支持 LED effect
**最小接入**
PWM 方案示例:
```conf
CONFIG_CAF_LEDS=y
CONFIG_CAF_LEDS_PWM=y
CONFIG_LED=y
CONFIG_LED_PWM=y
CONFIG_PWM=y
```
GPIO 方案示例:
```conf
CONFIG_CAF_LEDS=y
CONFIG_CAF_LEDS_GPIO=y
CONFIG_LED=y
CONFIG_LED_GPIO=y
CONFIG_GPIO=y
```
同时还需要:
- 在 DTS 或 overlay 中定义 LED 节点
- 在应用里由别的模块发 `led_event`
**何时使用**
- 做状态灯、层指示、配对指示、电量指示
**补充**
- 想做平滑呼吸灯,优先用 PWM
- GPIO 版只适合开关式 LED
参考:
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\leds.rst`
- `C:\ncs\v3.2.3\nrf\samples\caf`
### 5.5 `CAF_POWER_MANAGER`
**用途**
- 管理系统从 idle 到 suspended/off 的切换
- 对外广播 `power_down_event``wake_up_event``power_off_event`
**最小接入**
```conf
CONFIG_CAF_POWER_MANAGER=y
```
常用附加项:
```conf
CONFIG_CAF_POWER_MANAGER_TIMEOUT=120
CONFIG_CAF_POWER_MANAGER_ERROR_TIMEOUT=30
```
**何时使用**
- 电池设备
- 需要空闲休眠/关机
- 多模块都需要统一响应省电状态
**补充**
- 常和 `CAF_BUTTONS_PM_KEEP_ALIVE` 配合
- 其他模块可用 `power_manager_restrict_event` 限制最大省电级别
参考:
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\power_manager.rst`
### 5.6 `CAF_BLE_STATE`
**用途**
- 启动 BLE
- 处理连接和参数回调
- 向应用广播 BLE 连接状态事件
**最小接入**
```conf
CONFIG_BT=y
CONFIG_BT_SMP=y
CONFIG_CAF_BLE_STATE=y
```
常见附加项:
```conf
CONFIG_CAF_BLE_STATE_SECURITY_REQ=y
CONFIG_CAF_BLE_USE_LLPM=y
```
**何时使用**
- 只要 CAF 体系下要做 BLE几乎都先启用它
- 它本身不负责广播或扫描
参考:
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\ble_state.rst`
### 5.7 `CAF_BLE_STATE_PM`
**用途**
- 当 BLE 连接存在时,阻止系统进入过深省电级别
**最小接入**
```conf
CONFIG_CAF_BLE_STATE=y
CONFIG_CAF_POWER_MANAGER=y
CONFIG_CAF_BLE_STATE_PM=y
```
**何时使用**
- BLE 外设连接后不能立即休眠
- 要让 BLE 连接期间系统维持可通信
参考:
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\ble_state_pm.rst`
### 5.8 `CAF_BLE_ADV`
**用途**
- 作为 BLE Peripheral 控制广播
**最小接入**
1. 启用 `CAF_BLE_STATE`
2. 启用:
```conf
CONFIG_CAF_BLE_ADV=y
```
3. 配置 advertising data provider 和 scan response provider
**何时使用**
- 你的设备要作为 BLE Peripheral 被手机/PC/主机发现
**补充**
- 支持快慢广播
- 支持 directed advertising
- 支持 suspend/resume
- 支持 grace period
参考:
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\ble_adv.rst`
### 5.9 `CAF_BLE_BOND`
**用途**
- 提供默认 BLE bond 管理
- 可通过特定点击动作执行 bond erase
**最小接入**
```conf
CONFIG_CAF_BLE_BOND=y
CONFIG_BT_BONDABLE=y
CONFIG_BT_SETTINGS=y
CONFIG_CAF_SETTINGS_LOADER=y
CONFIG_CAF_BLE_COMMON_EVENTS=y
```
如果要支持按键清除 bond还要配置
```conf
CONFIG_CAF_BLE_BOND_PEER_ERASE_CLICK=y
CONFIG_CAF_BLE_BOND_PEER_ERASE_CLICK_KEY_ID=0x0000
```
并选择触发类型之一:
- `CONFIG_CAF_BLE_BOND_PEER_ERASE_CLICK_SHORT`
- `CONFIG_CAF_BLE_BOND_PEER_ERASE_CLICK_LONG`
- `CONFIG_CAF_BLE_BOND_PEER_ERASE_CLICK_DOUBLE`
**何时使用**
- 简单 BLE 应用需要默认配对/绑定位管理
**补充**
- 只适合简单应用
- 更复杂的多 identity / 多 peer 管理,通常要自己实现
参考:
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\ble_bond.rst`
### 5.10 `CAF_BLE_SMP`
**用途**
- 通过 BLE 做 MCUmgr DFU
**最小接入**
```conf
CONFIG_CAF_BLE_STATE=y
CONFIG_CAF_BLE_SMP=y
CONFIG_MCUMGR_GRP_IMG=y
CONFIG_MCUMGR_MGMT_NOTIFICATION_HOOKS=y
CONFIG_MCUMGR_GRP_IMG_UPLOAD_CHECK_HOOK=y
CONFIG_MCUMGR_TRANSPORT_BT=y
CONFIG_BOOTLOADER_MCUBOOT=y
```
**何时使用**
- 需要 BLE OTA/DFU
**补充**
- 依赖 MCUboot
- 构建后会在 build 目录生成 `dfu_application.zip`
参考:
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\ble_smp.rst`
### 5.11 `CAF_SETTINGS_LOADER`
**用途**
- 在合适的初始化时机调用 `settings_load()`
**最小接入**
```conf
CONFIG_CAF_SETTINGS_LOADER=y
CONFIG_SETTINGS=y
```
还需要:
- 新建配置头文件
- 实现 `get_req_modules(struct module_flags *mf)`
这个函数用于告诉 settings loader
- 哪些模块 ready 以后再加载 settings
**何时使用**
- 你的应用用了 settings/NVS/BT settings
- 比如 BLE bond、用户配置、持久化参数
参考:
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\settings_loader.rst`
### 5.12 `CAF_NET_STATE`
**用途**
- 上报网络连接状态
- 提供 LTE / OpenThread backend
**最小接入**
```conf
CONFIG_CAF_NET_STATE=y
```
具体 backend 由链路层决定,例如:
- `CONFIG_CAF_NET_STATE_LTE`
- `CONFIG_CAF_NET_STATE_OT`
**何时使用**
- 不是键盘/鼠标常用模块
- 更适合蜂窝或 Thread 设备
参考:
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\net_state.rst`
### 5.13 `CAF_SENSOR_MANAGER`
**用途**
- 周期采样传感器
- 统一生成 `sensor_event``sensor_state_event`
**最小接入**
```conf
CONFIG_CAF_SENSOR_MANAGER=y
CONFIG_SENSOR=y
```
还需要:
1. 在 DTS/overlay 中启用传感器
2. 打开对应传感器驱动 Kconfig
3. 新建 `sm_sensor_config[]` 配置文件
4.`CONFIG_CAF_SENSOR_MANAGER_DEF_PATH` 指向该文件
配置项通常至少包括:
- `dev_name`
- `event_descr`
- `chans`
- `chan_cnt`
- `sampling_period_ms`
- `active_events_limit`
**何时使用**
- 有 IMU、加速度计、光传感器、环境传感器等
**补充**
- 有独立采样线程
- 支持 trigger
- 支持 PM
参考:
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\sensor_manager.rst`
- `C:\ncs\v3.2.3\nrf\samples\caf_sensor_manager`
### 5.14 `CAF_SENSOR_DATA_AGGREGATOR`
**用途**
- 将多个 `sensor_event` 聚合成更大的数据包
- 多核 SoC 下可降低核间唤醒频率
**最小接入**
```conf
CONFIG_CAF_SENSOR_DATA_AGGREGATOR=y
```
如果另一核心要接收聚合事件,还可启用:
```conf
CONFIG_CAF_SENSOR_DATA_AGGREGATOR_EVENTS=y
```
还需要:
- 在 DTS/overlay 里添加 `compatible = "caf,aggregator"` 的节点
关键属性:
- `sensor_descr`
- `buf_data_length`
- `sample_size`
- `buf_count`
**何时使用**
- 传感器数据量较大
- 需要批处理
- 或者多核 SoC 上做功耗优化
参考:
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\sensor_data_aggregator.rst`
### 5.15 `CAF_FACTORY_RESET_REQUEST`
**用途**
- 在上电初始化窗口中检测某个按键是否被按住
- 若满足条件,发出 `factory_reset_event`
**最小接入**
```conf
CONFIG_CAF_FACTORY_RESET_REQUEST=y
CONFIG_CAF_FACTORY_RESET_REQUEST_BUTTON=0x0000
CONFIG_CAF_FACTORY_RESET_REQUEST_DELAY=50
```
它依赖:
- `CAF_BUTTONS`
- `button_event`
**何时使用**
- 开机长按某键请求恢复出厂
- 需要给上层模块一个统一 factory-reset 事件入口
**补充**
- 这个模块在 `NCS v3.2.3` 源码中存在
- 但没有找到与其他模块同等级的独立官方 `.rst` 页面
- 当前说明主要依据:
- `C:\ncs\v3.2.3\nrf\subsys\caf\modules\Kconfig.factory_reset_request`
- `C:\ncs\v3.2.3\nrf\subsys\caf\modules\factory_reset_request.c`
### 5.16 `CAF_SHELL`
**用途**
- 通过 Zephyr Shell 手工触发 CAF 事件
- 便于调试
**最小接入**
```conf
CONFIG_CAF_SHELL=y
CONFIG_SHELL=y
CONFIG_CAF=y
```
常见命令:
```text
caf_events button_event [button_id] [pressed]
```
例如:
```text
caf_events button_event 1 y
caf_events button_event 1 n
```
**何时使用**
- 没有真实按键硬件时做联调
- 验证 button/click/LED/状态机逻辑
参考:
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\caf_shell.rst`
## 6. 对键盘项目最常用的 CAF 组合
如果你的项目是 `C:\projects\blinky` 这种自定义键盘方向,最常见的组合通常是:
### 6.1 纯输入层
- `CAF_BUTTONS`
- `CAF_CLICK_DETECTOR`
适合:
- 扫描键盘按键
- 做短按/长按/双击功能键
### 6.2 带状态灯
- `CAF_BUTTONS`
- `CAF_CLICK_DETECTOR`
- `CAF_LEDS`
适合:
- Caps Lock 指示
- 蓝牙通道指示
- 层状态指示
### 6.3 电池设备
- `CAF_BUTTONS`
- `CAF_POWER_MANAGER`
- `CAF_BUTTONS_PM_KEEP_ALIVE`
- `CAF_LEDS`
适合:
- 一段时间无操作后休眠
- 按键恢复活跃状态
### 6.4 BLE 键盘
- `CAF_BLE_STATE`
- `CAF_BLE_ADV`
- `CAF_BLE_BOND`
- `CAF_SETTINGS_LOADER`
按需叠加:
- `CAF_BLE_STATE_PM`
- `CAF_BLE_SMP`
适合:
- 支持广播、连接、加密、绑定
- 支持设置装载
- 需要时支持 OTA
## 7. 推荐的接入顺序
如果你要在 `blinky` 里逐步引入 CAF建议顺序如下
1. 先接 `CAF_BUTTONS`
2. 再接 `CAF_LEDS`
3. 然后根据需要加 `CAF_CLICK_DETECTOR`
4. 如果是电池设备,再接 `CAF_POWER_MANAGER`
5. 如果要做 BLE再接 `CAF_BLE_STATE``CAF_BLE_ADV``CAF_BLE_BOND`
6. 如果要做 OTA再接 `CAF_BLE_SMP`
这样改动面最小,也最容易定位问题。
## 8. 官方参考路径
建议优先阅读这些本地官方文件:
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\caf_overview.rst`
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\buttons.rst`
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\click_detector.rst`
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\leds.rst`
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\power_manager.rst`
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\ble_state.rst`
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\ble_state_pm.rst`
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\ble_adv.rst`
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\ble_bond.rst`
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\ble_smp.rst`
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\settings_loader.rst`
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\net_state.rst`
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\sensor_manager.rst`
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\sensor_data_aggregator.rst`
- `C:\ncs\v3.2.3\nrf\doc\nrf\libraries\caf\caf_shell.rst`
同时可参考源码:
- `C:\ncs\v3.2.3\nrf\subsys\caf\modules`
- `C:\ncs\v3.2.3\nrf\samples\caf`
- `C:\ncs\v3.2.3\nrf\samples\caf_sensor_manager`
## 9. 一句话结论
如果只看键盘/鼠标类项目CAF 里最值得优先使用的官方模块通常是:
- `CAF_BUTTONS`
- `CAF_CLICK_DETECTOR`
- `CAF_LEDS`
- `CAF_POWER_MANAGER`
- `CAF_BLE_STATE`
- `CAF_BLE_ADV`
- `CAF_BLE_BOND`
- `CAF_SETTINGS_LOADER`
它们已经覆盖了一个 BLE/USB 输入设备项目里最常见的基础设施。

View File

@@ -0,0 +1,500 @@
# nRF Desktop 官方程序架构说明
本文基于 `C:\ncs\v3.2.3\nrf\applications\nrf_desktop` 中的官方源码与文档整理,目的是帮助在 `C:\projects\blinky` 中开发自定义键盘或 HID 设备时,理解 `nrf_desktop` 的整体设计思路。
## 1. nRF Desktop 是什么
`nrf_desktop` 不是一个单体应用,而是 Nordic 在 NCS 中提供的一个参考级 HID 框架。它可以通过不同配置,工作成以下几类设备:
- 鼠标
- 键盘
- Dongle
它同时支持以下传输方式:
- Bluetooth Low Energy
- USB
- BLE + USB 并存
官方文档的核心描述是:这个应用是一个基于 CAF 和 Application Event Manager 的模块化、事件驱动架构。
对应源码和文档位置:
- `C:\ncs\v3.2.3\nrf\applications\nrf_desktop\src\main.c`
- `C:\ncs\v3.2.3\nrf\applications\nrf_desktop\description.rst`
- `C:\ncs\v3.2.3\nrf\applications\nrf_desktop\modules.rst`
## 2. 整体设计思想
它的设计目标主要有三个:
- 高性能,尤其是 HID report rate 和输入延迟
- 可配置,不同板子和不同产品形态共用同一套代码骨架
- 可扩展,通过增加模块或替换模块实现新功能
`nrf_desktop` 的关键点在于:
- `main()` 几乎不做业务逻辑
- 功能被拆成很多独立模块
- 模块之间主要通过事件通信,而不是直接互相调用
- 不同产品形态通过 Kconfig、DTS overlay 和配置头文件组合出来
因此它更像一个“产品框架”,而不是一个简单示例。
## 3. 启动流程
`src/main.c` 非常简单,核心逻辑只有两步:
1. 初始化 `app_event_manager`
2. 发送 `module_state_event(MODULE_STATE_READY)`
也就是说,`main()` 只是启动系统并广播“主模块已经准备好”。其他模块监听这个事件后,再分别完成自己的初始化。
这和传统的串行初始化方式不同:
- 传统方式:`main -> init_ble -> init_usb -> init_keys -> init_hid`
- `nrf_desktop` 方式:`main` 只发启动事件,各模块自己响应并进入就绪状态
这种模式的优点是模块之间耦合更低,方便裁剪和重用。
## 4. 源码目录分层
`nrf_desktop` 的目录结构本身就体现了它的架构分层:
### 4.1 `src/events`
这里定义事件类型,相当于模块间通信协议。
常见事件包括:
- `motion_event`
- `hid_report_event`
- `hid_report_sent_event`
- `ble_event`
- `usb_event`
- `battery_event`
- `config_event`
这些事件不是“业务实现”,而是模块之间交换信息的数据载体。
### 4.2 `src/hw_interface`
这一层负责直接接触硬件,把硬件输入转换为内部事件。
例如:
- `board.c`
- `motion_sensor.c`
- `motion_buttons.c`
- `wheel.c`
- `battery_meas.c`
- `passkey_buttons.c`
这一层可以理解成“硬件抽象输入层”。
### 4.3 `src/modules`
这是最核心的一层,负责系统行为和业务逻辑。
例如:
- `hid_state.c`
- `hids.c`
- `usb_state.c`
- `hid_forward.c`
- `ble_scan.c`
- `ble_discovery.c`
- `ble_bond.c`
- `led_state.c`
- `dfu.c`
- `qos.c`
如果说 `hw_interface` 负责“采集输入”,那么 `modules` 负责“处理输入并把它交付给主机或其他设备”。
### 4.4 `src/util`
这一层放通用工具和公共基础能力。
例如:
- `hid_reportq.c`
- `hid_eventq.c`
- `hid_keymap.c`
- `hwid.c`
- `config_channel_transport.c`
这一层是支撑模块工作的辅助库。
## 5. 事件驱动架构
`nrf_desktop` 的核心是事件驱动。
典型模式是:
1. 某个模块监听一个或多个事件
2. 收到事件后更新内部状态
3. 如有需要,再提交新的事件
4. 其他模块继续响应
例如:
- 按键模块产生 `button_event`
- HID provider 收到后更新 report 数据
- `hid_state` 请求生成 HID report
- `usb_state``hids` 把 report 发送出去
- 发送完成后提交 `hid_report_sent_event`
- 上游模块再决定是否采下一帧输入
所以它的整体运行更像“事件链路”,而不是“函数调用链”。
官方对这种模式的说明可以参考:
- `description.rst`
- `doc/event_propagation.rst`
## 6. 两种核心设备角色
`nrf_desktop` 架构里最重要的划分不是“鼠标还是键盘”,而是以下两个角色:
- HID Peripheral
- HID Dongle
这两个角色决定了系统的核心数据流完全不同。
### 6.1 HID Peripheral
这种角色下,设备本身就是输入设备,比如键盘或鼠标。
它的职责是:
- 采集本地硬件输入
- 生成 HID report
- 通过 BLE 或 USB 发给主机
典型模块包括:
- `buttons`
- `motion`
- `wheel`
- `hid_provider_*`
- `hid_state`
- `hids`
- `usb_state`
### 6.2 HID Dongle
这种角色下,设备本身不直接生成输入,而是做桥接转发。
它的职责是:
- 作为 BLE Central 连接外部 HID 外设
- 接收这些外设通过 HOGP 发来的 HID report
- 再通过 USB 转发给 PC 主机
典型模块包括:
- `ble_scan`
- `ble_discovery`
- `ble_conn_params`
- `hid_forward`
- `usb_state`
所以:
- Peripheral 模式更像“输入源”
- Dongle 模式更像“协议桥”
## 7. Peripheral 模式的核心链路
在 Peripheral 模式下,系统最核心的中心模块是 `hid_state`
它负责:
- 管理哪些 HID subscriber 当前有效
- 决定 report 应该发给 USB 还是 BLE
- 和各类 `hid_provider` 交互
- 处理 HID output report例如键盘 LED 状态
你可以把它理解成“本地 HID 数据总调度器”。
### 7.1 典型数据流
以键盘或鼠标为例,数据流大致是:
`buttons / motion / wheel`
-> 产生原始输入事件
-> `hid_provider_*`
-> `hid_state`
-> `usb_state``hids`
-> 主机
其中:
- `hid_provider_mouse` 负责组装鼠标输入 report
- `hid_provider_keyboard` 负责组装键盘 report
- `hid_provider_consumer_ctrl` 负责多媒体键
- `hid_provider_system_ctrl` 负责系统控制键
它们都不是最终传输模块而是“report 生成器”。
### 7.2 `hid_state` 为什么重要
`hid_state` 的价值在于把“输入生成”和“传输介质”解耦:
- 上游模块只关心输入语义
- 下游模块只关心通过 USB 或 BLE 发送
- `hid_state` 负责把两边连起来
这样键盘逻辑不需要知道当前是 USB 主机在收,还是 BLE 主机在收。
## 8. 鼠标高性能链路
`nrf_desktop` 对鼠标场景做了专门优化,尤其是高 report rate。
官方文档里说明得很清楚:
- Motion sensor 的采样和 HID report 的发送是同步的
- `hid_report_sent_event` 会触发下一次采样
- 在 BLE 或某些 USB 配置下,会建立两个 report 的 pipeline
原因是:
- BLE 通知完成的确认存在一个连接间隔延迟
- USB poll 也可能有时间抖动
因此系统不是“采样器一直跑report 有空再发”,而是“根据发送节奏反推采样节奏”。
这是一种很典型的低延迟输入设备设计。
对键盘来说,这种 pipeline 不一定像鼠标那样关键,但它说明官方非常重视链路级时序设计。
## 9. BLE 传输层模块
在 Peripheral 角色下BLE 相关模块大致分为几类:
- `ble_state`
- `ble_adv`
- `ble_bond`
- `ble_latency`
- `hids`
- `bas`
- `dev_descr`
职责可以简单理解为:
- `ble_state`:打开蓝牙、处理连接状态和参数回调
- `ble_adv`:负责广播
- `ble_bond`:负责绑定和身份管理
- `ble_latency`:在配置或升级场景下降低连接延迟
- `hids`:真正承载 HID over GATT
- `bas`:电池服务
- `dev_descr`:设备描述和硬件 ID
其中真正“把 HID report 发到 BLE 主机”的是 `hids`
## 10. USB 传输层模块
USB 侧的核心模块是 `usb_state`
它负责:
- 跟踪 USB 连接状态
- 注册 HID class 实例
- 接收内部 `hid_report_event`
- 把 report 送入 USB 栈
- 发送完成后产生 `hid_report_sent_event`
- 在需要时处理 output report
它既是传输模块,也是系统状态模块。
官方还支持:
- legacy USB stack
- USB next stack
而且不同设备还能配置:
- 单个 HID USB 实例
- 多个 HID USB 实例
- boot protocol
- report protocol
这说明 `usb_state` 设计得非常通用,并不是只为单一 demo 服务。
## 11. Dongle 模式的核心链路
如果系统工作在 Dongle 模式,最核心的模块不再是 `hid_state`,而是 `hid_forward`
它负责:
- 从 BLE 外设接收 HID report
- 必要时用队列缓存 report
- 转成内部事件
- 再发给 `usb_state`
- 把主机下发的 output report 再转发回 BLE 外设
典型数据流是:
BLE HID Peripheral
-> `ble_discovery`
-> `hid_forward`
-> `usb_state`
-> PC 主机
在这个角色里设备自己不再生产键值或鼠标移动而是充当“BLE 到 USB 的协议转换桥”。
## 12. 配置通道和 DFU
`nrf_desktop` 很强的一点是,它不仅有“输入数据面”,还有“控制面”。
控制面主要由 `config_channel` 提供,基于 HID feature report 实现。
它可以做:
- 读取设备信息
- 修改模块参数
- 调节传感器 CPI
- 下发 LED 数据
- 执行 DFU
Dongle 还可以把这些请求继续转发给 BLE Peripheral。
这意味着官方架构已经把“量产设备常见需求”纳入了统一框架,而不是把配置、升级、输入完全割裂开。
## 13. 线程模型
`nrf_desktop` 总体上是少线程设计。
官方文档说明,大多数逻辑都运行在:
- system workqueue
- App Event Manager 回调上下文
只有少量功能单独开线程,例如:
- motion sensor sampling thread
- settings loader thread
- QoS sampling thread
这种设计的直接好处是:
- 降低并发复杂度
- 大部分路径不需要显式资源保护
- 更有利于保持时序可控
对于嵌入式 HID 设备,这是非常务实的选择。
## 14. 配置目录如何决定产品形态
`nrf_desktop` 的另一个重要架构点是“同一套源码,多套产品配置”。
配置目录位于:
- `C:\ncs\v3.2.3\nrf\applications\nrf_desktop\configuration`
每个板子一个目录,目录内通过这些文件控制构建结果:
- `prj.conf`
- `prj_keyboard.conf`
- `prj_dongle.conf`
- `app.overlay`
- 各种 `*_def.h`
- `sysbuild.conf`
- `pm_static.yml`
例如在 `nrf52840dk_nrf52840` 中:
- `prj_keyboard.conf` 把它构造成键盘
- `prj_dongle.conf` 把它构造成 dongle
也就是说,架构的复用不是靠复制工程,而是靠配置裁剪模块集合。
## 15. 对你的 `blinky` 项目的启发
你的项目路径是:
- `C:\projects\blinky`
如果你后续想把它做成一个更完整的自定义键盘,而不是只停留在简单 GPIO 读取和发送,那么 `nrf_desktop` 最值得借鉴的不是某一个文件,而是下面这些架构思想。
### 15.1 把硬件输入和 HID 输出分层
建议至少拆成两层:
- 输入层按键扫描、编码器、LED、传感器
- HID 层按键状态汇总、键值映射、report 生成、USB/BLE 发送
不要让扫描函数直接拼 USB report。
### 15.2 用事件或消息队列解耦模块
即使不完全照搬 CAF也可以参考它的思路
- 输入模块只上报事件
- HID 模块只处理事件
- 传输模块只发送 report
这样后面加 BLE、加层切换、加宏录制时不容易改崩整套逻辑。
### 15.3 先定义“角色”和“能力”
在正式扩展前,先明确你的设备属于哪一类:
- 纯 USB 键盘
- BLE 键盘
- 双模键盘
- 带配置通道的键盘
不同目标会直接影响:
- 模块边界
- report 设计
- 状态管理
- 功耗策略
### 15.4 把板级配置独立出来
你现在已经有:
- `boards/atguigu/mini_keyboard/mini_keyboard.dts`
- `boards/atguigu/mini_keyboard/Kconfig.mini_keyboard`
这条路是对的。后面建议继续把下列内容尽量配置化:
- matrix 行列定义
- LED 引脚
- 特殊按键定义
- 默认 keymap
这样应用逻辑就不会和某一块板子绑定太死。
## 16. 一句话总结
`nrf_desktop` 的官方架构可以概括为:
一个基于 CAF 和事件总线的模块化 HID 产品框架通过配置来组合出键盘、鼠标、dongle 等不同设备形态并在输入采集、HID report 生成、BLE/USB 传输、配置通道、DFU 和状态管理之间建立清晰分层。
如果你后续想把 `C:\projects\blinky` 往自定义键盘方向继续演进,那么最值得学习的是它的:
- 模块分层
- 事件驱动
- 角色化配置
- 传输层与输入层解耦
- 控制面与数据面分离
## 17. 参考源码位置
建议重点阅读以下路径:
- `C:\ncs\v3.2.3\nrf\applications\nrf_desktop\src\main.c`
- `C:\ncs\v3.2.3\nrf\applications\nrf_desktop\description.rst`
- `C:\ncs\v3.2.3\nrf\applications\nrf_desktop\modules.rst`
- `C:\ncs\v3.2.3\nrf\applications\nrf_desktop\bluetooth.rst`
- `C:\ncs\v3.2.3\nrf\applications\nrf_desktop\board_configuration.rst`
- `C:\ncs\v3.2.3\nrf\applications\nrf_desktop\doc\event_propagation.rst`
- `C:\ncs\v3.2.3\nrf\applications\nrf_desktop\doc\hid_state.rst`
- `C:\ncs\v3.2.3\nrf\applications\nrf_desktop\doc\hids.rst`
- `C:\ncs\v3.2.3\nrf\applications\nrf_desktop\doc\hid_forward.rst`
- `C:\ncs\v3.2.3\nrf\applications\nrf_desktop\doc\motion.rst`
- `C:\ncs\v3.2.3\nrf\applications\nrf_desktop\doc\usb_state.rst`
- `C:\ncs\v3.2.3\nrf\applications\nrf_desktop\doc\config_channel.rst`

1
drivers/CMakeLists.txt Normal file
View File

@@ -0,0 +1 @@
add_subdirectory(pmic)

1
drivers/Kconfig Normal file
View File

@@ -0,0 +1 @@
rsource "pmic/Kconfig"

View File

@@ -0,0 +1 @@
add_subdirectory(ip5306)

1
drivers/pmic/Kconfig Normal file
View File

@@ -0,0 +1 @@
rsource "ip5306/Kconfig"

View File

@@ -0,0 +1 @@
target_sources_ifdef(CONFIG_IP5306 app PRIVATE ip5306.c)

View File

@@ -0,0 +1,11 @@
menu "PMIC Drivers"
config IP5306
bool "IP5306 PMIC driver"
default y
depends on I2C
depends on DT_HAS_INJOINIC_IP5306_ENABLED
help
Enable the out-of-tree IP5306 PMIC driver.
endmenu

View File

@@ -0,0 +1,357 @@
#include <errno.h>
#include <stdint.h>
#include <zephyr/device.h>
#include <zephyr/devicetree.h>
#include <zephyr/drivers/gpio.h>
#include <zephyr/drivers/i2c.h>
#include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
#include <soc_nrf_common.h>
#include <zephyr/sys/util.h>
#include <helpers/nrfx_gppi.h>
#include <drivers/pmic/ip5306.h>
#include <gpiote_nrfx.h>
#include <nrfx_gpiote.h>
#include <nrfx_rtc.h>
#define DT_DRV_COMPAT injoinic_ip5306
LOG_MODULE_REGISTER(ip5306, LOG_LEVEL_INF);
#define IP5306_REG_READ0 0x70
#define IP5306_REG_READ1 0x71
#define IP5306_CHARGING_BIT BIT(3)
#define IP5306_FULL_BIT BIT(3)
#define IP5306_KEEPALIVE_RTC_FREQ_HZ 32768U
#define IP5306_KEEPALIVE_RTC_CHANNEL_END 0U
#define IP5306_KEEPALIVE_RTC_CHANNEL_START 1U
struct ip5306_config {
struct i2c_dt_spec bus;
nrfx_gpiote_t *gpiote;
struct gpio_dt_spec wakeup_gpio;
uint8_t wakeup_pin;
uint32_t keepalive_interval_ms;
uint32_t keepalive_pulse_width_ms;
bool keepalive_hardware;
};
struct ip5306_data {
const struct device *dev;
struct k_work_delayable keepalive_work;
uint8_t gpiote_channel;
nrfx_gppi_handle_t ppi_start;
nrfx_gppi_handle_t ppi_end;
nrfx_gppi_handle_t ppi_clear;
bool started;
bool pulse_active;
bool hardware_ready;
};
static const nrfx_rtc_t keepalive_rtc = NRFX_RTC_INSTANCE(2);
static uint32_t keepalive_low_delay_ms(const struct ip5306_config *config)
{
if (config->keepalive_interval_ms > config->keepalive_pulse_width_ms) {
return config->keepalive_interval_ms -
config->keepalive_pulse_width_ms;
}
return 0;
}
static uint32_t keepalive_ms_to_rtc_ticks(uint32_t time_ms)
{
return (uint32_t)(((uint64_t)time_ms * IP5306_KEEPALIVE_RTC_FREQ_HZ) / 1000U);
}
static void keepalive_work_handler(struct k_work *work)
{
struct k_work_delayable *dwork = k_work_delayable_from_work(work);
struct ip5306_data *data =
CONTAINER_OF(dwork, struct ip5306_data, keepalive_work);
const struct device *dev = data->dev;
const struct ip5306_config *config = dev->config;
int err;
if (!data->started) {
return;
}
if (!data->pulse_active) {
err = gpio_pin_set_dt(&config->wakeup_gpio, 1);
if (err) {
LOG_ERR("Failed to assert wakeup pulse (%d)", err);
}
data->pulse_active = true;
k_work_reschedule(&data->keepalive_work,
K_MSEC(config->keepalive_pulse_width_ms));
return;
}
err = gpio_pin_set_dt(&config->wakeup_gpio, 0);
if (err) {
LOG_ERR("Failed to deassert wakeup pulse (%d)", err);
}
data->pulse_active = false;
k_work_reschedule(&data->keepalive_work,
K_MSEC(keepalive_low_delay_ms(config)));
}
static void ip5306_keepalive_rtc_handler(nrfx_rtc_int_type_t int_type)
{
ARG_UNUSED(int_type);
}
static int hardware_keepalive_init(const struct device *dev)
{
const struct ip5306_config *config = dev->config;
struct ip5306_data *data = dev->data;
nrfx_gpiote_output_config_t output_config = NRFX_GPIOTE_DEFAULT_OUTPUT_CONFIG;
nrfx_gpiote_task_config_t task_config = {
.task_ch = 0,
.polarity = NRF_GPIOTE_POLARITY_TOGGLE,
.init_val = (config->wakeup_gpio.dt_flags & GPIO_ACTIVE_LOW) ?
NRF_GPIOTE_INITIAL_VALUE_HIGH :
NRF_GPIOTE_INITIAL_VALUE_LOW,
};
nrfx_rtc_config_t rtc_cfg = NRFX_RTC_DEFAULT_CONFIG;
uint32_t period_ticks = keepalive_ms_to_rtc_ticks(config->keepalive_interval_ms);
uint32_t pulse_ticks = keepalive_ms_to_rtc_ticks(config->keepalive_pulse_width_ms);
uint32_t start_ticks = period_ticks - pulse_ticks;
uint32_t eep_start;
uint32_t eep_end;
uint32_t tep_toggle;
uint32_t tep_clear;
int err;
if (data->hardware_ready) {
return 0;
}
if (!nrfx_gpiote_init_check(config->gpiote)) {
LOG_ERR("GPIOTE shared instance is not initialized");
return -ENODEV;
}
err = nrfx_gpiote_channel_alloc(config->gpiote, &data->gpiote_channel);
if (err) {
LOG_ERR("GPIOTE channel alloc failed (%d)", err);
return err;
}
task_config.task_ch = data->gpiote_channel;
err = nrfx_gpiote_output_configure(config->gpiote,
config->wakeup_pin,
&output_config,
&task_config);
if (err) {
LOG_ERR("GPIOTE output configure failed (%d)", err);
return err;
}
nrfx_gpiote_out_task_enable(config->gpiote, config->wakeup_pin);
err = nrfx_rtc_init(&keepalive_rtc, &rtc_cfg, ip5306_keepalive_rtc_handler);
if ((err != 0) && (err != -EALREADY)) {
LOG_ERR("RTC2 init failed (%d)", err);
return err;
}
err = nrfx_rtc_cc_set(&keepalive_rtc,
IP5306_KEEPALIVE_RTC_CHANNEL_END,
period_ticks,
false);
if (err) {
LOG_ERR("RTC2 CC end set failed (%d)", err);
return err;
}
err = nrfx_rtc_cc_set(&keepalive_rtc,
IP5306_KEEPALIVE_RTC_CHANNEL_START,
start_ticks,
false);
if (err) {
LOG_ERR("RTC2 CC start set failed (%d)", err);
return err;
}
eep_start = nrfx_rtc_event_address_get(&keepalive_rtc,
NRF_RTC_EVENT_COMPARE_1);
eep_end = nrfx_rtc_event_address_get(&keepalive_rtc,
NRF_RTC_EVENT_COMPARE_0);
tep_toggle = nrfx_gpiote_out_task_address_get(config->gpiote,
config->wakeup_pin);
tep_clear = nrfx_rtc_task_address_get(&keepalive_rtc, NRF_RTC_TASK_CLEAR);
err = nrfx_gppi_conn_alloc(eep_start, tep_toggle, &data->ppi_start);
if (err) {
LOG_ERR("GPPI start alloc failed (%d)", err);
return err;
}
err = nrfx_gppi_conn_alloc(eep_end, tep_toggle, &data->ppi_end);
if (err) {
LOG_ERR("GPPI end alloc failed (%d)", err);
return err;
}
err = nrfx_gppi_conn_alloc(eep_end, tep_clear, &data->ppi_clear);
if (err) {
LOG_ERR("GPPI clear alloc failed (%d)", err);
return err;
}
nrfx_gppi_conn_enable(data->ppi_start);
nrfx_gppi_conn_enable(data->ppi_end);
nrfx_gppi_conn_enable(data->ppi_clear);
nrfx_rtc_counter_clear(&keepalive_rtc);
nrfx_rtc_enable(&keepalive_rtc);
data->hardware_ready = true;
return 0;
}
static int software_keepalive_init(const struct device *dev)
{
struct ip5306_data *data = dev->data;
k_work_init_delayable(&data->keepalive_work, keepalive_work_handler);
return 0;
}
static int ip5306_init_api(const struct device *dev)
{
const struct ip5306_config *config = dev->config;
struct ip5306_data *data = dev->data;
uint8_t reg_val;
int err;
if (data->started) {
return 0;
}
err = i2c_reg_read_byte_dt(&config->bus, IP5306_REG_READ0, &reg_val);
if (err) {
LOG_ERR("IP5306 probe failed (%d)", err);
return err;
}
ARG_UNUSED(reg_val);
data->started = true;
data->pulse_active = false;
if (config->keepalive_hardware) {
return 0;
}
k_work_reschedule(&data->keepalive_work,
K_MSEC(keepalive_low_delay_ms(config)));
return 0;
}
static int ip5306_get_status_api(const struct device *dev,
struct ip5306_status *status)
{
const struct ip5306_config *config = dev->config;
uint8_t read0;
uint8_t read1;
int err;
if (status == NULL) {
return -EINVAL;
}
err = i2c_reg_read_byte_dt(&config->bus, IP5306_REG_READ0, &read0);
if (err) {
return err;
}
err = i2c_reg_read_byte_dt(&config->bus, IP5306_REG_READ1, &read1);
if (err) {
return err;
}
status->charging = (read0 & IP5306_CHARGING_BIT) != 0U;
status->full = (read1 & IP5306_FULL_BIT) != 0U;
return 0;
}
static int ip5306_dev_init(const struct device *dev)
{
const struct ip5306_config *config = dev->config;
struct ip5306_data *data = dev->data;
if (!i2c_is_ready_dt(&config->bus)) {
LOG_ERR("I2C bus not ready");
return -ENODEV;
}
if (!gpio_is_ready_dt(&config->wakeup_gpio)) {
LOG_ERR("Wakeup GPIO not ready");
return -ENODEV;
}
if (config->keepalive_pulse_width_ms == 0U) {
LOG_ERR("Invalid keepalive pulse width");
return -EINVAL;
}
if (config->keepalive_interval_ms == 0U) {
LOG_ERR("Invalid keepalive interval");
return -EINVAL;
}
if (config->keepalive_pulse_width_ms > config->keepalive_interval_ms) {
LOG_ERR("Pulse width cannot exceed interval");
return -EINVAL;
}
data->dev = dev;
data->started = false;
data->pulse_active = false;
data->hardware_ready = false;
if (config->keepalive_hardware) {
return hardware_keepalive_init(dev);
}
return software_keepalive_init(dev);
}
static const struct ip5306_driver_api ip5306_driver_api = {
.init = ip5306_init_api,
.get_status = ip5306_get_status_api,
};
#define IP5306_DEFINE(inst) \
static struct ip5306_data ip5306_data_##inst; \
\
static const struct ip5306_config ip5306_config_##inst = { \
.bus = I2C_DT_SPEC_INST_GET(inst), \
.gpiote = &GPIOTE_NRFX_INST_BY_NODE( \
NRF_DT_GPIOTE_NODE(DT_DRV_INST(inst), wakeup_gpios)), \
.wakeup_gpio = GPIO_DT_SPEC_INST_GET(inst, wakeup_gpios), \
.wakeup_pin = NRF_DT_GPIOS_TO_PSEL(DT_DRV_INST(inst), wakeup_gpios), \
.keepalive_interval_ms = \
DT_INST_PROP(inst, keepalive_interval_ms), \
.keepalive_pulse_width_ms = \
DT_INST_PROP(inst, keepalive_pulse_width_ms), \
.keepalive_hardware = \
DT_INST_NODE_HAS_PROP(inst, keepalive_hardware), \
}; \
\
DEVICE_DT_INST_DEFINE(inst, ip5306_dev_init, NULL, \
&ip5306_data_##inst, &ip5306_config_##inst, \
POST_KERNEL, CONFIG_KERNEL_INIT_PRIORITY_DEVICE, \
&ip5306_driver_api)
DT_INST_FOREACH_STATUS_OKAY(IP5306_DEFINE)

View File

@@ -0,0 +1,25 @@
description: Injoinic IP5306 PMIC with selectable software or hardware wakeup keepalive support
compatible: "injoinic,ip5306"
include: i2c-device.yaml
properties:
wakeup-gpios:
type: phandle-array
required: true
description: GPIO used to generate the wakeup keepalive pulse.
keepalive-interval-ms:
type: int
required: true
description: Period between two keepalive pulses, measured from pulse start.
keepalive-pulse-width-ms:
type: int
required: true
description: Active-high pulse width for the keepalive wakeup GPIO.
keepalive-hardware:
type: boolean
description: Enable RTC2 plus GPPI plus GPIOTE based hardware keepalive pulses.

View File

@@ -0,0 +1,2 @@
atguigu Atguigu
injoinic Injoinic

34
inc/buttons_def.h Normal file
View File

@@ -0,0 +1,34 @@
/*
* CAF buttons 矩阵引脚定义
*
* 设计说明:
* - 本文件被 CAF buttons 模块通过 CONFIG_CAF_BUTTONS_DEF_PATH 直接包含;
* - 行列引脚顺序必须与板级 DTS 中 my_keyboard 的 row-gpios/col-gpios 保持一致;
* - key_id 的行列编号完全基于这里的数组下标,不依赖 input-keymap 节点。
*/
#include <caf/gpio_pins.h>
/*
* 该符号用于保证配置文件只被链接一次:
* 若被重复包含到多个编译单元,会在链接阶段报重复定义,避免静默错配。
*/
const struct {} buttons_def_include_once;
/* 列引脚:对应 atguigu_mini_keyboard.dts 中 my_keyboard/col-gpios 顺序。 */
static const struct gpio_pin col[] = {
{ .port = 0, .pin = 5 },
{ .port = 0, .pin = 6 },
{ .port = 0, .pin = 26 },
{ .port = 0, .pin = 30 },
};
/* 行引脚:对应 atguigu_mini_keyboard.dts 中 my_keyboard/row-gpios 顺序。 */
static const struct gpio_pin row[] = {
{ .port = 0, .pin = 15 },
{ .port = 0, .pin = 7 },
{ .port = 0, .pin = 12 },
{ .port = 0, .pin = 4 },
{ .port = 1, .pin = 9 },
{ .port = 0, .pin = 8 },
};

12
inc/cdc_wrapper_module.h Normal file
View File

@@ -0,0 +1,12 @@
#ifndef BLINKY_CDC_WRAPPER_MODULE_H_
#define BLINKY_CDC_WRAPPER_MODULE_H_
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_CDC_WRAPPER_MODULE_H_ */

15
inc/click_detector_def.h Normal file
View File

@@ -0,0 +1,15 @@
/*
* This configuration file is included only once from the CAF click detector
* module and defines the keys that should produce click events.
*/
#include <caf/click_detector.h>
const struct {} click_detector_def_include_once;
static const struct click_detector_config click_detector_config[] = {
{
.key_id = 0x180,
.consume_button_event = true,
},
};

44
inc/drivers/pmic/ip5306.h Normal file
View File

@@ -0,0 +1,44 @@
#ifndef BLINKY_DRIVERS_PMIC_IP5306_H_
#define BLINKY_DRIVERS_PMIC_IP5306_H_
#include <errno.h>
#include <stdbool.h>
#include <zephyr/device.h>
struct ip5306_status {
bool charging;
bool full;
};
struct ip5306_driver_api {
int (*init)(const struct device *dev);
int (*get_status)(const struct device *dev, struct ip5306_status *status);
};
static inline int ip5306_init(const struct device *dev)
{
const struct ip5306_driver_api *api =
(const struct ip5306_driver_api *)dev->api;
if ((api == NULL) || (api->init == NULL)) {
return -ENOSYS;
}
return api->init(dev);
}
static inline int ip5306_get_status(const struct device *dev,
struct ip5306_status *status)
{
const struct ip5306_driver_api *api =
(const struct ip5306_driver_api *)dev->api;
if ((api == NULL) || (api->get_status == NULL)) {
return -ENOSYS;
}
return api->get_status(dev, status);
}
#endif /* BLINKY_DRIVERS_PMIC_IP5306_H_ */

View File

@@ -0,0 +1,27 @@
#ifndef BLINKY_BAT_STATE_EVENT_H_
#define BLINKY_BAT_STATE_EVENT_H_
#include <stdbool.h>
#include <stdint.h>
#include <app_event_manager.h>
#include <app_event_manager_profiler_tracer.h>
#ifdef __cplusplus
extern "C" {
#endif
struct bat_state_event {
struct app_event_header header;
uint8_t soc;
bool charging;
bool full;
};
APP_EVENT_TYPE_DECLARE(bat_state_event);
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_BAT_STATE_EVENT_H_ */

View File

@@ -0,0 +1,22 @@
#ifndef BLINKY_ENCODER_EVENT_H_
#define BLINKY_ENCODER_EVENT_H_
#include <app_event_manager.h>
#include <app_event_manager_profiler_tracer.h>
#ifdef __cplusplus
extern "C" {
#endif
struct encoder_event {
struct app_event_header header;
int8_t detents;
};
APP_EVENT_TYPE_DECLARE(encoder_event);
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_ENCODER_EVENT_H_ */

View File

@@ -0,0 +1,25 @@
#ifndef BLINKY_HID_LED_EVENT_H_
#define BLINKY_HID_LED_EVENT_H_
#include <app_event_manager.h>
#include <app_event_manager_profiler_tracer.h>
#include "keyboard_core.h"
#ifdef __cplusplus
extern "C" {
#endif
struct hid_led_event {
struct app_event_header header;
enum hid_transport transport;
uint8_t led_bm;
};
APP_EVENT_TYPE_DECLARE(hid_led_event);
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_HID_LED_EVENT_H_ */

View File

@@ -0,0 +1,27 @@
#ifndef BLINKY_HID_REPORT_SENT_EVENT_H_
#define BLINKY_HID_REPORT_SENT_EVENT_H_
#include <app_event_manager.h>
#include <app_event_manager_profiler_tracer.h>
#include "keyboard_core.h"
#ifdef __cplusplus
extern "C" {
#endif
struct hid_report_sent_event {
struct app_event_header header;
enum hid_transport transport;
enum keyboard_report_type report_type;
uint16_t sequence;
bool error;
};
APP_EVENT_TYPE_DECLARE(hid_report_sent_event);
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_HID_REPORT_SENT_EVENT_H_ */

View File

@@ -0,0 +1,28 @@
#ifndef BLINKY_HID_TRANSPORT_STATE_EVENT_H_
#define BLINKY_HID_TRANSPORT_STATE_EVENT_H_
#include <app_event_manager.h>
#include <app_event_manager_profiler_tracer.h>
#include "keyboard_core.h"
#ifdef __cplusplus
extern "C" {
#endif
struct hid_transport_state_event {
struct app_event_header header;
enum hid_transport transport;
bool ready;
bool keys_ready;
bool consumer_ready;
enum keyboard_protocol_mode protocol_mode;
};
APP_EVENT_TYPE_DECLARE(hid_transport_state_event);
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_HID_TRANSPORT_STATE_EVENT_H_ */

View File

@@ -0,0 +1,28 @@
#ifndef BLINKY_HID_TX_REPORT_EVENT_H_
#define BLINKY_HID_TX_REPORT_EVENT_H_
#include <app_event_manager.h>
#include <app_event_manager_profiler_tracer.h>
#include "keyboard_core.h"
#ifdef __cplusplus
extern "C" {
#endif
struct hid_tx_report_event {
struct app_event_header header;
enum hid_transport transport;
enum keyboard_report_type report_type;
enum keyboard_protocol_mode protocol_mode;
uint16_t sequence;
struct event_dyndata dyndata;
};
APP_EVENT_TYPE_DYNDATA_DECLARE(hid_tx_report_event);
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_HID_TX_REPORT_EVENT_H_ */

View File

@@ -0,0 +1,29 @@
#ifndef BLINKY_KEYBOARD_HID_REPORT_EVENT_H_
#define BLINKY_KEYBOARD_HID_REPORT_EVENT_H_
#include <app_event_manager.h>
#include <app_event_manager_profiler_tracer.h>
#include "keyboard_core.h"
#include "mode_switch_event.h"
#ifdef __cplusplus
extern "C" {
#endif
struct keyboard_hid_report_event {
struct app_event_header header;
enum mode_switch_mode mode;
enum keyboard_report_type report_type;
enum keyboard_protocol_mode protocol_mode;
enum hid_queue_policy queue_policy;
struct event_dyndata dyndata;
};
APP_EVENT_TYPE_DYNDATA_DECLARE(keyboard_hid_report_event);
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_KEYBOARD_HID_REPORT_EVENT_H_ */

View File

@@ -0,0 +1,29 @@
#ifndef BLINKY_MODE_SWITCH_EVENT_H_
#define BLINKY_MODE_SWITCH_EVENT_H_
#include <app_event_manager.h>
#include <app_event_manager_profiler_tracer.h>
#ifdef __cplusplus
extern "C" {
#endif
enum mode_switch_mode {
MODE_SWITCH_USB,
MODE_SWITCH_24G,
MODE_SWITCH_BLE,
};
struct mode_switch_event {
struct app_event_header header;
enum mode_switch_mode mode;
uint16_t voltage_mv;
};
APP_EVENT_TYPE_DECLARE(mode_switch_event);
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_MODE_SWITCH_EVENT_H_ */

View File

@@ -0,0 +1,25 @@
#ifndef BLINKY_SET_PROTOCOL_EVENT_H_
#define BLINKY_SET_PROTOCOL_EVENT_H_
#include <app_event_manager.h>
#include <app_event_manager_profiler_tracer.h>
#include "keyboard_core.h"
#ifdef __cplusplus
extern "C" {
#endif
struct set_protocol_event {
struct app_event_header header;
enum hid_transport transport;
enum keyboard_protocol_mode protocol_mode;
};
APP_EVENT_TYPE_DECLARE(set_protocol_event);
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_SET_PROTOCOL_EVENT_H_ */

View File

@@ -0,0 +1,22 @@
#ifndef BLINKY_USB_CDC_RX_EVENT_H_
#define BLINKY_USB_CDC_RX_EVENT_H_
#include <app_event_manager.h>
#include <app_event_manager_profiler_tracer.h>
#ifdef __cplusplus
extern "C" {
#endif
struct usb_cdc_rx_event {
struct app_event_header header;
struct event_dyndata dyndata;
};
APP_EVENT_TYPE_DYNDATA_DECLARE(usb_cdc_rx_event);
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_USB_CDC_RX_EVENT_H_ */

View File

@@ -0,0 +1,22 @@
#ifndef BLINKY_USB_CDC_TX_EVENT_H_
#define BLINKY_USB_CDC_TX_EVENT_H_
#include <app_event_manager.h>
#include <app_event_manager_profiler_tracer.h>
#ifdef __cplusplus
extern "C" {
#endif
struct usb_cdc_tx_event {
struct app_event_header header;
struct event_dyndata dyndata;
};
APP_EVENT_TYPE_DYNDATA_DECLARE(usb_cdc_tx_event);
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_USB_CDC_TX_EVENT_H_ */

View File

@@ -0,0 +1,24 @@
#ifndef BLINKY_USB_DEVICE_STATE_EVENT_H_
#define BLINKY_USB_DEVICE_STATE_EVENT_H_
#include <app_event_manager.h>
#include <app_event_manager_profiler_tracer.h>
#include "usb_device_module.h"
#ifdef __cplusplus
extern "C" {
#endif
struct usb_device_state_event {
struct app_event_header header;
enum usb_device_state state;
};
APP_EVENT_TYPE_DECLARE(usb_device_state_event);
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_USB_DEVICE_STATE_EVENT_H_ */

View File

@@ -0,0 +1,24 @@
#ifndef BLINKY_USB_FUNCTION_READY_EVENT_H_
#define BLINKY_USB_FUNCTION_READY_EVENT_H_
#include <app_event_manager.h>
#include <app_event_manager_profiler_tracer.h>
#include "usb_device_module.h"
#ifdef __cplusplus
extern "C" {
#endif
struct usb_function_ready_event {
struct app_event_header header;
uint8_t function_mask;
};
APP_EVENT_TYPE_DECLARE(usb_function_ready_event);
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_USB_FUNCTION_READY_EVENT_H_ */

View File

@@ -0,0 +1,21 @@
#ifndef BLINKY_USB_PREPARE_EVENT_H_
#define BLINKY_USB_PREPARE_EVENT_H_
#include <app_event_manager.h>
#include <app_event_manager_profiler_tracer.h>
#ifdef __cplusplus
extern "C" {
#endif
struct usb_prepare_event {
struct app_event_header header;
};
APP_EVENT_TYPE_DECLARE(usb_prepare_event);
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_USB_PREPARE_EVENT_H_ */

51
inc/keyboard_core.h Normal file
View File

@@ -0,0 +1,51 @@
#ifndef BLINKY_KEYBOARD_CORE_H_
#define BLINKY_KEYBOARD_CORE_H_
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#define KEYBOARD_BOOT_REPORT_SIZE 8U
#define KEYBOARD_NKRO_USAGE_MAX 0xDFU
#define KEYBOARD_NKRO_BITMAP_BYTES ((KEYBOARD_NKRO_USAGE_MAX + 8U) / 8U)
#define KEYBOARD_NKRO_REPORT_SIZE (1U + KEYBOARD_NKRO_BITMAP_BYTES)
#define KEYBOARD_CONSUMER_REPORT_SIZE 2U
enum keyboard_protocol_mode {
KEYBOARD_PROTOCOL_MODE_BOOT,
KEYBOARD_PROTOCOL_MODE_REPORT,
};
enum keyboard_report_type {
KEYBOARD_REPORT_TYPE_KEYS,
KEYBOARD_REPORT_TYPE_CONSUMER,
};
enum hid_queue_policy {
HID_QUEUE_POLICY_LATEST,
HID_QUEUE_POLICY_FIFO,
};
enum hid_transport {
HID_TRANSPORT_USB,
HID_TRANSPORT_BLE,
HID_TRANSPORT_COUNT,
};
enum keyboard_consumer_control {
KEYBOARD_CONSUMER_CTRL_MUTE,
KEYBOARD_CONSUMER_CTRL_VOLUME_UP,
KEYBOARD_CONSUMER_CTRL_VOLUME_DOWN,
KEYBOARD_CONSUMER_CTRL_PLAY_PAUSE,
KEYBOARD_CONSUMER_CTRL_NEXT_TRACK,
KEYBOARD_CONSUMER_CTRL_PREV_TRACK,
KEYBOARD_CONSUMER_CTRL_COUNT,
};
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_KEYBOARD_CORE_H_ */

26
inc/protocol_module.h Normal file
View File

@@ -0,0 +1,26 @@
#ifndef BLINKY_PROTOCOL_MODULE_H_
#define BLINKY_PROTOCOL_MODULE_H_
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#define CDC_PROTO_TYPE_HELLO_REQ 0x01U
#define CDC_PROTO_TYPE_HELLO_RSP 0x02U
int protocol_module_process_cdc_packet(uint8_t req_type,
const uint8_t *req_payload,
size_t req_payload_len,
uint8_t *rsp_type,
uint8_t *rsp_payload,
size_t rsp_payload_buf_size,
size_t *rsp_payload_len);
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_PROTOCOL_MODULE_H_ */

15
inc/settings_loader_def.h Normal file
View File

@@ -0,0 +1,15 @@
/*
* Settings must be loaded after HIDS has registered its dynamic GATT
* service and after BLE state is initialized.
*/
const struct {} settings_loader_def_include_once;
#include <caf/events/module_state_event.h>
static inline void get_req_modules(struct module_flags *mf)
{
module_flags_set_bit(mf, MODULE_IDX(main));
module_flags_set_bit(mf, MODULE_IDX(ble_hid_module));
module_flags_set_bit(mf, MODULE_IDX(ble_state));
}

26
inc/usb_device_module.h Normal file
View File

@@ -0,0 +1,26 @@
#ifndef BLINKY_USB_DEVICE_MODULE_H_
#define BLINKY_USB_DEVICE_MODULE_H_
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
enum usb_function {
USB_FUNCTION_HID = 0x01,
USB_FUNCTION_CDC_ACM = 0x02,
};
enum usb_device_state {
USB_DEVICE_STATE_DISCONNECTED,
USB_DEVICE_STATE_POWERED,
USB_DEVICE_STATE_ACTIVE,
USB_DEVICE_STATE_SUSPENDED,
};
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_USB_DEVICE_MODULE_H_ */

30
pm_static.yml Normal file
View File

@@ -0,0 +1,30 @@
mcuboot:
address: 0x0
size: 0x20000
mcuboot_pad:
address: 0x20000
size: 0x200
app:
address: 0x20200
size: 0xBFE00
mcuboot_primary:
orig_span: &id001
- mcuboot_pad
- app
span: *id001
address: 0x20000
size: 0xC0000
mcuboot_primary_app:
orig_span: &id002
- app
span: *id002
address: 0x20200
size: 0xBFE00
settings_storage:
address: 0xE0000
size: 0x20000

119
prj.conf
View File

@@ -1,4 +1,121 @@
CONFIG_CAF=y
CONFIG_HEAP_MEM_POOL_SIZE=2048
CONFIG_CAF_BUTTONS=y
CONFIG_CAF_BUTTONS_DEF_PATH="buttons_def.h"
CONFIG_CAF_CLICK_DETECTOR=y
CONFIG_CAF_CLICK_DETECTOR_DEF_PATH="click_detector_def.h"
CONFIG_GPIO=y
CONFIG_I2C=y
CONFIG_LED=y
CONFIG_PWM=y
CONFIG_SPI=y
CONFIG_NRFX_RTC2=y
CONFIG_NRFX_GPPI=y
CONFIG_NRFX_QDEC=y
CONFIG_PINCTRL_DYNAMIC=y
CONFIG_REBOOT=y
CONFIG_SENSOR=y
CONFIG_ADC=y
CONFIG_DISPLAY=y
CONFIG_DISPLAY_LOG_LEVEL_ERR=y
CONFIG_MIPI_DBI_LOG_LEVEL_ERR=y
CONFIG_SETTINGS=y
CONFIG_SETTINGS_NVS=y
CONFIG_FLASH=y
CONFIG_FLASH_PAGE_LAYOUT=y
CONFIG_FLASH_MAP=y
CONFIG_NVS=y
CONFIG_HEAP_MEM_POOL_SIZE=4096
CONFIG_LOG=y
CONFIG_ASSERT=y
# USB HID next stack
CONFIG_USB_DEVICE_STACK_NEXT=y
CONFIG_SERIAL=y
CONFIG_UART_INTERRUPT_DRIVEN=y
CONFIG_UART_LINE_CTRL=y
CONFIG_UART_USE_RUNTIME_CONFIGURE=y
CONFIG_NANOPB=y
CONFIG_USBD_HID_SUPPORT=y
CONFIG_USBD_CDC_ACM_CLASS=y
CONFIG_CDC_ACM_SERIAL_INITIALIZE_AT_BOOT=n
# BLE
CONFIG_BT=y
CONFIG_BT_PERIPHERAL=y
CONFIG_BT_SMP=y
CONFIG_BT_BONDABLE=y
CONFIG_BT_SETTINGS=y
CONFIG_BT_MAX_CONN=1
CONFIG_BT_MAX_PAIRED=1
CONFIG_BT_ATT_TX_COUNT=5
CONFIG_BT_CONN_CTX=y
CONFIG_BT_DEVICE_NAME="WH Mini Keyboard"
CONFIG_BT_DEVICE_APPEARANCE=961
CONFIG_BT_BAS=y
CONFIG_BT_HIDS=y
CONFIG_BT_HIDS_MAX_CLIENT_COUNT=1
CONFIG_BT_HIDS_DEFAULT_PERM_RW_ENCRYPT=y
CONFIG_BT_HIDS_INPUT_REP_MAX=2
CONFIG_BT_HIDS_OUTPUT_REP_MAX=1
CONFIG_BT_HIDS_FEATURE_REP_MAX=0
CONFIG_BT_GATT_UUID16_POOL_SIZE=40
CONFIG_BT_GATT_CHRC_POOL_SIZE=20
CONFIG_BT_DIS=y
CONFIG_BT_DIS_MANUF_NAME=y
CONFIG_BT_DIS_MANUF_NAME_STR="Atguigu"
CONFIG_BT_DIS_MODEL_NUMBER=y
CONFIG_BT_DIS_MODEL_NUMBER_STR="WH Mini Keyboard"
CONFIG_BT_DIS_PNP=y
CONFIG_BT_DIS_PNP_VID_SRC=2
CONFIG_BT_DIS_PNP_VID=0x1915
CONFIG_BT_DIS_PNP_PID=0x52F0
CONFIG_BT_DIS_PNP_VER=0x0100
# Power manager
CONFIG_CAF_POWER_MANAGER=y
CONFIG_CAF_POWER_MANAGER_TIMEOUT=120
# CONFIG_CAF_POWER_MANAGER_STAY_ON=y
# CAF BLE
CONFIG_CAF_SETTINGS_LOADER=y
CONFIG_CAF_SETTINGS_LOADER_DEF_PATH="settings_loader_def.h"
CONFIG_CAF_SETTINGS_LOADER_USE_THREAD=y
CONFIG_CAF_SETTINGS_LOADER_THREAD_STACK_SIZE=1792
CONFIG_CAF_BLE_STATE=y
CONFIG_CAF_BLE_STATE_SECURITY_REQ=y
CONFIG_CAF_BLE_STATE_PM=y
CONFIG_CAF_BLE_STATE_MAX_LOCAL_ID_BONDS=1
CONFIG_CAF_BLE_ADV=y
CONFIG_CAF_BLE_ADV_SUSPEND_ON_READY=y
CONFIG_CAF_BLE_ADV_FAST_ADV=y
CONFIG_CAF_BLE_ADV_FILTER_ACCEPT_LIST=y
CONFIG_CAF_BLE_ADV_MODULE_SUSPEND_EVENTS=y
CONFIG_CAF_BLE_BOND=y
CONFIG_CAF_BLE_BOND_PEER_ERASE_CLICK=y
CONFIG_CAF_BLE_BOND_PEER_ERASE_CLICK_KEY_ID=0x180
CONFIG_CAF_BLE_BOND_PEER_ERASE_CLICK_LONG=y
CONFIG_CAF_BLE_BOND_PEER_ERASE_CLICK_TIMEOUT=-1
CONFIG_CAF_MODULE_SUSPEND_EVENTS=y
CONFIG_BT_ADV_PROV_FLAGS=y
CONFIG_BT_ADV_PROV_GAP_APPEARANCE=y
CONFIG_BT_ADV_PROV_DEVICE_NAME=y
CONFIG_BT_ADV_PROV_DEVICE_NAME_SD=y
# LVGL
CONFIG_LVGL=y
CONFIG_LV_Z_AUTO_INIT=n
CONFIG_LV_Z_RUN_LVGL_ON_WORKQUEUE=y
CONFIG_LV_Z_LVGL_WORKQUEUE_STACK_SIZE=16384
CONFIG_LV_Z_LVGL_MUTEX=y
CONFIG_LV_COLOR_DEPTH_16=y
CONFIG_LV_COLOR_16_SWAP=y
CONFIG_LV_Z_BITS_PER_PIXEL=16
CONFIG_LV_Z_VDB_SIZE=25
CONFIG_LV_Z_DOUBLE_VDB=y
CONFIG_LV_Z_MEM_POOL_SIZE=16384
CONFIG_LV_USE_LABEL=y
CONFIG_LV_FONT_MONTSERRAT_14=y
CONFIG_LV_FONT_MONTSERRAT_32=y
CONFIG_MAIN_STACK_SIZE=4096

21
proto/device_comm.proto Normal file
View File

@@ -0,0 +1,21 @@
syntax = "proto3";
message HelloReq {
uint32 protocol_version = 1;
}
message HelloRsp {
uint32 protocol_version = 1;
uint32 vendor_id = 2;
uint32 product_id = 3;
uint32 firmware_major = 4;
uint32 firmware_minor = 5;
uint32 capability_flags = 6;
}
message CdcPacketBody {
oneof body {
HelloReq hello_req = 1;
HelloRsp hello_rsp = 2;
}
}

264
src/battery_module.c Normal file
View File

@@ -0,0 +1,264 @@
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <app_event_manager.h>
#define MODULE battery_module
#include <caf/events/module_state_event.h>
#include <caf/events/power_manager_event.h>
#include <caf/events/power_event.h>
#include <drivers/pmic/ip5306.h>
#include <zephyr/device.h>
#include <zephyr/devicetree.h>
#include <zephyr/drivers/sensor.h>
#include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
#include <zephyr/pm/device.h>
#include "bat_state_event.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
#define VBATT_NODE DT_PATH(vbatt)
#define IP5306_NODE DT_NODELABEL(ip5306)
#define BATTERY_SAMPLE_INTERVAL K_SECONDS(1)
#define BATTERY_SOC_MIN_MV 3300
#define BATTERY_SOC_MAX_MV 4200
BUILD_ASSERT(DT_NODE_HAS_STATUS(VBATT_NODE, okay),
"Missing /vbatt voltage-divider node in devicetree");
BUILD_ASSERT(DT_NODE_HAS_STATUS(IP5306_NODE, okay),
"Missing ip5306 node in devicetree");
static const struct device *const vbatt_dev = DEVICE_DT_GET(VBATT_NODE);
static const struct device *const ip5306_dev = DEVICE_DT_GET(IP5306_NODE);
static struct k_work_delayable battery_sample_work;
static struct {
bool valid;
uint8_t soc;
bool charging;
bool full;
} last_bat_state;
static bool initialized;
static bool running;
static int sensor_value_to_mv(const struct sensor_value *value)
{
return (value->val1 * 1000) + (value->val2 / 1000);
}
static int measurement_enable(bool enable)
{
enum pm_device_action action = enable ? PM_DEVICE_ACTION_RESUME
: PM_DEVICE_ACTION_SUSPEND;
int err = pm_device_action_run(vbatt_dev, action);
if (err && (err != -EALREADY) && (err != -ENOTSUP)) {
LOG_ERR("Cannot %s vbatt sensor (%d)", enable ? "resume" : "suspend", err);
return err;
}
return 0;
}
static uint8_t battery_soc_from_mv(int voltage_mv)
{
const int span_mv = BATTERY_SOC_MAX_MV - BATTERY_SOC_MIN_MV;
int bucket;
if (voltage_mv <= BATTERY_SOC_MIN_MV) {
return 0U;
}
if (voltage_mv >= BATTERY_SOC_MAX_MV) {
return 100U;
}
bucket = ((voltage_mv - BATTERY_SOC_MIN_MV) * 10 + (span_mv / 2)) / span_mv;
return (uint8_t)(bucket * 10);
}
static void submit_bat_state_event(uint8_t soc, bool charging, bool full)
{
struct bat_state_event *event;
if (last_bat_state.valid &&
(last_bat_state.soc == soc) &&
(last_bat_state.charging == charging) &&
(last_bat_state.full == full)) {
return;
}
last_bat_state.valid = true;
last_bat_state.soc = soc;
last_bat_state.charging = charging;
last_bat_state.full = full;
event = new_bat_state_event();
event->soc = soc;
event->charging = charging;
event->full = full;
APP_EVENT_SUBMIT(event);
}
static void battery_sample_fn(struct k_work *work)
{
struct ip5306_status pmic_status;
struct sensor_value voltage;
int voltage_mv;
int err;
ARG_UNUSED(work);
if (!running) {
return;
}
err = sensor_sample_fetch(vbatt_dev);
if (err) {
LOG_WRN("Battery sample fetch failed (%d)", err);
goto reschedule;
}
err = sensor_channel_get(vbatt_dev, SENSOR_CHAN_VOLTAGE, &voltage);
if (err) {
LOG_WRN("Battery channel get failed (%d)", err);
goto reschedule;
}
err = ip5306_get_status(ip5306_dev, &pmic_status);
if (err) {
LOG_WRN("IP5306 status read failed (%d)", err);
goto reschedule;
}
voltage_mv = sensor_value_to_mv(&voltage);
submit_bat_state_event(battery_soc_from_mv(voltage_mv),
pmic_status.charging,
pmic_status.full);
reschedule:
if (running) {
k_work_reschedule(&battery_sample_work, BATTERY_SAMPLE_INTERVAL);
}
}
static int module_init(void)
{
if (!device_is_ready(vbatt_dev)) {
LOG_ERR("vbatt device not ready");
return -ENODEV;
}
if (!device_is_ready(ip5306_dev)) {
LOG_ERR("ip5306 device not ready");
return -ENODEV;
}
int err = ip5306_init(ip5306_dev);
if (err) {
LOG_ERR("ip5306 init failed (%d)", err);
return err;
}
k_work_init_delayable(&battery_sample_work, battery_sample_fn);
memset(&last_bat_state, 0, sizeof(last_bat_state));
power_manager_restrict(MODULE_IDX(MODULE), POWER_MANAGER_LEVEL_SUSPENDED);
return 0;
}
static int module_start(void)
{
int err;
if (running) {
return 0;
}
err = measurement_enable(true);
if (err) {
return err;
}
running = true;
k_work_reschedule(&battery_sample_work, K_NO_WAIT);
return 0;
}
static void module_pause(void)
{
if (!running) {
return;
}
(void)k_work_cancel_delayable(&battery_sample_work);
(void)measurement_enable(false);
running = false;
}
static bool app_event_handler(const struct app_event_header *aeh)
{
if (is_module_state_event(aeh)) {
const struct module_state_event *event = cast_module_state_event(aeh);
if (check_state(event, MODULE_ID(main), MODULE_STATE_READY)) {
int err;
if (!initialized) {
err = module_init();
if (err) {
module_set_state(MODULE_STATE_ERROR);
return false;
}
initialized = true;
}
err = module_start();
if (err) {
module_set_state(MODULE_STATE_ERROR);
} else {
module_set_state(MODULE_STATE_READY);
}
}
return false;
}
if (is_power_down_event(aeh)) {
if (initialized) {
module_pause();
module_set_state(MODULE_STATE_STANDBY);
}
return false;
}
if (is_wake_up_event(aeh)) {
if (initialized) {
int err = module_start();
if (err) {
module_set_state(MODULE_STATE_ERROR);
} else {
module_set_state(MODULE_STATE_READY);
}
}
return false;
}
__ASSERT_NO_MSG(false);
return false;
}
APP_EVENT_LISTENER(MODULE, app_event_handler);
APP_EVENT_SUBSCRIBE(MODULE, module_state_event);
APP_EVENT_SUBSCRIBE_EARLY(MODULE, power_down_event);
APP_EVENT_SUBSCRIBE(MODULE, wake_up_event);

115
src/ble_adv_ctrl_module.c Normal file
View File

@@ -0,0 +1,115 @@
#include <stdbool.h>
#include <app_event_manager.h>
#define MODULE ble_adv_ctrl_module
#include <caf/events/module_state_event.h>
#include <caf/events/module_suspend_event.h>
#include <zephyr/logging/log.h>
#include "mode_switch_event.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
static bool initialized;
static bool running;
static bool ble_adv_suspended = true;
static void broadcast_ble_adv_req(bool suspend)
{
if (suspend) {
struct module_suspend_req_event *event = new_module_suspend_req_event();
event->sink_module_id = MODULE_ID(ble_adv);
event->src_module_id = MODULE_ID(MODULE);
APP_EVENT_SUBMIT(event);
} else {
struct module_resume_req_event *event = new_module_resume_req_event();
event->sink_module_id = MODULE_ID(ble_adv);
event->src_module_id = MODULE_ID(MODULE);
APP_EVENT_SUBMIT(event);
}
}
static int module_init(void)
{
ble_adv_suspended = true;
return 0;
}
static int module_start(void)
{
if (running) {
return 0;
}
running = true;
return 0;
}
static void module_pause(void)
{
running = false;
}
static bool handle_mode_switch_event(const struct mode_switch_event *event)
{
bool should_suspend;
if (!running) {
return false;
}
should_suspend = (event->mode != MODE_SWITCH_BLE);
if (should_suspend != ble_adv_suspended) {
ble_adv_suspended = should_suspend;
broadcast_ble_adv_req(should_suspend);
}
return false;
}
static bool app_event_handler(const struct app_event_header *aeh)
{
if (is_mode_switch_event(aeh)) {
return handle_mode_switch_event(cast_mode_switch_event(aeh));
}
if (is_module_state_event(aeh)) {
const struct module_state_event *event = cast_module_state_event(aeh);
if (check_state(event, MODULE_ID(main), MODULE_STATE_READY)) {
int err;
if (!initialized) {
err = module_init();
if (err) {
module_set_state(MODULE_STATE_ERROR);
return false;
}
initialized = true;
}
err = module_start();
if (err) {
module_set_state(MODULE_STATE_ERROR);
} else {
module_set_state(MODULE_STATE_READY);
}
}
return false;
}
return false;
}
APP_EVENT_LISTENER(MODULE, app_event_handler);
APP_EVENT_SUBSCRIBE(MODULE, mode_switch_event);
APP_EVENT_SUBSCRIBE(MODULE, module_state_event);

23
src/ble_adv_uuid16.c Normal file
View File

@@ -0,0 +1,23 @@
#include <zephyr/bluetooth/uuid.h>
#include <bluetooth/adv_prov.h>
static int get_data(struct bt_data *sd, const struct bt_le_adv_prov_adv_state *state,
struct bt_le_adv_prov_feedback *fb)
{
static const uint8_t data[] = {
BT_UUID_16_ENCODE(BT_UUID_HIDS_VAL),
BT_UUID_16_ENCODE(BT_UUID_BAS_VAL),
};
ARG_UNUSED(state);
ARG_UNUSED(fb);
sd->type = BT_DATA_UUID16_ALL;
sd->data_len = sizeof(data);
sd->data = data;
return 0;
}
BT_LE_ADV_PROV_SD_PROVIDER_REGISTER(uuid16_all, get_data);

121
src/ble_bas_module.c Normal file
View File

@@ -0,0 +1,121 @@
#include <stdbool.h>
#include <stdint.h>
#include <app_event_manager.h>
#define MODULE ble_bas_module
#include <caf/events/module_state_event.h>
#include <caf/events/ble_common_event.h>
#include <zephyr/bluetooth/services/bas.h>
#include <zephyr/logging/log.h>
#include "bat_state_event.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
static uint8_t current_soc = 100U;
static bool initialized;
static bool running;
static bool ble_ready;
static int module_init(void)
{
return 0;
}
static int module_start(void)
{
int err;
if (running) {
return 0;
}
running = true;
if (!ble_ready) {
return 0;
}
err = bt_bas_set_battery_level(current_soc);
if (err) {
LOG_WRN("bt_bas_set_battery_level failed (%d)", err);
return err;
}
return 0;
}
static void module_pause(void)
{
running = false;
}
static bool handle_bat_state_event(const struct bat_state_event *event)
{
current_soc = event->soc;
if (running && ble_ready) {
int err = bt_bas_set_battery_level(current_soc);
if (err) {
LOG_WRN("bt_bas_set_battery_level failed (%d)", err);
}
}
return false;
}
static bool app_event_handler(const struct app_event_header *aeh)
{
if (is_bat_state_event(aeh)) {
return handle_bat_state_event(cast_bat_state_event(aeh));
}
if (is_module_state_event(aeh)) {
const struct module_state_event *event = cast_module_state_event(aeh);
int err;
if (check_state(event, MODULE_ID(main), MODULE_STATE_READY)) {
if (!initialized) {
err = module_init();
if (err) {
module_set_state(MODULE_STATE_ERROR);
return false;
}
initialized = true;
}
err = module_start();
if (err) {
module_set_state(MODULE_STATE_ERROR);
}
return false;
}
if (check_state(event, MODULE_ID(ble_state), MODULE_STATE_READY)) {
ble_ready = true;
if (running) {
err = bt_bas_set_battery_level(current_soc);
if (err) {
LOG_WRN("bt_bas_set_battery_level failed (%d)", err);
}
}
module_set_state(MODULE_STATE_READY);
return false;
}
return false;
}
return false;
}
APP_EVENT_LISTENER(MODULE, app_event_handler);
APP_EVENT_SUBSCRIBE(MODULE, bat_state_event);
APP_EVENT_SUBSCRIBE(MODULE, module_state_event);

491
src/ble_hid_module.c Normal file
View File

@@ -0,0 +1,491 @@
#include <errno.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <app_event_manager.h>
#define MODULE ble_hid_module
#include <caf/events/module_state_event.h>
#include <caf/events/power_event.h>
#include <caf/events/ble_common_event.h>
#include <bluetooth/services/hids.h>
#include <zephyr/logging/log.h>
#include "hid_led_event.h"
#include "hid_report_sent_event.h"
#include "hid_transport_state_event.h"
#include "hid_tx_report_event.h"
#include "keyboard_core.h"
#include "set_protocol_event.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
#define BLE_HID_KEYS_REPORT_ID 0x01
#define BLE_HID_CONSUMER_REPORT_ID 0x02
#define BLE_HID_KEYS_REPORT_IDX 0
#define BLE_HID_CONSUMER_REPORT_IDX 1
#define BLE_HID_KEYS_LED_REPORT_SIZE 1U
#define BASE_USB_HID_SPEC_VERSION 0x0101
struct in_flight_report {
bool active;
enum keyboard_report_type report_type;
uint16_t sequence;
};
BT_HIDS_DEF(hids_obj,
KEYBOARD_NKRO_REPORT_SIZE,
KEYBOARD_CONSUMER_REPORT_SIZE,
BLE_HID_KEYS_LED_REPORT_SIZE);
static struct bt_conn *active_conn;
static struct in_flight_report in_flight;
static enum keyboard_protocol_mode protocol_mode = KEYBOARD_PROTOCOL_MODE_REPORT;
static bool initialized;
static bool running;
static bool secured;
static bool keyboard_report_notify_enabled;
static bool consumer_report_notify_enabled;
static bool boot_keyboard_notify_enabled;
static const uint8_t hid_report_desc[] = {
0x05, 0x01, /* Usage Page (Generic Desktop) */
0x09, 0x06, /* Usage (Keyboard) */
0xA1, 0x01, /* Collection (Application) */
0x85, BLE_HID_KEYS_REPORT_ID,
0x05, 0x07, /* Usage Page (Keyboard/Keypad) */
0x19, 0xE0, /* Usage Minimum (0xE0) */
0x29, 0xE7, /* Usage Maximum (0xE7) */
0x15, 0x00, /* Logical Minimum (0) */
0x25, 0x01, /* Logical Maximum (1) */
0x75, 0x01, /* Report Size (1) */
0x95, 0x08, /* Report Count (8) */
0x81, 0x02, /* Input (Data,Var,Abs) */
0x05, 0x07, /* Usage Page (Keyboard/Keypad) */
0x19, 0x00, /* Usage Minimum (0x00) */
0x2A, 0xDF, 0x00, /* Usage Maximum (0x00DF) */
0x15, 0x00, /* Logical Minimum (0) */
0x25, 0x01, /* Logical Maximum (1) */
0x75, 0x01, /* Report Size (1) */
0x96, 0xE0, 0x00, /* Report Count (224) */
0x81, 0x02, /* Input (Data,Var,Abs) */
0x85, BLE_HID_KEYS_REPORT_ID,
0x05, 0x08, /* Usage Page (LEDs) */
0x19, 0x01, /* Usage Minimum (1) */
0x29, 0x05, /* Usage Maximum (5) */
0x15, 0x00, /* Logical Minimum (0) */
0x25, 0x01, /* Logical Maximum (1) */
0x75, 0x01, /* Report Size (1) */
0x95, 0x05, /* Report Count (5) */
0x91, 0x02, /* Output (Data,Var,Abs) */
0x75, 0x03, /* Report Size (3) */
0x95, 0x01, /* Report Count (1) */
0x91, 0x01, /* Output (Const,Array,Abs) */
0xC0, /* End Collection */
0x05, 0x0C, /* Usage Page (Consumer) */
0x09, 0x01, /* Usage (Consumer Control) */
0xA1, 0x01, /* Collection (Application) */
0x85, BLE_HID_CONSUMER_REPORT_ID,
0x15, 0x00, /* Logical Minimum (0) */
0x26, 0xFF, 0x03, /* Logical Maximum (1023) */
0x19, 0x00, /* Usage Minimum (0) */
0x2A, 0xFF, 0x03, /* Usage Maximum (1023) */
0x75, 0x10, /* Report Size (16) */
0x95, 0x01, /* Report Count (1) */
0x81, 0x00, /* Input (Data,Array,Abs) */
0xC0 /* End Collection */
};
static void submit_set_protocol_event(void)
{
struct set_protocol_event *event = new_set_protocol_event();
event->transport = HID_TRANSPORT_BLE;
event->protocol_mode = protocol_mode;
APP_EVENT_SUBMIT(event);
}
static void submit_hid_led_event(uint8_t led_bm)
{
struct hid_led_event *event = new_hid_led_event();
event->transport = HID_TRANSPORT_BLE;
event->led_bm = led_bm;
APP_EVENT_SUBMIT(event);
}
static void submit_transport_state_event(void)
{
struct hid_transport_state_event *event = new_hid_transport_state_event();
bool ready = running && secured && (active_conn != NULL);
event->transport = HID_TRANSPORT_BLE;
event->ready = ready;
event->protocol_mode = protocol_mode;
event->keys_ready = ready &&
((protocol_mode == KEYBOARD_PROTOCOL_MODE_BOOT) ?
boot_keyboard_notify_enabled :
keyboard_report_notify_enabled);
event->consumer_ready = ready &&
(protocol_mode == KEYBOARD_PROTOCOL_MODE_REPORT) &&
consumer_report_notify_enabled;
APP_EVENT_SUBMIT(event);
}
static void submit_hid_report_sent_event(enum keyboard_report_type report_type,
uint16_t sequence, bool error)
{
struct hid_report_sent_event *event = new_hid_report_sent_event();
event->transport = HID_TRANSPORT_BLE;
event->report_type = report_type;
event->sequence = sequence;
event->error = error;
APP_EVENT_SUBMIT(event);
}
static void input_report_notify_handler(uint8_t report_id, enum bt_hids_notify_evt evt)
{
bool enabled = (evt == BT_HIDS_CCCD_EVT_NOTIFY_ENABLED);
if (report_id == BLE_HID_KEYS_REPORT_ID) {
keyboard_report_notify_enabled = enabled;
} else if (report_id == BLE_HID_CONSUMER_REPORT_ID) {
consumer_report_notify_enabled = enabled;
}
submit_transport_state_event();
}
static void boot_keyboard_notify_handler(enum bt_hids_notify_evt evt)
{
boot_keyboard_notify_enabled = (evt == BT_HIDS_CCCD_EVT_NOTIFY_ENABLED);
submit_transport_state_event();
}
static void hid_report_complete_cb(struct bt_conn *conn, void *user_data)
{
ARG_UNUSED(conn);
ARG_UNUSED(user_data);
if (!in_flight.active) {
return;
}
submit_hid_report_sent_event(in_flight.report_type, in_flight.sequence, false);
in_flight.active = false;
}
static void keyboard_led_report_common(struct bt_hids_rep *rep, bool write)
{
if (!write || (rep->data == NULL) || (rep->size < BLE_HID_KEYS_LED_REPORT_SIZE)) {
return;
}
submit_hid_led_event(rep->data[0]);
}
static void keyboard_led_report_handler(struct bt_hids_rep *rep,
struct bt_conn *conn,
bool write)
{
ARG_UNUSED(conn);
keyboard_led_report_common(rep, write);
}
static void boot_keyboard_led_report_handler(struct bt_hids_rep *rep,
struct bt_conn *conn,
bool write)
{
ARG_UNUSED(conn);
keyboard_led_report_common(rep, write);
}
static void pm_evt_handler(enum bt_hids_pm_evt evt, struct bt_conn *conn)
{
ARG_UNUSED(conn);
switch (evt) {
case BT_HIDS_PM_EVT_BOOT_MODE_ENTERED:
protocol_mode = KEYBOARD_PROTOCOL_MODE_BOOT;
break;
case BT_HIDS_PM_EVT_REPORT_MODE_ENTERED:
protocol_mode = KEYBOARD_PROTOCOL_MODE_REPORT;
break;
default:
return;
}
submit_set_protocol_event();
submit_transport_state_event();
}
static int module_init(void)
{
struct bt_hids_init_param hids_init_param = { 0 };
struct bt_hids_inp_rep *input_report;
struct bt_hids_outp_feat_rep *output_report;
hids_init_param.info.bcd_hid = BASE_USB_HID_SPEC_VERSION;
hids_init_param.info.b_country_code = 0x00;
hids_init_param.info.flags = BT_HIDS_REMOTE_WAKE | BT_HIDS_NORMALLY_CONNECTABLE;
hids_init_param.rep_map.data = hid_report_desc;
hids_init_param.rep_map.size = sizeof(hid_report_desc);
hids_init_param.pm_evt_handler = pm_evt_handler;
hids_init_param.is_kb = true;
hids_init_param.boot_kb_notif_handler = boot_keyboard_notify_handler;
hids_init_param.boot_kb_outp_rep_handler = boot_keyboard_led_report_handler;
input_report = &hids_init_param.inp_rep_group_init.reports[BLE_HID_KEYS_REPORT_IDX];
input_report->id = BLE_HID_KEYS_REPORT_ID;
input_report->size = KEYBOARD_NKRO_REPORT_SIZE;
input_report->handler_ext = input_report_notify_handler;
hids_init_param.inp_rep_group_init.cnt++;
input_report = &hids_init_param.inp_rep_group_init.reports[BLE_HID_CONSUMER_REPORT_IDX];
input_report->id = BLE_HID_CONSUMER_REPORT_ID;
input_report->size = KEYBOARD_CONSUMER_REPORT_SIZE;
input_report->handler_ext = input_report_notify_handler;
hids_init_param.inp_rep_group_init.cnt++;
output_report = &hids_init_param.outp_rep_group_init.reports[0];
output_report->id = BLE_HID_KEYS_REPORT_ID;
output_report->size = BLE_HID_KEYS_LED_REPORT_SIZE;
output_report->handler = keyboard_led_report_handler;
hids_init_param.outp_rep_group_init.cnt = 1U;
return bt_hids_init(&hids_obj, &hids_init_param);
}
static int module_start(void)
{
if (running) {
return 0;
}
running = true;
submit_transport_state_event();
return 0;
}
static void module_pause(void)
{
if (!running) {
return;
}
in_flight.active = false;
running = false;
submit_transport_state_event();
}
static void reset_connection_state(void)
{
active_conn = NULL;
secured = false;
keyboard_report_notify_enabled = false;
consumer_report_notify_enabled = false;
boot_keyboard_notify_enabled = false;
protocol_mode = KEYBOARD_PROTOCOL_MODE_REPORT;
in_flight.active = false;
}
static bool handle_ble_peer_event(const struct ble_peer_event *event)
{
int err;
switch (event->state) {
case PEER_STATE_CONNECTED:
if (active_conn != NULL) {
return false;
}
active_conn = event->id;
protocol_mode = KEYBOARD_PROTOCOL_MODE_REPORT;
submit_set_protocol_event();
err = bt_hids_connected(&hids_obj, event->id);
if (err) {
LOG_ERR("bt_hids_connected failed (%d)", err);
}
submit_transport_state_event();
return false;
case PEER_STATE_SECURED:
if (active_conn != event->id) {
return false;
}
secured = true;
submit_transport_state_event();
return false;
case PEER_STATE_DISCONNECTED:
if (active_conn != event->id) {
return false;
}
err = bt_hids_disconnected(&hids_obj, event->id);
if (err) {
LOG_WRN("bt_hids_disconnected failed (%d)", err);
}
reset_connection_state();
submit_transport_state_event();
return false;
default:
return false;
}
}
static bool handle_hid_tx_report_event(const struct hid_tx_report_event *event)
{
int err;
if (!running || (event->transport != HID_TRANSPORT_BLE) || in_flight.active) {
return false;
}
if ((active_conn == NULL) || !secured) {
return false;
}
if (event->report_type == KEYBOARD_REPORT_TYPE_KEYS) {
if (event->protocol_mode != protocol_mode) {
LOG_WRN("Drop BLE keys report due to protocol mismatch");
return false;
}
in_flight.active = true;
in_flight.report_type = event->report_type;
in_flight.sequence = event->sequence;
if (protocol_mode == KEYBOARD_PROTOCOL_MODE_BOOT) {
err = bt_hids_boot_kb_inp_rep_send(&hids_obj,
active_conn,
event->dyndata.data,
(uint8_t)event->dyndata.size,
hid_report_complete_cb);
} else {
err = bt_hids_inp_rep_send(&hids_obj,
active_conn,
BLE_HID_KEYS_REPORT_IDX,
event->dyndata.data,
(uint8_t)event->dyndata.size,
hid_report_complete_cb);
}
if (err) {
in_flight.active = false;
LOG_WRN("BLE keyboard report submit failed (%d)", err);
submit_hid_report_sent_event(KEYBOARD_REPORT_TYPE_KEYS,
event->sequence, true);
}
return false;
}
if (event->report_type == KEYBOARD_REPORT_TYPE_CONSUMER) {
if (protocol_mode != KEYBOARD_PROTOCOL_MODE_REPORT) {
LOG_WRN("Drop BLE consumer report in boot mode");
return false;
}
in_flight.active = true;
in_flight.report_type = event->report_type;
in_flight.sequence = event->sequence;
err = bt_hids_inp_rep_send(&hids_obj,
active_conn,
BLE_HID_CONSUMER_REPORT_IDX,
event->dyndata.data,
(uint8_t)event->dyndata.size,
hid_report_complete_cb);
if (err) {
in_flight.active = false;
LOG_WRN("BLE consumer report submit failed (%d)", err);
submit_hid_report_sent_event(KEYBOARD_REPORT_TYPE_CONSUMER,
event->sequence, true);
}
}
return false;
}
static bool app_event_handler(const struct app_event_header *aeh)
{
if (is_hid_tx_report_event(aeh)) {
return handle_hid_tx_report_event(cast_hid_tx_report_event(aeh));
}
if (is_ble_peer_event(aeh)) {
return handle_ble_peer_event(cast_ble_peer_event(aeh));
}
if (is_module_state_event(aeh)) {
const struct module_state_event *event = cast_module_state_event(aeh);
int err;
if (check_state(event, MODULE_ID(main), MODULE_STATE_READY)) {
if (!initialized) {
err = module_init();
if (err) {
module_set_state(MODULE_STATE_ERROR);
return false;
}
initialized = true;
}
err = module_start();
if (err) {
module_set_state(MODULE_STATE_ERROR);
} else {
module_set_state(MODULE_STATE_READY);
}
}
return false;
}
if (is_power_down_event(aeh)) {
if (initialized) {
module_pause();
module_set_state(MODULE_STATE_STANDBY);
}
return false;
}
if (is_wake_up_event(aeh)) {
if (initialized) {
int err = module_start();
if (err) {
module_set_state(MODULE_STATE_ERROR);
} else {
module_set_state(MODULE_STATE_READY);
}
}
return false;
}
return false;
}
APP_EVENT_LISTENER(MODULE, app_event_handler);
APP_EVENT_SUBSCRIBE_EARLY(MODULE, module_state_event);
APP_EVENT_SUBSCRIBE(MODULE, hid_tx_report_event);
APP_EVENT_SUBSCRIBE_EARLY(MODULE, ble_peer_event);
APP_EVENT_SUBSCRIBE_EARLY(MODULE, power_down_event);
APP_EVENT_SUBSCRIBE(MODULE, wake_up_event);

275
src/cdc_wrapper_module.c Normal file
View File

@@ -0,0 +1,275 @@
#include <errno.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <app_event_manager.h>
#define MODULE cdc_wrapper_module
#include <caf/events/module_state_event.h>
#include <caf/events/power_event.h>
#include <zephyr/logging/log.h>
#include "protocol_module.h"
#include "usb_cdc_rx_event.h"
#include "usb_cdc_tx_event.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
#define CDC_WRAPPER_HEAD1 0xAAU
#define CDC_WRAPPER_HEAD2 0x55U
#define CDC_WRAPPER_MAX_PAYLOAD_LEN 64U
#define CDC_WRAPPER_MAX_FRAME_LEN (2U + 1U + 1U + CDC_WRAPPER_MAX_PAYLOAD_LEN + 1U)
enum frame_parse_state {
FRAME_PARSE_HEAD1,
FRAME_PARSE_HEAD2,
FRAME_PARSE_LEN,
FRAME_PARSE_TYPE,
FRAME_PARSE_PAYLOAD,
FRAME_PARSE_CHECKSUM,
};
struct cdc_frame_parser {
enum frame_parse_state state;
uint8_t len;
uint8_t type;
uint8_t checksum;
uint8_t payload[CDC_WRAPPER_MAX_PAYLOAD_LEN];
size_t payload_pos;
};
static bool initialized;
static bool running;
static struct cdc_frame_parser parser;
static void parser_reset(void)
{
parser.state = FRAME_PARSE_HEAD1;
parser.len = 0U;
parser.type = 0U;
parser.checksum = 0U;
parser.payload_pos = 0U;
}
static uint8_t frame_checksum(uint8_t len, uint8_t type,
const uint8_t *payload, size_t payload_len)
{
uint8_t checksum = CDC_WRAPPER_HEAD1 ^ CDC_WRAPPER_HEAD2 ^ len ^ type;
for (size_t i = 0; i < payload_len; i++) {
checksum ^= payload[i];
}
return checksum;
}
static void submit_tx_frame(uint8_t type, const uint8_t *payload, size_t payload_len)
{
struct usb_cdc_tx_event *event;
size_t frame_len = 2U + 1U + 1U + payload_len + 1U;
event = new_usb_cdc_tx_event(frame_len);
event->dyndata.data[0] = CDC_WRAPPER_HEAD1;
event->dyndata.data[1] = CDC_WRAPPER_HEAD2;
event->dyndata.data[2] = (uint8_t)payload_len;
event->dyndata.data[3] = type;
memcpy(&event->dyndata.data[4], payload, payload_len);
event->dyndata.data[4U + payload_len] =
frame_checksum((uint8_t)payload_len, type, payload, payload_len);
APP_EVENT_SUBMIT(event);
}
static void process_complete_frame(void)
{
uint8_t rsp_type;
uint8_t rsp_payload[CDC_WRAPPER_MAX_PAYLOAD_LEN];
size_t rsp_payload_len = 0U;
int err;
err = protocol_module_process_cdc_packet(parser.type,
parser.payload,
parser.payload_pos,
&rsp_type,
rsp_payload,
sizeof(rsp_payload),
&rsp_payload_len);
if (err == -ENOTSUP) {
LOG_WRN("Ignore unsupported CDC packet type:0x%02x", parser.type);
return;
}
if (err) {
LOG_WRN("Protocol processing failed (%d)", err);
return;
}
LOG_INF("CDC HelloRsp encoded len:%u", (uint32_t)rsp_payload_len);
submit_tx_frame(rsp_type, rsp_payload, rsp_payload_len);
}
static void consume_byte(uint8_t byte)
{
switch (parser.state) {
case FRAME_PARSE_HEAD1:
if (byte == CDC_WRAPPER_HEAD1) {
parser.state = FRAME_PARSE_HEAD2;
}
break;
case FRAME_PARSE_HEAD2:
if (byte == CDC_WRAPPER_HEAD2) {
parser.state = FRAME_PARSE_LEN;
} else if (byte != CDC_WRAPPER_HEAD1) {
parser.state = FRAME_PARSE_HEAD1;
}
break;
case FRAME_PARSE_LEN:
if (byte > CDC_WRAPPER_MAX_PAYLOAD_LEN) {
LOG_WRN("Drop CDC frame with invalid len:%u", byte);
parser_reset();
break;
}
parser.len = byte;
parser.payload_pos = 0U;
parser.state = FRAME_PARSE_TYPE;
break;
case FRAME_PARSE_TYPE:
parser.type = byte;
parser.state = (parser.len == 0U) ? FRAME_PARSE_CHECKSUM :
FRAME_PARSE_PAYLOAD;
break;
case FRAME_PARSE_PAYLOAD:
parser.payload[parser.payload_pos++] = byte;
if (parser.payload_pos >= parser.len) {
parser.state = FRAME_PARSE_CHECKSUM;
}
break;
case FRAME_PARSE_CHECKSUM:
if (byte != frame_checksum(parser.len, parser.type,
parser.payload, parser.payload_pos)) {
LOG_WRN("Drop CDC frame with invalid checksum");
parser_reset();
break;
}
process_complete_frame();
parser_reset();
break;
default:
parser_reset();
break;
}
}
static bool handle_usb_cdc_rx_event(const struct usb_cdc_rx_event *event)
{
if (!running) {
return false;
}
for (size_t i = 0; i < event->dyndata.size; i++) {
consume_byte(event->dyndata.data[i]);
}
return false;
}
static int module_init(void)
{
parser_reset();
return 0;
}
static int module_start(void)
{
if (running) {
return 0;
}
running = true;
return 0;
}
static void module_pause(void)
{
if (!running) {
return;
}
running = false;
parser_reset();
}
static bool app_event_handler(const struct app_event_header *aeh)
{
if (is_usb_cdc_rx_event(aeh)) {
return handle_usb_cdc_rx_event(cast_usb_cdc_rx_event(aeh));
}
if (is_module_state_event(aeh)) {
const struct module_state_event *event = cast_module_state_event(aeh);
if (check_state(event, MODULE_ID(main), MODULE_STATE_READY)) {
int err;
if (!initialized) {
err = module_init();
if (err) {
module_set_state(MODULE_STATE_ERROR);
return false;
}
initialized = true;
}
err = module_start();
if (err) {
module_set_state(MODULE_STATE_ERROR);
} else {
module_set_state(MODULE_STATE_READY);
}
}
return false;
}
if (is_power_down_event(aeh)) {
if (initialized) {
module_pause();
module_set_state(MODULE_STATE_STANDBY);
}
return false;
}
if (is_wake_up_event(aeh)) {
if (initialized) {
int err = module_start();
if (err) {
module_set_state(MODULE_STATE_ERROR);
} else {
module_set_state(MODULE_STATE_READY);
}
}
return false;
}
return false;
}
APP_EVENT_LISTENER(MODULE, app_event_handler);
APP_EVENT_SUBSCRIBE(MODULE, module_state_event);
APP_EVENT_SUBSCRIBE(MODULE, usb_cdc_rx_event);
APP_EVENT_SUBSCRIBE_EARLY(MODULE, power_down_event);
APP_EVENT_SUBSCRIBE(MODULE, wake_up_event);

225
src/display_module.c Normal file
View File

@@ -0,0 +1,225 @@
#include <errno.h>
#include <stdbool.h>
#include <app_event_manager.h>
#define MODULE display_module
#include <caf/events/module_state_event.h>
#include <caf/events/power_event.h>
#include <lvgl_zephyr.h>
#include <zephyr/device.h>
#include <zephyr/drivers/display.h>
#include <zephyr/drivers/led.h>
#include <zephyr/logging/log.h>
#include "bat_state_event.h"
#include "hid_led_event.h"
#include "mode_switch_event.h"
#include "ui/ui_main.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
BUILD_ASSERT(DT_HAS_CHOSEN(zephyr_display), "Missing zephyr,display chosen node");
BUILD_ASSERT(DT_NODE_HAS_STATUS(DT_ALIAS(backlight), okay),
"Missing backlight alias");
static const struct device *const display_dev =
DEVICE_DT_GET(DT_CHOSEN(zephyr_display));
static const struct device *const backlight_dev =
DEVICE_DT_GET(DT_PARENT(DT_ALIAS(backlight)));
static const uint32_t backlight_idx = DT_NODE_CHILD_IDX(DT_ALIAS(backlight));
static struct ui_main_model ui_model = {
.theme_color = LV_COLOR_MAKE(0x4C, 0x9E, 0xF5),
.inactive_border_color = LV_COLOR_MAKE(0x3A, 0x44, 0x52),
.mode = MODE_SWITCH_BLE,
};
static bool initialized;
static bool running;
static bool lvgl_initialized;
static int backlight_set(bool on)
{
if (on) {
return led_on(backlight_dev, backlight_idx);
}
return led_off(backlight_dev, backlight_idx);
}
static int module_init(void)
{
int err;
LOG_INF("Display init on %s", display_dev->name);
if (!device_is_ready(display_dev)) {
LOG_ERR("Display device %s not ready", display_dev->name);
return -ENODEV;
}
if (!device_is_ready(backlight_dev)) {
LOG_ERR("Backlight device %s not ready", backlight_dev->name);
return -ENODEV;
}
err = backlight_set(false);
if (err) {
LOG_ERR("Backlight off failed (%d)", err);
return err;
}
return 0;
}
static int module_start(void)
{
int err;
if (running) {
return 0;
}
if (!lvgl_initialized) {
err = lvgl_init();
if (err) {
LOG_ERR("lvgl_init failed (%d)", err);
return err;
}
lvgl_initialized = true;
lvgl_lock();
ui_main_init(&ui_model, "WH Mini", "Hello World");
lvgl_unlock();
}
err = backlight_set(true);
if (err) {
LOG_ERR("Backlight enable failed (%d)", err);
return err;
}
err = display_blanking_off(display_dev);
if (err) {
LOG_ERR("display_blanking_off failed (%d)", err);
(void)backlight_set(false);
return err;
}
running = true;
LOG_INF("LVGL display started");
return 0;
}
static void module_pause(void)
{
if (!running) {
return;
}
(void)display_blanking_on(display_dev);
(void)backlight_set(false);
running = false;
LOG_INF("LVGL display paused");
}
static void refresh_ui(void)
{
if (!lvgl_initialized) {
return;
}
lvgl_lock();
ui_main_refresh_all(&ui_model, "WH Mini", "Hello World");
lvgl_unlock();
}
static bool app_event_handler(const struct app_event_header *aeh)
{
if (is_bat_state_event(aeh)) {
const struct bat_state_event *event = cast_bat_state_event(aeh);
ui_model.battery_level = event->soc;
ui_model.charging = event->charging;
ui_model.full = event->full;
refresh_ui();
return false;
}
if (is_mode_switch_event(aeh)) {
const struct mode_switch_event *event = cast_mode_switch_event(aeh);
ui_model.mode = event->mode;
refresh_ui();
return false;
}
if (is_hid_led_event(aeh)) {
const struct hid_led_event *event = cast_hid_led_event(aeh);
ui_model.led_mask = event->led_bm;
refresh_ui();
return false;
}
if (is_module_state_event(aeh)) {
const struct module_state_event *event = cast_module_state_event(aeh);
int err;
if (check_state(event, MODULE_ID(main), MODULE_STATE_READY)) {
if (!initialized) {
err = module_init();
if (err) {
module_set_state(MODULE_STATE_ERROR);
return false;
}
initialized = true;
}
err = module_start();
if (err) {
module_set_state(MODULE_STATE_ERROR);
} else {
module_set_state(MODULE_STATE_READY);
}
}
return false;
}
if (is_power_down_event(aeh)) {
if (initialized) {
module_pause();
module_set_state(MODULE_STATE_STANDBY);
}
return false;
}
if (is_wake_up_event(aeh)) {
if (initialized) {
int err = module_start();
if (err) {
module_set_state(MODULE_STATE_ERROR);
} else {
module_set_state(MODULE_STATE_READY);
}
}
return false;
}
return false;
}
APP_EVENT_LISTENER(MODULE, app_event_handler);
APP_EVENT_SUBSCRIBE(MODULE, bat_state_event);
APP_EVENT_SUBSCRIBE(MODULE, hid_led_event);
APP_EVENT_SUBSCRIBE(MODULE, module_state_event);
APP_EVENT_SUBSCRIBE(MODULE, mode_switch_event);
APP_EVENT_SUBSCRIBE_EARLY(MODULE, power_down_event);
APP_EVENT_SUBSCRIBE(MODULE, wake_up_event);

226
src/encoder_module.c Normal file
View File

@@ -0,0 +1,226 @@
#include <stdbool.h>
#include <stdint.h>
#include <app_event_manager.h>
#define MODULE encoder_module
#include <caf/events/module_state_event.h>
#include <caf/events/power_event.h>
#include <zephyr/drivers/sensor.h>
#include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
#include <zephyr/pm/device.h>
#include "encoder_event.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
#define ENCODER_QDEC_NODE DT_ALIAS(qdec0)
#define ENCODER_PULSES_PER_DETENT 4LL
#define ENCODER_DETENT_UDEG (360000000LL / (80LL / ENCODER_PULSES_PER_DETENT))
BUILD_ASSERT(DT_NODE_EXISTS(ENCODER_QDEC_NODE), "Missing qdec0 alias");
static const struct device *const qdec_dev = DEVICE_DT_GET(ENCODER_QDEC_NODE);
static struct k_work encoder_report_work;
static struct sensor_trigger encoder_trigger = {
.type = SENSOR_TRIG_DATA_READY,
.chan = SENSOR_CHAN_ROTATION,
};
static bool initialized;
static bool running;
static int64_t angle_remainder_udeg;
static int64_t sensor_value_to_udeg(const struct sensor_value *value)
{
return ((int64_t)value->val1 * 1000000LL) + value->val2;
}
static void submit_detents(int32_t detents)
{
while (detents != 0) {
struct encoder_event *event = new_encoder_event();
if (detents > INT8_MAX) {
event->detents = INT8_MAX;
detents -= INT8_MAX;
} else if (detents < INT8_MIN) {
event->detents = INT8_MIN;
detents -= INT8_MIN;
} else {
event->detents = (int8_t)detents;
detents = 0;
}
APP_EVENT_SUBMIT(event);
}
}
static void encoder_report_work_handler(struct k_work *work)
{
struct sensor_value rotation;
int64_t total_udeg;
int32_t detents;
int err;
ARG_UNUSED(work);
if (!running) {
return;
}
err = sensor_sample_fetch(qdec_dev);
if (err) {
LOG_WRN("QDEC sample fetch failed (%d)", err);
return;
}
err = sensor_channel_get(qdec_dev, SENSOR_CHAN_ROTATION, &rotation);
if (err) {
LOG_WRN("QDEC channel get failed (%d)", err);
return;
}
total_udeg = angle_remainder_udeg + sensor_value_to_udeg(&rotation);
detents = (int32_t)(total_udeg / ENCODER_DETENT_UDEG);
angle_remainder_udeg = total_udeg - ((int64_t)detents * ENCODER_DETENT_UDEG);
if (detents != 0) {
submit_detents(detents);
}
}
static void encoder_trigger_handler(const struct device *dev,
const struct sensor_trigger *trigger)
{
ARG_UNUSED(dev);
ARG_UNUSED(trigger);
if (!running) {
return;
}
k_work_submit(&encoder_report_work);
}
static int module_init(void)
{
int err;
if (!device_is_ready(qdec_dev)) {
LOG_ERR("QDEC device not ready");
return -ENODEV;
}
k_work_init(&encoder_report_work, encoder_report_work_handler);
angle_remainder_udeg = 0;
err = sensor_trigger_set(qdec_dev, &encoder_trigger, encoder_trigger_handler);
if (err) {
LOG_ERR("Cannot set QDEC trigger (%d)", err);
return err;
}
return 0;
}
static int module_start(void)
{
int err;
if (running) {
return 0;
}
err = pm_device_action_run(qdec_dev, PM_DEVICE_ACTION_RESUME);
if (err && (err != -EALREADY) && (err != -ENOTSUP)) {
LOG_ERR("Cannot resume QDEC device (%d)", err);
return err;
}
angle_remainder_udeg = 0;
running = true;
return 0;
}
static void module_pause(void)
{
int err;
if (!running) {
return;
}
err = pm_device_action_run(qdec_dev, PM_DEVICE_ACTION_SUSPEND);
if (err && (err != -EALREADY) && (err != -ENOTSUP)) {
LOG_WRN("Cannot suspend QDEC device (%d)", err);
}
angle_remainder_udeg = 0;
running = false;
}
static bool app_event_handler(const struct app_event_header *aeh)
{
if (is_module_state_event(aeh)) {
const struct module_state_event *event = cast_module_state_event(aeh);
if (check_state(event, MODULE_ID(main), MODULE_STATE_READY)) {
int err;
if (!initialized) {
err = module_init();
if (err) {
module_set_state(MODULE_STATE_ERROR);
return false;
}
initialized = true;
}
err = module_start();
if (err) {
module_set_state(MODULE_STATE_ERROR);
} else {
module_set_state(MODULE_STATE_READY);
}
}
return false;
}
if (is_power_down_event(aeh)) {
if (initialized) {
module_pause();
module_set_state(MODULE_STATE_STANDBY);
}
return false;
}
if (is_wake_up_event(aeh)) {
if (initialized) {
int err = module_start();
if (err) {
module_set_state(MODULE_STATE_ERROR);
} else {
module_set_state(MODULE_STATE_READY);
}
}
return false;
}
__ASSERT_NO_MSG(false);
return false;
}
APP_EVENT_LISTENER(MODULE, app_event_handler);
APP_EVENT_SUBSCRIBE(MODULE, module_state_event);
APP_EVENT_SUBSCRIBE_EARLY(MODULE, power_down_event);
APP_EVENT_SUBSCRIBE(MODULE, wake_up_event);

View File

@@ -0,0 +1,32 @@
#include "bat_state_event.h"
static void log_bat_state_event(const struct app_event_header *aeh)
{
const struct bat_state_event *event = cast_bat_state_event(aeh);
APP_EVENT_MANAGER_LOG(aeh, "soc:%u charging:%u full:%u",
event->soc, event->charging, event->full);
}
static void profile_bat_state_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
const struct bat_state_event *event = cast_bat_state_event(aeh);
nrf_profiler_log_encode_uint8(buf, event->soc);
nrf_profiler_log_encode_uint8(buf, event->charging);
nrf_profiler_log_encode_uint8(buf, event->full);
}
APP_EVENT_INFO_DEFINE(bat_state_event,
ENCODE(NRF_PROFILER_ARG_U8,
NRF_PROFILER_ARG_U8,
NRF_PROFILER_ARG_U8),
ENCODE("soc", "charging", "full"),
profile_bat_state_event);
APP_EVENT_TYPE_DEFINE(bat_state_event,
log_bat_state_event,
&bat_state_event_info,
APP_EVENT_FLAGS_CREATE(
APP_EVENT_TYPE_FLAGS_INIT_LOG_ENABLE));

View File

@@ -0,0 +1,27 @@
#include "encoder_event.h"
static void log_encoder_event(const struct app_event_header *aeh)
{
const struct encoder_event *event = cast_encoder_event(aeh);
APP_EVENT_MANAGER_LOG(aeh, "detents:%d", event->detents);
}
static void profile_encoder_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
const struct encoder_event *event = cast_encoder_event(aeh);
nrf_profiler_log_encode_int8(buf, event->detents);
}
APP_EVENT_INFO_DEFINE(encoder_event,
ENCODE(NRF_PROFILER_ARG_S8),
ENCODE("detents"),
profile_encoder_event);
APP_EVENT_TYPE_DEFINE(encoder_event,
log_encoder_event,
&encoder_event_info,
APP_EVENT_FLAGS_CREATE(
APP_EVENT_TYPE_FLAGS_INIT_LOG_ENABLE));

View File

@@ -0,0 +1,41 @@
#include "hid_led_event.h"
static const char *transport_name(enum hid_transport transport)
{
switch (transport) {
case HID_TRANSPORT_USB:
return "USB";
case HID_TRANSPORT_BLE:
return "BLE";
default:
return "?";
}
}
static void log_hid_led_event(const struct app_event_header *aeh)
{
const struct hid_led_event *event = cast_hid_led_event(aeh);
APP_EVENT_MANAGER_LOG(aeh, "transport:%s led_bm:0x%02x",
transport_name(event->transport), event->led_bm);
}
static void profile_hid_led_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
const struct hid_led_event *event = cast_hid_led_event(aeh);
nrf_profiler_log_encode_uint8(buf, event->transport);
nrf_profiler_log_encode_uint8(buf, event->led_bm);
}
APP_EVENT_INFO_DEFINE(hid_led_event,
ENCODE(NRF_PROFILER_ARG_U8, NRF_PROFILER_ARG_U8),
ENCODE("transport", "led_bm"),
profile_hid_led_event);
APP_EVENT_TYPE_DEFINE(hid_led_event,
log_hid_led_event,
&hid_led_event_info,
APP_EVENT_FLAGS_CREATE(
APP_EVENT_TYPE_FLAGS_INIT_LOG_ENABLE));

View File

@@ -0,0 +1,61 @@
#include "hid_report_sent_event.h"
static const char *transport_name(enum hid_transport transport)
{
switch (transport) {
case HID_TRANSPORT_USB:
return "USB";
case HID_TRANSPORT_BLE:
return "BLE";
default:
return "?";
}
}
static const char *report_type_name(enum keyboard_report_type report_type)
{
switch (report_type) {
case KEYBOARD_REPORT_TYPE_KEYS:
return "keys";
case KEYBOARD_REPORT_TYPE_CONSUMER:
return "consumer";
default:
return "?";
}
}
static void log_hid_report_sent_event(const struct app_event_header *aeh)
{
const struct hid_report_sent_event *event = cast_hid_report_sent_event(aeh);
APP_EVENT_MANAGER_LOG(aeh, "transport:%s type:%s seq:%u error:%u",
transport_name(event->transport),
report_type_name(event->report_type),
event->sequence,
event->error);
}
static void profile_hid_report_sent_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
const struct hid_report_sent_event *event = cast_hid_report_sent_event(aeh);
nrf_profiler_log_encode_uint8(buf, event->transport);
nrf_profiler_log_encode_uint8(buf, event->report_type);
nrf_profiler_log_encode_uint16(buf, event->sequence);
nrf_profiler_log_encode_uint8(buf, event->error);
}
APP_EVENT_INFO_DEFINE(hid_report_sent_event,
ENCODE(NRF_PROFILER_ARG_U8,
NRF_PROFILER_ARG_U8,
NRF_PROFILER_ARG_U16,
NRF_PROFILER_ARG_U8),
ENCODE("transport", "report_type", "sequence", "error"),
profile_hid_report_sent_event);
APP_EVENT_TYPE_DEFINE(hid_report_sent_event,
log_hid_report_sent_event,
&hid_report_sent_event_info,
APP_EVENT_FLAGS_CREATE(
APP_EVENT_TYPE_FLAGS_INIT_LOG_ENABLE));

View File

@@ -0,0 +1,68 @@
#include "hid_transport_state_event.h"
static const char *transport_name(enum hid_transport transport)
{
switch (transport) {
case HID_TRANSPORT_USB:
return "USB";
case HID_TRANSPORT_BLE:
return "BLE";
default:
return "?";
}
}
static const char *protocol_mode_name(enum keyboard_protocol_mode protocol_mode)
{
switch (protocol_mode) {
case KEYBOARD_PROTOCOL_MODE_BOOT:
return "boot";
case KEYBOARD_PROTOCOL_MODE_REPORT:
return "report";
default:
return "?";
}
}
static void log_hid_transport_state_event(const struct app_event_header *aeh)
{
const struct hid_transport_state_event *event =
cast_hid_transport_state_event(aeh);
APP_EVENT_MANAGER_LOG(aeh,
"transport:%s ready:%u keys_ready:%u consumer_ready:%u protocol:%s",
transport_name(event->transport),
event->ready,
event->keys_ready,
event->consumer_ready,
protocol_mode_name(event->protocol_mode));
}
static void profile_hid_transport_state_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
const struct hid_transport_state_event *event =
cast_hid_transport_state_event(aeh);
nrf_profiler_log_encode_uint8(buf, event->transport);
nrf_profiler_log_encode_uint8(buf, event->ready);
nrf_profiler_log_encode_uint8(buf, event->keys_ready);
nrf_profiler_log_encode_uint8(buf, event->consumer_ready);
nrf_profiler_log_encode_uint8(buf, event->protocol_mode);
}
APP_EVENT_INFO_DEFINE(hid_transport_state_event,
ENCODE(NRF_PROFILER_ARG_U8,
NRF_PROFILER_ARG_U8,
NRF_PROFILER_ARG_U8,
NRF_PROFILER_ARG_U8,
NRF_PROFILER_ARG_U8),
ENCODE("transport", "ready", "keys_ready", "consumer_ready",
"protocol_mode"),
profile_hid_transport_state_event);
APP_EVENT_TYPE_DEFINE(hid_transport_state_event,
log_hid_transport_state_event,
&hid_transport_state_event_info,
APP_EVENT_FLAGS_CREATE(
APP_EVENT_TYPE_FLAGS_INIT_LOG_ENABLE));

View File

@@ -0,0 +1,107 @@
#include <stdio.h>
#include "hid_tx_report_event.h"
#define HID_TX_REPORT_EVENT_LOG_BUF_LEN 192
static const char *transport_name(enum hid_transport transport)
{
switch (transport) {
case HID_TRANSPORT_USB:
return "USB";
case HID_TRANSPORT_BLE:
return "BLE";
default:
return "?";
}
}
static const char *report_type_name(enum keyboard_report_type report_type)
{
switch (report_type) {
case KEYBOARD_REPORT_TYPE_KEYS:
return "keys";
case KEYBOARD_REPORT_TYPE_CONSUMER:
return "consumer";
default:
return "?";
}
}
static const char *protocol_mode_name(enum keyboard_protocol_mode protocol_mode)
{
switch (protocol_mode) {
case KEYBOARD_PROTOCOL_MODE_BOOT:
return "boot";
case KEYBOARD_PROTOCOL_MODE_REPORT:
return "report";
default:
return "?";
}
}
static void log_hid_tx_report_event(const struct app_event_header *aeh)
{
const struct hid_tx_report_event *event = cast_hid_tx_report_event(aeh);
char log_buf[HID_TX_REPORT_EVENT_LOG_BUF_LEN];
int pos;
pos = snprintf(log_buf, sizeof(log_buf),
"transport:%s type:%s protocol:%s seq:%u len:%zu",
transport_name(event->transport),
report_type_name(event->report_type),
protocol_mode_name(event->protocol_mode),
event->sequence,
event->dyndata.size);
if ((pos > 0) && (pos < sizeof(log_buf))) {
for (size_t i = 0; i < event->dyndata.size; i++) {
int tmp = snprintf(&log_buf[pos], sizeof(log_buf) - pos,
" %02x", event->dyndata.data[i]);
if (tmp < 0) {
log_buf[sizeof(log_buf) - 2] = '~';
pos = tmp;
break;
}
pos += tmp;
if (pos >= sizeof(log_buf)) {
break;
}
}
}
if (pos < 0) {
APP_EVENT_MANAGER_LOG(aeh, "log message preparation failure");
return;
}
APP_EVENT_MANAGER_LOG(aeh, "%s", log_buf);
}
static void profile_hid_tx_report_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
const struct hid_tx_report_event *event = cast_hid_tx_report_event(aeh);
nrf_profiler_log_encode_uint8(buf, event->transport);
nrf_profiler_log_encode_uint8(buf, event->report_type);
nrf_profiler_log_encode_uint8(buf, event->protocol_mode);
nrf_profiler_log_encode_uint16(buf, event->sequence);
nrf_profiler_log_encode_uint8(buf, (uint8_t)event->dyndata.size);
}
APP_EVENT_INFO_DEFINE(hid_tx_report_event,
ENCODE(NRF_PROFILER_ARG_U8,
NRF_PROFILER_ARG_U8,
NRF_PROFILER_ARG_U8,
NRF_PROFILER_ARG_U16,
NRF_PROFILER_ARG_U8),
ENCODE("transport", "report_type", "protocol_mode", "sequence", "len"),
profile_hid_tx_report_event);
APP_EVENT_TYPE_DEFINE(hid_tx_report_event,
log_hid_tx_report_event,
&hid_tx_report_event_info,
APP_EVENT_FLAGS_CREATE(
APP_EVENT_TYPE_FLAGS_INIT_LOG_ENABLE));

View File

@@ -0,0 +1,123 @@
#include <stdio.h>
#include "keyboard_hid_report_event.h"
#define KEYBOARD_HID_REPORT_EVENT_LOG_BUF_LEN 192
static const char *mode_name(enum mode_switch_mode mode)
{
switch (mode) {
case MODE_SWITCH_USB:
return "USB";
case MODE_SWITCH_24G:
return "2.4G";
case MODE_SWITCH_BLE:
return "BLE";
default:
return "?";
}
}
static const char *report_type_name(enum keyboard_report_type report_type)
{
switch (report_type) {
case KEYBOARD_REPORT_TYPE_KEYS:
return "keys";
case KEYBOARD_REPORT_TYPE_CONSUMER:
return "consumer";
default:
return "?";
}
}
static const char *protocol_mode_name(enum keyboard_protocol_mode protocol_mode)
{
switch (protocol_mode) {
case KEYBOARD_PROTOCOL_MODE_BOOT:
return "boot";
case KEYBOARD_PROTOCOL_MODE_REPORT:
return "report";
default:
return "?";
}
}
static const char *queue_policy_name(enum hid_queue_policy queue_policy)
{
switch (queue_policy) {
case HID_QUEUE_POLICY_LATEST:
return "latest";
case HID_QUEUE_POLICY_FIFO:
return "fifo";
default:
return "?";
}
}
static void log_keyboard_hid_report_event(const struct app_event_header *aeh)
{
const struct keyboard_hid_report_event *event =
cast_keyboard_hid_report_event(aeh);
char log_buf[KEYBOARD_HID_REPORT_EVENT_LOG_BUF_LEN];
int pos;
pos = snprintf(log_buf, sizeof(log_buf),
"mode:%s type:%s protocol:%s queue:%s len:%zu",
mode_name(event->mode),
report_type_name(event->report_type),
protocol_mode_name(event->protocol_mode),
queue_policy_name(event->queue_policy),
event->dyndata.size);
if ((pos > 0) && (pos < sizeof(log_buf))) {
for (size_t i = 0; i < event->dyndata.size; i++) {
int tmp = snprintf(&log_buf[pos], sizeof(log_buf) - pos,
" %02x", event->dyndata.data[i]);
if (tmp < 0) {
log_buf[sizeof(log_buf) - 2] = '~';
pos = tmp;
break;
}
pos += tmp;
if (pos >= sizeof(log_buf)) {
break;
}
}
}
if (pos < 0) {
APP_EVENT_MANAGER_LOG(aeh, "log message preparation failure");
return;
}
APP_EVENT_MANAGER_LOG(aeh, "%s", log_buf);
}
static void profile_keyboard_hid_report_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
const struct keyboard_hid_report_event *event =
cast_keyboard_hid_report_event(aeh);
nrf_profiler_log_encode_uint8(buf, event->mode);
nrf_profiler_log_encode_uint8(buf, event->report_type);
nrf_profiler_log_encode_uint8(buf, event->protocol_mode);
nrf_profiler_log_encode_uint8(buf, event->queue_policy);
nrf_profiler_log_encode_uint8(buf, (uint8_t)event->dyndata.size);
}
APP_EVENT_INFO_DEFINE(keyboard_hid_report_event,
ENCODE(NRF_PROFILER_ARG_U8,
NRF_PROFILER_ARG_U8,
NRF_PROFILER_ARG_U8,
NRF_PROFILER_ARG_U8,
NRF_PROFILER_ARG_U8),
ENCODE("mode", "report_type", "protocol_mode", "queue_policy", "len"),
profile_keyboard_hid_report_event);
APP_EVENT_TYPE_DEFINE(keyboard_hid_report_event,
log_keyboard_hid_report_event,
&keyboard_hid_report_event_info,
APP_EVENT_FLAGS_CREATE(
APP_EVENT_TYPE_FLAGS_INIT_LOG_ENABLE));

View File

@@ -0,0 +1,45 @@
#include <inttypes.h>
#include "mode_switch_event.h"
static const char *mode_name(enum mode_switch_mode mode)
{
switch (mode) {
case MODE_SWITCH_USB:
return "USB";
case MODE_SWITCH_24G:
return "2.4G";
case MODE_SWITCH_BLE:
return "BLE";
default:
return "?";
}
}
static void log_mode_switch_event(const struct app_event_header *aeh)
{
const struct mode_switch_event *event = cast_mode_switch_event(aeh);
APP_EVENT_MANAGER_LOG(aeh, "mode:%s voltage:%" PRIu16 "mV",
mode_name(event->mode), event->voltage_mv);
}
static void profile_mode_switch_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
const struct mode_switch_event *event = cast_mode_switch_event(aeh);
nrf_profiler_log_encode_uint8(buf, event->mode);
nrf_profiler_log_encode_uint16(buf, event->voltage_mv);
}
APP_EVENT_INFO_DEFINE(mode_switch_event,
ENCODE(NRF_PROFILER_ARG_U8, NRF_PROFILER_ARG_U16),
ENCODE("mode", "voltage_mv"),
profile_mode_switch_event);
APP_EVENT_TYPE_DEFINE(mode_switch_event,
log_mode_switch_event,
&mode_switch_event_info,
APP_EVENT_FLAGS_CREATE(
APP_EVENT_TYPE_FLAGS_INIT_LOG_ENABLE));

View File

@@ -0,0 +1,54 @@
#include "set_protocol_event.h"
static const char *transport_name(enum hid_transport transport)
{
switch (transport) {
case HID_TRANSPORT_USB:
return "USB";
case HID_TRANSPORT_BLE:
return "BLE";
default:
return "?";
}
}
static const char *protocol_mode_name(enum keyboard_protocol_mode protocol_mode)
{
switch (protocol_mode) {
case KEYBOARD_PROTOCOL_MODE_BOOT:
return "boot";
case KEYBOARD_PROTOCOL_MODE_REPORT:
return "report";
default:
return "?";
}
}
static void log_set_protocol_event(const struct app_event_header *aeh)
{
const struct set_protocol_event *event = cast_set_protocol_event(aeh);
APP_EVENT_MANAGER_LOG(aeh, "transport:%s protocol:%s",
transport_name(event->transport),
protocol_mode_name(event->protocol_mode));
}
static void profile_set_protocol_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
const struct set_protocol_event *event = cast_set_protocol_event(aeh);
nrf_profiler_log_encode_uint8(buf, event->transport);
nrf_profiler_log_encode_uint8(buf, event->protocol_mode);
}
APP_EVENT_INFO_DEFINE(set_protocol_event,
ENCODE(NRF_PROFILER_ARG_U8, NRF_PROFILER_ARG_U8),
ENCODE("transport", "protocol_mode"),
profile_set_protocol_event);
APP_EVENT_TYPE_DEFINE(set_protocol_event,
log_set_protocol_event,
&set_protocol_event_info,
APP_EVENT_FLAGS_CREATE(
APP_EVENT_TYPE_FLAGS_INIT_LOG_ENABLE));

View File

@@ -0,0 +1,73 @@
#include <ctype.h>
#include <stdio.h>
#include "usb_cdc_rx_event.h"
#define USB_CDC_RX_EVENT_LOG_BUF_LEN 384
static void log_usb_cdc_rx_event(const struct app_event_header *aeh)
{
const struct usb_cdc_rx_event *event = cast_usb_cdc_rx_event(aeh);
char log_buf[USB_CDC_RX_EVENT_LOG_BUF_LEN];
int pos;
pos = snprintf(log_buf, sizeof(log_buf), "len:%zu ascii:\"",
event->dyndata.size);
if ((pos < 0) || (pos >= sizeof(log_buf))) {
APP_EVENT_MANAGER_LOG(aeh, "log message preparation failure");
return;
}
for (size_t i = 0; i < event->dyndata.size; i++) {
int tmp = snprintf(&log_buf[pos], sizeof(log_buf) - pos, "%c",
isprint(event->dyndata.data[i]) ?
event->dyndata.data[i] : '.');
if ((tmp < 0) || ((pos + tmp) >= sizeof(log_buf))) {
APP_EVENT_MANAGER_LOG(aeh, "len:%zu ascii:\"...\"",
event->dyndata.size);
return;
}
pos += tmp;
}
pos += snprintf(&log_buf[pos], sizeof(log_buf) - pos, "\" hex:");
if ((pos < 0) || (pos >= sizeof(log_buf))) {
APP_EVENT_MANAGER_LOG(aeh, "len:%zu ascii:\"...\"",
event->dyndata.size);
return;
}
for (size_t i = 0; i < event->dyndata.size; i++) {
int tmp = snprintf(&log_buf[pos], sizeof(log_buf) - pos, " %02x",
event->dyndata.data[i]);
if ((tmp < 0) || ((pos + tmp) >= sizeof(log_buf))) {
break;
}
pos += tmp;
}
APP_EVENT_MANAGER_LOG(aeh, "%s", log_buf);
}
static void profile_usb_cdc_rx_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
const struct usb_cdc_rx_event *event = cast_usb_cdc_rx_event(aeh);
nrf_profiler_log_encode_uint8(buf, (uint8_t)event->dyndata.size);
}
APP_EVENT_INFO_DEFINE(usb_cdc_rx_event,
ENCODE(NRF_PROFILER_ARG_U8),
ENCODE("len"),
profile_usb_cdc_rx_event);
APP_EVENT_TYPE_DEFINE(usb_cdc_rx_event,
log_usb_cdc_rx_event,
&usb_cdc_rx_event_info,
APP_EVENT_FLAGS_CREATE(
APP_EVENT_TYPE_FLAGS_INIT_LOG_ENABLE));

View File

@@ -0,0 +1,62 @@
#include <ctype.h>
#include <stdio.h>
#include "usb_cdc_tx_event.h"
#define USB_CDC_TX_EVENT_LOG_BUF_LEN 256
static void log_usb_cdc_tx_event(const struct app_event_header *aeh)
{
const struct usb_cdc_tx_event *event = cast_usb_cdc_tx_event(aeh);
char log_buf[USB_CDC_TX_EVENT_LOG_BUF_LEN];
int pos;
pos = snprintf(log_buf, sizeof(log_buf), "len:%zu ascii:\"",
event->dyndata.size);
if ((pos < 0) || (pos >= sizeof(log_buf))) {
APP_EVENT_MANAGER_LOG(aeh, "log message preparation failure");
return;
}
for (size_t i = 0; i < event->dyndata.size; i++) {
int tmp = snprintf(&log_buf[pos], sizeof(log_buf) - pos, "%c",
isprint(event->dyndata.data[i]) ?
event->dyndata.data[i] : '.');
if ((tmp < 0) || ((pos + tmp) >= sizeof(log_buf))) {
APP_EVENT_MANAGER_LOG(aeh, "len:%zu ascii:\"...\"",
event->dyndata.size);
return;
}
pos += tmp;
}
pos += snprintf(&log_buf[pos], sizeof(log_buf) - pos, "\"");
if ((pos < 0) || (pos >= sizeof(log_buf))) {
APP_EVENT_MANAGER_LOG(aeh, "len:%zu ascii:\"...\"",
event->dyndata.size);
return;
}
APP_EVENT_MANAGER_LOG(aeh, "%s", log_buf);
}
static void profile_usb_cdc_tx_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
const struct usb_cdc_tx_event *event = cast_usb_cdc_tx_event(aeh);
nrf_profiler_log_encode_uint8(buf, (uint8_t)event->dyndata.size);
}
APP_EVENT_INFO_DEFINE(usb_cdc_tx_event,
ENCODE(NRF_PROFILER_ARG_U8),
ENCODE("len"),
profile_usb_cdc_tx_event);
APP_EVENT_TYPE_DEFINE(usb_cdc_tx_event,
log_usb_cdc_tx_event,
&usb_cdc_tx_event_info,
APP_EVENT_FLAGS_CREATE(
APP_EVENT_TYPE_FLAGS_INIT_LOG_ENABLE));

View File

@@ -0,0 +1,46 @@
#include "usb_device_state_event.h"
static const char *usb_device_state_name(enum usb_device_state state)
{
switch (state) {
case USB_DEVICE_STATE_DISCONNECTED:
return "disconnected";
case USB_DEVICE_STATE_POWERED:
return "powered";
case USB_DEVICE_STATE_ACTIVE:
return "active";
case USB_DEVICE_STATE_SUSPENDED:
return "suspended";
default:
return "?";
}
}
static void log_usb_device_state_event(const struct app_event_header *aeh)
{
const struct usb_device_state_event *event =
cast_usb_device_state_event(aeh);
APP_EVENT_MANAGER_LOG(aeh, "state:%s",
usb_device_state_name(event->state));
}
static void profile_usb_device_state_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
const struct usb_device_state_event *event =
cast_usb_device_state_event(aeh);
nrf_profiler_log_encode_uint8(buf, event->state);
}
APP_EVENT_INFO_DEFINE(usb_device_state_event,
ENCODE(NRF_PROFILER_ARG_U8),
ENCODE("state"),
profile_usb_device_state_event);
APP_EVENT_TYPE_DEFINE(usb_device_state_event,
log_usb_device_state_event,
&usb_device_state_event_info,
APP_EVENT_FLAGS_CREATE(
APP_EVENT_TYPE_FLAGS_INIT_LOG_ENABLE));

View File

@@ -0,0 +1,42 @@
#include "usb_function_ready_event.h"
static const char *usb_function_name(uint8_t function_mask)
{
switch (function_mask) {
case USB_FUNCTION_HID:
return "hid";
case USB_FUNCTION_CDC_ACM:
return "cdc_acm";
default:
return "?";
}
}
static void log_usb_function_ready_event(const struct app_event_header *aeh)
{
const struct usb_function_ready_event *event =
cast_usb_function_ready_event(aeh);
APP_EVENT_MANAGER_LOG(aeh, "function:%s",
usb_function_name(event->function_mask));
}
static void profile_usb_function_ready_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
const struct usb_function_ready_event *event =
cast_usb_function_ready_event(aeh);
nrf_profiler_log_encode_uint8(buf, event->function_mask);
}
APP_EVENT_INFO_DEFINE(usb_function_ready_event,
ENCODE(NRF_PROFILER_ARG_U8),
ENCODE("function_mask"),
profile_usb_function_ready_event);
APP_EVENT_TYPE_DEFINE(usb_function_ready_event,
log_usb_function_ready_event,
&usb_function_ready_event_info,
APP_EVENT_FLAGS_CREATE(
APP_EVENT_TYPE_FLAGS_INIT_LOG_ENABLE));

View File

@@ -0,0 +1,24 @@
#include "usb_prepare_event.h"
static void log_usb_prepare_event(const struct app_event_header *aeh)
{
APP_EVENT_MANAGER_LOG(aeh, "prepare");
}
static void profile_usb_prepare_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
ARG_UNUSED(buf);
ARG_UNUSED(aeh);
}
APP_EVENT_INFO_DEFINE(usb_prepare_event,
ENCODE(),
ENCODE(),
profile_usb_prepare_event);
APP_EVENT_TYPE_DEFINE(usb_prepare_event,
log_usb_prepare_event,
&usb_prepare_event_info,
APP_EVENT_FLAGS_CREATE(
APP_EVENT_TYPE_FLAGS_INIT_LOG_ENABLE));

468
src/hid_flowctrl_module.c Normal file
View File

@@ -0,0 +1,468 @@
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <app_event_manager.h>
#define MODULE hid_flowctrl_module
#include <caf/events/module_state_event.h>
#include <caf/events/power_event.h>
#include <zephyr/logging/log.h>
#include "hid_report_sent_event.h"
#include "hid_transport_state_event.h"
#include "hid_tx_report_event.h"
#include "keyboard_core.h"
#include "keyboard_hid_report_event.h"
#include "mode_switch_event.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
#define HID_FLOWCTRL_FIFO_DEPTH 32U
#define HID_FLOWCTRL_REPORT_DATA_MAX KEYBOARD_NKRO_REPORT_SIZE
struct pending_report {
bool valid;
enum keyboard_report_type report_type;
enum keyboard_protocol_mode protocol_mode;
size_t size;
uint8_t data[HID_FLOWCTRL_REPORT_DATA_MAX];
};
struct queued_report {
enum keyboard_report_type report_type;
enum keyboard_protocol_mode protocol_mode;
size_t size;
uint8_t data[HID_FLOWCTRL_REPORT_DATA_MAX];
};
struct hid_transport_state_data {
bool ready;
bool keys_ready;
bool consumer_ready;
enum keyboard_protocol_mode protocol_mode;
};
struct in_flight_report {
bool active;
enum hid_transport transport;
enum keyboard_report_type report_type;
uint16_t sequence;
};
static struct hid_transport_state_data transport_state[HID_TRANSPORT_COUNT] = {
[HID_TRANSPORT_USB] = {
.protocol_mode = KEYBOARD_PROTOCOL_MODE_REPORT,
},
[HID_TRANSPORT_BLE] = {
.protocol_mode = KEYBOARD_PROTOCOL_MODE_REPORT,
},
};
static struct pending_report pending_keys;
static struct pending_report pending_consumer_latest;
static struct queued_report consumer_fifo[HID_FLOWCTRL_FIFO_DEPTH];
static uint8_t consumer_fifo_head;
static uint8_t consumer_fifo_tail;
static uint8_t consumer_fifo_count;
static struct in_flight_report in_flight;
static enum mode_switch_mode current_mode;
static uint16_t next_sequence;
static bool initialized;
static bool running;
static bool mode_to_transport(enum mode_switch_mode mode, enum hid_transport *transport)
{
switch (mode) {
case MODE_SWITCH_USB:
*transport = HID_TRANSPORT_USB;
return true;
case MODE_SWITCH_BLE:
*transport = HID_TRANSPORT_BLE;
return true;
default:
return false;
}
}
static void clear_pending_reports(void)
{
memset(&pending_keys, 0, sizeof(pending_keys));
memset(&pending_consumer_latest, 0, sizeof(pending_consumer_latest));
consumer_fifo_head = 0U;
consumer_fifo_tail = 0U;
consumer_fifo_count = 0U;
memset(&in_flight, 0, sizeof(in_flight));
}
static void consumer_fifo_push(enum keyboard_report_type report_type,
enum keyboard_protocol_mode protocol_mode,
const uint8_t *data, size_t size)
{
if (consumer_fifo_count == HID_FLOWCTRL_FIFO_DEPTH) {
LOG_WRN("Consumer FIFO full, dropping oldest pulse");
consumer_fifo_head = (consumer_fifo_head + 1U) % HID_FLOWCTRL_FIFO_DEPTH;
consumer_fifo_count--;
}
struct queued_report *entry = &consumer_fifo[consumer_fifo_tail];
entry->report_type = report_type;
entry->protocol_mode = protocol_mode;
entry->size = size;
memcpy(entry->data, data, size);
consumer_fifo_tail = (consumer_fifo_tail + 1U) % HID_FLOWCTRL_FIFO_DEPTH;
consumer_fifo_count++;
}
static bool consumer_fifo_pop(struct queued_report *entry)
{
if (consumer_fifo_count == 0U) {
return false;
}
*entry = consumer_fifo[consumer_fifo_head];
consumer_fifo_head = (consumer_fifo_head + 1U) % HID_FLOWCTRL_FIFO_DEPTH;
consumer_fifo_count--;
return true;
}
static bool transport_can_send_report(enum keyboard_report_type report_type)
{
enum hid_transport transport;
struct hid_transport_state_data *state;
if (!mode_to_transport(current_mode, &transport) || in_flight.active) {
return false;
}
state = &transport_state[transport];
if (!state->ready) {
return false;
}
if (report_type == KEYBOARD_REPORT_TYPE_KEYS) {
return state->keys_ready;
}
return state->consumer_ready;
}
static void submit_hid_tx_report_event(enum hid_transport transport,
enum keyboard_report_type report_type,
enum keyboard_protocol_mode protocol_mode,
const uint8_t *data, size_t size)
{
struct hid_tx_report_event *event = new_hid_tx_report_event(size);
event->transport = transport;
event->report_type = report_type;
event->protocol_mode = protocol_mode;
event->sequence = next_sequence++;
memcpy(event->dyndata.data, data, size);
in_flight.active = true;
in_flight.transport = transport;
in_flight.report_type = report_type;
in_flight.sequence = event->sequence;
APP_EVENT_SUBMIT(event);
}
static void try_send_next(void)
{
struct queued_report queued;
enum hid_transport transport;
struct hid_transport_state_data *state;
if (!running || in_flight.active || !mode_to_transport(current_mode, &transport)) {
return;
}
state = &transport_state[transport];
if (!state->ready) {
return;
}
if (pending_keys.valid && transport_can_send_report(KEYBOARD_REPORT_TYPE_KEYS)) {
if (pending_keys.protocol_mode != state->protocol_mode) {
LOG_WRN("Drop stale keys report after protocol change");
pending_keys.valid = false;
} else {
submit_hid_tx_report_event(transport,
pending_keys.report_type,
pending_keys.protocol_mode,
pending_keys.data,
pending_keys.size);
pending_keys.valid = false;
return;
}
}
if ((consumer_fifo_count > 0U) &&
transport_can_send_report(KEYBOARD_REPORT_TYPE_CONSUMER) &&
consumer_fifo_pop(&queued)) {
if (queued.protocol_mode != state->protocol_mode) {
LOG_WRN("Drop stale consumer report after protocol change");
} else {
submit_hid_tx_report_event(transport,
queued.report_type,
queued.protocol_mode,
queued.data,
queued.size);
return;
}
}
if (pending_consumer_latest.valid &&
transport_can_send_report(KEYBOARD_REPORT_TYPE_CONSUMER)) {
if (pending_consumer_latest.protocol_mode != state->protocol_mode) {
LOG_WRN("Drop stale latest consumer report after protocol change");
pending_consumer_latest.valid = false;
} else {
submit_hid_tx_report_event(transport,
pending_consumer_latest.report_type,
pending_consumer_latest.protocol_mode,
pending_consumer_latest.data,
pending_consumer_latest.size);
pending_consumer_latest.valid = false;
}
}
}
static bool handle_keyboard_hid_report_event(const struct keyboard_hid_report_event *event)
{
if (!running ||
((event->mode != MODE_SWITCH_USB) && (event->mode != MODE_SWITCH_BLE))) {
return false;
}
if (event->queue_policy == HID_QUEUE_POLICY_FIFO) {
consumer_fifo_push(event->report_type,
event->protocol_mode,
event->dyndata.data,
event->dyndata.size);
} else if (event->report_type == KEYBOARD_REPORT_TYPE_KEYS) {
pending_keys.valid = true;
pending_keys.report_type = event->report_type;
pending_keys.protocol_mode = event->protocol_mode;
pending_keys.size = event->dyndata.size;
memcpy(pending_keys.data, event->dyndata.data, event->dyndata.size);
} else {
pending_consumer_latest.valid = true;
pending_consumer_latest.report_type = event->report_type;
pending_consumer_latest.protocol_mode = event->protocol_mode;
pending_consumer_latest.size = event->dyndata.size;
memcpy(pending_consumer_latest.data, event->dyndata.data,
event->dyndata.size);
}
try_send_next();
return false;
}
static bool handle_hid_transport_state_event(const struct hid_transport_state_event *event)
{
enum hid_transport active_transport;
struct hid_transport_state_data *state;
if (event->transport >= HID_TRANSPORT_COUNT) {
return false;
}
state = &transport_state[event->transport];
state->ready = event->ready;
state->keys_ready = event->keys_ready;
state->consumer_ready = event->consumer_ready;
if (state->protocol_mode != event->protocol_mode) {
state->protocol_mode = event->protocol_mode;
if (mode_to_transport(current_mode, &active_transport) &&
(active_transport == event->transport)) {
pending_keys.valid = false;
pending_consumer_latest.valid = false;
consumer_fifo_head = 0U;
consumer_fifo_tail = 0U;
consumer_fifo_count = 0U;
}
}
if (!state->ready &&
mode_to_transport(current_mode, &active_transport) &&
(active_transport == event->transport)) {
consumer_fifo_head = 0U;
consumer_fifo_tail = 0U;
consumer_fifo_count = 0U;
in_flight.active = false;
}
try_send_next();
return false;
}
static bool handle_hid_report_sent_event(const struct hid_report_sent_event *event)
{
if (!in_flight.active || (event->transport != in_flight.transport)) {
return false;
}
if (event->sequence != in_flight.sequence) {
LOG_WRN("Unexpected HID sent sequence %u (expected %u)",
event->sequence, in_flight.sequence);
return false;
}
in_flight.active = false;
if (event->error) {
LOG_WRN("HID report send failed for seq %u", event->sequence);
}
try_send_next();
return false;
}
static bool handle_mode_switch_event(const struct mode_switch_event *event)
{
bool mode_changed = (current_mode != event->mode);
current_mode = event->mode;
if (mode_changed || ((current_mode != MODE_SWITCH_USB) &&
(current_mode != MODE_SWITCH_BLE))) {
clear_pending_reports();
}
try_send_next();
return false;
}
static int module_init(void)
{
clear_pending_reports();
current_mode = MODE_SWITCH_USB;
transport_state[HID_TRANSPORT_USB].ready = false;
transport_state[HID_TRANSPORT_USB].keys_ready = false;
transport_state[HID_TRANSPORT_USB].consumer_ready = false;
transport_state[HID_TRANSPORT_USB].protocol_mode =
KEYBOARD_PROTOCOL_MODE_REPORT;
transport_state[HID_TRANSPORT_BLE].ready = false;
transport_state[HID_TRANSPORT_BLE].keys_ready = false;
transport_state[HID_TRANSPORT_BLE].consumer_ready = false;
transport_state[HID_TRANSPORT_BLE].protocol_mode =
KEYBOARD_PROTOCOL_MODE_REPORT;
next_sequence = 1U;
return 0;
}
static int module_start(void)
{
if (running) {
return 0;
}
running = true;
try_send_next();
return 0;
}
static void module_pause(void)
{
if (!running) {
return;
}
clear_pending_reports();
running = false;
}
static bool app_event_handler(const struct app_event_header *aeh)
{
if (is_keyboard_hid_report_event(aeh)) {
return handle_keyboard_hid_report_event(cast_keyboard_hid_report_event(aeh));
}
if (is_hid_transport_state_event(aeh)) {
return handle_hid_transport_state_event(cast_hid_transport_state_event(aeh));
}
if (is_hid_report_sent_event(aeh)) {
return handle_hid_report_sent_event(cast_hid_report_sent_event(aeh));
}
if (is_mode_switch_event(aeh)) {
return handle_mode_switch_event(cast_mode_switch_event(aeh));
}
if (is_module_state_event(aeh)) {
const struct module_state_event *event = cast_module_state_event(aeh);
if (check_state(event, MODULE_ID(main), MODULE_STATE_READY)) {
int err;
if (!initialized) {
err = module_init();
if (err) {
module_set_state(MODULE_STATE_ERROR);
return false;
}
initialized = true;
}
err = module_start();
if (err) {
module_set_state(MODULE_STATE_ERROR);
} else {
module_set_state(MODULE_STATE_READY);
}
}
return false;
}
if (is_power_down_event(aeh)) {
if (initialized) {
module_pause();
module_set_state(MODULE_STATE_STANDBY);
}
return false;
}
if (is_wake_up_event(aeh)) {
if (initialized) {
int err = module_start();
if (err) {
module_set_state(MODULE_STATE_ERROR);
} else {
module_set_state(MODULE_STATE_READY);
}
}
return false;
}
__ASSERT_NO_MSG(false);
return false;
}
APP_EVENT_LISTENER(MODULE, app_event_handler);
APP_EVENT_SUBSCRIBE(MODULE, keyboard_hid_report_event);
APP_EVENT_SUBSCRIBE(MODULE, hid_transport_state_event);
APP_EVENT_SUBSCRIBE(MODULE, hid_report_sent_event);
APP_EVENT_SUBSCRIBE(MODULE, mode_switch_event);
APP_EVENT_SUBSCRIBE(MODULE, module_state_event);
APP_EVENT_SUBSCRIBE_EARLY(MODULE, power_down_event);
APP_EVENT_SUBSCRIBE(MODULE, wake_up_event);

630
src/keyboard_core_module.c Normal file
View File

@@ -0,0 +1,630 @@
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <app_event_manager.h>
#define MODULE keyboard_core_module
#include <caf/events/button_event.h>
#include <caf/events/module_state_event.h>
#include <caf/events/power_event.h>
#include <caf/key_id.h>
#include <zephyr/logging/log.h>
#include <zephyr/sys/byteorder.h>
#include <zephyr/sys/util.h>
#include "encoder_event.h"
#include "keyboard_core.h"
#include "keyboard_hid_report_event.h"
#include "mode_switch_event.h"
#include "set_protocol_event.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
#define KEYBOARD_USAGE_FIRST_MODIFIER 0xE0U
#define KEYBOARD_USAGE_LAST_MODIFIER 0xE7U
#define KEYBOARD_USAGE_ERROR_ROLLOVER 0x01U
#define KEYBOARD_BOOT_RESERVED_BYTE 0x00U
enum key_usage_type {
KEY_USAGE_TYPE_KEYBOARD,
KEY_USAGE_TYPE_CONSUMER,
};
struct keymap_entry {
uint16_t key_id;
uint8_t usage_type;
uint16_t usage_id;
};
struct keyboard_state {
uint8_t modifiers;
uint8_t keys_bitmap[KEYBOARD_NKRO_BITMAP_BYTES];
uint32_t consumer_bits;
};
struct keyboard_reports_cache {
uint8_t boot_report[KEYBOARD_BOOT_REPORT_SIZE];
uint8_t nkro_report[KEYBOARD_NKRO_REPORT_SIZE];
uint8_t consumer_report[KEYBOARD_CONSUMER_REPORT_SIZE];
bool boot_valid;
bool nkro_valid;
bool consumer_valid;
};
static const struct keymap_entry keymap[] = {
{ KEY_ID(0, 1), KEY_USAGE_TYPE_KEYBOARD, 0x0053 }, /* num lock */
{ KEY_ID(0, 2), KEY_USAGE_TYPE_KEYBOARD, 0x005F }, /* keypad 7 */
{ KEY_ID(0, 3), KEY_USAGE_TYPE_KEYBOARD, 0x005C }, /* keypad 4 */
{ KEY_ID(0, 4), KEY_USAGE_TYPE_KEYBOARD, 0x0059 }, /* keypad 1 */
{ KEY_ID(0, 5), KEY_USAGE_TYPE_KEYBOARD, 0x0062 }, /* keypad 0 */
{ KEY_ID(1, 1), KEY_USAGE_TYPE_KEYBOARD, 0x0054 }, /* keypad / */
{ KEY_ID(1, 2), KEY_USAGE_TYPE_KEYBOARD, 0x0060 }, /* keypad 8 */
{ KEY_ID(1, 3), KEY_USAGE_TYPE_KEYBOARD, 0x005D }, /* keypad 5 */
{ KEY_ID(1, 4), KEY_USAGE_TYPE_KEYBOARD, 0x005A }, /* keypad 2 */
{ KEY_ID(1, 5), KEY_USAGE_TYPE_KEYBOARD, 0x0063 }, /* keypad . */
{ KEY_ID(2, 1), KEY_USAGE_TYPE_KEYBOARD, 0x0055 }, /* keypad * */
{ KEY_ID(2, 2), KEY_USAGE_TYPE_KEYBOARD, 0x0061 }, /* keypad 9 */
{ KEY_ID(2, 3), KEY_USAGE_TYPE_KEYBOARD, 0x005E }, /* keypad 6 */
{ KEY_ID(2, 4), KEY_USAGE_TYPE_KEYBOARD, 0x005B }, /* keypad 3 */
{ KEY_ID(3, 0), KEY_USAGE_TYPE_CONSUMER, KEYBOARD_CONSUMER_CTRL_MUTE },
{ KEY_ID(3, 1), KEY_USAGE_TYPE_KEYBOARD, 0x0056 }, /* keypad - */
{ KEY_ID(3, 3), KEY_USAGE_TYPE_KEYBOARD, 0x0057 }, /* keypad + */
{ KEY_ID(3, 5), KEY_USAGE_TYPE_KEYBOARD, 0x0058 }, /* keypad enter */
};
static const uint16_t consumer_usage_map[KEYBOARD_CONSUMER_CTRL_COUNT] = {
[KEYBOARD_CONSUMER_CTRL_MUTE] = 0x00E2,
[KEYBOARD_CONSUMER_CTRL_VOLUME_UP] = 0x00E9,
[KEYBOARD_CONSUMER_CTRL_VOLUME_DOWN] = 0x00EA,
[KEYBOARD_CONSUMER_CTRL_PLAY_PAUSE] = 0x00CD,
[KEYBOARD_CONSUMER_CTRL_NEXT_TRACK] = 0x00B5,
[KEYBOARD_CONSUMER_CTRL_PREV_TRACK] = 0x00B6,
};
static struct keyboard_state keyboard_state;
static struct keyboard_reports_cache reports_cache;
static enum keyboard_protocol_mode transport_protocol_modes[HID_TRANSPORT_COUNT] = {
[HID_TRANSPORT_USB] = KEYBOARD_PROTOCOL_MODE_REPORT,
[HID_TRANSPORT_BLE] = KEYBOARD_PROTOCOL_MODE_REPORT,
};
static enum mode_switch_mode current_mode;
static bool initialized;
static bool running;
static bool mode_valid;
static bool mode_to_transport(enum mode_switch_mode mode, enum hid_transport *transport)
{
switch (mode) {
case MODE_SWITCH_USB:
*transport = HID_TRANSPORT_USB;
return true;
case MODE_SWITCH_BLE:
*transport = HID_TRANSPORT_BLE;
return true;
default:
return false;
}
}
static enum keyboard_protocol_mode active_protocol_mode_get(void)
{
enum hid_transport transport;
if (mode_valid && mode_to_transport(current_mode, &transport)) {
return transport_protocol_modes[transport];
}
return KEYBOARD_PROTOCOL_MODE_REPORT;
}
static const struct keymap_entry *keymap_get(uint16_t key_id)
{
size_t left = 0;
size_t right = ARRAY_SIZE(keymap);
while (left < right) {
size_t mid = left + ((right - left) / 2U);
if (keymap[mid].key_id == key_id) {
return &keymap[mid];
}
if (keymap[mid].key_id < key_id) {
left = mid + 1U;
} else {
right = mid;
}
}
return NULL;
}
static bool usage_is_modifier(uint16_t usage_id)
{
return IN_RANGE(usage_id, KEYBOARD_USAGE_FIRST_MODIFIER,
KEYBOARD_USAGE_LAST_MODIFIER);
}
static bool keyboard_key_update(uint16_t usage_id, bool pressed)
{
if (usage_is_modifier(usage_id)) {
uint8_t new_modifiers = keyboard_state.modifiers;
WRITE_BIT(new_modifiers, usage_id - KEYBOARD_USAGE_FIRST_MODIFIER, pressed);
if (new_modifiers == keyboard_state.modifiers) {
return false;
}
keyboard_state.modifiers = new_modifiers;
return true;
}
if (usage_id > KEYBOARD_NKRO_USAGE_MAX) {
LOG_WRN("Unsupported keyboard usage 0x%04x", usage_id);
return false;
}
uint8_t byte_idx = usage_id / 8U;
uint8_t bit_idx = usage_id % 8U;
bool was_pressed = (keyboard_state.keys_bitmap[byte_idx] & BIT(bit_idx)) != 0U;
if (was_pressed == pressed) {
return false;
}
WRITE_BIT(keyboard_state.keys_bitmap[byte_idx], bit_idx, pressed);
return true;
}
static bool consumer_key_update(uint16_t consumer_id, bool pressed)
{
if (consumer_id >= KEYBOARD_CONSUMER_CTRL_COUNT) {
LOG_WRN("Unsupported consumer id %u", consumer_id);
return false;
}
bool was_pressed = (keyboard_state.consumer_bits & BIT(consumer_id)) != 0U;
if (was_pressed == pressed) {
return false;
}
WRITE_BIT(keyboard_state.consumer_bits, consumer_id, pressed);
return true;
}
static void keyboard_state_clear(void)
{
memset(&keyboard_state, 0, sizeof(keyboard_state));
}
static void reports_cache_invalidate(void)
{
reports_cache.boot_valid = false;
reports_cache.nkro_valid = false;
reports_cache.consumer_valid = false;
}
static void build_boot_report(uint8_t report[KEYBOARD_BOOT_REPORT_SIZE])
{
size_t key_count = 0;
memset(report, 0, KEYBOARD_BOOT_REPORT_SIZE);
report[0] = keyboard_state.modifiers;
report[1] = KEYBOARD_BOOT_RESERVED_BYTE;
for (uint16_t usage_id = 0; usage_id <= KEYBOARD_NKRO_USAGE_MAX; usage_id++) {
uint8_t byte_idx = usage_id / 8U;
uint8_t bit_idx = usage_id % 8U;
if ((keyboard_state.keys_bitmap[byte_idx] & BIT(bit_idx)) == 0U) {
continue;
}
if (key_count == (KEYBOARD_BOOT_REPORT_SIZE - 2U)) {
memset(&report[2], KEYBOARD_USAGE_ERROR_ROLLOVER,
KEYBOARD_BOOT_REPORT_SIZE - 2U);
return;
}
report[2U + key_count] = (uint8_t)usage_id;
key_count++;
}
}
static void build_nkro_report(uint8_t report[KEYBOARD_NKRO_REPORT_SIZE])
{
report[0] = keyboard_state.modifiers;
memcpy(&report[1], keyboard_state.keys_bitmap, KEYBOARD_NKRO_BITMAP_BYTES);
}
static uint16_t active_consumer_usage_get(void)
{
for (uint8_t consumer_id = 0; consumer_id < KEYBOARD_CONSUMER_CTRL_COUNT; consumer_id++) {
if ((keyboard_state.consumer_bits & BIT(consumer_id)) != 0U) {
return consumer_usage_map[consumer_id];
}
}
return 0U;
}
static void build_consumer_report(uint8_t report[KEYBOARD_CONSUMER_REPORT_SIZE])
{
sys_put_le16(active_consumer_usage_get(), report);
}
static void submit_keyboard_report_event(enum keyboard_report_type report_type,
enum hid_queue_policy queue_policy,
const uint8_t *data, size_t size)
{
struct keyboard_hid_report_event *event =
new_keyboard_hid_report_event(size);
enum keyboard_protocol_mode protocol_mode = active_protocol_mode_get();
event->mode = current_mode;
event->report_type = report_type;
event->protocol_mode = protocol_mode;
event->queue_policy = queue_policy;
memcpy(event->dyndata.data, data, size);
APP_EVENT_SUBMIT(event);
}
static void submit_consumer_fifo_frame(uint16_t usage_id)
{
uint8_t report_buf[KEYBOARD_CONSUMER_REPORT_SIZE];
enum keyboard_protocol_mode protocol_mode = active_protocol_mode_get();
if (!running || !mode_valid ||
(protocol_mode == KEYBOARD_PROTOCOL_MODE_BOOT)) {
return;
}
sys_put_le16(usage_id, report_buf);
submit_keyboard_report_event(KEYBOARD_REPORT_TYPE_CONSUMER,
HID_QUEUE_POLICY_FIFO,
report_buf,
KEYBOARD_CONSUMER_REPORT_SIZE);
}
static void submit_consumer_pulse_frames(enum keyboard_consumer_control control_id,
uint8_t pulse_count)
{
uint16_t usage_id;
if (active_protocol_mode_get() == KEYBOARD_PROTOCOL_MODE_BOOT) {
return;
}
if (control_id >= KEYBOARD_CONSUMER_CTRL_COUNT) {
LOG_WRN("Unsupported consumer control id %u", control_id);
return;
}
usage_id = consumer_usage_map[control_id];
if (usage_id == 0U) {
LOG_WRN("Unmapped consumer control id %u", control_id);
return;
}
for (uint8_t i = 0; i < pulse_count; i++) {
submit_consumer_fifo_frame(usage_id);
submit_consumer_fifo_frame(0U);
}
}
static void emit_keys_report(bool force)
{
uint8_t report_buf[KEYBOARD_NKRO_REPORT_SIZE];
uint8_t report_size;
uint8_t *cache_buf;
bool *cache_valid;
enum keyboard_protocol_mode protocol_mode = active_protocol_mode_get();
if (!mode_valid) {
return;
}
if (protocol_mode == KEYBOARD_PROTOCOL_MODE_BOOT) {
build_boot_report(report_buf);
report_size = KEYBOARD_BOOT_REPORT_SIZE;
cache_buf = reports_cache.boot_report;
cache_valid = &reports_cache.boot_valid;
} else {
build_nkro_report(report_buf);
report_size = KEYBOARD_NKRO_REPORT_SIZE;
cache_buf = reports_cache.nkro_report;
cache_valid = &reports_cache.nkro_valid;
}
if (!force && *cache_valid && (memcmp(cache_buf, report_buf, report_size) == 0)) {
return;
}
memcpy(cache_buf, report_buf, report_size);
*cache_valid = true;
submit_keyboard_report_event(KEYBOARD_REPORT_TYPE_KEYS,
HID_QUEUE_POLICY_LATEST,
report_buf,
report_size);
}
static void emit_consumer_report(bool force)
{
uint8_t report_buf[KEYBOARD_CONSUMER_REPORT_SIZE];
enum keyboard_protocol_mode protocol_mode = active_protocol_mode_get();
if (!mode_valid || (protocol_mode == KEYBOARD_PROTOCOL_MODE_BOOT)) {
return;
}
build_consumer_report(report_buf);
if (!force && reports_cache.consumer_valid &&
(memcmp(reports_cache.consumer_report, report_buf,
KEYBOARD_CONSUMER_REPORT_SIZE) == 0)) {
return;
}
memcpy(reports_cache.consumer_report, report_buf, KEYBOARD_CONSUMER_REPORT_SIZE);
reports_cache.consumer_valid = true;
submit_keyboard_report_event(KEYBOARD_REPORT_TYPE_CONSUMER,
HID_QUEUE_POLICY_LATEST,
report_buf,
KEYBOARD_CONSUMER_REPORT_SIZE);
}
static void emit_all_reports(bool force)
{
emit_keys_report(force);
if (active_protocol_mode_get() != KEYBOARD_PROTOCOL_MODE_BOOT) {
emit_consumer_report(force);
}
}
static void emit_release_reports(enum mode_switch_mode mode)
{
struct keyboard_hid_report_event *event;
uint8_t keys_report[KEYBOARD_NKRO_REPORT_SIZE] = { 0 };
uint8_t consumer_report[KEYBOARD_CONSUMER_REPORT_SIZE] = { 0 };
enum keyboard_protocol_mode protocol_mode = active_protocol_mode_get();
size_t keys_report_size =
(protocol_mode == KEYBOARD_PROTOCOL_MODE_BOOT) ?
KEYBOARD_BOOT_REPORT_SIZE : KEYBOARD_NKRO_REPORT_SIZE;
event = new_keyboard_hid_report_event(keys_report_size);
event->mode = mode;
event->report_type = KEYBOARD_REPORT_TYPE_KEYS;
event->protocol_mode = protocol_mode;
memcpy(event->dyndata.data, keys_report, keys_report_size);
APP_EVENT_SUBMIT(event);
if (protocol_mode != KEYBOARD_PROTOCOL_MODE_BOOT) {
event = new_keyboard_hid_report_event(KEYBOARD_CONSUMER_REPORT_SIZE);
event->mode = mode;
event->report_type = KEYBOARD_REPORT_TYPE_CONSUMER;
event->protocol_mode = protocol_mode;
memcpy(event->dyndata.data, consumer_report,
KEYBOARD_CONSUMER_REPORT_SIZE);
APP_EVENT_SUBMIT(event);
}
}
static int module_init(void)
{
keyboard_state_clear();
reports_cache_invalidate();
mode_valid = false;
transport_protocol_modes[HID_TRANSPORT_USB] =
KEYBOARD_PROTOCOL_MODE_REPORT;
transport_protocol_modes[HID_TRANSPORT_BLE] =
KEYBOARD_PROTOCOL_MODE_REPORT;
return 0;
}
static int module_start(void)
{
if (running) {
return 0;
}
running = true;
return 0;
}
static void module_pause(void)
{
if (!running) {
return;
}
if (mode_valid) {
emit_release_reports(current_mode);
}
keyboard_state_clear();
reports_cache_invalidate();
mode_valid = false;
running = false;
}
static bool handle_button_event(const struct button_event *event)
{
const struct keymap_entry *entry;
bool changed;
if (!running) {
return false;
}
entry = keymap_get(event->key_id);
if (!entry) {
LOG_WRN("Unmapped key id 0x%04x", event->key_id);
return false;
}
if (entry->usage_type == KEY_USAGE_TYPE_KEYBOARD) {
changed = keyboard_key_update(entry->usage_id, event->pressed);
if (changed) {
emit_keys_report(false);
}
} else {
changed = consumer_key_update(entry->usage_id, event->pressed);
if (changed) {
emit_consumer_report(false);
}
}
return false;
}
static bool handle_mode_switch_event(const struct mode_switch_event *event)
{
bool mode_changed;
if (!running) {
current_mode = event->mode;
return false;
}
mode_changed = mode_valid && (current_mode != event->mode);
if (mode_changed) {
emit_release_reports(current_mode);
keyboard_state_clear();
reports_cache_invalidate();
}
current_mode = event->mode;
mode_valid = true;
emit_all_reports(true);
return false;
}
static bool handle_encoder_event(const struct encoder_event *event)
{
if (!running || !mode_valid) {
return false;
}
if (event->detents > 0) {
submit_consumer_pulse_frames(KEYBOARD_CONSUMER_CTRL_VOLUME_UP,
(uint8_t)event->detents);
} else if (event->detents < 0) {
submit_consumer_pulse_frames(KEYBOARD_CONSUMER_CTRL_VOLUME_DOWN,
(uint8_t)(-event->detents));
}
return false;
}
static bool app_event_handler(const struct app_event_header *aeh)
{
if (is_button_event(aeh)) {
return handle_button_event(cast_button_event(aeh));
}
if (is_encoder_event(aeh)) {
return handle_encoder_event(cast_encoder_event(aeh));
}
if (is_set_protocol_event(aeh)) {
const struct set_protocol_event *event = cast_set_protocol_event(aeh);
enum hid_transport active_transport;
if (event->transport >= HID_TRANSPORT_COUNT) {
return false;
}
if (transport_protocol_modes[event->transport] != event->protocol_mode) {
transport_protocol_modes[event->transport] = event->protocol_mode;
if (running && mode_valid &&
mode_to_transport(current_mode, &active_transport) &&
(active_transport == event->transport)) {
reports_cache_invalidate();
emit_keys_report(true);
if (event->protocol_mode != KEYBOARD_PROTOCOL_MODE_BOOT) {
emit_consumer_report(true);
}
}
}
return false;
}
if (is_mode_switch_event(aeh)) {
return handle_mode_switch_event(cast_mode_switch_event(aeh));
}
if (is_module_state_event(aeh)) {
const struct module_state_event *event = cast_module_state_event(aeh);
if (check_state(event, MODULE_ID(main), MODULE_STATE_READY)) {
int err;
if (!initialized) {
err = module_init();
if (err) {
module_set_state(MODULE_STATE_ERROR);
return false;
}
initialized = true;
}
err = module_start();
if (err) {
module_set_state(MODULE_STATE_ERROR);
} else {
module_set_state(MODULE_STATE_READY);
}
}
return false;
}
if (is_power_down_event(aeh)) {
if (initialized) {
module_pause();
module_set_state(MODULE_STATE_STANDBY);
}
return false;
}
if (is_wake_up_event(aeh)) {
if (initialized) {
int err = module_start();
if (err) {
module_set_state(MODULE_STATE_ERROR);
} else {
module_set_state(MODULE_STATE_READY);
}
}
return false;
}
__ASSERT_NO_MSG(false);
return false;
}
APP_EVENT_LISTENER(MODULE, app_event_handler);
APP_EVENT_SUBSCRIBE(MODULE, button_event);
APP_EVENT_SUBSCRIBE(MODULE, encoder_event);
APP_EVENT_SUBSCRIBE(MODULE, set_protocol_event);
APP_EVENT_SUBSCRIBE(MODULE, mode_switch_event);
APP_EVENT_SUBSCRIBE(MODULE, module_state_event);
APP_EVENT_SUBSCRIBE_EARLY(MODULE, power_down_event);
APP_EVENT_SUBSCRIBE(MODULE, wake_up_event);

215
src/mode_switch_module.c Normal file
View File

@@ -0,0 +1,215 @@
#include <stdbool.h>
#include <stdint.h>
#include <app_event_manager.h>
#define MODULE mode_switch_module
#include <caf/events/module_state_event.h>
#include <caf/events/power_event.h>
#include <zephyr/device.h>
#include <zephyr/devicetree.h>
#include <zephyr/drivers/sensor.h>
#include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
#include <zephyr/pm/device.h>
#include "mode_switch_event.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
#define MODE_SWITCH_ADC_NODE DT_NODELABEL(mode_switch_adc)
#define MODE_SWITCH_SAMPLE_INTERVAL K_MSEC(500)
#define MODE_SWITCH_USB_MAX_MV 825
#define MODE_SWITCH_24G_MAX_MV 2475
BUILD_ASSERT(DT_NODE_EXISTS(MODE_SWITCH_ADC_NODE),
"Missing mode_switch_adc node in devicetree");
static const struct device *const mode_switch_adc_dev =
DEVICE_DT_GET(MODE_SWITCH_ADC_NODE);
static struct k_work_delayable mode_switch_sample_work;
static bool initialized;
static bool running;
static bool force_report;
static bool mode_valid;
static enum mode_switch_mode last_mode;
static enum mode_switch_mode detect_mode(uint16_t voltage_mv)
{
if (voltage_mv < MODE_SWITCH_USB_MAX_MV) {
return MODE_SWITCH_USB;
}
if (voltage_mv < MODE_SWITCH_24G_MAX_MV) {
return MODE_SWITCH_24G;
}
return MODE_SWITCH_BLE;
}
static int mode_switch_enable(bool enable)
{
enum pm_device_action action = enable ? PM_DEVICE_ACTION_RESUME
: PM_DEVICE_ACTION_SUSPEND;
int err = pm_device_action_run(mode_switch_adc_dev, action);
if (err && (err != -EALREADY) && (err != -ENOTSUP)) {
LOG_ERR("Cannot %s mode switch ADC (%d)",
enable ? "resume" : "suspend", err);
return err;
}
return 0;
}
static void mode_switch_sample_fn(struct k_work *work)
{
struct sensor_value voltage;
int err;
ARG_UNUSED(work);
if (!running) {
return;
}
err = sensor_sample_fetch(mode_switch_adc_dev);
if (err) {
LOG_WRN("Mode switch ADC sample fetch failed (%d)", err);
goto reschedule;
}
err = sensor_channel_get(mode_switch_adc_dev, SENSOR_CHAN_VOLTAGE, &voltage);
if (err) {
LOG_WRN("Mode switch ADC channel get failed (%d)", err);
goto reschedule;
}
uint16_t sample_mv = (uint16_t)((voltage.val1 * 1000) + (voltage.val2 / 1000));
enum mode_switch_mode mode = detect_mode(sample_mv);
if (force_report || !mode_valid || (mode != last_mode)) {
struct mode_switch_event *event = new_mode_switch_event();
event->mode = mode;
event->voltage_mv = sample_mv;
APP_EVENT_SUBMIT(event);
last_mode = mode;
mode_valid = true;
force_report = false;
}
reschedule:
if (running) {
k_work_reschedule(&mode_switch_sample_work, MODE_SWITCH_SAMPLE_INTERVAL);
}
}
static int module_init(void)
{
if (!device_is_ready(mode_switch_adc_dev)) {
LOG_ERR("Mode switch ADC device not ready");
return -ENODEV;
}
k_work_init_delayable(&mode_switch_sample_work, mode_switch_sample_fn);
mode_valid = false;
force_report = false;
return 0;
}
static int module_start(void)
{
int err;
if (running) {
return 0;
}
err = mode_switch_enable(true);
if (err) {
return err;
}
running = true;
force_report = true;
k_work_reschedule(&mode_switch_sample_work, K_NO_WAIT);
return 0;
}
static void module_pause(void)
{
if (!running) {
return;
}
(void)k_work_cancel_delayable(&mode_switch_sample_work);
(void)mode_switch_enable(false);
running = false;
}
static bool app_event_handler(const struct app_event_header *aeh)
{
if (is_module_state_event(aeh)) {
const struct module_state_event *event = cast_module_state_event(aeh);
if (check_state(event, MODULE_ID(main), MODULE_STATE_READY)) {
int err;
if (!initialized) {
err = module_init();
if (err) {
module_set_state(MODULE_STATE_ERROR);
return false;
}
initialized = true;
}
err = module_start();
if (err) {
module_set_state(MODULE_STATE_ERROR);
} else {
module_set_state(MODULE_STATE_READY);
}
}
return false;
}
if (is_power_down_event(aeh)) {
if (initialized) {
module_pause();
module_set_state(MODULE_STATE_STANDBY);
}
return false;
}
if (is_wake_up_event(aeh)) {
if (initialized) {
int err = module_start();
if (err) {
module_set_state(MODULE_STATE_ERROR);
} else {
module_set_state(MODULE_STATE_READY);
}
}
return false;
}
__ASSERT_NO_MSG(false);
return false;
}
APP_EVENT_LISTENER(MODULE, app_event_handler);
APP_EVENT_SUBSCRIBE(MODULE, module_state_event);
APP_EVENT_SUBSCRIBE_EARLY(MODULE, power_down_event);
APP_EVENT_SUBSCRIBE(MODULE, wake_up_event);

133
src/protocol_module.c Normal file
View File

@@ -0,0 +1,133 @@
#include <errno.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <zephyr/logging/log.h>
#include <pb_decode.h>
#include <pb_encode.h>
#include <proto/device_comm.pb.h>
#include "protocol_module.h"
LOG_MODULE_REGISTER(protocol_module, LOG_LEVEL_INF);
#define PROTOCOL_VERSION 1U
#define PROTOCOL_VENDOR_ID 0x1915U
#define PROTOCOL_PRODUCT_ID 0x52F0U
#define PROTOCOL_FIRMWARE_MAJOR 0U
#define PROTOCOL_FIRMWARE_MINOR 0U
#define PROTOCOL_CAPABILITY_FLAGS 0U
static bool type_matches_body(uint8_t type, const CdcPacketBody *body)
{
switch (type) {
case CDC_PROTO_TYPE_HELLO_REQ:
return body->which_body == CdcPacketBody_hello_req_tag;
case CDC_PROTO_TYPE_HELLO_RSP:
return body->which_body == CdcPacketBody_hello_rsp_tag;
default:
return false;
}
}
static int decode_body(const uint8_t *payload, size_t payload_len,
CdcPacketBody *body)
{
pb_istream_t stream;
if ((payload == NULL) || (body == NULL)) {
return -EINVAL;
}
*body = (CdcPacketBody)CdcPacketBody_init_zero;
stream = pb_istream_from_buffer(payload, payload_len);
if (!pb_decode(&stream, CdcPacketBody_fields, body)) {
LOG_WRN("pb_decode failed: %s", PB_GET_ERROR(&stream));
return -EBADMSG;
}
return 0;
}
static int encode_hello_rsp(uint8_t *rsp_payload, size_t rsp_payload_buf_size,
size_t *rsp_payload_len)
{
CdcPacketBody body = CdcPacketBody_init_zero;
pb_ostream_t stream;
if ((rsp_payload == NULL) || (rsp_payload_len == NULL)) {
return -EINVAL;
}
body.which_body = CdcPacketBody_hello_rsp_tag;
body.body.hello_rsp.protocol_version = PROTOCOL_VERSION;
body.body.hello_rsp.vendor_id = PROTOCOL_VENDOR_ID;
body.body.hello_rsp.product_id = PROTOCOL_PRODUCT_ID;
body.body.hello_rsp.firmware_major = PROTOCOL_FIRMWARE_MAJOR;
body.body.hello_rsp.firmware_minor = PROTOCOL_FIRMWARE_MINOR;
body.body.hello_rsp.capability_flags = PROTOCOL_CAPABILITY_FLAGS;
stream = pb_ostream_from_buffer(rsp_payload, rsp_payload_buf_size);
if (!pb_encode(&stream, CdcPacketBody_fields, &body)) {
LOG_WRN("pb_encode failed: %s", PB_GET_ERROR(&stream));
return -EIO;
}
*rsp_payload_len = stream.bytes_written;
return 0;
}
int protocol_module_process_cdc_packet(uint8_t req_type,
const uint8_t *req_payload,
size_t req_payload_len,
uint8_t *rsp_type,
uint8_t *rsp_payload,
size_t rsp_payload_buf_size,
size_t *rsp_payload_len)
{
CdcPacketBody body;
int err;
if ((rsp_type == NULL) || (rsp_payload == NULL) || (rsp_payload_len == NULL)) {
return -EINVAL;
}
err = decode_body(req_payload, req_payload_len, &body);
if (err) {
return err;
}
if (!type_matches_body(req_type, &body)) {
LOG_WRN("CDC type/body mismatch type:0x%02x body_case:%d",
req_type, body.which_body);
return -EBADMSG;
}
switch (req_type) {
case CDC_PROTO_TYPE_HELLO_REQ:
LOG_INF("HelloReq protocol_version:%u",
body.body.hello_req.protocol_version);
if (body.body.hello_req.protocol_version != PROTOCOL_VERSION) {
LOG_WRN("Unexpected protocol version:%u",
body.body.hello_req.protocol_version);
}
err = encode_hello_rsp(rsp_payload, rsp_payload_buf_size, rsp_payload_len);
if (err) {
return err;
}
*rsp_type = CDC_PROTO_TYPE_HELLO_RSP;
return 0;
default:
LOG_WRN("Unsupported CDC protocol type:0x%02x", req_type);
return -ENOTSUP;
}
}

291
src/ui/ui_main.c Normal file
View File

@@ -0,0 +1,291 @@
#include <string.h>
#include <lvgl.h>
#include <zephyr/sys/printk.h>
#include "ui_main.h"
enum ui_status_id {
UI_STATUS_USB = 0,
UI_STATUS_BLE,
UI_STATUS_NUMLOCK,
UI_STATUS_CAPSLOCK,
UI_STATUS_COUNT,
};
enum {
UI_LED_MASK_NUM_LOCK = BIT(0),
UI_LED_MASK_CAPS_LOCK = BIT(1),
};
struct ui_main_ctx {
lv_obj_t *status_badges[UI_STATUS_COUNT];
lv_obj_t *status_labels[UI_STATUS_COUNT];
lv_obj_t *battery_icon;
lv_obj_t *battery_label;
lv_obj_t *battery_state_label;
lv_obj_t *date_label;
lv_obj_t *time_label;
};
static struct ui_main_ctx g_ui;
static bool ui_initialized;
static const char *const status_texts[UI_STATUS_COUNT] = {
LV_SYMBOL_USB,
LV_SYMBOL_BLUETOOTH,
"1",
"A",
};
static lv_color_t ui_main_get_battery_color(uint8_t battery_level)
{
if (battery_level > 70U) {
return lv_color_hex(0x8BD450);
}
if (battery_level >= 20U) {
return lv_color_hex(0xF4D35E);
}
return lv_color_hex(0xE63946);
}
static const char *ui_main_get_battery_symbol(uint8_t battery_level)
{
if (battery_level > 85U) {
return LV_SYMBOL_BATTERY_FULL;
}
if (battery_level > 60U) {
return LV_SYMBOL_BATTERY_3;
}
if (battery_level > 35U) {
return LV_SYMBOL_BATTERY_2;
}
if (battery_level >= 20U) {
return LV_SYMBOL_BATTERY_1;
}
return LV_SYMBOL_BATTERY_EMPTY;
}
static bool ui_main_status_is_active(enum ui_status_id id,
const struct ui_main_model *model)
{
switch (id) {
case UI_STATUS_USB:
return model->mode == MODE_SWITCH_USB;
case UI_STATUS_BLE:
return model->mode == MODE_SWITCH_BLE;
case UI_STATUS_NUMLOCK:
return (model->led_mask & UI_LED_MASK_NUM_LOCK) != 0U;
case UI_STATUS_CAPSLOCK:
return (model->led_mask & UI_LED_MASK_CAPS_LOCK) != 0U;
default:
return false;
}
}
static void ui_main_create_status_chip(lv_obj_t *parent, enum ui_status_id id)
{
lv_obj_t *badge = lv_obj_create(parent);
lv_obj_t *label = lv_label_create(badge);
lv_obj_remove_style_all(badge);
lv_obj_set_size(badge, 50, 32);
lv_obj_set_style_radius(badge, 10, 0);
lv_obj_set_style_bg_opa(badge, LV_OPA_COVER, 0);
lv_obj_set_style_pad_all(badge, 0, 0);
lv_label_set_text(label, status_texts[id]);
lv_obj_set_width(label, LV_PCT(100));
lv_obj_set_style_text_font(label, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_align(label, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_center(label);
g_ui.status_badges[id] = badge;
g_ui.status_labels[id] = label;
}
void ui_main_refresh_status_bar(const struct ui_main_model *model)
{
for (uint32_t i = 0; i < UI_STATUS_COUNT; i++) {
lv_obj_t *badge = g_ui.status_badges[i];
lv_obj_t *label = g_ui.status_labels[i];
bool active = ui_main_status_is_active((enum ui_status_id)i, model);
if ((badge == NULL) || (label == NULL)) {
continue;
}
lv_obj_set_style_border_width(badge, 3, 0);
lv_obj_set_style_border_color(
badge,
active ? model->theme_color : model->inactive_border_color, 0);
lv_obj_set_style_bg_color(
badge,
active ? lv_color_hex(0x1D2735) : lv_color_hex(0x161A20), 0);
lv_obj_set_style_text_color(
label,
active ? lv_color_white() : lv_color_hex(0x7C8798), 0);
}
}
void ui_main_refresh_battery(const struct ui_main_model *model)
{
char battery_text[8];
const char *state_symbol = "";
lv_color_t battery_color;
lv_color_t state_color = lv_color_white();
if ((g_ui.battery_icon == NULL) || (g_ui.battery_label == NULL) ||
(g_ui.battery_state_label == NULL)) {
return;
}
battery_color = ui_main_get_battery_color(model->battery_level);
snprintk(battery_text, sizeof(battery_text), "%u%%", model->battery_level);
if (model->full) {
state_symbol = LV_SYMBOL_USB;
state_color = lv_color_hex(0x4C9EF5);
} else if (model->charging) {
state_symbol = LV_SYMBOL_CHARGE;
state_color = lv_color_hex(0xF4D35E);
}
lv_label_set_text(g_ui.battery_icon,
ui_main_get_battery_symbol(model->battery_level));
lv_obj_set_style_text_color(g_ui.battery_icon, battery_color, 0);
lv_label_set_text(g_ui.battery_label, battery_text);
lv_label_set_text(g_ui.battery_state_label, state_symbol);
lv_obj_set_style_text_color(g_ui.battery_state_label, state_color, 0);
}
void ui_main_refresh_datetime(const char *date_text, const char *time_text)
{
if ((g_ui.date_label == NULL) || (g_ui.time_label == NULL)) {
return;
}
lv_label_set_text(g_ui.date_label, date_text);
lv_label_set_text(g_ui.time_label, time_text);
}
void ui_main_refresh_all(const struct ui_main_model *model,
const char *date_text,
const char *time_text)
{
ui_main_refresh_status_bar(model);
ui_main_refresh_battery(model);
ui_main_refresh_datetime(date_text, time_text);
}
void ui_main_init(const struct ui_main_model *model,
const char *date_text,
const char *time_text)
{
lv_obj_t *screen = lv_screen_active();
lv_obj_t *content;
lv_obj_t *top_row;
lv_obj_t *battery_wrap;
lv_obj_t *middle_row;
lv_obj_t *bottom_row;
if (ui_initialized) {
return;
}
memset(&g_ui, 0, sizeof(g_ui));
lv_obj_clean(screen);
lv_obj_set_style_bg_color(screen, lv_color_hex(0x0F1115), 0);
lv_obj_set_style_bg_grad_color(screen, lv_color_hex(0x1A1F29), 0);
lv_obj_set_style_bg_grad_dir(screen, LV_GRAD_DIR_VER, 0);
lv_obj_set_style_bg_opa(screen, LV_OPA_COVER, 0);
lv_obj_set_style_text_color(screen, lv_color_white(), 0);
lv_obj_set_style_pad_all(screen, 0, 0);
lv_obj_set_scrollbar_mode(screen, LV_SCROLLBAR_MODE_OFF);
content = lv_obj_create(screen);
lv_obj_remove_style_all(content);
lv_obj_set_size(content, LV_PCT(100), LV_PCT(100));
lv_obj_set_style_bg_opa(content, LV_OPA_TRANSP, 0);
lv_obj_set_style_pad_left(content, 14, 0);
lv_obj_set_style_pad_right(content, 14, 0);
lv_obj_set_style_pad_top(content, 8, 0);
lv_obj_set_style_pad_bottom(content, 8, 0);
lv_obj_set_layout(content, LV_LAYOUT_FLEX);
lv_obj_set_flex_flow(content, LV_FLEX_FLOW_COLUMN);
lv_obj_set_flex_align(content, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER,
LV_FLEX_ALIGN_CENTER);
top_row = lv_obj_create(content);
lv_obj_remove_style_all(top_row);
lv_obj_set_width(top_row, LV_PCT(100));
lv_obj_set_flex_grow(top_row, 1);
lv_obj_set_style_bg_opa(top_row, LV_OPA_TRANSP, 0);
lv_obj_set_layout(top_row, LV_LAYOUT_FLEX);
lv_obj_set_flex_flow(top_row, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(top_row, LV_FLEX_ALIGN_SPACE_BETWEEN,
LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
g_ui.date_label = lv_label_create(top_row);
lv_obj_set_style_text_font(g_ui.date_label, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(g_ui.date_label, lv_color_hex(0xD8DEE9), 0);
battery_wrap = lv_obj_create(top_row);
lv_obj_remove_style_all(battery_wrap);
lv_obj_set_width(battery_wrap, LV_SIZE_CONTENT);
lv_obj_set_layout(battery_wrap, LV_LAYOUT_FLEX);
lv_obj_set_flex_flow(battery_wrap, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(battery_wrap, LV_FLEX_ALIGN_CENTER,
LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_set_style_pad_column(battery_wrap, 4, 0);
g_ui.battery_icon = lv_label_create(battery_wrap);
lv_obj_set_style_text_font(g_ui.battery_icon, &lv_font_montserrat_14, 0);
g_ui.battery_label = lv_label_create(battery_wrap);
lv_obj_set_style_text_font(g_ui.battery_label, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(g_ui.battery_label, lv_color_hex(0xD8DEE9), 0);
g_ui.battery_state_label = lv_label_create(battery_wrap);
lv_obj_set_style_text_font(g_ui.battery_state_label, &lv_font_montserrat_14, 0);
middle_row = lv_obj_create(content);
lv_obj_remove_style_all(middle_row);
lv_obj_set_width(middle_row, LV_PCT(100));
lv_obj_set_flex_grow(middle_row, 2);
lv_obj_set_style_bg_opa(middle_row, LV_OPA_TRANSP, 0);
g_ui.time_label = lv_label_create(middle_row);
lv_obj_set_style_text_font(g_ui.time_label, &lv_font_montserrat_32, 0);
lv_obj_set_style_text_color(g_ui.time_label, lv_color_white(), 0);
lv_obj_center(g_ui.time_label);
bottom_row = lv_obj_create(content);
lv_obj_remove_style_all(bottom_row);
lv_obj_set_width(bottom_row, LV_PCT(100));
lv_obj_set_flex_grow(bottom_row, 1);
lv_obj_set_style_bg_opa(bottom_row, LV_OPA_TRANSP, 0);
lv_obj_set_layout(bottom_row, LV_LAYOUT_FLEX);
lv_obj_set_flex_flow(bottom_row, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(bottom_row, LV_FLEX_ALIGN_CENTER,
LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_set_style_pad_column(bottom_row, 6, 0);
for (uint32_t i = 0; i < UI_STATUS_COUNT; i++) {
ui_main_create_status_chip(bottom_row, (enum ui_status_id)i);
}
ui_main_refresh_all(model, date_text, time_text);
ui_initialized = true;
}

39
src/ui/ui_main.h Normal file
View File

@@ -0,0 +1,39 @@
#ifndef BLINKY_UI_MAIN_H_
#define BLINKY_UI_MAIN_H_
#include <stdbool.h>
#include <stdint.h>
#include <lvgl.h>
#include "mode_switch_event.h"
#ifdef __cplusplus
extern "C" {
#endif
struct ui_main_model {
lv_color_t theme_color;
lv_color_t inactive_border_color;
uint8_t battery_level;
enum mode_switch_mode mode;
uint8_t led_mask;
bool charging;
bool full;
};
void ui_main_init(const struct ui_main_model *model,
const char *date_text,
const char *time_text);
void ui_main_refresh_all(const struct ui_main_model *model,
const char *date_text,
const char *time_text);
void ui_main_refresh_status_bar(const struct ui_main_model *model);
void ui_main_refresh_battery(const struct ui_main_model *model);
void ui_main_refresh_datetime(const char *date_text, const char *time_text);
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_UI_MAIN_H_ */

426
src/usb_cdc_module.c Normal file
View File

@@ -0,0 +1,426 @@
#include <errno.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <app_event_manager.h>
#define MODULE usb_cdc_module
#include <caf/events/module_state_event.h>
#include <caf/events/power_event.h>
#include <zephyr/device.h>
#include <zephyr/drivers/uart.h>
#include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
#include <zephyr/sys/ring_buffer.h>
#include <zephyr/sys/util.h>
#include "usb_cdc_rx_event.h"
#include "usb_cdc_tx_event.h"
#include "usb_function_ready_event.h"
#include "usb_prepare_event.h"
#include "usb_device_module.h"
#include "usb_device_state_event.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
#define USB_CDC_RX_RING_BUF_SIZE 256
#define USB_CDC_TX_RING_BUF_SIZE 256
#define USB_CDC_RX_CHUNK_SIZE 32
#define USB_CDC_CONTROL_POLL_INTERVAL K_MSEC(100)
#define USB_CDC_EXPECTED_BAUDRATE 115200U
static const struct device *const cdc_dev = DEVICE_DT_GET_ONE(zephyr_cdc_acm_uart);
static uint8_t rx_ring_buffer[USB_CDC_RX_RING_BUF_SIZE];
static uint8_t tx_ring_buffer[USB_CDC_TX_RING_BUF_SIZE];
static struct ring_buf rx_ringbuf;
static struct ring_buf tx_ringbuf;
static struct k_work rx_work;
static struct k_work_delayable control_work;
static bool initialized;
static bool running;
static bool usb_active;
static bool usb_function_prepared;
static bool dtr_ready;
static bool rx_enabled;
static void submit_usb_cdc_rx_event(const uint8_t *data, size_t len)
{
struct usb_cdc_rx_event *event = new_usb_cdc_rx_event(len);
memcpy(event->dyndata.data, data, len);
APP_EVENT_SUBMIT(event);
}
static void submit_usb_function_ready_event(void)
{
struct usb_function_ready_event *event = new_usb_function_ready_event();
event->function_mask = USB_FUNCTION_CDC_ACM;
APP_EVENT_SUBMIT(event);
}
static void reset_ring_buffers(void)
{
unsigned int key = irq_lock();
ring_buf_init(&rx_ringbuf, sizeof(rx_ring_buffer), rx_ring_buffer);
ring_buf_init(&tx_ringbuf, sizeof(tx_ring_buffer), tx_ring_buffer);
irq_unlock(key);
}
static void disable_uart_io(void)
{
uart_irq_rx_disable(cdc_dev);
uart_irq_tx_disable(cdc_dev);
rx_enabled = false;
dtr_ready = false;
reset_ring_buffers();
}
static void kick_tx(void)
{
if (!running || !usb_active || !dtr_ready) {
return;
}
uart_irq_tx_enable(cdc_dev);
}
static void validate_line_coding(void)
{
uint32_t baudrate = 0U;
int err;
err = uart_line_ctrl_get(cdc_dev, UART_LINE_CTRL_BAUD_RATE, &baudrate);
if (err) {
LOG_WRN("Failed to get CDC baudrate (%d)", err);
} else {
LOG_INF("CDC baudrate %u", baudrate);
if (baudrate != USB_CDC_EXPECTED_BAUDRATE) {
LOG_WRN("Expected CDC baudrate %u, got %u",
USB_CDC_EXPECTED_BAUDRATE, baudrate);
}
}
#ifdef CONFIG_UART_USE_RUNTIME_CONFIGURE
{
struct uart_config cfg;
err = uart_config_get(cdc_dev, &cfg);
if (err) {
LOG_WRN("uart_config_get failed (%d)", err);
} else {
LOG_INF("CDC line coding data:%u stop:%u parity:%u flow:%u",
cfg.data_bits, cfg.stop_bits, cfg.parity,
cfg.flow_ctrl);
if ((cfg.data_bits != UART_CFG_DATA_BITS_8) ||
(cfg.stop_bits != UART_CFG_STOP_BITS_1) ||
(cfg.parity != UART_CFG_PARITY_NONE) ||
(cfg.flow_ctrl != UART_CFG_FLOW_CTRL_NONE)) {
LOG_WRN("Expected CDC line coding 115200 8N1 no flow control");
}
}
}
#endif
}
static void rx_work_handler(struct k_work *work)
{
uint8_t buffer[USB_CDC_RX_CHUNK_SIZE];
ARG_UNUSED(work);
while (true) {
uint32_t len;
unsigned int key = irq_lock();
len = ring_buf_get(&rx_ringbuf, buffer, sizeof(buffer));
irq_unlock(key);
if (len == 0U) {
return;
}
submit_usb_cdc_rx_event(buffer, len);
}
}
static void control_work_handler(struct k_work *work)
{
uint32_t dtr = 0U;
int err;
ARG_UNUSED(work);
if (!running || !usb_active) {
return;
}
err = uart_line_ctrl_get(cdc_dev, UART_LINE_CTRL_DTR, &dtr);
if (err) {
LOG_WRN("Failed to get CDC DTR (%d)", err);
goto reschedule;
}
if (dtr && !dtr_ready) {
dtr_ready = true;
LOG_INF("CDC DTR set");
validate_line_coding();
err = uart_line_ctrl_set(cdc_dev, UART_LINE_CTRL_DCD, 1);
if (err) {
LOG_WRN("Failed to set DCD (%d)", err);
}
err = uart_line_ctrl_set(cdc_dev, UART_LINE_CTRL_DSR, 1);
if (err) {
LOG_WRN("Failed to set DSR (%d)", err);
}
if (!rx_enabled) {
uart_irq_rx_enable(cdc_dev);
rx_enabled = true;
}
kick_tx();
} else if (!dtr && dtr_ready) {
LOG_INF("CDC DTR cleared");
disable_uart_io();
}
reschedule:
k_work_reschedule(&control_work, USB_CDC_CONTROL_POLL_INTERVAL);
}
static void cdc_interrupt_handler(const struct device *dev, void *user_data)
{
ARG_UNUSED(user_data);
while (uart_irq_update(dev) && uart_irq_is_pending(dev)) {
if (uart_irq_rx_ready(dev)) {
uint8_t buffer[USB_CDC_RX_CHUNK_SIZE];
int recv_len = uart_fifo_read(dev, buffer, sizeof(buffer));
if (recv_len < 0) {
LOG_ERR("Failed to read CDC RX FIFO");
continue;
}
if (recv_len > 0) {
uint32_t written;
unsigned int key = irq_lock();
written = ring_buf_put(&rx_ringbuf, buffer,
(uint32_t)recv_len);
irq_unlock(key);
if (written < (uint32_t)recv_len) {
LOG_WRN("Drop %d CDC RX bytes", recv_len - (int)written);
}
k_work_submit(&rx_work);
}
}
if (uart_irq_tx_ready(dev)) {
uint8_t buffer[USB_CDC_RX_CHUNK_SIZE];
uint32_t len;
int sent_len;
unsigned int key = irq_lock();
len = ring_buf_get(&tx_ringbuf, buffer, sizeof(buffer));
irq_unlock(key);
if (len == 0U) {
uart_irq_tx_disable(dev);
continue;
}
sent_len = uart_fifo_fill(dev, buffer, len);
if (sent_len < 0) {
LOG_ERR("Failed to write CDC TX FIFO");
uart_irq_tx_disable(dev);
} else if ((uint32_t)sent_len < len) {
LOG_WRN("Drop %u CDC TX bytes",
(unsigned int)(len - (uint32_t)sent_len));
}
}
}
}
static int module_init(void)
{
if (!device_is_ready(cdc_dev)) {
LOG_ERR("CDC ACM device not ready");
return -ENODEV;
}
reset_ring_buffers();
k_work_init(&rx_work, rx_work_handler);
k_work_init_delayable(&control_work, control_work_handler);
uart_irq_callback_set(cdc_dev, cdc_interrupt_handler);
usb_function_prepared = false;
return 0;
}
static int module_start(void)
{
if (running) {
return 0;
}
running = true;
if (usb_active) {
k_work_reschedule(&control_work, K_NO_WAIT);
}
return 0;
}
static void module_pause(void)
{
if (!running) {
return;
}
k_work_cancel_delayable(&control_work);
disable_uart_io();
running = false;
}
static bool handle_usb_prepare_event(const struct usb_prepare_event *event)
{
ARG_UNUSED(event);
if (!running || usb_function_prepared) {
return false;
}
usb_function_prepared = true;
submit_usb_function_ready_event();
return false;
}
static bool handle_usb_device_state_event(const struct usb_device_state_event *event)
{
bool new_usb_active = (event->state == USB_DEVICE_STATE_ACTIVE);
if (new_usb_active == usb_active) {
return false;
}
usb_active = new_usb_active;
if (!usb_active) {
k_work_cancel_delayable(&control_work);
disable_uart_io();
} else if (running) {
k_work_reschedule(&control_work, K_NO_WAIT);
}
return false;
}
static bool handle_usb_cdc_tx_event(const struct usb_cdc_tx_event *event)
{
uint32_t written;
unsigned int key;
if (!running || !usb_active || !dtr_ready) {
return false;
}
key = irq_lock();
written = ring_buf_put(&tx_ringbuf, event->dyndata.data,
(uint32_t)event->dyndata.size);
irq_unlock(key);
if (written < event->dyndata.size) {
LOG_WRN("Drop %zu CDC TX bytes", event->dyndata.size - written);
}
if (written > 0U) {
kick_tx();
}
return false;
}
static bool app_event_handler(const struct app_event_header *aeh)
{
if (is_usb_device_state_event(aeh)) {
return handle_usb_device_state_event(cast_usb_device_state_event(aeh));
}
if (is_usb_prepare_event(aeh)) {
return handle_usb_prepare_event(cast_usb_prepare_event(aeh));
}
if (is_usb_cdc_tx_event(aeh)) {
return handle_usb_cdc_tx_event(cast_usb_cdc_tx_event(aeh));
}
if (is_module_state_event(aeh)) {
const struct module_state_event *event = cast_module_state_event(aeh);
if (check_state(event, MODULE_ID(main), MODULE_STATE_READY)) {
int err;
if (!initialized) {
err = module_init();
if (err) {
module_set_state(MODULE_STATE_ERROR);
return false;
}
initialized = true;
}
err = module_start();
if (err) {
module_set_state(MODULE_STATE_ERROR);
} else {
module_set_state(MODULE_STATE_READY);
}
}
return false;
}
if (is_power_down_event(aeh)) {
if (initialized) {
module_pause();
module_set_state(MODULE_STATE_STANDBY);
}
return false;
}
if (is_wake_up_event(aeh)) {
if (initialized) {
int err = module_start();
if (err) {
module_set_state(MODULE_STATE_ERROR);
} else {
module_set_state(MODULE_STATE_READY);
}
}
return false;
}
return false;
}
APP_EVENT_LISTENER(MODULE, app_event_handler);
APP_EVENT_SUBSCRIBE(MODULE, module_state_event);
APP_EVENT_SUBSCRIBE(MODULE, usb_prepare_event);
APP_EVENT_SUBSCRIBE(MODULE, usb_device_state_event);
APP_EVENT_SUBSCRIBE(MODULE, usb_cdc_tx_event);
APP_EVENT_SUBSCRIBE_EARLY(MODULE, power_down_event);
APP_EVENT_SUBSCRIBE(MODULE, wake_up_event);

164
src/usb_cdc_test_module.c Normal file
View File

@@ -0,0 +1,164 @@
#include <stdbool.h>
#include <string.h>
#include <app_event_manager.h>
#define MODULE usb_cdc_test_module
#include <caf/events/module_state_event.h>
#include <caf/events/power_event.h>
#include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
#include "usb_cdc_tx_event.h"
#include "usb_device_state_event.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
#define USB_CDC_TEST_PERIOD K_SECONDS(1)
static const uint8_t hello_message[] = "hello\r\n";
static struct k_work_delayable hello_work;
static bool initialized;
static bool running;
static bool usb_active;
static void submit_hello_message(void)
{
struct usb_cdc_tx_event *event =
new_usb_cdc_tx_event(sizeof(hello_message) - 1U);
memcpy(event->dyndata.data, hello_message, sizeof(hello_message) - 1U);
APP_EVENT_SUBMIT(event);
}
static void hello_work_handler(struct k_work *work)
{
ARG_UNUSED(work);
if (!running || !usb_active) {
return;
}
submit_hello_message();
k_work_reschedule(&hello_work, USB_CDC_TEST_PERIOD);
}
static int module_init(void)
{
k_work_init_delayable(&hello_work, hello_work_handler);
return 0;
}
static int module_start(void)
{
if (running) {
return 0;
}
running = true;
if (usb_active) {
k_work_reschedule(&hello_work, USB_CDC_TEST_PERIOD);
}
return 0;
}
static void module_pause(void)
{
if (!running) {
return;
}
k_work_cancel_delayable(&hello_work);
running = false;
}
static bool handle_usb_device_state_event(const struct usb_device_state_event *event)
{
bool new_usb_active = (event->state == USB_DEVICE_STATE_ACTIVE);
if (new_usb_active == usb_active) {
return false;
}
usb_active = new_usb_active;
if (!running) {
return false;
}
if (usb_active) {
k_work_reschedule(&hello_work, USB_CDC_TEST_PERIOD);
} else {
k_work_cancel_delayable(&hello_work);
}
return false;
}
static bool app_event_handler(const struct app_event_header *aeh)
{
if (is_usb_device_state_event(aeh)) {
return handle_usb_device_state_event(cast_usb_device_state_event(aeh));
}
if (is_module_state_event(aeh)) {
const struct module_state_event *event = cast_module_state_event(aeh);
if (check_state(event, MODULE_ID(main), MODULE_STATE_READY)) {
int err;
if (!initialized) {
err = module_init();
if (err) {
module_set_state(MODULE_STATE_ERROR);
return false;
}
initialized = true;
}
err = module_start();
if (err) {
module_set_state(MODULE_STATE_ERROR);
} else {
module_set_state(MODULE_STATE_READY);
}
}
return false;
}
if (is_power_down_event(aeh)) {
if (initialized) {
module_pause();
module_set_state(MODULE_STATE_STANDBY);
}
return false;
}
if (is_wake_up_event(aeh)) {
if (initialized) {
int err = module_start();
if (err) {
module_set_state(MODULE_STATE_ERROR);
} else {
module_set_state(MODULE_STATE_READY);
}
}
return false;
}
return false;
}
APP_EVENT_LISTENER(MODULE, app_event_handler);
APP_EVENT_SUBSCRIBE(MODULE, module_state_event);
APP_EVENT_SUBSCRIBE(MODULE, usb_device_state_event);
APP_EVENT_SUBSCRIBE_EARLY(MODULE, power_down_event);
APP_EVENT_SUBSCRIBE(MODULE, wake_up_event);

349
src/usb_device_module.c Normal file
View File

@@ -0,0 +1,349 @@
#include <errno.h>
#include <stdbool.h>
#include <stdint.h>
#include <app_event_manager.h>
#define MODULE usb_device_module
#include <caf/events/module_state_event.h>
#include <caf/events/power_event.h>
#include <zephyr/logging/log.h>
#include <zephyr/usb/usbd.h>
#include <caf/events/power_manager_event.h>
#include "usb_device_module.h"
#include "usb_device_state_event.h"
#include "usb_function_ready_event.h"
#include "usb_prepare_event.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
#define USB_DEVICE_VID 0x1915
#define USB_DEVICE_PID 0x52F0
#define USB_DEVICE_MANUFACTURER "Atguigu"
#define USB_DEVICE_PRODUCT "WH Mini Keyboard"
#define USB_REQUIRED_FUNCTION_MASK (USB_FUNCTION_HID | USB_FUNCTION_CDC_ACM)
USBD_DEVICE_DEFINE(blinky_usbd, DEVICE_DT_GET(DT_NODELABEL(usbd)),
USB_DEVICE_VID, USB_DEVICE_PID);
USBD_DESC_LANG_DEFINE(blinky_lang);
USBD_DESC_MANUFACTURER_DEFINE(blinky_mfr, USB_DEVICE_MANUFACTURER);
USBD_DESC_PRODUCT_DEFINE(blinky_product, USB_DEVICE_PRODUCT);
USBD_DESC_CONFIG_DEFINE(blinky_fs_cfg_desc, "FS Configuration");
USBD_CONFIGURATION_DEFINE(blinky_fs_config, 0, 250, &blinky_fs_cfg_desc);
static const char *const class_blocklist[] = {
NULL,
};
static bool initialized;
static bool running;
static bool prepare_broadcasted;
static bool usbd_initialized;
static bool usb_enabled;
static uint8_t ready_function_mask;
static enum usb_device_state device_state = USB_DEVICE_STATE_DISCONNECTED;
static void submit_usb_device_state_event(enum usb_device_state state)
{
struct usb_device_state_event *event = new_usb_device_state_event();
event->state = state;
APP_EVENT_SUBMIT(event);
}
static void submit_usb_prepare_event(void)
{
struct usb_prepare_event *event = new_usb_prepare_event();
APP_EVENT_SUBMIT(event);
}
static void update_usb_device_state(enum usb_device_state state)
{
if (device_state == state) {
return;
}
device_state = state;
submit_usb_device_state_event(state);
}
static void update_power_manager_restriction(bool vbus_present)
{
power_manager_restrict(MODULE_IDX(MODULE),
vbus_present ? POWER_MANAGER_LEVEL_ALIVE :
POWER_MANAGER_LEVEL_SUSPENDED);
}
static int usb_descriptors_init(void)
{
int err;
err = usbd_add_descriptor(&blinky_usbd, &blinky_lang);
if (err) {
return err;
}
err = usbd_add_descriptor(&blinky_usbd, &blinky_mfr);
if (err) {
return err;
}
err = usbd_add_descriptor(&blinky_usbd, &blinky_product);
if (err) {
return err;
}
err = usbd_add_configuration(&blinky_usbd, USBD_SPEED_FS, &blinky_fs_config);
if (err) {
return err;
}
err = usbd_register_all_classes(&blinky_usbd, USBD_SPEED_FS, 1, class_blocklist);
if (err) {
return err;
}
usbd_device_set_code_triple(&blinky_usbd, USBD_SPEED_FS, 0, 0, 0);
return 0;
}
static void usbd_msg_cb(struct usbd_context *const usbd_ctx,
const struct usbd_msg *const msg)
{
ARG_UNUSED(usbd_ctx);
switch (msg->type) {
case USBD_MSG_VBUS_READY:
update_power_manager_restriction(true);
if (!usb_enabled) {
int err = usbd_enable(&blinky_usbd);
if (err) {
LOG_ERR("usbd_enable failed (%d)", err);
} else {
usb_enabled = true;
update_usb_device_state(USB_DEVICE_STATE_POWERED);
}
}
break;
case USBD_MSG_VBUS_REMOVED:
update_power_manager_restriction(false);
if (usb_enabled) {
int err = usbd_disable(&blinky_usbd);
if (err) {
LOG_ERR("usbd_disable failed (%d)", err);
}
}
usb_enabled = false;
update_usb_device_state(USB_DEVICE_STATE_DISCONNECTED);
break;
case USBD_MSG_CONFIGURATION:
if (msg->status) {
update_usb_device_state(USB_DEVICE_STATE_ACTIVE);
} else if (usb_enabled) {
update_usb_device_state(USB_DEVICE_STATE_POWERED);
}
break;
case USBD_MSG_SUSPEND:
if (usb_enabled) {
update_usb_device_state(USB_DEVICE_STATE_SUSPENDED);
}
break;
case USBD_MSG_RESUME:
if (usb_enabled) {
update_usb_device_state(USB_DEVICE_STATE_ACTIVE);
}
break;
default:
break;
}
}
static int usb_stack_init(void)
{
int err;
err = usbd_msg_register_cb(&blinky_usbd, usbd_msg_cb);
if (err) {
LOG_ERR("usbd_msg_register_cb failed (%d)", err);
return err;
}
err = usb_descriptors_init();
if (err) {
LOG_ERR("usb descriptor init failed (%d)", err);
return err;
}
err = usbd_init(&blinky_usbd);
if (err) {
LOG_ERR("usbd_init failed (%d)", err);
return err;
}
usbd_initialized = true;
if (!usbd_can_detect_vbus(&blinky_usbd)) {
err = usbd_enable(&blinky_usbd);
if (err) {
LOG_ERR("usbd_enable failed (%d)", err);
return err;
}
usb_enabled = true;
update_usb_device_state(USB_DEVICE_STATE_POWERED);
}
return 0;
}
static int module_init(void)
{
device_state = USB_DEVICE_STATE_DISCONNECTED;
usb_enabled = false;
ready_function_mask = 0U;
prepare_broadcasted = false;
usbd_initialized = false;
update_power_manager_restriction(false);
return 0;
}
static int module_start(void)
{
if (running) {
return 0;
}
running = true;
if (usbd_initialized || prepare_broadcasted) {
return 0;
}
ready_function_mask = 0U;
prepare_broadcasted = true;
submit_usb_prepare_event();
return 0;
}
static void module_pause(void)
{
if (!running) {
return;
}
running = false;
}
static bool handle_module_state_event(const struct module_state_event *event)
{
if (!check_state(event, MODULE_ID(main), MODULE_STATE_READY)) {
return false;
}
if (!initialized) {
int err = module_init();
if (err) {
module_set_state(MODULE_STATE_ERROR);
return false;
}
initialized = true;
}
if (!running) {
int err = module_start();
if (err) {
module_set_state(MODULE_STATE_ERROR);
} else if (usbd_initialized) {
module_set_state(MODULE_STATE_READY);
}
}
return false;
}
static bool handle_usb_function_ready_event(const struct usb_function_ready_event *event)
{
int err;
if (!running || !prepare_broadcasted || usbd_initialized) {
return false;
}
ready_function_mask |= event->function_mask;
if ((ready_function_mask & USB_REQUIRED_FUNCTION_MASK) !=
USB_REQUIRED_FUNCTION_MASK) {
return false;
}
err = usb_stack_init();
if (err) {
module_set_state(MODULE_STATE_ERROR);
return false;
}
module_set_state(MODULE_STATE_READY);
return false;
}
static bool app_event_handler(const struct app_event_header *aeh)
{
if (is_module_state_event(aeh)) {
return handle_module_state_event(cast_module_state_event(aeh));
}
if (is_usb_function_ready_event(aeh)) {
return handle_usb_function_ready_event(cast_usb_function_ready_event(aeh));
}
if (is_power_down_event(aeh)) {
if (initialized) {
module_pause();
module_set_state(MODULE_STATE_STANDBY);
}
return false;
}
if (is_wake_up_event(aeh)) {
if (initialized) {
int err = module_start();
if (err) {
module_set_state(MODULE_STATE_ERROR);
} else if (usbd_initialized) {
module_set_state(MODULE_STATE_READY);
}
}
return false;
}
return false;
}
APP_EVENT_LISTENER(MODULE, app_event_handler);
APP_EVENT_SUBSCRIBE(MODULE, module_state_event);
APP_EVENT_SUBSCRIBE(MODULE, usb_function_ready_event);
APP_EVENT_SUBSCRIBE_EARLY(MODULE, power_down_event);
APP_EVENT_SUBSCRIBE(MODULE, wake_up_event);

647
src/usb_hid_module.c Normal file
View File

@@ -0,0 +1,647 @@
#include <errno.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <app_event_manager.h>
#define MODULE usb_hid_module
#include <caf/events/module_state_event.h>
#include <caf/events/power_event.h>
#include <zephyr/device.h>
#include <zephyr/drivers/usb/udc_buf.h>
#include <zephyr/logging/log.h>
#include <zephyr/sys/util.h>
#include <zephyr/usb/class/usbd_hid.h>
#include "hid_led_event.h"
#include "hid_report_sent_event.h"
#include "hid_transport_state_event.h"
#include "hid_tx_report_event.h"
#include "keyboard_core.h"
#include "set_protocol_event.h"
#include "usb_function_ready_event.h"
#include "usb_prepare_event.h"
#include "usb_device_module.h"
#include "usb_device_state_event.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
#define KBD_LED_REPORT_SIZE 1U
enum usb_hid_interface {
USB_HID_INTERFACE_KEYBOARD,
USB_HID_INTERFACE_CONSUMER,
USB_HID_INTERFACE_COUNT,
};
struct usb_hid_interface_state {
const struct device *dev;
bool ready;
};
static const uint8_t keyboard_report_desc[] = {
0x05, 0x01, /* Usage Page (Generic Desktop) */
0x09, 0x06, /* Usage (Keyboard) */
0xA1, 0x01, /* Collection (Application) */
0x05, 0x07, /* Usage Page (Keyboard/Keypad) */
0x19, 0xE0, /* Usage Minimum (0xE0) */
0x29, 0xE7, /* Usage Maximum (0xE7) */
0x15, 0x00, /* Logical Minimum (0) */
0x25, 0x01, /* Logical Maximum (1) */
0x75, 0x01, /* Report Size (1) */
0x95, 0x08, /* Report Count (8) */
0x81, 0x02, /* Input (Data,Var,Abs) */
0x05, 0x07, /* Usage Page (Keyboard/Keypad) */
0x19, 0x00, /* Usage Minimum (0x00) */
0x2A, 0xDF, 0x00, /* Usage Maximum (0x00DF) */
0x15, 0x00, /* Logical Minimum (0) */
0x25, 0x01, /* Logical Maximum (1) */
0x75, 0x01, /* Report Size (1) */
0x96, 0xE0, 0x00, /* Report Count (224) */
0x81, 0x02, /* Input (Data,Var,Abs) */
0x05, 0x08, /* Usage Page (LEDs) */
0x19, 0x01, /* Usage Minimum (1) */
0x29, 0x05, /* Usage Maximum (5) */
0x15, 0x00, /* Logical Minimum (0) */
0x25, 0x01, /* Logical Maximum (1) */
0x75, 0x01, /* Report Size (1) */
0x95, 0x05, /* Report Count (5) */
0x91, 0x02, /* Output (Data,Var,Abs) */
0x75, 0x03, /* Report Size (3) */
0x95, 0x01, /* Report Count (1) */
0x91, 0x01, /* Output (Const,Array,Abs) */
0xC0 /* End Collection */
};
static const uint8_t consumer_report_desc[] = {
0x05, 0x0C, /* Usage Page (Consumer) */
0x09, 0x01, /* Usage (Consumer Control) */
0xA1, 0x01, /* Collection (Application) */
0x15, 0x00, /* Logical Minimum (0) */
0x26, 0xFF, 0x03, /* Logical Maximum (1023) */
0x19, 0x00, /* Usage Minimum (0) */
0x2A, 0xFF, 0x03, /* Usage Maximum (1023) */
0x75, 0x10, /* Report Size (16) */
0x95, 0x01, /* Report Count (1) */
0x81, 0x00, /* Input (Data,Array,Abs) */
0xC0 /* End Collection */
};
static struct usb_hid_interface_state hid_ifaces[USB_HID_INTERFACE_COUNT] = {
[USB_HID_INTERFACE_KEYBOARD] = {
.dev = DEVICE_DT_GET(DT_NODELABEL(hid_kbd)),
},
[USB_HID_INTERFACE_CONSUMER] = {
.dev = DEVICE_DT_GET(DT_NODELABEL(hid_consumer)),
},
};
static enum keyboard_protocol_mode keyboard_protocol_mode =
KEYBOARD_PROTOCOL_MODE_REPORT;
static bool initialized;
static bool running;
static bool usb_active;
static bool usb_function_prepared;
static bool keyboard_report_in_flight;
static bool consumer_report_in_flight;
static uint16_t keyboard_in_flight_sequence;
static uint16_t consumer_in_flight_sequence;
UDC_STATIC_BUF_DEFINE(keyboard_tx_buf, KEYBOARD_NKRO_REPORT_SIZE);
UDC_STATIC_BUF_DEFINE(consumer_tx_buf, KEYBOARD_CONSUMER_REPORT_SIZE);
static struct usb_hid_interface_state *iface_from_dev(const struct device *dev)
{
for (size_t i = 0; i < ARRAY_SIZE(hid_ifaces); i++) {
if (hid_ifaces[i].dev == dev) {
return &hid_ifaces[i];
}
}
return NULL;
}
static enum keyboard_protocol_mode usb_proto_to_keyboard_proto(uint8_t proto)
{
return (proto == HID_PROTOCOL_BOOT) ? KEYBOARD_PROTOCOL_MODE_BOOT
: KEYBOARD_PROTOCOL_MODE_REPORT;
}
static void reset_usb_runtime_state(void)
{
for (size_t i = 0; i < ARRAY_SIZE(hid_ifaces); i++) {
hid_ifaces[i].ready = false;
}
usb_active = false;
keyboard_report_in_flight = false;
consumer_report_in_flight = false;
}
static void submit_set_protocol_event(enum keyboard_protocol_mode protocol_mode)
{
struct set_protocol_event *event = new_set_protocol_event();
event->transport = HID_TRANSPORT_USB;
event->protocol_mode = protocol_mode;
APP_EVENT_SUBMIT(event);
}
static void submit_hid_led_event(uint8_t led_bm)
{
struct hid_led_event *event = new_hid_led_event();
event->transport = HID_TRANSPORT_USB;
event->led_bm = led_bm;
APP_EVENT_SUBMIT(event);
}
static void submit_transport_state_event(void)
{
struct hid_transport_state_event *event = new_hid_transport_state_event();
bool ready = running && usb_active;
event->transport = HID_TRANSPORT_USB;
event->ready = ready;
event->keys_ready = ready &&
hid_ifaces[USB_HID_INTERFACE_KEYBOARD].ready;
event->consumer_ready = ready &&
hid_ifaces[USB_HID_INTERFACE_CONSUMER].ready;
event->protocol_mode = keyboard_protocol_mode;
APP_EVENT_SUBMIT(event);
}
static void submit_hid_report_sent_event(enum keyboard_report_type report_type,
uint16_t sequence, bool error)
{
struct hid_report_sent_event *event = new_hid_report_sent_event();
event->transport = HID_TRANSPORT_USB;
event->report_type = report_type;
event->sequence = sequence;
event->error = error;
APP_EVENT_SUBMIT(event);
}
static void submit_usb_function_ready_event(void)
{
struct usb_function_ready_event *event = new_usb_function_ready_event();
event->function_mask = USB_FUNCTION_HID;
APP_EVENT_SUBMIT(event);
}
static void keyboard_iface_ready(const struct device *dev, const bool ready)
{
struct usb_hid_interface_state *iface = iface_from_dev(dev);
if (!iface) {
return;
}
iface->ready = ready;
if (!ready) {
keyboard_report_in_flight = false;
}
LOG_INF("%s interface %s", dev->name, ready ? "ready" : "not ready");
submit_transport_state_event();
}
static int keyboard_get_report(const struct device *dev,
const uint8_t type, const uint8_t id,
const uint16_t len, uint8_t *const buf)
{
ARG_UNUSED(dev);
ARG_UNUSED(type);
ARG_UNUSED(id);
ARG_UNUSED(len);
ARG_UNUSED(buf);
return -ENOTSUP;
}
static int keyboard_set_report(const struct device *dev,
const uint8_t type, const uint8_t id,
const uint16_t len, const uint8_t *const buf)
{
ARG_UNUSED(dev);
ARG_UNUSED(type);
ARG_UNUSED(id);
ARG_UNUSED(len);
ARG_UNUSED(buf);
return -ENOTSUP;
}
static void keyboard_set_idle(const struct device *dev,
const uint8_t id, const uint32_t duration)
{
ARG_UNUSED(dev);
ARG_UNUSED(id);
ARG_UNUSED(duration);
}
static uint32_t keyboard_get_idle(const struct device *dev, const uint8_t id)
{
ARG_UNUSED(dev);
ARG_UNUSED(id);
return 0U;
}
static void keyboard_set_protocol(const struct device *dev, const uint8_t proto)
{
ARG_UNUSED(dev);
enum keyboard_protocol_mode new_mode = usb_proto_to_keyboard_proto(proto);
if (keyboard_protocol_mode == new_mode) {
return;
}
keyboard_protocol_mode = new_mode;
LOG_INF("USB keyboard protocol -> %s",
(new_mode == KEYBOARD_PROTOCOL_MODE_BOOT) ? "boot" : "report");
submit_set_protocol_event(new_mode);
submit_transport_state_event();
}
static void keyboard_input_report_done(const struct device *dev,
const uint8_t *const report)
{
ARG_UNUSED(report);
keyboard_report_in_flight = false;
LOG_DBG("USB keyboard report sent by %s", dev->name);
submit_hid_report_sent_event(KEYBOARD_REPORT_TYPE_KEYS,
keyboard_in_flight_sequence, false);
}
static void keyboard_output_report(const struct device *dev,
const uint16_t len,
const uint8_t *const buf)
{
ARG_UNUSED(dev);
if ((len < KBD_LED_REPORT_SIZE) || (buf == NULL)) {
LOG_WRN("Invalid keyboard output report");
return;
}
submit_hid_led_event(buf[0]);
}
static const struct hid_device_ops keyboard_ops = {
.iface_ready = keyboard_iface_ready,
.get_report = keyboard_get_report,
.set_report = keyboard_set_report,
.set_idle = keyboard_set_idle,
.get_idle = keyboard_get_idle,
.set_protocol = keyboard_set_protocol,
.input_report_done = keyboard_input_report_done,
.output_report = keyboard_output_report,
};
static void consumer_iface_ready(const struct device *dev, const bool ready)
{
struct usb_hid_interface_state *iface = iface_from_dev(dev);
if (!iface) {
return;
}
iface->ready = ready;
if (!ready) {
consumer_report_in_flight = false;
}
LOG_INF("%s interface %s", dev->name, ready ? "ready" : "not ready");
submit_transport_state_event();
}
static int consumer_get_report(const struct device *dev,
const uint8_t type, const uint8_t id,
const uint16_t len, uint8_t *const buf)
{
ARG_UNUSED(dev);
ARG_UNUSED(type);
ARG_UNUSED(id);
ARG_UNUSED(len);
ARG_UNUSED(buf);
return -ENOTSUP;
}
static int consumer_set_report(const struct device *dev,
const uint8_t type, const uint8_t id,
const uint16_t len, const uint8_t *const buf)
{
ARG_UNUSED(dev);
ARG_UNUSED(type);
ARG_UNUSED(id);
ARG_UNUSED(len);
ARG_UNUSED(buf);
return -ENOTSUP;
}
static void consumer_set_idle(const struct device *dev,
const uint8_t id, const uint32_t duration)
{
ARG_UNUSED(dev);
ARG_UNUSED(id);
ARG_UNUSED(duration);
}
static uint32_t consumer_get_idle(const struct device *dev, const uint8_t id)
{
ARG_UNUSED(dev);
ARG_UNUSED(id);
return 0U;
}
static void consumer_set_protocol(const struct device *dev, const uint8_t proto)
{
ARG_UNUSED(dev);
ARG_UNUSED(proto);
}
static void consumer_input_report_done(const struct device *dev,
const uint8_t *const report)
{
ARG_UNUSED(report);
consumer_report_in_flight = false;
LOG_DBG("USB consumer report sent by %s", dev->name);
submit_hid_report_sent_event(KEYBOARD_REPORT_TYPE_CONSUMER,
consumer_in_flight_sequence, false);
}
static void consumer_output_report(const struct device *dev,
const uint16_t len,
const uint8_t *const buf)
{
ARG_UNUSED(dev);
ARG_UNUSED(len);
ARG_UNUSED(buf);
}
static const struct hid_device_ops consumer_ops = {
.iface_ready = consumer_iface_ready,
.get_report = consumer_get_report,
.set_report = consumer_set_report,
.set_idle = consumer_set_idle,
.get_idle = consumer_get_idle,
.set_protocol = consumer_set_protocol,
.input_report_done = consumer_input_report_done,
.output_report = consumer_output_report,
};
static int usb_hid_register_devices(void)
{
int err;
for (size_t i = 0; i < ARRAY_SIZE(hid_ifaces); i++) {
if (!device_is_ready(hid_ifaces[i].dev)) {
LOG_ERR("HID device %s not ready", hid_ifaces[i].dev->name);
return -ENODEV;
}
}
err = hid_device_register(hid_ifaces[USB_HID_INTERFACE_KEYBOARD].dev,
keyboard_report_desc,
sizeof(keyboard_report_desc),
&keyboard_ops);
if (err) {
return err;
}
err = hid_device_register(hid_ifaces[USB_HID_INTERFACE_CONSUMER].dev,
consumer_report_desc,
sizeof(consumer_report_desc),
&consumer_ops);
if (err) {
return err;
}
return 0;
}
static int module_init(void)
{
reset_usb_runtime_state();
keyboard_protocol_mode = KEYBOARD_PROTOCOL_MODE_REPORT;
usb_function_prepared = false;
return 0;
}
static int module_start(void)
{
if (running) {
return 0;
}
running = true;
submit_transport_state_event();
return 0;
}
static void module_pause(void)
{
running = false;
submit_transport_state_event();
}
static bool handle_usb_prepare_event(const struct usb_prepare_event *event)
{
int err;
ARG_UNUSED(event);
if (!running || usb_function_prepared) {
return false;
}
err = usb_hid_register_devices();
if (err) {
LOG_ERR("hid_device_register failed (%d)", err);
module_set_state(MODULE_STATE_ERROR);
return false;
}
usb_function_prepared = true;
submit_usb_function_ready_event();
return false;
}
static bool handle_usb_device_state_event(const struct usb_device_state_event *event)
{
bool new_usb_active = (event->state == USB_DEVICE_STATE_ACTIVE);
if (new_usb_active == usb_active) {
return false;
}
if (!new_usb_active) {
reset_usb_runtime_state();
} else {
usb_active = true;
}
submit_transport_state_event();
return false;
}
static bool handle_hid_tx_report_event(const struct hid_tx_report_event *event)
{
int err;
if (!running || !usb_active || (event->transport != HID_TRANSPORT_USB)) {
return false;
}
if (event->report_type == KEYBOARD_REPORT_TYPE_KEYS) {
if (event->protocol_mode != keyboard_protocol_mode) {
LOG_WRN("Drop USB keys report due to protocol mismatch");
return false;
}
if (!hid_ifaces[USB_HID_INTERFACE_KEYBOARD].ready) {
LOG_DBG("USB keyboard interface not ready");
return false;
}
if (keyboard_report_in_flight) {
LOG_WRN("Drop USB keyboard report while previous report is in flight");
return false;
}
memcpy(keyboard_tx_buf, event->dyndata.data, event->dyndata.size);
err = hid_device_submit_report(
hid_ifaces[USB_HID_INTERFACE_KEYBOARD].dev,
(uint16_t)event->dyndata.size,
keyboard_tx_buf);
if (err) {
LOG_WRN("USB keyboard report submit failed (%d)", err);
submit_hid_report_sent_event(KEYBOARD_REPORT_TYPE_KEYS,
event->sequence, true);
} else {
keyboard_report_in_flight = true;
keyboard_in_flight_sequence = event->sequence;
}
return false;
}
if (event->report_type == KEYBOARD_REPORT_TYPE_CONSUMER) {
if (!hid_ifaces[USB_HID_INTERFACE_CONSUMER].ready) {
LOG_DBG("USB consumer interface not ready");
return false;
}
if (consumer_report_in_flight) {
LOG_WRN("Drop USB consumer report while previous report is in flight");
return false;
}
memcpy(consumer_tx_buf, event->dyndata.data, event->dyndata.size);
err = hid_device_submit_report(
hid_ifaces[USB_HID_INTERFACE_CONSUMER].dev,
(uint16_t)event->dyndata.size,
consumer_tx_buf);
if (err) {
LOG_WRN("USB consumer report submit failed (%d)", err);
submit_hid_report_sent_event(KEYBOARD_REPORT_TYPE_CONSUMER,
event->sequence, true);
} else {
consumer_report_in_flight = true;
consumer_in_flight_sequence = event->sequence;
}
}
return false;
}
static bool app_event_handler(const struct app_event_header *aeh)
{
if (is_hid_tx_report_event(aeh)) {
return handle_hid_tx_report_event(cast_hid_tx_report_event(aeh));
}
if (is_usb_device_state_event(aeh)) {
return handle_usb_device_state_event(cast_usb_device_state_event(aeh));
}
if (is_usb_prepare_event(aeh)) {
return handle_usb_prepare_event(cast_usb_prepare_event(aeh));
}
if (is_module_state_event(aeh)) {
const struct module_state_event *event = cast_module_state_event(aeh);
if (check_state(event, MODULE_ID(main), MODULE_STATE_READY)) {
int err;
if (!initialized) {
err = module_init();
if (err) {
module_set_state(MODULE_STATE_ERROR);
return false;
}
initialized = true;
}
err = module_start();
if (err) {
module_set_state(MODULE_STATE_ERROR);
} else {
module_set_state(MODULE_STATE_READY);
}
}
return false;
}
if (is_power_down_event(aeh)) {
if (initialized) {
module_pause();
module_set_state(MODULE_STATE_STANDBY);
}
return false;
}
if (is_wake_up_event(aeh)) {
if (initialized) {
int err = module_start();
if (err) {
module_set_state(MODULE_STATE_ERROR);
} else {
module_set_state(MODULE_STATE_READY);
}
}
return false;
}
return false;
}
APP_EVENT_LISTENER(MODULE, app_event_handler);
APP_EVENT_SUBSCRIBE(MODULE, module_state_event);
APP_EVENT_SUBSCRIBE(MODULE, hid_tx_report_event);
APP_EVENT_SUBSCRIBE(MODULE, usb_prepare_event);
APP_EVENT_SUBSCRIBE(MODULE, usb_device_state_event);
APP_EVENT_SUBSCRIBE_EARLY(MODULE, power_down_event);
APP_EVENT_SUBSCRIBE(MODULE, wake_up_event);

2
sysbuild.conf Normal file
View File

@@ -0,0 +1,2 @@
SB_CONFIG_BOOTLOADER_MCUBOOT=y
SB_CONFIG_MCUBOOT_MODE_SINGLE_APP=y