Compare commits

..

21 Commits

Author SHA1 Message Date
0a1357c62d refactor(module_lifecycle): 重构模块生命周期管理实现
移除了LC_SUSPENDED状态并简化了生命周期状态转换逻辑,
将状态名称查询功能统一到module_lifecycle_name函数中,
删除了不再需要的状态检查和路径验证函数,
同时更新了相关的配置文件和模块调用以适配新的API。
2026-04-21 14:34:08 +08:00
e0817a7b44 feat(module_lifecycle): 完善模块生命周期管理功能
- 添加了模块生命周期状态转换验证函数,包括目标状态允许性检查和路径允许性检查
- 实现了模块操作验证功能,确保必要的回调函数存在
- 更新了状态报告逻辑,增加了模式检查以防止无效状态转换
- 修改了生命周期转换流程,区分运行启动和停止操作
- 优化了错误处理机制,返回适当的错误码

refactor(ble_modules): 简化BLE模块生命周期配置

- 将多个BLE模块(lifecycle_cfg)的模式从ML_MODE_POWER改为ML_MODE_NONE
- 移除了power_event相关依赖和事件订阅
- 更新了BLE BAS模块的状态转换逻辑
- 简化了BLE HID/NUS/Protocol模块的电源管理相关代码

fix(mode_switch): 修复唤醒后模式恢复功能

- 在唤醒事件处理中添加了最后模式的恢复逻辑
- 确保设备唤醒后能够重新提交之前的模式切换事件
2026-04-18 14:17:23 +08:00
caf8d5acc6 feat(mode_switch): 添加无效模式枚举值并更新事件处理
添加 MODE_SWITCH_INVALID 枚举值到 mode_switch_mode 中,
用于表示无效的模式状态。同时更新相关的事件处理逻辑,
确保在模式切换时能够正确处理无效模式的情况。

refactor(mode_policy): 简化模块上下文结构并优化模式策略

将模块上下文中的 ble_adv_suspended 和 usb_enabled 标志位
替换为 active_mode 枚举值,简化了数据结构。重新设计了
模式策略应用逻辑,使其更清晰易懂,并改进了BLE和USB设备
的启用/暂停控制流程。

refactor(usb_device): 重构USB设备生命周期管理

移除了 USB_STACK_DISABLED 状态,简化了USB栈的状态管理。
改进了USB设备的启动和停止逻辑,更好地与模块生命周期
集成。现在USB状态事件仅在模块初始化后提交,避免了
不必要的事件发布。

feat(logging): 增加详细的状态转换日志记录

为BLE NUS模块添加了业务状态转换的日志记录功能,
增加了详细的错误和警告日志,包括生命周期状态、
业务状态和连接信息,便于调试和问题排查。

refactor(mode_switch): 优化模式检测和报告机制

修改了模式切换采样的判断逻辑,移除了force_report和
mode_valid标志位,改用last_mode状态来决定是否提交
模式切换事件,使代码更简洁且易于理解。
2026-04-18 11:27:48 +08:00
ceebaaa600 feat: 添加模块生命周期管理框架并重构现有模块
添加了模块生命周期管理头文件 module_lifecycle.h,定义了完整的生命周期状态机,
包括初始化、运行、停止、挂起和错误状态。同时将电池模块、BLE BAS模块、BLE HID
模块和BLE NUS模块重构为使用新的生命周期框架进行状态管理。

提升日志缓冲区大小以支持更详细的调试信息记录。
2026-04-17 19:12:57 +08:00
8bfb8b540c feat(bt): 添加蓝牙外设首选超时配置
新增 CONFIG_BT_PERIPHERAL_PREF_TIMEOUT 配置项,
设置为 400 以优化蓝牙连接超时参数
2026-04-17 16:17:13 +08:00
0cbb16052d feat(protocol): 添加传输状态事件管理协议会话状态
添加了新的 proto_transport_state_event 事件类型来跟踪协议传输连接状态,
包括链接断开和就绪状态。为 BLE NUS 和 USB CDC 模块实现了状态机管理,
替换原有的简单布尔标志,提供更精确的连接状态跟踪。

- 添加 proto_transport_state_event 事件定义和实现
- 为 BLE NUS 模块引入业务状态机管理
- 为 USB CDC 模块引入业务状态机管理
- 实现协议模块中的会话状态管理
- 移除 protocol_module_reset_transport_state 函数
- 更新 CMakeLists.txt 包含新事件源文件
2026-04-17 11:55:03 +08:00
2ca02325c1 feat(usb_hid_keyboard): 支持键盘LED报告处理
- 添加KBD_LED_REPORT_WITH_ID_SIZE宏定义以支持带ID的LED报告
- 实现keyboard_handle_led_report函数来处理不同长度的LED报告
- 在keyboard_set_report中添加对HID_REPORT_TYPE_OUTPUT类型的支持
- 优化keyboard_output_report函数以复用LED报告处理逻辑
- 移除datetime_event中的INIT_LOG_ENABLE标志

支持处理长度为1字节或2字节(包含report ID)的键盘LED报告,
并提供适当的错误日志记录功能。
2026-04-15 17:54:21 +08:00
bd57b00080 feat(hid): 实现HID通道状态管理和多通道支持
- 将原来的HID传输状态事件替换为新的HID通道状态事件,支持USB键盘、USB消费者和BLE共享通道
- 添加usb_hid_consumer_module.c模块来处理USB消费者HID报告
- 添加usb_hid_keyboard_module.c模块来处理USB键盘HID报告
- 修改CMakeLists.txt以包含新的HID模块源文件
- 更新事件系统中的transport字段为channel字段,并相应修改所有相关处理逻辑
- 在hid_flowctrl_module.c中实现多通道并发处理机制
- 删除过时的hid_transport_state_event相关代码
- 添加新的hid_channel_state_event用于报告各通道就绪状态
2026-04-15 15:47:14 +08:00
6125f04102 feat(usb): 简化USB状态管理并引入模式策略模块
- 修改usb_state_event结构,将复杂的flag操作简化为单一的state枚举值
- 新增usb_function_hook机制用于USB功能预初始化
- 将ble_adv_ctrl_module重命名为mode_policy_module以更好地反映其功能
- 在mode_policy_module中添加USB设备启用/暂停控制逻辑
- 添加对电源事件的处理支持休眠/唤醒功能
- 更新CMakeLists.txt添加必要的链接器脚本和源文件
- 移除不再需要的ble_adv_ctrl_module并添加新的mode_policy_module
2026-04-15 15:13:44 +08:00
0a905d280d refactor(ui): 移除屏幕背景渐变样式
移除了UI主界面屏幕对象的背景渐变颜色和垂直渐变方向样式设置,
统一使用纯色背景以简化界面设计并提升渲染性能。
2026-04-15 10:59:03 +08:00
79af0eb025 feat(events): 添加功能位图状态事件并移除旧的按键功能事件
- 添加新的 function_bitmap_state_event 事件类型用于跟踪功能键位图状态
- 移除已废弃的 key_function_event 事件及其相关文件
- 更新 CMakeLists.txt 中的源文件列表以包含新事件文件
- 修改协议定义文件 device_comm.options 和 device_comm.proto
  以使用位图方式传输功能键状态而不是单独的按键事件
- 更新键盘核心模块中的位图处理逻辑,添加 usage_to_bitmap_pos
 辅助函数来正确定位修饰键和普通按键的位置
- 修改报告构建逻辑以正确处理新的位图布局
- 更新协议模块以处理新的功能位图状态事件和 LED 状态事件
- 实现协议模块中的 ACK、错误响应和 LED 状态编码功能
2026-04-15 10:52:01 +08:00
bc42a4dd63 feat(ble): 添加BLE NUS模块替换原有的BLE串口功能
- 将ble_serial_module替换为ble_nus_module以使用标准的BLE NUS服务
- 移除不再使用的cdc_wrapper_module和相关事件处理
- 更新协议传输层抽象,支持USB CDC和BLE NUS两种传输方式
- 创建统一的proto_rx_event和proto_tx_event替代专用的串行通信事件
- 添加proto_common.h定义传输类型枚举
- 修改protocol_module接口以支持多传输方式
- 在prj.conf中启用CONFIG_BT_ZEPHYR_NUS配置选项
2026-04-15 10:34:12 +08:00
c4b205b8a1 feat(usb): 引入统一的USB状态事件系统
重构USB事件管理,将原有的多个专用事件(usb_device_state_event、
usb_function_ready_event、usb_prepare_event)合并为统一的
usb_state_event。新的事件系统采用位标志方式管理USB状态,
提供更灵活的状态跟踪机制。

BREAKING CHANGE: 移除了旧的USB相关事件类型,需要更新依赖这些
事件的模块代码。
2026-04-15 09:30:40 +08:00
78a6dc212d feat(events): 添加事件提交函数到各个头文件中
为多个事件头文件添加了静态内联提交函数,包括:
- bat_state_event: 添加submit_bat_state_event函数
- ble_serial_rx_event: 添加submit_ble_serial_rx_event函数
- ble_serial_tx_event: 添加submit_ble_serial_tx_event函数
- cdc_proto_tx_event: 添加submit_cdc_proto_tx_event函数
- datetime_event: 添加submit_datetime_event函数
- encoder_event: 添加submit_encoder_event函数
- function_bitmap_update_event: 添加submit_function_bitmap_update_event函数
- hid_led_event: 添加submit_hid_led_event函数
- hid_report_sent_event: 添加submit_hid_report_sent_event函数
- hid_transport_state_event: 添加submit_hid_transport_state_event函数
- hid_tx_report_event: 添加submit_hid_tx_report_event函数
- key_function_event: 添加submit_key_function_event函数
- keyboard_hid_report_event: 添加submit_keyboard_hid_report_event函数
- led_strip_en_event: 添加submit_led_strip_en_event函数
- mode_switch_event: 添加submit_mode_switch_event函数
- set_protocol_event: 添加submit_set_protocol_event函数
- theme_rgb_update_event: 添加submit_theme_rgb_update_event函数
- time_sync_event: 添加submit_time_sync_event函数
- usb_cdc_rx_event: 添加submit_usb_cdc_rx_event函数
- usb_cdc_tx_event: 添加submit_usb_cdc_tx_event函数
- usb_device_state_event: 添加submit_usb_device_state_event函数
- usb_function_ready_event: 添加submit_usb_function_ready_event函数
- usb_prepare_event: 添加submit_usb_prepare_event函数

这些函数提供了一致的事件提交接口,简化了事件创建和提交过程。
2026-04-14 16:42:04 +08:00
c342a8d3f0 feat(protocol): 添加时间同步和主题颜色协议支持
- 添加CDC_PROTO_TYPE_LED_STATE、CDC_PROTO_TYPE_TIME_SYNC和
  CDC_PROTO_TYPE_THEME_RGB协议类型定义
- 在protobuf中定义LedState、TimeSync和ThemeRgb消息结构
- 更新CdcPacketBody消息以包含新的协议类型
- 增加协议能力标志位以支持新功能
2026-04-13 16:43:17 +08:00
23e23f63a7 feat(led): 添加LED按键淡入淡出效果并重构LED条模块
添加了完整的LED效果系统架构,包括:
- 新增主题颜色定义文件theme_color.h
- 实现key fade LED效果算法,支持按键触发的渐变效果
- 创建LED效果注册机制和通用接口
- 配置17个LED像素与按键映射关系
- 将原有简单的周期性效果替换为基于按键事件的动态效果

CMakeLists.txt中添加了新的源文件路径和实现文件。

BREAKING CHANGE: LED效果从固定的周期性变化改为响应按键事件的动态效果。
2026-04-13 15:56:45 +08:00
ff8f0d81d7 feat: 添加LED灯带模块支持
- 在CMakeLists.txt中添加led_strip_module.c源文件和led_strip_en_event.c事件文件
- 在设备树配置中添加SPI1接口的WS2812灯带引脚控制配置
- 在板级配置文件中添加LED灯带设备节点和别名定义
- 新增led_strip_en_event事件头文件和实现,用于控制灯带使能状态
- 配置prj.conf启用LED Strip和WS2812 SPI驱动
- 实现完整的LED灯带模块功能,包括:
  - 初始化和电源管理
  - RGB色彩效果渲染
  - 通过GPIO控制灯带供电
  - 响应应用事件进行启停控制
2026-04-13 15:23:46 +08:00
968fb626bb feat(nvs): 增加应用事件管理器最大事件计数配置
新增 CONFIG_APP_EVENT_MANAGER_MAX_EVENT_CNT 配置项,
设置最大事件计数为64,以支持更多的应用事件管理需求。
2026-04-13 14:10:15 +08:00
30bc314698 feat(protocol): 添加键盘协议功能支持
添加了完整的键盘协议功能,包括:
- 新增多个事件类型:cdc_proto_tx_event、function_bitmap_update_event、key_function_event
- 在CMakeLists.txt中注册新的事件源文件
- 扩展keyboard_core.h定义键盘协议相关宏
- 增强protocol_module.h定义协议消息类型常量
- 更新protobuf定义device_comm.proto添加Bitmap、FunctionKeyEvent、Ack、Error消息
- 实现CDC协议包装器模块处理协议消息传输
- 改进键盘核心模块实现按键功能映射和位图管理
- 添加协议模块处理Hello、Bitmap、FunctionKeyEvent等协议消息
- 实现USB设备状态管理和错误响应机制
2026-04-13 11:55:59 +08:00
d86f0d6b78 Merge branch 'dev' 2026-04-13 10:11:18 +08:00
15307dfde5 feat: 添加蓝牙串口模块支持
- 添加 ble_serial_module.c 实现蓝牙串口功能
- 添加 ble_serial_rx_event 和 ble_serial_tx_event 事件定义及实现
- 在 CMakeLists.txt 中注册新的源文件和事件
- 配置蓝牙 L2CAP MTU 和缓冲区大小参数
- 修改 usb_cdc_test_module 支持通过蓝牙发送测试消息
- 实现蓝牙连接状态管理及数据收发功能
2026-04-13 10:10:46 +08:00
89 changed files with 5504 additions and 2887 deletions

View File

@@ -6,10 +6,12 @@ project(blinky)
list(APPEND CMAKE_MODULE_PATH ${ZEPHYR_BASE}/modules/nanopb)
include(nanopb)
zephyr_linker_sources(SECTIONS src/usb_function_hook.ld)
zephyr_include_directories(
inc
inc/events
src
)
add_subdirectory(drivers)
@@ -20,33 +22,44 @@ zephyr_nanopb_sources(app
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/ble_nus_module.c
src/display_module.c
src/encoder_module.c
src/hid_flowctrl_module.c
src/keyboard_core_module.c
src/led_effect/led_effect_registry.c
src/led_effect/effects/led_effect_key_fade.c
src/led_strip_module.c
src/mode_policy_module.c
src/time_sync_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/usb_hid_consumer_module.c
src/usb_hid_keyboard_module.c
src/events/bat_state_event.c
src/events/datetime_event.c
src/events/encoder_event.c
src/events/function_bitmap_state_event.c
src/events/function_bitmap_update_event.c
src/events/hid_channel_state_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/events/led_strip_en_event.c
src/mode_switch_module.c
src/events/keyboard_hid_report_event.c
src/events/mode_switch_event.c
src/events/proto_rx_event.c
src/events/proto_transport_state_event.c
src/events/proto_tx_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
src/events/theme_rgb_update_event.c
src/events/time_sync_event.c
src/events/usb_control_event.c
src/events/usb_state_event.c
)

View File

@@ -46,6 +46,21 @@
};
};
spi1_ws2812_default: spi1_ws2812_default {
group1 {
psels = <NRF_PSEL(SPIM_SCK, 1, 4)>,
<NRF_PSEL(SPIM_MOSI, 0, 20)>;
};
};
spi1_ws2812_sleep: spi1_ws2812_sleep {
group1 {
psels = <NRF_PSEL(SPIM_SCK, 1, 4)>,
<NRF_PSEL(SPIM_MOSI, 0, 20)>;
low-power-enable;
};
};
pwm0_default: pwm0_default {
group1 {
psels = <NRF_PSEL(PWM_OUT0, 1, 11)>;

View File

@@ -2,6 +2,7 @@
#include <nordic/nrf52840_qiaa.dtsi>
#include "mini_keyboard-pinctrl.dtsi"
#include <zephyr/dt-bindings/adc/adc.h>
#include <zephyr/dt-bindings/led/led.h>
#include <zephyr/dt-bindings/mipi_dbi/mipi_dbi.h>
#include <zephyr/dt-bindings/pwm/pwm.h>
@@ -14,10 +15,12 @@
zephyr,flash = &flash0;
zephyr,code-partition = &slot0_partition;
zephyr,display = &screen_lcd;
zephyr,led-strip = &led_strip;
};
aliases {
led0 = &myled0;
led-strip = &led_strip;
qdec0 = &qdec;
backlight = &backlight;
};
@@ -27,7 +30,7 @@
label = "HID_KBD";
protocol-code = "keyboard";
in-report-size = <29>;
out-report-size = <1>;
out-report-size = <29>;
in-polling-period-us = <1000>;
out-polling-period-us = <1000>;
};
@@ -206,6 +209,28 @@
cs-gpios = <&gpio0 2 GPIO_ACTIVE_LOW>;
};
&spi1 {
status = "okay";
pinctrl-0 = <&spi1_ws2812_default>;
pinctrl-1 = <&spi1_ws2812_sleep>;
pinctrl-names = "default", "sleep";
led_strip: ws2812@0 {
compatible = "worldsemi,ws2812-spi";
reg = <0>;
spi-max-frequency = <6400000>;
chain-length = <17>;
color-mapping = <LED_COLOR_ID_GREEN
LED_COLOR_ID_RED
LED_COLOR_ID_BLUE>;
spi-one-frame = <0x70>;
spi-zero-frame = <0x40>;
bits-per-symbol = <8>;
reset-delay = <8>;
supply-gpios = <&gpio0 13 GPIO_ACTIVE_HIGH>;
};
};
&pwm0 {
status = "okay";
pinctrl-0 = <&pwm0_default>;

View File

@@ -1,12 +0,0 @@
#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_ */

View File

@@ -20,6 +20,16 @@ struct bat_state_event {
APP_EVENT_TYPE_DECLARE(bat_state_event);
static inline void submit_bat_state_event(uint8_t soc, bool charging, bool full)
{
struct bat_state_event *event = new_bat_state_event();
event->soc = soc;
event->charging = charging;
event->full = full;
APP_EVENT_SUBMIT(event);
}
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,45 @@
#ifndef BLINKY_DATETIME_EVENT_H_
#define BLINKY_DATETIME_EVENT_H_
#include <errno.h>
#include <string.h>
#include <app_event_manager.h>
#include <app_event_manager_profiler_tracer.h>
#ifdef __cplusplus
extern "C" {
#endif
#define DATETIME_EVENT_DATE_TEXT_LEN 16
#define DATETIME_EVENT_TIME_TEXT_LEN 16
struct datetime_event {
struct app_event_header header;
char date_text[DATETIME_EVENT_DATE_TEXT_LEN];
char time_text[DATETIME_EVENT_TIME_TEXT_LEN];
};
APP_EVENT_TYPE_DECLARE(datetime_event);
static inline int submit_datetime_event(const char *date_text, const char *time_text)
{
struct datetime_event *event = new_datetime_event();
if ((date_text == NULL) || (time_text == NULL)) {
return -EINVAL;
}
strncpy(event->date_text, date_text, sizeof(event->date_text));
event->date_text[sizeof(event->date_text) - 1] = '\0';
strncpy(event->time_text, time_text, sizeof(event->time_text));
event->time_text[sizeof(event->time_text) - 1] = '\0';
APP_EVENT_SUBMIT(event);
return 0;
}
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_DATETIME_EVENT_H_ */

View File

@@ -15,6 +15,14 @@ struct encoder_event {
APP_EVENT_TYPE_DECLARE(encoder_event);
static inline void submit_encoder_event(int8_t detents)
{
struct encoder_event *event = new_encoder_event();
event->detents = detents;
APP_EVENT_SUBMIT(event);
}
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,41 @@
#ifndef BLINKY_FUNCTION_BITMAP_STATE_EVENT_H_
#define BLINKY_FUNCTION_BITMAP_STATE_EVENT_H_
#include <errno.h>
#include <string.h>
#include <app_event_manager.h>
#include <app_event_manager_profiler_tracer.h>
#include "keyboard_core.h"
#ifdef __cplusplus
extern "C" {
#endif
struct function_bitmap_state_event {
struct app_event_header header;
uint8_t bitmap[KEYBOARD_PROTOCOL_BITMAP_BYTES];
};
APP_EVENT_TYPE_DECLARE(function_bitmap_state_event);
static inline int submit_function_bitmap_state_event(const uint8_t *bitmap)
{
struct function_bitmap_state_event *event;
if (bitmap == NULL) {
return -EINVAL;
}
event = new_function_bitmap_state_event();
memcpy(event->bitmap, bitmap, sizeof(event->bitmap));
APP_EVENT_SUBMIT(event);
return 0;
}
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_FUNCTION_BITMAP_STATE_EVENT_H_ */

View File

@@ -0,0 +1,41 @@
#ifndef BLINKY_FUNCTION_BITMAP_UPDATE_EVENT_H_
#define BLINKY_FUNCTION_BITMAP_UPDATE_EVENT_H_
#include <errno.h>
#include <string.h>
#include <app_event_manager.h>
#include <app_event_manager_profiler_tracer.h>
#include "keyboard_core.h"
#ifdef __cplusplus
extern "C" {
#endif
struct function_bitmap_update_event {
struct app_event_header header;
uint8_t bitmap[KEYBOARD_PROTOCOL_BITMAP_BYTES];
};
APP_EVENT_TYPE_DECLARE(function_bitmap_update_event);
static inline int submit_function_bitmap_update_event(const uint8_t *bitmap)
{
struct function_bitmap_update_event *event;
if (bitmap == NULL) {
return -EINVAL;
}
event = new_function_bitmap_update_event();
memcpy(event->bitmap, bitmap, sizeof(event->bitmap));
APP_EVENT_SUBMIT(event);
return 0;
}
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_FUNCTION_BITMAP_UPDATE_EVENT_H_ */

View File

@@ -0,0 +1,38 @@
#ifndef BLINKY_HID_CHANNEL_STATE_EVENT_H_
#define BLINKY_HID_CHANNEL_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_channel_state_event {
struct app_event_header header;
enum hid_send_channel channel;
uint8_t report_ready_bm;
enum keyboard_protocol_mode protocol_mode;
};
APP_EVENT_TYPE_DECLARE(hid_channel_state_event);
static inline void submit_hid_channel_state_event(
enum hid_send_channel channel, uint8_t report_ready_bm,
enum keyboard_protocol_mode protocol_mode)
{
struct hid_channel_state_event *event = new_hid_channel_state_event();
event->channel = channel;
event->report_ready_bm = report_ready_bm;
event->protocol_mode = protocol_mode;
APP_EVENT_SUBMIT(event);
}
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_HID_CHANNEL_STATE_EVENT_H_ */

View File

@@ -18,6 +18,15 @@ struct hid_led_event {
APP_EVENT_TYPE_DECLARE(hid_led_event);
static inline void submit_hid_led_event(enum hid_transport transport, uint8_t led_bm)
{
struct hid_led_event *event = new_hid_led_event();
event->transport = transport;
event->led_bm = led_bm;
APP_EVENT_SUBMIT(event);
}
#ifdef __cplusplus
}
#endif

View File

@@ -12,7 +12,7 @@ extern "C" {
struct hid_report_sent_event {
struct app_event_header header;
enum hid_transport transport;
enum hid_send_channel channel;
enum keyboard_report_type report_type;
uint16_t sequence;
bool error;
@@ -20,6 +20,19 @@ struct hid_report_sent_event {
APP_EVENT_TYPE_DECLARE(hid_report_sent_event);
static inline void submit_hid_report_sent_event(enum hid_send_channel channel,
enum keyboard_report_type report_type,
uint16_t sequence, bool error)
{
struct hid_report_sent_event *event = new_hid_report_sent_event();
event->channel = channel;
event->report_type = report_type;
event->sequence = sequence;
event->error = error;
APP_EVENT_SUBMIT(event);
}
#ifdef __cplusplus
}
#endif

View File

@@ -1,28 +0,0 @@
#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

@@ -1,6 +1,10 @@
#ifndef BLINKY_HID_TX_REPORT_EVENT_H_
#define BLINKY_HID_TX_REPORT_EVENT_H_
#include <errno.h>
#include <stddef.h>
#include <string.h>
#include <app_event_manager.h>
#include <app_event_manager_profiler_tracer.h>
@@ -12,7 +16,7 @@ extern "C" {
struct hid_tx_report_event {
struct app_event_header header;
enum hid_transport transport;
enum hid_send_channel channel;
enum keyboard_report_type report_type;
enum keyboard_protocol_mode protocol_mode;
uint16_t sequence;
@@ -21,6 +25,31 @@ struct hid_tx_report_event {
APP_EVENT_TYPE_DYNDATA_DECLARE(hid_tx_report_event);
static inline int submit_hid_tx_report_event(enum hid_send_channel channel,
enum keyboard_report_type report_type,
enum keyboard_protocol_mode protocol_mode,
uint16_t sequence,
const uint8_t *data, size_t size)
{
struct hid_tx_report_event *event;
if ((data == NULL) && (size > 0U)) {
return -EINVAL;
}
event = new_hid_tx_report_event(size);
event->channel = channel;
event->report_type = report_type;
event->protocol_mode = protocol_mode;
event->sequence = sequence;
if (size > 0U) {
memcpy(event->dyndata.data, data, size);
}
APP_EVENT_SUBMIT(event);
return 0;
}
#ifdef __cplusplus
}
#endif

View File

@@ -1,6 +1,10 @@
#ifndef BLINKY_KEYBOARD_HID_REPORT_EVENT_H_
#define BLINKY_KEYBOARD_HID_REPORT_EVENT_H_
#include <errno.h>
#include <stddef.h>
#include <string.h>
#include <app_event_manager.h>
#include <app_event_manager_profiler_tracer.h>
@@ -22,6 +26,30 @@ struct keyboard_hid_report_event {
APP_EVENT_TYPE_DYNDATA_DECLARE(keyboard_hid_report_event);
static inline int submit_keyboard_hid_report_event(
enum mode_switch_mode mode, enum keyboard_report_type report_type,
enum keyboard_protocol_mode protocol_mode,
enum hid_queue_policy queue_policy, const uint8_t *data, size_t size)
{
struct keyboard_hid_report_event *event;
if ((data == NULL) && (size > 0U)) {
return -EINVAL;
}
event = new_keyboard_hid_report_event(size);
event->mode = mode;
event->report_type = report_type;
event->protocol_mode = protocol_mode;
event->queue_policy = queue_policy;
if (size > 0U) {
memcpy(event->dyndata.data, data, size);
}
APP_EVENT_SUBMIT(event);
return 0;
}
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,32 @@
#ifndef BLINKY_LED_STRIP_EN_EVENT_H_
#define BLINKY_LED_STRIP_EN_EVENT_H_
#include <stdbool.h>
#include <app_event_manager.h>
#include <app_event_manager_profiler_tracer.h>
#ifdef __cplusplus
extern "C" {
#endif
struct led_strip_en_event {
struct app_event_header header;
bool enabled;
};
APP_EVENT_TYPE_DECLARE(led_strip_en_event);
static inline void submit_led_strip_en_event(bool enabled)
{
struct led_strip_en_event *event = new_led_strip_en_event();
event->enabled = enabled;
APP_EVENT_SUBMIT(event);
}
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_LED_STRIP_EN_EVENT_H_ */

View File

@@ -9,6 +9,7 @@ extern "C" {
#endif
enum mode_switch_mode {
MODE_SWITCH_INVALID,
MODE_SWITCH_USB,
MODE_SWITCH_24G,
MODE_SWITCH_BLE,
@@ -22,6 +23,16 @@ struct mode_switch_event {
APP_EVENT_TYPE_DECLARE(mode_switch_event);
static inline void submit_mode_switch_event(enum mode_switch_mode mode,
uint16_t voltage_mv)
{
struct mode_switch_event *event = new_mode_switch_event();
event->mode = mode;
event->voltage_mv = voltage_mv;
APP_EVENT_SUBMIT(event);
}
#ifdef __cplusplus
}
#endif

23
inc/events/proto_common.h Normal file
View File

@@ -0,0 +1,23 @@
#ifndef BLINKY_PROTO_COMMON_H_
#define BLINKY_PROTO_COMMON_H_
#ifdef __cplusplus
extern "C" {
#endif
enum proto_transport {
PROTO_TRANSPORT_USB_CDC = 0,
PROTO_TRANSPORT_BLE_NUS,
PROTO_TRANSPORT_COUNT,
};
enum proto_transport_link_state {
PROTO_TRANSPORT_LINK_DOWN = 0,
PROTO_TRANSPORT_LINK_READY,
};
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_PROTO_COMMON_H_ */

View File

@@ -0,0 +1,50 @@
#ifndef BLINKY_PROTO_RX_EVENT_H_
#define BLINKY_PROTO_RX_EVENT_H_
#include <errno.h>
#include <stddef.h>
#include <string.h>
#include <app_event_manager.h>
#include <app_event_manager_profiler_tracer.h>
#include "proto_common.h"
#ifdef __cplusplus
extern "C" {
#endif
struct proto_rx_event {
struct app_event_header header;
enum proto_transport transport;
struct event_dyndata dyndata;
};
APP_EVENT_TYPE_DYNDATA_DECLARE(proto_rx_event);
static inline int submit_proto_rx_event(enum proto_transport transport,
const uint8_t *data, size_t len)
{
struct proto_rx_event *event;
if ((transport >= PROTO_TRANSPORT_COUNT) ||
((data == NULL) && (len > 0U))) {
return -EINVAL;
}
event = new_proto_rx_event(len);
event->transport = transport;
if (len > 0U) {
memcpy(event->dyndata.data, data, len);
}
APP_EVENT_SUBMIT(event);
return 0;
}
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_PROTO_RX_EVENT_H_ */

View File

@@ -0,0 +1,36 @@
#ifndef BLINKY_PROTO_TRANSPORT_STATE_EVENT_H_
#define BLINKY_PROTO_TRANSPORT_STATE_EVENT_H_
#include <app_event_manager.h>
#include <app_event_manager_profiler_tracer.h>
#include "proto_common.h"
#ifdef __cplusplus
extern "C" {
#endif
struct proto_transport_state_event {
struct app_event_header header;
enum proto_transport transport;
enum proto_transport_link_state state;
};
APP_EVENT_TYPE_DECLARE(proto_transport_state_event);
static inline void submit_proto_transport_state_event(
enum proto_transport transport, enum proto_transport_link_state state)
{
struct proto_transport_state_event *event =
new_proto_transport_state_event();
event->transport = transport;
event->state = state;
APP_EVENT_SUBMIT(event);
}
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_PROTO_TRANSPORT_STATE_EVENT_H_ */

View File

@@ -0,0 +1,50 @@
#ifndef BLINKY_PROTO_TX_EVENT_H_
#define BLINKY_PROTO_TX_EVENT_H_
#include <errno.h>
#include <stddef.h>
#include <string.h>
#include <app_event_manager.h>
#include <app_event_manager_profiler_tracer.h>
#include "proto_common.h"
#ifdef __cplusplus
extern "C" {
#endif
struct proto_tx_event {
struct app_event_header header;
enum proto_transport transport;
struct event_dyndata dyndata;
};
APP_EVENT_TYPE_DYNDATA_DECLARE(proto_tx_event);
static inline int submit_proto_tx_event(enum proto_transport transport,
const uint8_t *data, size_t len)
{
struct proto_tx_event *event;
if ((transport >= PROTO_TRANSPORT_COUNT) ||
((data == NULL) && (len > 0U))) {
return -EINVAL;
}
event = new_proto_tx_event(len);
event->transport = transport;
if (len > 0U) {
memcpy(event->dyndata.data, data, len);
}
APP_EVENT_SUBMIT(event);
return 0;
}
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_PROTO_TX_EVENT_H_ */

View File

@@ -18,6 +18,16 @@ struct set_protocol_event {
APP_EVENT_TYPE_DECLARE(set_protocol_event);
static inline void submit_set_protocol_event(enum hid_transport transport,
enum keyboard_protocol_mode protocol_mode)
{
struct set_protocol_event *event = new_set_protocol_event();
event->transport = transport;
event->protocol_mode = protocol_mode;
APP_EVENT_SUBMIT(event);
}
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,32 @@
#ifndef BLINKY_THEME_RGB_UPDATE_EVENT_H_
#define BLINKY_THEME_RGB_UPDATE_EVENT_H_
#include <app_event_manager.h>
#include <app_event_manager_profiler_tracer.h>
#include "theme_color.h"
#ifdef __cplusplus
extern "C" {
#endif
struct theme_rgb_update_event {
struct app_event_header header;
struct theme_rgb theme;
};
APP_EVENT_TYPE_DECLARE(theme_rgb_update_event);
static inline void submit_theme_rgb_update_event(struct theme_rgb theme)
{
struct theme_rgb_update_event *event = new_theme_rgb_update_event();
event->theme = theme;
APP_EVENT_SUBMIT(event);
}
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_THEME_RGB_UPDATE_EVENT_H_ */

View File

@@ -0,0 +1,40 @@
#ifndef BLINKY_TIME_SYNC_EVENT_H_
#define BLINKY_TIME_SYNC_EVENT_H_
#include <app_event_manager.h>
#include <app_event_manager_profiler_tracer.h>
#ifdef __cplusplus
extern "C" {
#endif
struct time_sync_event {
struct app_event_header header;
uint32_t version;
uint32_t flags;
int32_t timezone_min;
uint64_t utc_ms;
uint32_t accuracy_ms;
};
APP_EVENT_TYPE_DECLARE(time_sync_event);
static inline void submit_time_sync_event(uint32_t version, uint32_t flags,
int32_t timezone_min, uint64_t utc_ms,
uint32_t accuracy_ms)
{
struct time_sync_event *event = new_time_sync_event();
event->version = version;
event->flags = flags;
event->timezone_min = timezone_min;
event->utc_ms = utc_ms;
event->accuracy_ms = accuracy_ms;
APP_EVENT_SUBMIT(event);
}
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_TIME_SYNC_EVENT_H_ */

View File

@@ -1,22 +0,0 @@
#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

@@ -1,22 +0,0 @@
#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,71 @@
#ifndef BLINKY_USB_CONTROL_EVENT_H_
#define BLINKY_USB_CONTROL_EVENT_H_
#include <stdbool.h>
#include <stdint.h>
#include <app_event_manager.h>
#include <app_event_manager_profiler_tracer.h>
#include <zephyr/device.h>
#ifdef __cplusplus
extern "C" {
#endif
enum usb_control_event_type {
USB_CONTROL_EVENT_CDC_LINE_STATE = 0,
USB_CONTROL_EVENT_CDC_LINE_CODING,
};
struct usb_control_event {
struct app_event_header header;
enum usb_control_event_type type;
const struct device *dev;
union {
struct {
bool dtr;
} cdc_line_state;
struct {
uint32_t baudrate;
uint8_t data_bits;
uint8_t stop_bits;
uint8_t parity;
uint8_t flow_ctrl;
} cdc_line_coding;
} data;
};
APP_EVENT_TYPE_DECLARE(usb_control_event);
static inline void submit_usb_control_cdc_line_state_event(
const struct device *dev, bool dtr)
{
struct usb_control_event *event = new_usb_control_event();
event->type = USB_CONTROL_EVENT_CDC_LINE_STATE;
event->dev = dev;
event->data.cdc_line_state.dtr = dtr;
APP_EVENT_SUBMIT(event);
}
static inline void submit_usb_control_cdc_line_coding_event(
const struct device *dev, uint32_t baudrate, uint8_t data_bits,
uint8_t stop_bits, uint8_t parity, uint8_t flow_ctrl)
{
struct usb_control_event *event = new_usb_control_event();
event->type = USB_CONTROL_EVENT_CDC_LINE_CODING;
event->dev = dev;
event->data.cdc_line_coding.baudrate = baudrate;
event->data.cdc_line_coding.data_bits = data_bits;
event->data.cdc_line_coding.stop_bits = stop_bits;
event->data.cdc_line_coding.parity = parity;
event->data.cdc_line_coding.flow_ctrl = flow_ctrl;
APP_EVENT_SUBMIT(event);
}
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_USB_CONTROL_EVENT_H_ */

View File

@@ -1,24 +0,0 @@
#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

@@ -1,24 +0,0 @@
#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

@@ -1,21 +0,0 @@
#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_ */

View File

@@ -0,0 +1,41 @@
#ifndef BLINKY_USB_STATE_EVENT_H_
#define BLINKY_USB_STATE_EVENT_H_
#include <stdint.h>
#include <app_event_manager.h>
#include <app_event_manager_profiler_tracer.h>
#include <zephyr/sys/util.h>
#ifdef __cplusplus
extern "C" {
#endif
enum usb_state {
USB_STATE_DISABLED = 0,
USB_STATE_DISCONNECTED,
USB_STATE_POWERED,
USB_STATE_ACTIVE,
USB_STATE_SUSPENDED,
};
struct usb_state_event {
struct app_event_header header;
enum usb_state state;
};
APP_EVENT_TYPE_DECLARE(usb_state_event);
static inline void submit_usb_state(enum usb_state state)
{
struct usb_state_event *event = new_usb_state_event();
event->state = state;
APP_EVENT_SUBMIT(event);
}
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_USB_STATE_EVENT_H_ */

View File

@@ -8,6 +8,8 @@ extern "C" {
#endif
#define KEYBOARD_BOOT_REPORT_SIZE 8U
#define KEYBOARD_PROTOCOL_USAGE_MAX 0xE7U
#define KEYBOARD_PROTOCOL_BITMAP_BYTES ((KEYBOARD_PROTOCOL_USAGE_MAX + 8U) / 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)
@@ -34,6 +36,13 @@ enum hid_transport {
HID_TRANSPORT_COUNT,
};
enum hid_send_channel {
HID_SEND_CH_USB_KEYS,
HID_SEND_CH_USB_CONSUMER,
HID_SEND_CH_BLE_SHARED,
HID_SEND_CH_COUNT,
};
enum keyboard_consumer_control {
KEYBOARD_CONSUMER_CTRL_MUTE,
KEYBOARD_CONSUMER_CTRL_VOLUME_UP,

207
inc/module_lifecycle.h Normal file
View File

@@ -0,0 +1,207 @@
#ifndef MODULE_LIFECYCLE_H_
#define MODULE_LIFECYCLE_H_
#include <errno.h>
#include <stdbool.h>
#include <caf/events/module_state_event.h>
enum module_lifecycle {
LC_UNINIT,
LC_STOPPED,
LC_RUNNING,
LC_ERROR,
};
enum module_lifecycle_mode {
ML_MODE_NONE,
ML_MODE_POWER,
ML_MODE_SUSPEND,
};
struct module_lifecycle_ops {
int (*do_init)(void);
int (*do_start)(void);
int (*do_stop)(void);
};
struct module_lifecycle_cfg {
enum module_lifecycle_mode mode;
enum module_state stopped_state;
};
struct module_lifecycle_ctx {
enum module_lifecycle state;
const struct module_lifecycle_cfg *cfg;
const struct module_lifecycle_ops *ops;
};
static inline bool module_lifecycle_is_running(
const struct module_lifecycle_ctx *ctx)
{
return ctx->state == LC_RUNNING;
}
static inline bool module_lifecycle_is_initialized(
const struct module_lifecycle_ctx *ctx)
{
return (ctx->state != LC_UNINIT) && (ctx->state != LC_ERROR);
}
static inline const char *module_lifecycle_name(enum module_lifecycle state)
{
switch (state) {
case LC_UNINIT:
return "UNINIT";
case LC_STOPPED:
return "STOPPED";
case LC_RUNNING:
return "RUNNING";
case LC_ERROR:
return "ERROR";
default:
return "?";
}
}
static inline int module_lifecycle_validate_ops(
const struct module_lifecycle_ctx *ctx)
{
if ((ctx == NULL) || (ctx->cfg == NULL) || (ctx->ops == NULL) ||
(ctx->ops->do_init == NULL)) {
return -EINVAL;
}
switch (ctx->cfg->mode) {
case ML_MODE_NONE:
return 0;
case ML_MODE_POWER:
case ML_MODE_SUSPEND:
return (ctx->ops->do_start != NULL) && (ctx->ops->do_stop != NULL) ?
0 :
-EINVAL;
default:
return -EINVAL;
}
}
static inline int module_lifecycle_report_state(
struct module_lifecycle_ctx *ctx,
enum module_lifecycle state)
{
switch (state) {
case LC_RUNNING:
module_set_state(MODULE_STATE_READY);
return 0;
case LC_STOPPED:
switch (ctx->cfg->mode) {
case ML_MODE_POWER:
module_set_state(ctx->cfg->stopped_state);
return 0;
case ML_MODE_SUSPEND:
module_set_state(MODULE_STATE_SUSPENDED);
return 0;
case ML_MODE_NONE:
return 0;
default:
return -EINVAL;
}
case LC_ERROR:
module_set_state(MODULE_STATE_ERROR);
return 0;
case LC_UNINIT:
default:
return -EINVAL;
}
}
static inline int module_lifecycle_fail(struct module_lifecycle_ctx *ctx, int err)
{
ctx->state = LC_ERROR;
(void)module_lifecycle_report_state(ctx, LC_ERROR);
return err ? err : -EIO;
}
static inline int module_set_lifecycle(struct module_lifecycle_ctx *ctx,
enum module_lifecycle target)
{
int err;
err = module_lifecycle_validate_ops(ctx);
if (err) {
return err;
}
if (ctx->state == LC_ERROR) {
return -EFAULT;
}
if (ctx->state == target) {
return 0;
}
if (target == LC_ERROR) {
return module_lifecycle_fail(ctx, -EIO);
}
if ((target != LC_STOPPED) && (target != LC_RUNNING)) {
return -EPERM;
}
switch (ctx->state) {
case LC_UNINIT:
err = ctx->ops->do_init();
if (err) {
return module_lifecycle_fail(ctx, err);
}
ctx->state = LC_STOPPED;
err = module_lifecycle_report_state(ctx, LC_STOPPED);
if (err) {
return module_lifecycle_fail(ctx, err);
}
return module_set_lifecycle(ctx, target);
case LC_STOPPED:
if (target != LC_RUNNING) {
return -EPERM;
}
err = ctx->ops->do_start ? ctx->ops->do_start() : 0;
if (err) {
return module_lifecycle_fail(ctx, err);
}
ctx->state = LC_RUNNING;
return module_lifecycle_report_state(ctx, LC_RUNNING);
case LC_RUNNING:
if (target != LC_STOPPED) {
return -EPERM;
}
err = ctx->ops->do_stop ? ctx->ops->do_stop() : 0;
if (err) {
return module_lifecycle_fail(ctx, err);
}
ctx->state = LC_STOPPED;
return module_lifecycle_report_state(ctx, LC_STOPPED);
case LC_ERROR:
default:
return -EPERM;
}
}
#endif /* MODULE_LIFECYCLE_H_ */

View File

@@ -1,23 +1,22 @@
#ifndef BLINKY_PROTOCOL_MODULE_H_
#define BLINKY_PROTOCOL_MODULE_H_
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include "proto_common.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);
int protocol_module_process_message(enum proto_transport transport,
const uint8_t *req_payload,
size_t req_payload_len,
uint8_t *rsp_payload,
size_t rsp_payload_buf_size,
size_t *rsp_payload_len);
#ifdef __cplusplus
}

24
inc/theme_color.h Normal file
View File

@@ -0,0 +1,24 @@
#ifndef BLINKY_THEME_COLOR_H_
#define BLINKY_THEME_COLOR_H_
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#define BLINKY_THEME_DEFAULT_R 0x4CU
#define BLINKY_THEME_DEFAULT_G 0x9EU
#define BLINKY_THEME_DEFAULT_B 0xF5U
struct theme_rgb {
uint8_t r;
uint8_t g;
uint8_t b;
};
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_THEME_COLOR_H_ */

View File

@@ -1,26 +0,0 @@
#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_ */

25
inc/usb_function_hook.h Normal file
View File

@@ -0,0 +1,25 @@
#ifndef BLINKY_USB_FUNCTION_HOOK_H_
#define BLINKY_USB_FUNCTION_HOOK_H_
#include <zephyr/sys/iterable_sections.h>
#ifdef __cplusplus
extern "C" {
#endif
struct usb_function_hook {
const char *name;
int (*pre_stack_init)(void);
};
#define USB_FUNCTION_HOOK_DEFINE(_name, _pre_stack_init) \
const STRUCT_SECTION_ITERABLE(usb_function_hook, _name) = { \
.name = STRINGIFY(_name), \
.pre_stack_init = (_pre_stack_init), \
}
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_USB_FUNCTION_HOOK_H_ */

View File

@@ -26,7 +26,13 @@ CONFIG_FLASH_MAP=y
CONFIG_NVS=y
CONFIG_HEAP_MEM_POOL_SIZE=4096
CONFIG_LOG=y
CONFIG_LOG_BUFFER_SIZE=16384
CONFIG_LOG_BACKEND_RTT_OUTPUT_BUFFER_SIZE=16384
CONFIG_ASSERT=y
CONFIG_SEGGER_RTT_BUFFER_SIZE_UP=16384
CONFIG_APP_EVENT_MANAGER_MAX_EVENT_CNT=64
CONFIG_LED_STRIP=y
CONFIG_WS2812_STRIP_SPI=y
# USB HID next stack
CONFIG_USB_DEVICE_STACK_NEXT=y
@@ -42,12 +48,17 @@ CONFIG_CDC_ACM_SERIAL_INITIALIZE_AT_BOOT=n
# BLE
CONFIG_BT=y
CONFIG_BT_PERIPHERAL=y
CONFIG_BT_ZEPHYR_NUS=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_L2CAP_TX_MTU=65
CONFIG_BT_BUF_ACL_RX_SIZE=69
CONFIG_BT_BUF_ACL_TX_SIZE=69
CONFIG_BT_PERIPHERAL_PREF_TIMEOUT=400
CONFIG_BT_CONN_CTX=y
CONFIG_BT_DEVICE_NAME="WH Mini Keyboard"
CONFIG_BT_DEVICE_APPEARANCE=961
@@ -119,3 +130,6 @@ CONFIG_LV_USE_LABEL=y
CONFIG_LV_FONT_MONTSERRAT_14=y
CONFIG_LV_FONT_MONTSERRAT_32=y
CONFIG_MAIN_STACK_SIZE=4096
CONFIG_USE_SEGGER_RTT=y
CONFIG_SPEED_OPTIMIZATIONS=y

View File

@@ -0,0 +1,2 @@
Bitmap.usage_bitmap max_size:29
FunctionKeyEvent.usage_bitmap max_size:29

View File

@@ -13,9 +13,59 @@ message HelloRsp {
uint32 capability_flags = 6;
}
message Bitmap {
bytes usage_bitmap = 1;
}
message FunctionKeyEvent {
bytes usage_bitmap = 1;
}
message LedState {
uint32 led_mask = 1;
}
message TimeSync {
uint32 version = 1;
uint32 flags = 2;
sint32 timezone_min = 3;
fixed64 utc_ms = 4;
fixed32 accuracy_ms = 5;
}
message ThemeRgb {
uint32 red = 1;
uint32 green = 2;
uint32 blue = 3;
}
message Ack {
uint32 acked_type = 1;
}
enum ErrorCode {
ERROR_CODE_NONE = 0;
ERROR_CODE_UNKNOWN_TYPE = 1;
ERROR_CODE_INVALID_LENGTH = 2;
ERROR_CODE_INVALID_PARAM = 3;
ERROR_CODE_NOT_READY = 4;
}
message Error {
uint32 error_type = 1;
ErrorCode error_code = 2;
}
message CdcPacketBody {
oneof body {
HelloReq hello_req = 1;
HelloRsp hello_rsp = 2;
Bitmap bitmap = 3;
FunctionKeyEvent function_key_event = 4;
LedState led_state = 5;
TimeSync time_sync = 6;
ThemeRgb theme_rgb = 7;
Ack ack = 8;
Error error = 9;
}
}

View File

@@ -18,6 +18,7 @@
#include <zephyr/pm/device.h>
#include "bat_state_event.h"
#include "module_lifecycle.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
@@ -32,17 +33,43 @@ BUILD_ASSERT(DT_NODE_HAS_STATUS(VBATT_NODE, okay),
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;
struct battery_module_ctx {
struct module_lifecycle_ctx lc;
const struct device *vbatt_dev;
const struct device *ip5306_dev;
struct k_work_delayable battery_sample_work;
struct {
bool valid;
uint8_t soc;
bool charging;
bool full;
} last_bat_state;
};
static int do_init(void);
static int do_start(void);
static int do_stop(void);
static const struct module_lifecycle_cfg lifecycle_cfg = {
.mode = ML_MODE_POWER,
.stopped_state = MODULE_STATE_STANDBY,
};
static const struct module_lifecycle_ops lifecycle_ops = {
.do_init = do_init,
.do_start = do_start,
.do_stop = do_stop,
};
static struct battery_module_ctx ctx = {
.lc = {
.state = LC_UNINIT,
.cfg = &lifecycle_cfg,
.ops = &lifecycle_ops,
},
.vbatt_dev = DEVICE_DT_GET(VBATT_NODE),
.ip5306_dev = DEVICE_DT_GET(IP5306_NODE),
};
static int sensor_value_to_mv(const struct sensor_value *value)
{
@@ -53,7 +80,7 @@ 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);
int err = pm_device_action_run(ctx.vbatt_dev, action);
if (err && (err != -EALREADY) && (err != -ENOTSUP)) {
LOG_ERR("Cannot %s vbatt sensor (%d)", enable ? "resume" : "suspend", err);
@@ -81,30 +108,6 @@ static uint8_t battery_soc_from_mv(int voltage_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;
@@ -114,69 +117,78 @@ static void battery_sample_fn(struct k_work *work)
ARG_UNUSED(work);
if (!running) {
if (!module_lifecycle_is_running(&ctx.lc)) {
return;
}
err = sensor_sample_fetch(vbatt_dev);
err = sensor_sample_fetch(ctx.vbatt_dev);
if (err) {
LOG_WRN("Battery sample fetch failed (%d)", err);
goto reschedule;
}
err = sensor_channel_get(vbatt_dev, SENSOR_CHAN_VOLTAGE, &voltage);
err = sensor_channel_get(ctx.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);
err = ip5306_get_status(ctx.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);
uint8_t soc = battery_soc_from_mv(voltage_mv);
if (!ctx.last_bat_state.valid ||
(ctx.last_bat_state.soc != soc) ||
(ctx.last_bat_state.charging != pmic_status.charging) ||
(ctx.last_bat_state.full != pmic_status.full)) {
ctx.last_bat_state.valid = true;
ctx.last_bat_state.soc = soc;
ctx.last_bat_state.charging = pmic_status.charging;
ctx.last_bat_state.full = pmic_status.full;
submit_bat_state_event(soc, pmic_status.charging, pmic_status.full);
}
reschedule:
if (running) {
k_work_reschedule(&battery_sample_work, BATTERY_SAMPLE_INTERVAL);
if (module_lifecycle_is_running(&ctx.lc)) {
k_work_reschedule(&ctx.battery_sample_work, BATTERY_SAMPLE_INTERVAL);
}
}
static int module_init(void)
static int do_init(void)
{
if (!device_is_ready(vbatt_dev)) {
if (!device_is_ready(ctx.vbatt_dev)) {
LOG_ERR("vbatt device not ready");
return -ENODEV;
}
if (!device_is_ready(ip5306_dev)) {
if (!device_is_ready(ctx.ip5306_dev)) {
LOG_ERR("ip5306 device not ready");
return -ENODEV;
}
int err = ip5306_init(ip5306_dev);
int err = ip5306_init(ctx.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));
k_work_init_delayable(&ctx.battery_sample_work, battery_sample_fn);
memset(&ctx.last_bat_state, 0, sizeof(ctx.last_bat_state));
power_manager_restrict(MODULE_IDX(MODULE), POWER_MANAGER_LEVEL_SUSPENDED);
return 0;
}
static int module_start(void)
static int do_start(void)
{
int err;
if (running) {
if (module_lifecycle_is_running(&ctx.lc)) {
return 0;
}
@@ -185,21 +197,21 @@ static int module_start(void)
return err;
}
running = true;
k_work_reschedule(&battery_sample_work, K_NO_WAIT);
k_work_reschedule(&ctx.battery_sample_work, K_NO_WAIT);
return 0;
}
static void module_pause(void)
static int do_stop(void)
{
if (!running) {
return;
if (!module_lifecycle_is_running(&ctx.lc)) {
return 0;
}
(void)k_work_cancel_delayable(&battery_sample_work);
(void)k_work_cancel_delayable(&ctx.battery_sample_work);
(void)measurement_enable(false);
running = false;
return 0;
}
static bool app_event_handler(const struct app_event_header *aeh)
@@ -208,47 +220,23 @@ static bool app_event_handler(const struct app_event_header *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);
}
(void)module_set_lifecycle(&ctx.lc, LC_RUNNING);
}
return false;
}
if (is_power_down_event(aeh)) {
if (initialized) {
module_pause();
module_set_state(MODULE_STATE_STANDBY);
if (module_lifecycle_is_initialized(&ctx.lc)) {
(void)module_set_lifecycle(&ctx.lc, LC_STOPPED);
}
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);
}
if (module_lifecycle_is_initialized(&ctx.lc)) {
(void)module_set_lifecycle(&ctx.lc, LC_RUNNING);
}
return false;

View File

@@ -1,115 +0,0 @@
#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);

View File

@@ -11,34 +11,54 @@
#include <zephyr/logging/log.h>
#include "bat_state_event.h"
#include "module_lifecycle.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
static uint8_t current_soc = 100U;
static bool initialized;
static bool running;
static bool ble_ready;
struct ble_bas_module_ctx {
struct module_lifecycle_ctx lc;
uint8_t current_soc;
bool ble_ready;
};
static int module_init(void)
static int do_init(void);
static int do_start(void);
static int do_stop(void);
static const struct module_lifecycle_cfg lifecycle_cfg = {
.mode = ML_MODE_NONE,
.stopped_state = MODULE_STATE_OFF,
};
static const struct module_lifecycle_ops lifecycle_ops = {
.do_init = do_init,
.do_start = do_start,
.do_stop = do_stop,
};
static struct ble_bas_module_ctx ctx = {
.lc = {
.state = LC_UNINIT,
.cfg = &lifecycle_cfg,
.ops = &lifecycle_ops,
},
.current_soc = 100U,
};
static int do_init(void)
{
return 0;
}
static int module_start(void)
static int bas_update_level(void)
{
int err;
int err = bt_bas_set_battery_level(ctx.current_soc);
if (running) {
if ((err == -EAGAIN) || (err == -ENOTCONN)) {
LOG_INF("BAS notify deferred (%d)", err);
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;
@@ -47,21 +67,30 @@ static int module_start(void)
return 0;
}
static void module_pause(void)
static int do_start(void)
{
running = false;
if (module_lifecycle_is_running(&ctx.lc)) {
return 0;
}
if (!ctx.ble_ready) {
return 0;
}
return bas_update_level();
}
static int do_stop(void)
{
return 0;
}
static bool handle_bat_state_event(const struct bat_state_event *event)
{
current_soc = event->soc;
ctx.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);
}
if (module_lifecycle_is_running(&ctx.lc) && ctx.ble_ready) {
(void)bas_update_level();
}
return false;
@@ -75,38 +104,18 @@ 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);
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);
}
(void)module_set_lifecycle(&ctx.lc, LC_RUNNING);
return false;
}
if (check_state(event, MODULE_ID(ble_state), MODULE_STATE_READY)) {
ble_ready = true;
ctx.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);
}
if (module_lifecycle_is_running(&ctx.lc)) {
(void)bas_update_level();
}
module_set_state(MODULE_STATE_READY);
return false;
}

View File

@@ -7,17 +7,17 @@
#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_channel_state_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 "module_lifecycle.h"
#include "set_protocol_event.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
@@ -40,15 +40,40 @@ BT_HIDS_DEF(hids_obj,
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;
struct ble_hid_module_ctx {
struct module_lifecycle_ctx lc;
struct bt_conn *active_conn;
struct in_flight_report in_flight;
enum keyboard_protocol_mode protocol_mode;
bool secured;
bool keyboard_report_notify_enabled;
bool consumer_report_notify_enabled;
bool boot_keyboard_notify_enabled;
};
static int do_init(void);
static int do_start(void);
static int do_stop(void);
static const struct module_lifecycle_cfg lifecycle_cfg = {
.mode = ML_MODE_NONE,
.stopped_state = MODULE_STATE_OFF,
};
static const struct module_lifecycle_ops lifecycle_ops = {
.do_init = do_init,
.do_start = do_start,
.do_stop = do_stop,
};
static struct ble_hid_module_ctx ctx = {
.lc = {
.state = LC_UNINIT,
.cfg = &lifecycle_cfg,
.ops = &lifecycle_ops,
},
.protocol_mode = KEYBOARD_PROTOCOL_MODE_REPORT,
};
static const uint8_t hid_report_desc[] = {
0x05, 0x01, /* Usage Page (Generic Desktop) */
@@ -98,54 +123,27 @@ static const uint8_t hid_report_desc[] = {
0xC0 /* End Collection */
};
static void submit_set_protocol_event(void)
static void submit_ble_transport_state_event(void)
{
struct set_protocol_event *event = new_set_protocol_event();
bool ready = module_lifecycle_is_running(&ctx.lc) &&
ctx.secured && (ctx.active_conn != NULL);
uint8_t report_ready_bm = 0U;
event->transport = HID_TRANSPORT_BLE;
event->protocol_mode = protocol_mode;
APP_EVENT_SUBMIT(event);
}
if (ready && ((ctx.protocol_mode == KEYBOARD_PROTOCOL_MODE_BOOT) ?
ctx.boot_keyboard_notify_enabled :
ctx.keyboard_report_notify_enabled)) {
report_ready_bm |= BIT(KEYBOARD_REPORT_TYPE_KEYS);
}
static void submit_hid_led_event(uint8_t led_bm)
{
struct hid_led_event *event = new_hid_led_event();
if (ready && (ctx.protocol_mode == KEYBOARD_PROTOCOL_MODE_REPORT) &&
ctx.consumer_report_notify_enabled) {
report_ready_bm |= BIT(KEYBOARD_REPORT_TYPE_CONSUMER);
}
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);
submit_hid_channel_state_event(
HID_SEND_CH_BLE_SHARED,
report_ready_bm,
ctx.protocol_mode);
}
static void input_report_notify_handler(uint8_t report_id, enum bt_hids_notify_evt evt)
@@ -153,18 +151,18 @@ static void input_report_notify_handler(uint8_t report_id, enum bt_hids_notify_e
bool enabled = (evt == BT_HIDS_CCCD_EVT_NOTIFY_ENABLED);
if (report_id == BLE_HID_KEYS_REPORT_ID) {
keyboard_report_notify_enabled = enabled;
ctx.keyboard_report_notify_enabled = enabled;
} else if (report_id == BLE_HID_CONSUMER_REPORT_ID) {
consumer_report_notify_enabled = enabled;
ctx.consumer_report_notify_enabled = enabled;
}
submit_transport_state_event();
submit_ble_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();
ctx.boot_keyboard_notify_enabled = (evt == BT_HIDS_CCCD_EVT_NOTIFY_ENABLED);
submit_ble_transport_state_event();
}
static void hid_report_complete_cb(struct bt_conn *conn, void *user_data)
@@ -172,12 +170,14 @@ static void hid_report_complete_cb(struct bt_conn *conn, void *user_data)
ARG_UNUSED(conn);
ARG_UNUSED(user_data);
if (!in_flight.active) {
if (!ctx.in_flight.active) {
return;
}
submit_hid_report_sent_event(in_flight.report_type, in_flight.sequence, false);
in_flight.active = false;
submit_hid_report_sent_event(HID_SEND_CH_BLE_SHARED,
ctx.in_flight.report_type,
ctx.in_flight.sequence, false);
ctx.in_flight.active = false;
}
static void keyboard_led_report_common(struct bt_hids_rep *rep, bool write)
@@ -186,7 +186,7 @@ static void keyboard_led_report_common(struct bt_hids_rep *rep, bool write)
return;
}
submit_hid_led_event(rep->data[0]);
submit_hid_led_event(HID_TRANSPORT_BLE, rep->data[0]);
}
static void keyboard_led_report_handler(struct bt_hids_rep *rep,
@@ -213,22 +213,22 @@ static void pm_evt_handler(enum bt_hids_pm_evt evt, struct bt_conn *conn)
switch (evt) {
case BT_HIDS_PM_EVT_BOOT_MODE_ENTERED:
protocol_mode = KEYBOARD_PROTOCOL_MODE_BOOT;
ctx.protocol_mode = KEYBOARD_PROTOCOL_MODE_BOOT;
break;
case BT_HIDS_PM_EVT_REPORT_MODE_ENTERED:
protocol_mode = KEYBOARD_PROTOCOL_MODE_REPORT;
ctx.protocol_mode = KEYBOARD_PROTOCOL_MODE_REPORT;
break;
default:
return;
}
submit_set_protocol_event();
submit_transport_state_event();
submit_set_protocol_event(HID_TRANSPORT_BLE, ctx.protocol_mode);
submit_ble_transport_state_event();
}
static int module_init(void)
static int do_init(void)
{
struct bt_hids_init_param hids_init_param = { 0 };
struct bt_hids_inp_rep *input_report;
@@ -265,38 +265,38 @@ static int module_init(void)
return bt_hids_init(&hids_obj, &hids_init_param);
}
static int module_start(void)
static int do_start(void)
{
if (running) {
if (module_lifecycle_is_running(&ctx.lc)) {
return 0;
}
running = true;
submit_transport_state_event();
submit_ble_transport_state_event();
return 0;
}
static void module_pause(void)
static int do_stop(void)
{
if (!running) {
return;
if (!module_lifecycle_is_running(&ctx.lc)) {
return 0;
}
in_flight.active = false;
running = false;
submit_transport_state_event();
ctx.in_flight.active = false;
submit_ble_transport_state_event();
return 0;
}
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;
ctx.active_conn = NULL;
ctx.secured = false;
ctx.keyboard_report_notify_enabled = false;
ctx.consumer_report_notify_enabled = false;
ctx.boot_keyboard_notify_enabled = false;
ctx.protocol_mode = KEYBOARD_PROTOCOL_MODE_REPORT;
ctx.in_flight.active = false;
}
static bool handle_ble_peer_event(const struct ble_peer_event *event)
@@ -305,31 +305,31 @@ static bool handle_ble_peer_event(const struct ble_peer_event *event)
switch (event->state) {
case PEER_STATE_CONNECTED:
if (active_conn != NULL) {
if (ctx.active_conn != NULL) {
return false;
}
active_conn = event->id;
protocol_mode = KEYBOARD_PROTOCOL_MODE_REPORT;
submit_set_protocol_event();
ctx.active_conn = event->id;
ctx.protocol_mode = KEYBOARD_PROTOCOL_MODE_REPORT;
submit_set_protocol_event(HID_TRANSPORT_BLE, ctx.protocol_mode);
err = bt_hids_connected(&hids_obj, event->id);
if (err) {
LOG_ERR("bt_hids_connected failed (%d)", err);
}
submit_transport_state_event();
submit_ble_transport_state_event();
return false;
case PEER_STATE_SECURED:
if (active_conn != event->id) {
if (ctx.active_conn != event->id) {
return false;
}
secured = true;
submit_transport_state_event();
ctx.secured = true;
submit_ble_transport_state_event();
return false;
case PEER_STATE_DISCONNECTED:
if (active_conn != event->id) {
if (ctx.active_conn != event->id) {
return false;
}
@@ -339,7 +339,7 @@ static bool handle_ble_peer_event(const struct ble_peer_event *event)
}
reset_connection_state();
submit_transport_state_event();
submit_ble_transport_state_event();
return false;
default:
@@ -351,33 +351,35 @@ 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) {
if (!module_lifecycle_is_running(&ctx.lc) ||
(event->channel != HID_SEND_CH_BLE_SHARED) ||
ctx.in_flight.active) {
return false;
}
if ((active_conn == NULL) || !secured) {
if ((ctx.active_conn == NULL) || !ctx.secured) {
return false;
}
if (event->report_type == KEYBOARD_REPORT_TYPE_KEYS) {
if (event->protocol_mode != protocol_mode) {
if (event->protocol_mode != ctx.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;
ctx.in_flight.active = true;
ctx.in_flight.report_type = event->report_type;
ctx.in_flight.sequence = event->sequence;
if (protocol_mode == KEYBOARD_PROTOCOL_MODE_BOOT) {
if (ctx.protocol_mode == KEYBOARD_PROTOCOL_MODE_BOOT) {
err = bt_hids_boot_kb_inp_rep_send(&hids_obj,
active_conn,
ctx.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,
ctx.active_conn,
BLE_HID_KEYS_REPORT_IDX,
event->dyndata.data,
(uint8_t)event->dyndata.size,
@@ -385,9 +387,10 @@ static bool handle_hid_tx_report_event(const struct hid_tx_report_event *event)
}
if (err) {
in_flight.active = false;
ctx.in_flight.active = false;
LOG_WRN("BLE keyboard report submit failed (%d)", err);
submit_hid_report_sent_event(KEYBOARD_REPORT_TYPE_KEYS,
submit_hid_report_sent_event(HID_SEND_CH_BLE_SHARED,
KEYBOARD_REPORT_TYPE_KEYS,
event->sequence, true);
}
@@ -395,25 +398,26 @@ static bool handle_hid_tx_report_event(const struct hid_tx_report_event *event)
}
if (event->report_type == KEYBOARD_REPORT_TYPE_CONSUMER) {
if (protocol_mode != KEYBOARD_PROTOCOL_MODE_REPORT) {
if (ctx.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;
ctx.in_flight.active = true;
ctx.in_flight.report_type = event->report_type;
ctx.in_flight.sequence = event->sequence;
err = bt_hids_inp_rep_send(&hids_obj,
active_conn,
ctx.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;
ctx.in_flight.active = false;
LOG_WRN("BLE consumer report submit failed (%d)", err);
submit_hid_report_sent_event(KEYBOARD_REPORT_TYPE_CONSUMER,
submit_hid_report_sent_event(HID_SEND_CH_BLE_SHARED,
KEYBOARD_REPORT_TYPE_CONSUMER,
event->sequence, true);
}
}
@@ -433,48 +437,9 @@ 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);
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);
}
(void)module_set_lifecycle(&ctx.lc, LC_RUNNING);
}
return false;
@@ -487,5 +452,3 @@ 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);

319
src/ble_nus_module.c Normal file
View File

@@ -0,0 +1,319 @@
#include <errno.h>
#include <stdbool.h>
#include <stdint.h>
#include <app_event_manager.h>
#define MODULE ble_nus_module
#include <caf/events/module_state_event.h>
#include <caf/events/ble_common_event.h>
#include <zephyr/bluetooth/conn.h>
#include <zephyr/bluetooth/services/nus.h>
#include <zephyr/logging/log.h>
#include "module_lifecycle.h"
#include "proto_rx_event.h"
#include "proto_transport_state_event.h"
#include "proto_tx_event.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
enum ble_nus_business_state {
BLE_NUS_STACK_OFFLINE = 0,
BLE_NUS_IDLE,
BLE_NUS_WAIT_NOTIFY,
BLE_NUS_SESSION_READY,
};
struct ble_nus_ctx {
struct module_lifecycle_ctx lc;
enum ble_nus_business_state business;
struct bt_conn *active_conn;
};
static int do_init(void);
static int do_start(void);
static int do_stop(void);
static const struct module_lifecycle_cfg lifecycle_cfg = {
.mode = ML_MODE_NONE,
.stopped_state = MODULE_STATE_OFF,
};
static const struct module_lifecycle_ops lifecycle_ops = {
.do_init = do_init,
.do_start = do_start,
.do_stop = do_stop,
};
static struct ble_nus_ctx ctx = {
.lc = {
.state = LC_UNINIT,
.cfg = &lifecycle_cfg,
.ops = &lifecycle_ops,
},
.business = BLE_NUS_STACK_OFFLINE,
.active_conn = NULL,
};
static const char *business_state_name(enum ble_nus_business_state state)
{
switch (state) {
case BLE_NUS_STACK_OFFLINE:
return "STACK_OFFLINE";
case BLE_NUS_IDLE:
return "IDLE";
case BLE_NUS_WAIT_NOTIFY:
return "WAIT_NOTIFY";
case BLE_NUS_SESSION_READY:
return "SESSION_READY";
default:
return "?";
}
}
static const char *link_state_name(enum proto_transport_link_state state)
{
switch (state) {
case PROTO_TRANSPORT_LINK_DOWN:
return "DOWN";
case PROTO_TRANSPORT_LINK_READY:
return "READY";
default:
return "?";
}
}
static bool lifecycle_is_ready(void)
{
return module_lifecycle_is_running(&ctx.lc);
}
static enum proto_transport_link_state transport_link_state_get(void)
{
return (lifecycle_is_ready() &&
(ctx.business == BLE_NUS_SESSION_READY)) ?
PROTO_TRANSPORT_LINK_READY :
PROTO_TRANSPORT_LINK_DOWN;
}
static void state_reconcile(enum module_lifecycle old_lifecycle,
enum ble_nus_business_state old_business)
{
enum proto_transport_link_state old_link =
((old_lifecycle == LC_RUNNING) &&
(old_business == BLE_NUS_SESSION_READY)) ?
PROTO_TRANSPORT_LINK_READY :
PROTO_TRANSPORT_LINK_DOWN;
enum proto_transport_link_state new_link = transport_link_state_get();
if (old_link != new_link) {
submit_proto_transport_state_event(PROTO_TRANSPORT_BLE_NUS,
new_link);
}
}
static void business_state_set(enum ble_nus_business_state new_state)
{
enum module_lifecycle old_lifecycle = ctx.lc.state;
enum ble_nus_business_state old_business = ctx.business;
if (ctx.business == new_state) {
return;
}
LOG_INF("BLE NUS business %s -> %s",
business_state_name(ctx.business),
business_state_name(new_state));
ctx.business = new_state;
state_reconcile(old_lifecycle, old_business);
}
static void business_state_set_stack_ready(void)
{
if (ctx.business == BLE_NUS_STACK_OFFLINE) {
business_state_set(BLE_NUS_IDLE);
}
}
static void business_state_set_from_notify(bool enabled)
{
if (ctx.business == BLE_NUS_STACK_OFFLINE) {
return;
}
if (ctx.active_conn == NULL) {
return;
}
business_state_set(enabled ? BLE_NUS_SESSION_READY :
BLE_NUS_WAIT_NOTIFY);
}
static void notif_enabled(bool enabled, void *ctx_ptr)
{
ARG_UNUSED(ctx_ptr);
LOG_INF("BLE NUS TX notify %s", enabled ? "enabled" : "disabled");
business_state_set_from_notify(enabled);
}
static void received(struct bt_conn *conn, const void *data, uint16_t len,
void *ctx_ptr)
{
ARG_UNUSED(ctx_ptr);
if (!lifecycle_is_ready() || (ctx.business == BLE_NUS_STACK_OFFLINE) ||
(conn != ctx.active_conn)) {
LOG_WRN("BLE NUS drop RX len:%u lc:%s business:%s active_conn:%p conn:%p link:%s",
len, module_lifecycle_name(ctx.lc.state),
business_state_name(ctx.business),
(void *)ctx.active_conn, (void *)conn,
link_state_name(transport_link_state_get()));
return;
}
(void)submit_proto_rx_event(PROTO_TRANSPORT_BLE_NUS, data, len);
}
static struct bt_nus_cb nus_listener = {
.notif_enabled = notif_enabled,
.received = received,
};
static void reset_connection_state(void)
{
ctx.active_conn = NULL;
if (ctx.business != BLE_NUS_STACK_OFFLINE) {
business_state_set(BLE_NUS_IDLE);
}
}
static int do_init(void)
{
int err;
err = bt_nus_cb_register(&nus_listener, NULL);
if (err) {
LOG_ERR("bt_nus_cb_register failed (%d)", err);
return err;
}
ctx.business = BLE_NUS_STACK_OFFLINE;
ctx.active_conn = NULL;
return 0;
}
static int do_start(void)
{
return 0;
}
static int do_stop(void)
{
return 0;
}
static int apply_lifecycle(enum module_lifecycle target)
{
enum module_lifecycle old_lifecycle = ctx.lc.state;
enum ble_nus_business_state old_business = ctx.business;
int err = module_set_lifecycle(&ctx.lc, target);
if (!err) {
state_reconcile(old_lifecycle, old_business);
} else {
LOG_WRN("BLE NUS lifecycle change failed target:%s err:%d",
module_lifecycle_name(target), err);
}
return err;
}
static bool handle_ble_peer_event(const struct ble_peer_event *event)
{
switch (event->state) {
case PEER_STATE_CONNECTED:
if (ctx.active_conn != NULL) {
return false;
}
ctx.active_conn = event->id;
if (ctx.business != BLE_NUS_STACK_OFFLINE) {
business_state_set(BLE_NUS_WAIT_NOTIFY);
}
return false;
case PEER_STATE_DISCONNECTED:
if (ctx.active_conn != event->id) {
return false;
}
reset_connection_state();
return false;
default:
return false;
}
}
static bool handle_proto_tx_event(const struct proto_tx_event *event)
{
int err;
if (event->transport != PROTO_TRANSPORT_BLE_NUS) {
return false;
}
if ((transport_link_state_get() != PROTO_TRANSPORT_LINK_READY) ||
(ctx.active_conn == NULL)) {
return false;
}
err = bt_nus_send(ctx.active_conn, event->dyndata.data,
(uint16_t)event->dyndata.size);
if (err) {
LOG_WRN("bt_nus_send failed (%d)", err);
}
return false;
}
static bool app_event_handler(const struct app_event_header *aeh)
{
if (is_proto_tx_event(aeh)) {
return handle_proto_tx_event(cast_proto_tx_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);
if (check_state(event, MODULE_ID(main), MODULE_STATE_READY)) {
(void)apply_lifecycle(LC_RUNNING);
return false;
}
if (check_state(event, MODULE_ID(ble_state), MODULE_STATE_READY)) {
business_state_set_stack_ready();
return false;
}
return false;
}
return false;
}
APP_EVENT_LISTENER(MODULE, app_event_handler);
APP_EVENT_SUBSCRIBE(MODULE, module_state_event);
APP_EVENT_SUBSCRIBE(MODULE, proto_tx_event);
APP_EVENT_SUBSCRIBE_EARLY(MODULE, ble_peer_event);

View File

@@ -1,275 +0,0 @@
#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);

View File

@@ -14,8 +14,12 @@
#include <zephyr/logging/log.h>
#include "bat_state_event.h"
#include "datetime_event.h"
#include "hid_led_event.h"
#include "module_lifecycle.h"
#include "mode_switch_event.h"
#include "theme_rgb_update_event.h"
#include "theme_color.h"
#include "ui/ui_main.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
@@ -24,42 +28,74 @@ 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,
struct display_module_ctx {
struct module_lifecycle_ctx lc;
const struct device *display_dev;
const struct device *backlight_dev;
uint32_t backlight_idx;
struct ui_main_model ui_model;
bool lvgl_initialized;
char date_text[DATETIME_EVENT_DATE_TEXT_LEN];
char time_text[DATETIME_EVENT_TIME_TEXT_LEN];
};
static int do_init(void);
static int do_start(void);
static int do_stop(void);
static const struct module_lifecycle_cfg lifecycle_cfg = {
.mode = ML_MODE_POWER,
.stopped_state = MODULE_STATE_STANDBY,
};
static const struct module_lifecycle_ops lifecycle_ops = {
.do_init = do_init,
.do_start = do_start,
.do_stop = do_stop,
};
static struct display_module_ctx ctx = {
.lc = {
.state = LC_UNINIT,
.cfg = &lifecycle_cfg,
.ops = &lifecycle_ops,
},
.display_dev = DEVICE_DT_GET(DT_CHOSEN(zephyr_display)),
.backlight_dev = DEVICE_DT_GET(DT_PARENT(DT_ALIAS(backlight))),
.backlight_idx = DT_NODE_CHILD_IDX(DT_ALIAS(backlight)),
.ui_model = {
.theme_color = LV_COLOR_MAKE(BLINKY_THEME_DEFAULT_R,
BLINKY_THEME_DEFAULT_G,
BLINKY_THEME_DEFAULT_B),
.inactive_border_color = LV_COLOR_MAKE(0x3A, 0x44, 0x52),
.mode = MODE_SWITCH_BLE,
},
.date_text = "1970/01/01",
.time_text = "00:00:00",
};
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_on(ctx.backlight_dev, ctx.backlight_idx);
}
return led_off(backlight_dev, backlight_idx);
return led_off(ctx.backlight_dev, ctx.backlight_idx);
}
static int module_init(void)
static int do_init(void)
{
int err;
LOG_INF("Display init on %s", display_dev->name);
LOG_INF("Display init on %s", ctx.display_dev->name);
if (!device_is_ready(display_dev)) {
LOG_ERR("Display device %s not ready", display_dev->name);
if (!device_is_ready(ctx.display_dev)) {
LOG_ERR("Display device %s not ready", ctx.display_dev->name);
return -ENODEV;
}
if (!device_is_ready(backlight_dev)) {
LOG_ERR("Backlight device %s not ready", backlight_dev->name);
if (!device_is_ready(ctx.backlight_dev)) {
LOG_ERR("Backlight device %s not ready", ctx.backlight_dev->name);
return -ENODEV;
}
@@ -72,25 +108,25 @@ static int module_init(void)
return 0;
}
static int module_start(void)
static int do_start(void)
{
int err;
if (running) {
if (module_lifecycle_is_running(&ctx.lc)) {
return 0;
}
if (!lvgl_initialized) {
if (!ctx.lvgl_initialized) {
err = lvgl_init();
if (err) {
LOG_ERR("lvgl_init failed (%d)", err);
return err;
}
lvgl_initialized = true;
ctx.lvgl_initialized = true;
lvgl_lock();
ui_main_init(&ui_model, "WH Mini", "Hello World");
ui_main_init(&ctx.ui_model, ctx.date_text, ctx.time_text);
lvgl_unlock();
}
@@ -100,39 +136,39 @@ static int module_start(void)
return err;
}
err = display_blanking_off(display_dev);
err = display_blanking_off(ctx.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)
static int do_stop(void)
{
if (!running) {
return;
if (!module_lifecycle_is_running(&ctx.lc)) {
return 0;
}
(void)display_blanking_on(display_dev);
(void)display_blanking_on(ctx.display_dev);
(void)backlight_set(false);
running = false;
LOG_INF("LVGL display paused");
return 0;
}
static void refresh_ui(void)
{
if (!lvgl_initialized) {
if (!ctx.lvgl_initialized) {
return;
}
lvgl_lock();
ui_main_refresh_all(&ui_model, "WH Mini", "Hello World");
ui_main_refresh_all(&ctx.ui_model, ctx.date_text, ctx.time_text);
lvgl_unlock();
}
@@ -141,9 +177,9 @@ 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;
ctx.ui_model.battery_level = event->soc;
ctx.ui_model.charging = event->charging;
ctx.ui_model.full = event->full;
refresh_ui();
return false;
}
@@ -151,7 +187,7 @@ static bool app_event_handler(const struct app_event_header *aeh)
if (is_mode_switch_event(aeh)) {
const struct mode_switch_event *event = cast_mode_switch_event(aeh);
ui_model.mode = event->mode;
ctx.ui_model.mode = event->mode;
refresh_ui();
return false;
}
@@ -159,55 +195,54 @@ static bool app_event_handler(const struct app_event_header *aeh)
if (is_hid_led_event(aeh)) {
const struct hid_led_event *event = cast_hid_led_event(aeh);
ui_model.led_mask = event->led_bm;
ctx.ui_model.led_mask = event->led_bm;
refresh_ui();
return false;
}
if (is_theme_rgb_update_event(aeh)) {
const struct theme_rgb_update_event *event =
cast_theme_rgb_update_event(aeh);
ctx.ui_model.theme_color = (lv_color_t)LV_COLOR_MAKE(event->theme.r,
event->theme.g,
event->theme.b);
refresh_ui();
return false;
}
if (is_datetime_event(aeh)) {
const struct datetime_event *event = cast_datetime_event(aeh);
strncpy(ctx.date_text, event->date_text, sizeof(ctx.date_text));
ctx.date_text[sizeof(ctx.date_text) - 1] = '\0';
strncpy(ctx.time_text, event->time_text, sizeof(ctx.time_text));
ctx.time_text[sizeof(ctx.time_text) - 1] = '\0';
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);
}
(void)module_set_lifecycle(&ctx.lc, LC_RUNNING);
}
return false;
}
if (is_power_down_event(aeh)) {
if (initialized) {
module_pause();
module_set_state(MODULE_STATE_STANDBY);
if (module_lifecycle_is_initialized(&ctx.lc)) {
(void)module_set_lifecycle(&ctx.lc, LC_STOPPED);
}
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);
}
if (module_lifecycle_is_initialized(&ctx.lc)) {
(void)module_set_lifecycle(&ctx.lc, LC_RUNNING);
}
return false;
@@ -218,8 +253,10 @@ static bool app_event_handler(const struct app_event_header *aeh)
APP_EVENT_LISTENER(MODULE, app_event_handler);
APP_EVENT_SUBSCRIBE(MODULE, bat_state_event);
APP_EVENT_SUBSCRIBE(MODULE, datetime_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(MODULE, theme_rgb_update_event);
APP_EVENT_SUBSCRIBE_EARLY(MODULE, power_down_event);
APP_EVENT_SUBSCRIBE(MODULE, wake_up_event);

View File

@@ -13,6 +13,7 @@
#include <zephyr/pm/device.h>
#include "encoder_event.h"
#include "module_lifecycle.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
@@ -22,40 +23,64 @@ LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
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,
struct encoder_module_ctx {
struct module_lifecycle_ctx lc;
const struct device *qdec_dev;
struct k_work encoder_report_work;
struct sensor_trigger encoder_trigger;
int64_t angle_remainder_udeg;
};
static bool initialized;
static bool running;
static int64_t angle_remainder_udeg;
static int do_init(void);
static int do_start(void);
static int do_stop(void);
static const struct module_lifecycle_cfg lifecycle_cfg = {
.mode = ML_MODE_POWER,
.stopped_state = MODULE_STATE_STANDBY,
};
static const struct module_lifecycle_ops lifecycle_ops = {
.do_init = do_init,
.do_start = do_start,
.do_stop = do_stop,
};
static struct encoder_module_ctx ctx = {
.lc = {
.state = LC_UNINIT,
.cfg = &lifecycle_cfg,
.ops = &lifecycle_ops,
},
.qdec_dev = DEVICE_DT_GET(ENCODER_QDEC_NODE),
.encoder_trigger = {
.type = SENSOR_TRIG_DATA_READY,
.chan = SENSOR_CHAN_ROTATION,
},
};
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)
static void submit_detents_batched(int32_t detents)
{
while (detents != 0) {
struct encoder_event *event = new_encoder_event();
int8_t event_detents;
if (detents > INT8_MAX) {
event->detents = INT8_MAX;
event_detents = INT8_MAX;
detents -= INT8_MAX;
} else if (detents < INT8_MIN) {
event->detents = INT8_MIN;
event_detents = INT8_MIN;
detents -= INT8_MIN;
} else {
event->detents = (int8_t)detents;
event_detents = (int8_t)detents;
detents = 0;
}
APP_EVENT_SUBMIT(event);
submit_encoder_event(event_detents);
}
}
@@ -68,28 +93,29 @@ static void encoder_report_work_handler(struct k_work *work)
ARG_UNUSED(work);
if (!running) {
if (!module_lifecycle_is_running(&ctx.lc)) {
return;
}
err = sensor_sample_fetch(qdec_dev);
err = sensor_sample_fetch(ctx.qdec_dev);
if (err) {
LOG_WRN("QDEC sample fetch failed (%d)", err);
return;
}
err = sensor_channel_get(qdec_dev, SENSOR_CHAN_ROTATION, &rotation);
err = sensor_channel_get(ctx.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);
total_udeg = ctx.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);
ctx.angle_remainder_udeg =
total_udeg - ((int64_t)detents * ENCODER_DETENT_UDEG);
if (detents != 0) {
submit_detents(detents);
submit_detents_batched(detents);
}
}
@@ -99,26 +125,27 @@ static void encoder_trigger_handler(const struct device *dev,
ARG_UNUSED(dev);
ARG_UNUSED(trigger);
if (!running) {
if (!module_lifecycle_is_running(&ctx.lc)) {
return;
}
k_work_submit(&encoder_report_work);
k_work_submit(&ctx.encoder_report_work);
}
static int module_init(void)
static int do_init(void)
{
int err;
if (!device_is_ready(qdec_dev)) {
if (!device_is_ready(ctx.qdec_dev)) {
LOG_ERR("QDEC device not ready");
return -ENODEV;
}
k_work_init(&encoder_report_work, encoder_report_work_handler);
angle_remainder_udeg = 0;
k_work_init(&ctx.encoder_report_work, encoder_report_work_handler);
ctx.angle_remainder_udeg = 0;
err = sensor_trigger_set(qdec_dev, &encoder_trigger, encoder_trigger_handler);
err = sensor_trigger_set(ctx.qdec_dev, &ctx.encoder_trigger,
encoder_trigger_handler);
if (err) {
LOG_ERR("Cannot set QDEC trigger (%d)", err);
return err;
@@ -127,41 +154,41 @@ static int module_init(void)
return 0;
}
static int module_start(void)
static int do_start(void)
{
int err;
if (running) {
if (module_lifecycle_is_running(&ctx.lc)) {
return 0;
}
err = pm_device_action_run(qdec_dev, PM_DEVICE_ACTION_RESUME);
err = pm_device_action_run(ctx.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;
ctx.angle_remainder_udeg = 0;
return 0;
}
static void module_pause(void)
static int do_stop(void)
{
int err;
if (!running) {
return;
if (!module_lifecycle_is_running(&ctx.lc)) {
return 0;
}
err = pm_device_action_run(qdec_dev, PM_DEVICE_ACTION_SUSPEND);
err = pm_device_action_run(ctx.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;
ctx.angle_remainder_udeg = 0;
return 0;
}
static bool app_event_handler(const struct app_event_header *aeh)
@@ -170,47 +197,23 @@ static bool app_event_handler(const struct app_event_header *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);
}
(void)module_set_lifecycle(&ctx.lc, LC_RUNNING);
}
return false;
}
if (is_power_down_event(aeh)) {
if (initialized) {
module_pause();
module_set_state(MODULE_STATE_STANDBY);
if (module_lifecycle_is_initialized(&ctx.lc)) {
(void)module_set_lifecycle(&ctx.lc, LC_STOPPED);
}
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);
}
if (module_lifecycle_is_initialized(&ctx.lc)) {
(void)module_set_lifecycle(&ctx.lc, LC_RUNNING);
}
return false;

View File

@@ -0,0 +1,26 @@
#include "datetime_event.h"
static void log_datetime_event(const struct app_event_header *aeh)
{
const struct datetime_event *event = cast_datetime_event(aeh);
APP_EVENT_MANAGER_LOG(aeh, "date:%s time:%s",
event->date_text, event->time_text);
}
static void profile_datetime_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
ARG_UNUSED(buf);
ARG_UNUSED(aeh);
}
APP_EVENT_INFO_DEFINE(datetime_event,
ENCODE(),
ENCODE(),
profile_datetime_event);
APP_EVENT_TYPE_DEFINE(datetime_event,
log_datetime_event,
&datetime_event_info,
APP_EVENT_FLAGS_CREATE());

View File

@@ -0,0 +1,27 @@
#include "function_bitmap_state_event.h"
static void log_function_bitmap_state_event(const struct app_event_header *aeh)
{
const struct function_bitmap_state_event *event =
cast_function_bitmap_state_event(aeh);
APP_EVENT_MANAGER_LOG(aeh, "bitmap_len:%zu", sizeof(event->bitmap));
}
static void profile_function_bitmap_state_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
ARG_UNUSED(buf);
ARG_UNUSED(aeh);
}
APP_EVENT_INFO_DEFINE(function_bitmap_state_event,
ENCODE(),
ENCODE(),
profile_function_bitmap_state_event);
APP_EVENT_TYPE_DEFINE(function_bitmap_state_event,
log_function_bitmap_state_event,
&function_bitmap_state_event_info,
APP_EVENT_FLAGS_CREATE(
APP_EVENT_TYPE_FLAGS_INIT_LOG_ENABLE));

View File

@@ -0,0 +1,24 @@
#include "function_bitmap_update_event.h"
static void log_function_bitmap_update_event(const struct app_event_header *aeh)
{
APP_EVENT_MANAGER_LOG(aeh, "bitmap updated");
}
static void profile_function_bitmap_update_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
ARG_UNUSED(buf);
ARG_UNUSED(aeh);
}
APP_EVENT_INFO_DEFINE(function_bitmap_update_event,
ENCODE(),
ENCODE(),
profile_function_bitmap_update_event);
APP_EVENT_TYPE_DEFINE(function_bitmap_update_event,
log_function_bitmap_update_event,
&function_bitmap_update_event_info,
APP_EVENT_FLAGS_CREATE(
APP_EVENT_TYPE_FLAGS_INIT_LOG_ENABLE));

View File

@@ -0,0 +1,51 @@
#include "hid_channel_state_event.h"
static const char *channel_name(enum hid_send_channel channel)
{
switch (channel) {
case HID_SEND_CH_USB_KEYS:
return "usb_keys";
case HID_SEND_CH_USB_CONSUMER:
return "usb_consumer";
case HID_SEND_CH_BLE_SHARED:
return "ble_shared";
default:
return "?";
}
}
static void log_hid_channel_state_event(const struct app_event_header *aeh)
{
const struct hid_channel_state_event *event =
cast_hid_channel_state_event(aeh);
APP_EVENT_MANAGER_LOG(aeh,
"channel:%s ready_bm:0x%02x protocol:%d",
channel_name(event->channel),
event->report_ready_bm,
event->protocol_mode);
}
static void profile_hid_channel_state_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
const struct hid_channel_state_event *event =
cast_hid_channel_state_event(aeh);
nrf_profiler_log_encode_uint8(buf, event->channel);
nrf_profiler_log_encode_uint8(buf, event->report_ready_bm);
nrf_profiler_log_encode_uint8(buf, event->protocol_mode);
}
APP_EVENT_INFO_DEFINE(hid_channel_state_event,
ENCODE(NRF_PROFILER_ARG_U8,
NRF_PROFILER_ARG_U8,
NRF_PROFILER_ARG_U8),
ENCODE("channel", "ready_bm", "protocol_mode"),
profile_hid_channel_state_event);
APP_EVENT_TYPE_DEFINE(hid_channel_state_event,
log_hid_channel_state_event,
&hid_channel_state_event_info,
APP_EVENT_FLAGS_CREATE(
APP_EVENT_TYPE_FLAGS_INIT_LOG_ENABLE));

View File

@@ -1,12 +1,14 @@
#include "hid_report_sent_event.h"
static const char *transport_name(enum hid_transport transport)
static const char *channel_name(enum hid_send_channel channel)
{
switch (transport) {
case HID_TRANSPORT_USB:
return "USB";
case HID_TRANSPORT_BLE:
return "BLE";
switch (channel) {
case HID_SEND_CH_USB_KEYS:
return "usb_keys";
case HID_SEND_CH_USB_CONSUMER:
return "usb_consumer";
case HID_SEND_CH_BLE_SHARED:
return "ble_shared";
default:
return "?";
}
@@ -28,8 +30,8 @@ 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),
APP_EVENT_MANAGER_LOG(aeh, "channel:%s type:%s seq:%u error:%u",
channel_name(event->channel),
report_type_name(event->report_type),
event->sequence,
event->error);
@@ -40,7 +42,7 @@ static void profile_hid_report_sent_event(struct log_event_buf *buf,
{
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->channel);
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);
@@ -51,7 +53,7 @@ APP_EVENT_INFO_DEFINE(hid_report_sent_event,
NRF_PROFILER_ARG_U8,
NRF_PROFILER_ARG_U16,
NRF_PROFILER_ARG_U8),
ENCODE("transport", "report_type", "sequence", "error"),
ENCODE("channel", "report_type", "sequence", "error"),
profile_hid_report_sent_event);
APP_EVENT_TYPE_DEFINE(hid_report_sent_event,

View File

@@ -1,68 +0,0 @@
#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

@@ -4,13 +4,15 @@
#define HID_TX_REPORT_EVENT_LOG_BUF_LEN 192
static const char *transport_name(enum hid_transport transport)
static const char *channel_name(enum hid_send_channel channel)
{
switch (transport) {
case HID_TRANSPORT_USB:
return "USB";
case HID_TRANSPORT_BLE:
return "BLE";
switch (channel) {
case HID_SEND_CH_USB_KEYS:
return "usb_keys";
case HID_SEND_CH_USB_CONSUMER:
return "usb_consumer";
case HID_SEND_CH_BLE_SHARED:
return "ble_shared";
default:
return "?";
}
@@ -47,8 +49,8 @@ static void log_hid_tx_report_event(const struct app_event_header *aeh)
int pos;
pos = snprintf(log_buf, sizeof(log_buf),
"transport:%s type:%s protocol:%s seq:%u len:%zu",
transport_name(event->transport),
"channel:%s type:%s protocol:%s seq:%u len:%zu",
channel_name(event->channel),
report_type_name(event->report_type),
protocol_mode_name(event->protocol_mode),
event->sequence,
@@ -84,7 +86,7 @@ static void profile_hid_tx_report_event(struct log_event_buf *buf,
{
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->channel);
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);
@@ -97,7 +99,7 @@ APP_EVENT_INFO_DEFINE(hid_tx_report_event,
NRF_PROFILER_ARG_U8,
NRF_PROFILER_ARG_U16,
NRF_PROFILER_ARG_U8),
ENCODE("transport", "report_type", "protocol_mode", "sequence", "len"),
ENCODE("channel", "report_type", "protocol_mode", "sequence", "len"),
profile_hid_tx_report_event);
APP_EVENT_TYPE_DEFINE(hid_tx_report_event,

View File

@@ -7,6 +7,8 @@
static const char *mode_name(enum mode_switch_mode mode)
{
switch (mode) {
case MODE_SWITCH_INVALID:
return "INVALID";
case MODE_SWITCH_USB:
return "USB";
case MODE_SWITCH_24G:

View File

@@ -0,0 +1,27 @@
#include "led_strip_en_event.h"
static void log_led_strip_en_event(const struct app_event_header *aeh)
{
const struct led_strip_en_event *event = cast_led_strip_en_event(aeh);
APP_EVENT_MANAGER_LOG(aeh, "enabled:%u", event->enabled);
}
static void profile_led_strip_en_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
const struct led_strip_en_event *event = cast_led_strip_en_event(aeh);
nrf_profiler_log_encode_uint8(buf, event->enabled);
}
APP_EVENT_INFO_DEFINE(led_strip_en_event,
ENCODE(NRF_PROFILER_ARG_U8),
ENCODE("enabled"),
profile_led_strip_en_event);
APP_EVENT_TYPE_DEFINE(led_strip_en_event,
log_led_strip_en_event,
&led_strip_en_event_info,
APP_EVENT_FLAGS_CREATE(
APP_EVENT_TYPE_FLAGS_INIT_LOG_ENABLE));

View File

@@ -5,6 +5,8 @@
static const char *mode_name(enum mode_switch_mode mode)
{
switch (mode) {
case MODE_SWITCH_INVALID:
return "INVALID";
case MODE_SWITCH_USB:
return "USB";
case MODE_SWITCH_24G:

View File

@@ -0,0 +1,42 @@
#include "proto_rx_event.h"
static const char *transport_name(enum proto_transport transport)
{
switch (transport) {
case PROTO_TRANSPORT_USB_CDC:
return "usb_cdc";
case PROTO_TRANSPORT_BLE_NUS:
return "ble_nus";
default:
return "?";
}
}
static void log_proto_rx_event(const struct app_event_header *aeh)
{
const struct proto_rx_event *event = cast_proto_rx_event(aeh);
APP_EVENT_MANAGER_LOG(aeh, "transport:%s len:%zu",
transport_name(event->transport),
event->dyndata.size);
}
static void profile_proto_rx_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
const struct proto_rx_event *event = cast_proto_rx_event(aeh);
nrf_profiler_log_encode_uint8(buf, event->transport);
nrf_profiler_log_encode_uint16(buf, (uint16_t)event->dyndata.size);
}
APP_EVENT_INFO_DEFINE(proto_rx_event,
ENCODE(NRF_PROFILER_ARG_U8, NRF_PROFILER_ARG_U16),
ENCODE("transport", "len"),
profile_proto_rx_event);
APP_EVENT_TYPE_DEFINE(proto_rx_event,
log_proto_rx_event,
&proto_rx_event_info,
APP_EVENT_FLAGS_CREATE(
APP_EVENT_TYPE_FLAGS_INIT_LOG_ENABLE));

View File

@@ -0,0 +1,56 @@
#include "proto_transport_state_event.h"
static const char *transport_name(enum proto_transport transport)
{
switch (transport) {
case PROTO_TRANSPORT_USB_CDC:
return "usb_cdc";
case PROTO_TRANSPORT_BLE_NUS:
return "ble_nus";
default:
return "?";
}
}
static const char *state_name(enum proto_transport_link_state state)
{
switch (state) {
case PROTO_TRANSPORT_LINK_DOWN:
return "down";
case PROTO_TRANSPORT_LINK_READY:
return "ready";
default:
return "?";
}
}
static void log_proto_transport_state_event(const struct app_event_header *aeh)
{
const struct proto_transport_state_event *event =
cast_proto_transport_state_event(aeh);
APP_EVENT_MANAGER_LOG(aeh, "transport:%s state:%s",
transport_name(event->transport),
state_name(event->state));
}
static void profile_proto_transport_state_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
const struct proto_transport_state_event *event =
cast_proto_transport_state_event(aeh);
nrf_profiler_log_encode_uint8(buf, event->transport);
nrf_profiler_log_encode_uint8(buf, event->state);
}
APP_EVENT_INFO_DEFINE(proto_transport_state_event,
ENCODE(NRF_PROFILER_ARG_U8, NRF_PROFILER_ARG_U8),
ENCODE("transport", "state"),
profile_proto_transport_state_event);
APP_EVENT_TYPE_DEFINE(proto_transport_state_event,
log_proto_transport_state_event,
&proto_transport_state_event_info,
APP_EVENT_FLAGS_CREATE(
APP_EVENT_TYPE_FLAGS_INIT_LOG_ENABLE));

View File

@@ -0,0 +1,42 @@
#include "proto_tx_event.h"
static const char *transport_name(enum proto_transport transport)
{
switch (transport) {
case PROTO_TRANSPORT_USB_CDC:
return "usb_cdc";
case PROTO_TRANSPORT_BLE_NUS:
return "ble_nus";
default:
return "?";
}
}
static void log_proto_tx_event(const struct app_event_header *aeh)
{
const struct proto_tx_event *event = cast_proto_tx_event(aeh);
APP_EVENT_MANAGER_LOG(aeh, "transport:%s len:%zu",
transport_name(event->transport),
event->dyndata.size);
}
static void profile_proto_tx_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
const struct proto_tx_event *event = cast_proto_tx_event(aeh);
nrf_profiler_log_encode_uint8(buf, event->transport);
nrf_profiler_log_encode_uint16(buf, (uint16_t)event->dyndata.size);
}
APP_EVENT_INFO_DEFINE(proto_tx_event,
ENCODE(NRF_PROFILER_ARG_U8, NRF_PROFILER_ARG_U16),
ENCODE("transport", "len"),
profile_proto_tx_event);
APP_EVENT_TYPE_DEFINE(proto_tx_event,
log_proto_tx_event,
&proto_tx_event_info,
APP_EVENT_FLAGS_CREATE(
APP_EVENT_TYPE_FLAGS_INIT_LOG_ENABLE));

View File

@@ -0,0 +1,34 @@
#include "theme_rgb_update_event.h"
static void log_theme_rgb_update_event(const struct app_event_header *aeh)
{
const struct theme_rgb_update_event *event =
cast_theme_rgb_update_event(aeh);
APP_EVENT_MANAGER_LOG(aeh, "r:%u g:%u b:%u",
event->theme.r, event->theme.g, event->theme.b);
}
static void profile_theme_rgb_update_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
const struct theme_rgb_update_event *event =
cast_theme_rgb_update_event(aeh);
nrf_profiler_log_encode_uint8(buf, event->theme.r);
nrf_profiler_log_encode_uint8(buf, event->theme.g);
nrf_profiler_log_encode_uint8(buf, event->theme.b);
}
APP_EVENT_INFO_DEFINE(theme_rgb_update_event,
ENCODE(NRF_PROFILER_ARG_U8,
NRF_PROFILER_ARG_U8,
NRF_PROFILER_ARG_U8),
ENCODE("r", "g", "b"),
profile_theme_rgb_update_event);
APP_EVENT_TYPE_DEFINE(theme_rgb_update_event,
log_theme_rgb_update_event,
&theme_rgb_update_event_info,
APP_EVENT_FLAGS_CREATE(
APP_EVENT_TYPE_FLAGS_INIT_LOG_ENABLE));

View File

@@ -0,0 +1,41 @@
#include "time_sync_event.h"
static void log_time_sync_event(const struct app_event_header *aeh)
{
const struct time_sync_event *event = cast_time_sync_event(aeh);
APP_EVENT_MANAGER_LOG(aeh,
"ver:%u flags:0x%08x tz:%d utc_ms:%llu acc:%u",
event->version,
event->flags,
event->timezone_min,
event->utc_ms,
event->accuracy_ms);
}
static void profile_time_sync_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
const struct time_sync_event *event = cast_time_sync_event(aeh);
nrf_profiler_log_encode_uint32(buf, event->version);
nrf_profiler_log_encode_uint32(buf, event->flags);
nrf_profiler_log_encode_int32(buf, event->timezone_min);
nrf_profiler_log_encode_uint32(buf, (uint32_t)(event->utc_ms & 0xFFFFFFFFULL));
nrf_profiler_log_encode_uint32(buf, event->accuracy_ms);
}
APP_EVENT_INFO_DEFINE(time_sync_event,
ENCODE(NRF_PROFILER_ARG_U32,
NRF_PROFILER_ARG_U32,
NRF_PROFILER_ARG_S32,
NRF_PROFILER_ARG_U32,
NRF_PROFILER_ARG_U32),
ENCODE("version", "flags", "timezone_min", "utc_ms_lo", "accuracy_ms"),
profile_time_sync_event);
APP_EVENT_TYPE_DEFINE(time_sync_event,
log_time_sync_event,
&time_sync_event_info,
APP_EVENT_FLAGS_CREATE(
APP_EVENT_TYPE_FLAGS_INIT_LOG_ENABLE));

View File

@@ -1,73 +0,0 @@
#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

@@ -1,62 +0,0 @@
#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,82 @@
#include "usb_control_event.h"
static const char *control_event_name(enum usb_control_event_type type)
{
switch (type) {
case USB_CONTROL_EVENT_CDC_LINE_STATE:
return "cdc_line_state";
case USB_CONTROL_EVENT_CDC_LINE_CODING:
return "cdc_line_coding";
default:
return "?";
}
}
static void log_usb_control_event(const struct app_event_header *aeh)
{
const struct usb_control_event *event = cast_usb_control_event(aeh);
switch (event->type) {
case USB_CONTROL_EVENT_CDC_LINE_STATE:
APP_EVENT_MANAGER_LOG(aeh, "type:%s dtr:%u",
control_event_name(event->type),
event->data.cdc_line_state.dtr);
break;
case USB_CONTROL_EVENT_CDC_LINE_CODING:
APP_EVENT_MANAGER_LOG(aeh,
"type:%s baud:%u data:%u stop:%u parity:%u flow:%u",
control_event_name(event->type),
event->data.cdc_line_coding.baudrate,
event->data.cdc_line_coding.data_bits,
event->data.cdc_line_coding.stop_bits,
event->data.cdc_line_coding.parity,
event->data.cdc_line_coding.flow_ctrl);
break;
default:
APP_EVENT_MANAGER_LOG(aeh, "type:%s",
control_event_name(event->type));
break;
}
}
static void profile_usb_control_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
const struct usb_control_event *event = cast_usb_control_event(aeh);
nrf_profiler_log_encode_uint8(buf, event->type);
switch (event->type) {
case USB_CONTROL_EVENT_CDC_LINE_STATE:
nrf_profiler_log_encode_uint8(buf, event->data.cdc_line_state.dtr);
break;
case USB_CONTROL_EVENT_CDC_LINE_CODING:
nrf_profiler_log_encode_uint32(buf, event->data.cdc_line_coding.baudrate);
nrf_profiler_log_encode_uint8(buf, event->data.cdc_line_coding.data_bits);
nrf_profiler_log_encode_uint8(buf, event->data.cdc_line_coding.stop_bits);
nrf_profiler_log_encode_uint8(buf, event->data.cdc_line_coding.parity);
nrf_profiler_log_encode_uint8(buf, event->data.cdc_line_coding.flow_ctrl);
break;
default:
break;
}
}
APP_EVENT_INFO_DEFINE(usb_control_event,
ENCODE(NRF_PROFILER_ARG_U8,
NRF_PROFILER_ARG_U32,
NRF_PROFILER_ARG_U8,
NRF_PROFILER_ARG_U8,
NRF_PROFILER_ARG_U8,
NRF_PROFILER_ARG_U8),
ENCODE("type", "baud_or_zero", "arg1", "arg2", "arg3", "arg4"),
profile_usb_control_event);
APP_EVENT_TYPE_DEFINE(usb_control_event,
log_usb_control_event,
&usb_control_event_info,
APP_EVENT_FLAGS_CREATE(
APP_EVENT_TYPE_FLAGS_INIT_LOG_ENABLE));

View File

@@ -1,46 +0,0 @@
#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

@@ -1,42 +0,0 @@
#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

@@ -1,24 +0,0 @@
#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));

View File

@@ -0,0 +1,47 @@
#include <caf/events/module_state_event.h>
#include "usb_state_event.h"
static const char *usb_state_name(enum usb_state state)
{
switch (state) {
case USB_STATE_DISABLED:
return "disabled";
case USB_STATE_DISCONNECTED:
return "disconnected";
case USB_STATE_POWERED:
return "powered";
case USB_STATE_ACTIVE:
return "active";
case USB_STATE_SUSPENDED:
return "suspended";
default:
return "?";
}
}
static void log_usb_state_event(const struct app_event_header *aeh)
{
const struct usb_state_event *event = cast_usb_state_event(aeh);
APP_EVENT_MANAGER_LOG(aeh, "state:%s", usb_state_name(event->state));
}
static void profile_usb_state_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
const struct usb_state_event *event = cast_usb_state_event(aeh);
nrf_profiler_log_encode_uint8(buf, event->state);
}
APP_EVENT_INFO_DEFINE(usb_state_event,
ENCODE(NRF_PROFILER_ARG_U8),
ENCODE("state"),
profile_usb_state_event);
APP_EVENT_TYPE_DEFINE(usb_state_event,
log_usb_state_event,
&usb_state_event_info,
APP_EVENT_FLAGS_CREATE(
APP_EVENT_TYPE_FLAGS_INIT_LOG_ENABLE));

View File

@@ -10,11 +10,12 @@
#include <zephyr/logging/log.h>
#include "hid_channel_state_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 "keyboard_hid_report_event.h"
#include "module_lifecycle.h"
#include "mode_switch_event.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
@@ -37,49 +38,95 @@ struct queued_report {
uint8_t data[HID_FLOWCTRL_REPORT_DATA_MAX];
};
struct hid_transport_state_data {
bool ready;
bool keys_ready;
bool consumer_ready;
struct hid_channel_state_data {
uint8_t report_ready_bm;
enum keyboard_protocol_mode protocol_mode;
};
struct in_flight_report {
bool active;
enum hid_transport transport;
enum hid_send_channel channel;
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,
struct hid_flowctrl_module_ctx {
struct module_lifecycle_ctx lc;
struct hid_channel_state_data channel_state[HID_SEND_CH_COUNT];
struct pending_report pending_keys;
struct pending_report pending_consumer_latest;
struct queued_report consumer_fifo[HID_FLOWCTRL_FIFO_DEPTH];
uint8_t consumer_fifo_head;
uint8_t consumer_fifo_tail;
uint8_t consumer_fifo_count;
struct in_flight_report in_flight[HID_SEND_CH_COUNT];
enum mode_switch_mode current_mode;
uint16_t next_sequence;
};
static int do_init(void);
static int do_start(void);
static int do_stop(void);
static const struct module_lifecycle_cfg lifecycle_cfg = {
.mode = ML_MODE_POWER,
.stopped_state = MODULE_STATE_STANDBY,
};
static const struct module_lifecycle_ops lifecycle_ops = {
.do_init = do_init,
.do_start = do_start,
.do_stop = do_stop,
};
static struct hid_flowctrl_module_ctx ctx = {
.lc = {
.state = LC_UNINIT,
.cfg = &lifecycle_cfg,
.ops = &lifecycle_ops,
},
[HID_TRANSPORT_BLE] = {
.protocol_mode = KEYBOARD_PROTOCOL_MODE_REPORT,
.channel_state = {
[HID_SEND_CH_USB_KEYS] = {
.protocol_mode = KEYBOARD_PROTOCOL_MODE_REPORT,
},
[HID_SEND_CH_USB_CONSUMER] = {
.protocol_mode = KEYBOARD_PROTOCOL_MODE_REPORT,
},
[HID_SEND_CH_BLE_SHARED] = {
.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)
#define lifecycle ctx.lc
#define channel_state ctx.channel_state
#define pending_keys ctx.pending_keys
#define pending_consumer_latest ctx.pending_consumer_latest
#define consumer_fifo ctx.consumer_fifo
#define consumer_fifo_head ctx.consumer_fifo_head
#define consumer_fifo_tail ctx.consumer_fifo_tail
#define consumer_fifo_count ctx.consumer_fifo_count
#define in_flight ctx.in_flight
#define current_mode ctx.current_mode
#define next_sequence ctx.next_sequence
#define running module_lifecycle_is_running(&ctx.lc)
static bool current_mode_to_channel(enum keyboard_report_type report_type,
enum hid_send_channel *channel)
{
switch (mode) {
if (channel == NULL) {
return false;
}
switch (current_mode) {
case MODE_SWITCH_USB:
*transport = HID_TRANSPORT_USB;
*channel = (report_type == KEYBOARD_REPORT_TYPE_KEYS) ?
HID_SEND_CH_USB_KEYS :
HID_SEND_CH_USB_CONSUMER;
return true;
case MODE_SWITCH_BLE:
*transport = HID_TRANSPORT_BLE;
*channel = HID_SEND_CH_BLE_SHARED;
return true;
default:
@@ -131,112 +178,137 @@ static bool consumer_fifo_pop(struct queued_report *entry)
return true;
}
static bool transport_can_send_report(enum keyboard_report_type report_type)
static bool channel_can_send_report(enum hid_send_channel channel,
enum keyboard_report_type report_type,
enum keyboard_protocol_mode protocol_mode)
{
enum hid_transport transport;
struct hid_transport_state_data *state;
const struct hid_channel_state_data *state = &channel_state[channel];
if (!mode_to_transport(current_mode, &transport) || in_flight.active) {
return false;
}
state = &transport_state[transport];
if (!state->ready) {
if (in_flight[channel].active) {
return false;
}
if (report_type == KEYBOARD_REPORT_TYPE_KEYS) {
return state->keys_ready;
return (state->report_ready_bm & BIT(KEYBOARD_REPORT_TYPE_KEYS)) &&
(state->protocol_mode == protocol_mode);
}
return state->consumer_ready;
if (channel == HID_SEND_CH_BLE_SHARED) {
return (state->report_ready_bm & BIT(KEYBOARD_REPORT_TYPE_CONSUMER)) &&
(state->protocol_mode == KEYBOARD_PROTOCOL_MODE_REPORT);
}
return (state->report_ready_bm & BIT(KEYBOARD_REPORT_TYPE_CONSUMER)) != 0U;
}
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)
static void try_send_keys(void)
{
struct hid_tx_report_event *event = new_hid_tx_report_event(size);
enum hid_send_channel channel;
event->transport = transport;
event->report_type = report_type;
event->protocol_mode = protocol_mode;
event->sequence = next_sequence++;
memcpy(event->dyndata.data, data, size);
if (!pending_keys.valid) {
return;
}
in_flight.active = true;
in_flight.transport = transport;
in_flight.report_type = report_type;
in_flight.sequence = event->sequence;
if (!current_mode_to_channel(KEYBOARD_REPORT_TYPE_KEYS, &channel)) {
return;
}
APP_EVENT_SUBMIT(event);
if (!channel_can_send_report(channel, pending_keys.report_type,
pending_keys.protocol_mode)) {
return;
}
in_flight[channel].active = true;
in_flight[channel].channel = channel;
in_flight[channel].report_type = pending_keys.report_type;
in_flight[channel].sequence = next_sequence++;
(void)submit_hid_tx_report_event(channel, pending_keys.report_type,
pending_keys.protocol_mode,
in_flight[channel].sequence,
pending_keys.data, pending_keys.size);
pending_keys.valid = false;
}
static void try_send_consumer_fifo(void)
{
struct queued_report queued;
enum hid_send_channel channel;
if (consumer_fifo_count == 0U) {
return;
}
if (!current_mode_to_channel(KEYBOARD_REPORT_TYPE_CONSUMER, &channel)) {
return;
}
if (!consumer_fifo_pop(&queued)) {
return;
}
if (!channel_can_send_report(channel, queued.report_type,
queued.protocol_mode)) {
if (queued.protocol_mode == channel_state[channel].protocol_mode) {
consumer_fifo_push(queued.report_type, queued.protocol_mode,
queued.data, queued.size);
}
return;
}
in_flight[channel].active = true;
in_flight[channel].channel = channel;
in_flight[channel].report_type = queued.report_type;
in_flight[channel].sequence = next_sequence++;
(void)submit_hid_tx_report_event(channel, queued.report_type,
queued.protocol_mode,
in_flight[channel].sequence,
queued.data, queued.size);
}
static void try_send_consumer_latest(void)
{
enum hid_send_channel channel;
if (!pending_consumer_latest.valid) {
return;
}
if (!current_mode_to_channel(KEYBOARD_REPORT_TYPE_CONSUMER, &channel)) {
return;
}
if (!channel_can_send_report(channel,
pending_consumer_latest.report_type,
pending_consumer_latest.protocol_mode)) {
return;
}
in_flight[channel].active = true;
in_flight[channel].channel = channel;
in_flight[channel].report_type = pending_consumer_latest.report_type;
in_flight[channel].sequence = next_sequence++;
(void)submit_hid_tx_report_event(channel,
pending_consumer_latest.report_type,
pending_consumer_latest.protocol_mode,
in_flight[channel].sequence,
pending_consumer_latest.data,
pending_consumer_latest.size);
pending_consumer_latest.valid = false;
}
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)) {
if (!running) {
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;
}
}
try_send_keys();
try_send_consumer_fifo();
try_send_consumer_latest();
}
static bool handle_keyboard_hid_report_event(const struct keyboard_hid_report_event *event)
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))) {
@@ -267,41 +339,18 @@ static bool handle_keyboard_hid_report_event(const struct keyboard_hid_report_ev
return false;
}
static bool handle_hid_transport_state_event(const struct hid_transport_state_event *event)
static bool handle_hid_channel_state_event(
const struct hid_channel_state_event *event)
{
enum hid_transport active_transport;
struct hid_transport_state_data *state;
if (event->transport >= HID_TRANSPORT_COUNT) {
if (event->channel >= HID_SEND_CH_COUNT) {
return false;
}
state = &transport_state[event->transport];
channel_state[event->channel].report_ready_bm = event->report_ready_bm;
channel_state[event->channel].protocol_mode = event->protocol_mode;
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;
if (event->report_ready_bm == 0U) {
in_flight[event->channel].active = false;
}
try_send_next();
@@ -310,17 +359,21 @@ static bool handle_hid_transport_state_event(const struct hid_transport_state_ev
static bool handle_hid_report_sent_event(const struct hid_report_sent_event *event)
{
if (!in_flight.active || (event->transport != in_flight.transport)) {
if (event->channel >= HID_SEND_CH_COUNT) {
return false;
}
if (event->sequence != in_flight.sequence) {
if (!in_flight[event->channel].active) {
return false;
}
if (event->sequence != in_flight[event->channel].sequence) {
LOG_WRN("Unexpected HID sent sequence %u (expected %u)",
event->sequence, in_flight.sequence);
event->sequence, in_flight[event->channel].sequence);
return false;
}
in_flight.active = false;
in_flight[event->channel].active = false;
if (event->error) {
LOG_WRN("HID report send failed for seq %u", event->sequence);
@@ -345,59 +398,57 @@ static bool handle_mode_switch_event(const struct mode_switch_event *event)
return false;
}
static int module_init(void)
static int do_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 =
memset(channel_state, 0, sizeof(channel_state));
channel_state[HID_SEND_CH_USB_KEYS].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 =
channel_state[HID_SEND_CH_USB_CONSUMER].protocol_mode =
KEYBOARD_PROTOCOL_MODE_REPORT;
channel_state[HID_SEND_CH_BLE_SHARED].protocol_mode =
KEYBOARD_PROTOCOL_MODE_REPORT;
next_sequence = 1U;
return 0;
}
static int module_start(void)
static int do_start(void)
{
if (running) {
return 0;
}
running = true;
try_send_next();
return 0;
}
static void module_pause(void)
static int do_stop(void)
{
if (!running) {
return;
return 0;
}
clear_pending_reports();
running = false;
return 0;
}
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));
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_channel_state_event(aeh)) {
return handle_hid_channel_state_event(
cast_hid_channel_state_event(aeh));
}
if (is_hid_report_sent_event(aeh)) {
return handle_hid_report_sent_event(cast_hid_report_sent_event(aeh));
return handle_hid_report_sent_event(
cast_hid_report_sent_event(aeh));
}
if (is_mode_switch_event(aeh)) {
@@ -405,50 +456,27 @@ 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);
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);
}
(void)module_set_lifecycle(&lifecycle, LC_RUNNING);
}
return false;
}
if (is_power_down_event(aeh)) {
if (initialized) {
module_pause();
module_set_state(MODULE_STATE_STANDBY);
if (module_lifecycle_is_initialized(&lifecycle)) {
(void)module_set_lifecycle(&lifecycle, LC_STOPPED);
}
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);
}
if (module_lifecycle_is_initialized(&lifecycle)) {
(void)module_set_lifecycle(&lifecycle, LC_RUNNING);
}
return false;
@@ -460,7 +488,7 @@ static bool app_event_handler(const struct app_event_header *aeh)
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_channel_state_event);
APP_EVENT_SUBSCRIBE(MODULE, hid_report_sent_event);
APP_EVENT_SUBSCRIBE(MODULE, mode_switch_event);
APP_EVENT_SUBSCRIBE(MODULE, module_state_event);

View File

@@ -15,8 +15,11 @@
#include <zephyr/sys/util.h>
#include "encoder_event.h"
#include "function_bitmap_state_event.h"
#include "function_bitmap_update_event.h"
#include "keyboard_core.h"
#include "keyboard_hid_report_event.h"
#include "module_lifecycle.h"
#include "mode_switch_event.h"
#include "set_protocol_event.h"
@@ -39,8 +42,8 @@ struct keymap_entry {
};
struct keyboard_state {
uint8_t modifiers;
uint8_t keys_bitmap[KEYBOARD_NKRO_BITMAP_BYTES];
uint8_t pressed_usage_bitmap[KEYBOARD_PROTOCOL_BITMAP_BYTES];
uint8_t function_pressed_bitmap[KEYBOARD_PROTOCOL_BITMAP_BYTES];
uint32_t consumer_bits;
};
@@ -83,16 +86,51 @@ static const uint16_t consumer_usage_map[KEYBOARD_CONSUMER_CTRL_COUNT] = {
[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,
struct keyboard_core_module_ctx {
struct module_lifecycle_ctx lc;
struct keyboard_state keyboard_state;
struct keyboard_reports_cache reports_cache;
uint8_t function_usage_mask[KEYBOARD_PROTOCOL_BITMAP_BYTES];
enum keyboard_protocol_mode transport_protocol_modes[HID_TRANSPORT_COUNT];
enum mode_switch_mode current_mode;
bool mode_valid;
};
static enum mode_switch_mode current_mode;
static bool initialized;
static bool running;
static bool mode_valid;
static int do_init(void);
static int do_start(void);
static int do_stop(void);
static const struct module_lifecycle_cfg lifecycle_cfg = {
.mode = ML_MODE_POWER,
.stopped_state = MODULE_STATE_STANDBY,
};
static const struct module_lifecycle_ops lifecycle_ops = {
.do_init = do_init,
.do_start = do_start,
.do_stop = do_stop,
};
static struct keyboard_core_module_ctx ctx = {
.lc = {
.state = LC_UNINIT,
.cfg = &lifecycle_cfg,
.ops = &lifecycle_ops,
},
.transport_protocol_modes = {
[HID_TRANSPORT_USB] = KEYBOARD_PROTOCOL_MODE_REPORT,
[HID_TRANSPORT_BLE] = KEYBOARD_PROTOCOL_MODE_REPORT,
},
};
#define lifecycle ctx.lc
#define keyboard_state ctx.keyboard_state
#define reports_cache ctx.reports_cache
#define function_usage_mask ctx.function_usage_mask
#define transport_protocol_modes ctx.transport_protocol_modes
#define current_mode ctx.current_mode
#define mode_valid ctx.mode_valid
#define running module_lifecycle_is_running(&ctx.lc)
static bool mode_to_transport(enum mode_switch_mode mode, enum hid_transport *transport)
{
@@ -143,40 +181,61 @@ static const struct keymap_entry *keymap_get(uint16_t key_id)
return NULL;
}
static bool usage_is_modifier(uint16_t usage_id)
static bool usage_to_bitmap_pos(uint16_t usage_id, uint8_t *byte_idx,
uint8_t *bit_idx)
{
return IN_RANGE(usage_id, KEYBOARD_USAGE_FIRST_MODIFIER,
KEYBOARD_USAGE_LAST_MODIFIER);
}
if ((byte_idx == NULL) || (bit_idx == NULL)) {
return false;
}
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;
if ((usage_id >= KEYBOARD_USAGE_FIRST_MODIFIER) &&
(usage_id <= KEYBOARD_USAGE_LAST_MODIFIER)) {
*byte_idx = 0U;
*bit_idx = (uint8_t)(usage_id - KEYBOARD_USAGE_FIRST_MODIFIER);
return true;
}
if (usage_id > KEYBOARD_NKRO_USAGE_MAX) {
if (usage_id <= KEYBOARD_NKRO_USAGE_MAX) {
*byte_idx = (uint8_t)(1U + (usage_id / 8U));
*bit_idx = (uint8_t)(usage_id % 8U);
return true;
}
return false;
}
static bool usage_bitmap_test(const uint8_t *bitmap, uint16_t usage_id)
{
uint8_t byte_idx;
uint8_t bit_idx;
if ((bitmap == NULL) ||
!usage_to_bitmap_pos(usage_id, &byte_idx, &bit_idx)) {
return false;
}
return (bitmap[byte_idx] & BIT(bit_idx)) != 0U;
}
static bool usage_bitmap_write(uint8_t *bitmap, uint16_t usage_id, bool pressed)
{
uint8_t byte_idx;
uint8_t bit_idx;
bool was_pressed;
if ((bitmap == NULL) ||
!usage_to_bitmap_pos(usage_id, &byte_idx, &bit_idx)) {
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;
was_pressed = (bitmap[byte_idx] & BIT(bit_idx)) != 0U;
if (was_pressed == pressed) {
return false;
}
WRITE_BIT(keyboard_state.keys_bitmap[byte_idx], bit_idx, pressed);
WRITE_BIT(bitmap[byte_idx], bit_idx, pressed);
return true;
}
@@ -202,6 +261,11 @@ static void keyboard_state_clear(void)
memset(&keyboard_state, 0, sizeof(keyboard_state));
}
static void function_usage_mask_clear(void)
{
memset(function_usage_mask, 0, sizeof(function_usage_mask));
}
static void reports_cache_invalidate(void)
{
reports_cache.boot_valid = false;
@@ -209,19 +273,31 @@ static void reports_cache_invalidate(void)
reports_cache.consumer_valid = false;
}
static void build_effective_hid_bitmap(uint8_t bitmap[KEYBOARD_PROTOCOL_BITMAP_BYTES])
{
for (size_t i = 0; i < KEYBOARD_PROTOCOL_BITMAP_BYTES; i++) {
bitmap[i] = keyboard_state.pressed_usage_bitmap[i] &
(uint8_t)~keyboard_state.function_pressed_bitmap[i];
}
}
static void build_boot_report(uint8_t report[KEYBOARD_BOOT_REPORT_SIZE])
{
uint8_t effective_hid_bitmap[KEYBOARD_PROTOCOL_BITMAP_BYTES];
size_t key_count = 0;
build_effective_hid_bitmap(effective_hid_bitmap);
memset(report, 0, KEYBOARD_BOOT_REPORT_SIZE);
report[0] = keyboard_state.modifiers;
report[0] = effective_hid_bitmap[0];
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;
uint8_t byte_idx;
uint8_t bit_idx;
if ((keyboard_state.keys_bitmap[byte_idx] & BIT(bit_idx)) == 0U) {
(void)usage_to_bitmap_pos(usage_id, &byte_idx, &bit_idx);
if ((effective_hid_bitmap[byte_idx] & BIT(bit_idx)) == 0U) {
continue;
}
@@ -238,8 +314,11 @@ static void build_boot_report(uint8_t report[KEYBOARD_BOOT_REPORT_SIZE])
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);
uint8_t effective_hid_bitmap[KEYBOARD_PROTOCOL_BITMAP_BYTES];
build_effective_hid_bitmap(effective_hid_bitmap);
report[0] = effective_hid_bitmap[0];
memcpy(&report[1], &effective_hid_bitmap[1], KEYBOARD_NKRO_BITMAP_BYTES);
}
static uint16_t active_consumer_usage_get(void)
@@ -258,23 +337,6 @@ 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];
@@ -286,10 +348,9 @@ static void submit_consumer_fifo_frame(uint16_t usage_id)
}
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);
(void)submit_keyboard_hid_report_event(
current_mode, KEYBOARD_REPORT_TYPE_CONSUMER, protocol_mode,
HID_QUEUE_POLICY_FIFO, report_buf, KEYBOARD_CONSUMER_REPORT_SIZE);
}
static void submit_consumer_pulse_frames(enum keyboard_consumer_control control_id,
@@ -349,10 +410,9 @@ static void emit_keys_report(bool force)
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);
(void)submit_keyboard_hid_report_event(
current_mode, KEYBOARD_REPORT_TYPE_KEYS, protocol_mode,
HID_QUEUE_POLICY_LATEST, report_buf, report_size);
}
static void emit_consumer_report(bool force)
@@ -374,10 +434,10 @@ static void emit_consumer_report(bool force)
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);
(void)submit_keyboard_hid_report_event(
current_mode, KEYBOARD_REPORT_TYPE_CONSUMER, protocol_mode,
HID_QUEUE_POLICY_LATEST, report_buf,
KEYBOARD_CONSUMER_REPORT_SIZE);
}
static void emit_all_reports(bool force)
@@ -389,9 +449,13 @@ static void emit_all_reports(bool force)
}
}
static void emit_function_state_event(void)
{
(void)submit_function_bitmap_state_event(keyboard_state.pressed_usage_bitmap);
}
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();
@@ -399,28 +463,23 @@ static void emit_release_reports(enum mode_switch_mode mode)
(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);
(void)submit_keyboard_hid_report_event(
mode, KEYBOARD_REPORT_TYPE_KEYS, protocol_mode,
HID_QUEUE_POLICY_LATEST, keys_report, keys_report_size);
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);
(void)submit_keyboard_hid_report_event(
mode, KEYBOARD_REPORT_TYPE_CONSUMER, protocol_mode,
HID_QUEUE_POLICY_LATEST, consumer_report,
KEYBOARD_CONSUMER_REPORT_SIZE);
}
}
static int module_init(void)
static int do_init(void)
{
keyboard_state_clear();
reports_cache_invalidate();
function_usage_mask_clear();
mode_valid = false;
transport_protocol_modes[HID_TRANSPORT_USB] =
KEYBOARD_PROTOCOL_MODE_REPORT;
@@ -430,30 +489,31 @@ static int module_init(void)
return 0;
}
static int module_start(void)
static int do_start(void)
{
if (running) {
return 0;
}
running = true;
return 0;
}
static void module_pause(void)
static int do_stop(void)
{
if (!running) {
return;
return 0;
}
if (mode_valid) {
emit_release_reports(current_mode);
}
emit_function_state_event();
keyboard_state_clear();
reports_cache_invalidate();
mode_valid = false;
running = false;
return 0;
}
static bool handle_button_event(const struct button_event *event)
@@ -472,8 +532,30 @@ static bool handle_button_event(const struct button_event *event)
}
if (entry->usage_type == KEY_USAGE_TYPE_KEYBOARD) {
changed = keyboard_key_update(entry->usage_id, event->pressed);
if (changed) {
bool routed_to_function;
changed = usage_bitmap_write(keyboard_state.pressed_usage_bitmap,
entry->usage_id, event->pressed);
if (!changed) {
return false;
}
if (event->pressed) {
routed_to_function =
usage_bitmap_test(function_usage_mask, entry->usage_id);
(void)usage_bitmap_write(keyboard_state.function_pressed_bitmap,
entry->usage_id, routed_to_function);
} else {
routed_to_function =
usage_bitmap_test(keyboard_state.function_pressed_bitmap,
entry->usage_id);
(void)usage_bitmap_write(keyboard_state.function_pressed_bitmap,
entry->usage_id, false);
}
if (routed_to_function) {
emit_function_state_event();
} else {
emit_keys_report(false);
}
} else {
@@ -498,6 +580,7 @@ static bool handle_mode_switch_event(const struct mode_switch_event *event)
mode_changed = mode_valid && (current_mode != event->mode);
if (mode_changed) {
emit_release_reports(current_mode);
emit_function_state_event();
keyboard_state_clear();
reports_cache_invalidate();
}
@@ -526,6 +609,13 @@ static bool handle_encoder_event(const struct encoder_event *event)
return false;
}
static bool handle_function_bitmap_update_event(
const struct function_bitmap_update_event *event)
{
memcpy(function_usage_mask, event->bitmap, sizeof(function_usage_mask));
return false;
}
static bool app_event_handler(const struct app_event_header *aeh)
{
if (is_button_event(aeh)) {
@@ -536,6 +626,11 @@ static bool app_event_handler(const struct app_event_header *aeh)
return handle_encoder_event(cast_encoder_event(aeh));
}
if (is_function_bitmap_update_event(aeh)) {
return handle_function_bitmap_update_event(
cast_function_bitmap_update_event(aeh));
}
if (is_set_protocol_event(aeh)) {
const struct set_protocol_event *event = cast_set_protocol_event(aeh);
enum hid_transport active_transport;
@@ -570,47 +665,23 @@ static bool app_event_handler(const struct app_event_header *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);
}
(void)module_set_lifecycle(&lifecycle, LC_RUNNING);
}
return false;
}
if (is_power_down_event(aeh)) {
if (initialized) {
module_pause();
module_set_state(MODULE_STATE_STANDBY);
if (module_lifecycle_is_initialized(&lifecycle)) {
(void)module_set_lifecycle(&lifecycle, LC_STOPPED);
}
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);
}
if (module_lifecycle_is_initialized(&lifecycle)) {
(void)module_set_lifecycle(&lifecycle, LC_RUNNING);
}
return false;
@@ -623,6 +694,7 @@ static bool app_event_handler(const struct app_event_header *aeh)
APP_EVENT_LISTENER(MODULE, app_event_handler);
APP_EVENT_SUBSCRIBE(MODULE, button_event);
APP_EVENT_SUBSCRIBE(MODULE, encoder_event);
APP_EVENT_SUBSCRIBE(MODULE, function_bitmap_update_event);
APP_EVENT_SUBSCRIBE(MODULE, set_protocol_event);
APP_EVENT_SUBSCRIBE(MODULE, mode_switch_event);
APP_EVENT_SUBSCRIBE(MODULE, module_state_event);

View File

@@ -0,0 +1,155 @@
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <zephyr/sys/util.h>
#include "led_effect/led_effect.h"
#define KEY_FADE_LEVEL_MAX 255U
#define KEY_FADE_STEP_PER_TICK 12U
struct led_effect_key_fade_state {
const struct led_key_map *key_map;
size_t key_map_len;
size_t pixel_count;
uint8_t default_brightness;
uint8_t level[17];
struct theme_rgb theme;
};
static struct led_effect_key_fade_state key_fade_state;
static const struct led_key_map *find_key(const struct led_effect *effect,
uint16_t key_id)
{
const struct led_effect_key_fade_state *state = effect->state;
for (size_t i = 0; i < state->key_map_len; i++) {
if (state->key_map[i].key_id == key_id) {
return &state->key_map[i];
}
}
return NULL;
}
static int led_effect_key_fade_init(struct led_effect *effect,
const struct led_effect_config *cfg)
{
struct led_effect_key_fade_state *state = effect->state;
if ((effect == NULL) || (cfg == NULL) || (cfg->key_map == NULL) ||
(cfg->pixel_count > ARRAY_SIZE(state->level))) {
return -EINVAL;
}
memset(state, 0, sizeof(*state));
state->key_map = cfg->key_map;
state->key_map_len = cfg->key_map_len;
state->pixel_count = cfg->pixel_count;
state->default_brightness = cfg->default_brightness;
state->theme.r = BLINKY_THEME_DEFAULT_R;
state->theme.g = BLINKY_THEME_DEFAULT_G;
state->theme.b = BLINKY_THEME_DEFAULT_B;
return 0;
}
static void led_effect_key_fade_reset(struct led_effect *effect)
{
struct led_effect_key_fade_state *state = effect->state;
memset(state->level, 0, sizeof(state->level));
}
static void led_effect_key_fade_set_theme(struct led_effect *effect,
const struct theme_rgb *theme)
{
struct led_effect_key_fade_state *state = effect->state;
if (theme == NULL) {
return;
}
state->theme = *theme;
}
static void led_effect_key_fade_on_key_press(struct led_effect *effect,
uint16_t key_id)
{
struct led_effect_key_fade_state *state = effect->state;
const struct led_key_map *map = find_key(effect, key_id);
if ((map == NULL) || (map->led_idx >= state->pixel_count)) {
return;
}
state->level[map->led_idx] =
(state->default_brightness == 0U) ? KEY_FADE_LEVEL_MAX :
state->default_brightness;
}
static bool led_effect_key_fade_tick(struct led_effect *effect, uint32_t dt_ms,
struct led_rgb *pixels, size_t pixel_count)
{
struct led_effect_key_fade_state *state = effect->state;
bool active = false;
bool visible = false;
uint8_t decay;
ARG_UNUSED(dt_ms);
if ((pixels == NULL) || (pixel_count < state->pixel_count)) {
return false;
}
memset(pixels, 0, sizeof(*pixels) * pixel_count);
decay = KEY_FADE_STEP_PER_TICK;
for (size_t i = 0; i < state->pixel_count; i++) {
uint8_t level = state->level[i];
if (level == 0U) {
continue;
}
visible = true;
pixels[i].r = (uint8_t)(((uint16_t)state->theme.r * level) / 255U);
pixels[i].g = (uint8_t)(((uint16_t)state->theme.g * level) / 255U);
pixels[i].b = (uint8_t)(((uint16_t)state->theme.b * level) / 255U);
state->level[i] = (level > decay) ? (uint8_t)(level - decay) : 0U;
active = active || (state->level[i] > 0U);
}
return visible || active;
}
static bool led_effect_key_fade_is_active(const struct led_effect *effect)
{
const struct led_effect_key_fade_state *state = effect->state;
for (size_t i = 0; i < state->pixel_count; i++) {
if (state->level[i] > 0U) {
return true;
}
}
return false;
}
static const struct led_effect_ops key_fade_ops = {
.init = led_effect_key_fade_init,
.reset = led_effect_key_fade_reset,
.set_theme = led_effect_key_fade_set_theme,
.on_key_press = led_effect_key_fade_on_key_press,
.tick = led_effect_key_fade_tick,
.is_active = led_effect_key_fade_is_active,
};
struct led_effect led_effect_key_fade = {
.ops = &key_fade_ops,
.state = &key_fade_state,
};

View File

@@ -0,0 +1,50 @@
#ifndef BLINKY_LED_EFFECT_H_
#define BLINKY_LED_EFFECT_H_
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <zephyr/drivers/led_strip.h>
#include "led_effect_types.h"
#include "theme_color.h"
#ifdef __cplusplus
extern "C" {
#endif
struct led_effect;
struct led_effect_config {
const struct led_key_map *key_map;
size_t key_map_len;
size_t pixel_count;
uint8_t default_brightness;
};
struct led_effect_ops {
int (*init)(struct led_effect *effect,
const struct led_effect_config *cfg);
void (*reset)(struct led_effect *effect);
void (*set_theme)(struct led_effect *effect,
const struct theme_rgb *theme);
void (*on_key_press)(struct led_effect *effect, uint16_t key_id);
bool (*tick)(struct led_effect *effect, uint32_t dt_ms,
struct led_rgb *pixels, size_t pixel_count);
bool (*is_active)(const struct led_effect *effect);
};
struct led_effect {
const struct led_effect_ops *ops;
void *state;
};
const struct led_effect *led_effect_get(enum led_effect_id id);
struct led_effect *led_effect_get_mutable(enum led_effect_id id);
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_LED_EFFECT_H_ */

View File

@@ -0,0 +1,27 @@
#include <stddef.h>
#include "led_effect.h"
extern struct led_effect led_effect_key_fade;
static struct led_effect *const effect_registry[LED_EFFECT_ID_COUNT] = {
[LED_EFFECT_ID_KEY_FADE] = &led_effect_key_fade,
};
const struct led_effect *led_effect_get(enum led_effect_id id)
{
if (id >= LED_EFFECT_ID_COUNT) {
return NULL;
}
return effect_registry[id];
}
struct led_effect *led_effect_get_mutable(enum led_effect_id id)
{
if (id >= LED_EFFECT_ID_COUNT) {
return NULL;
}
return effect_registry[id];
}

View File

@@ -0,0 +1,24 @@
#ifndef BLINKY_LED_EFFECT_TYPES_H_
#define BLINKY_LED_EFFECT_TYPES_H_
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
struct led_key_map {
uint16_t key_id;
uint8_t led_idx;
};
enum led_effect_id {
LED_EFFECT_ID_KEY_FADE = 0,
LED_EFFECT_ID_COUNT,
};
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_LED_EFFECT_TYPES_H_ */

370
src/led_strip_module.c Normal file
View File

@@ -0,0 +1,370 @@
#include <errno.h>
#include <stdbool.h>
#include <string.h>
#include <app_event_manager.h>
#define MODULE led_strip_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/device.h>
#include <zephyr/drivers/gpio.h>
#include <zephyr/drivers/led_strip.h>
#include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
#include "led_effect/led_effect.h"
#include "led_strip_en_event.h"
#include "module_lifecycle.h"
#include "theme_rgb_update_event.h"
#include "theme_color.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
#define LED_STRIP_NODE DT_CHOSEN(zephyr_led_strip)
#define LED_STRIP_NUM_PIXELS DT_PROP(LED_STRIP_NODE, chain_length)
#define LED_STRIP_TICK_INTERVAL K_MSEC(20)
BUILD_ASSERT(DT_NODE_HAS_STATUS(LED_STRIP_NODE, okay),
"Missing zephyr,led-strip chosen node");
BUILD_ASSERT(DT_NODE_HAS_PROP(LED_STRIP_NODE, supply_gpios),
"Missing supply-gpios on zephyr,led-strip node");
BUILD_ASSERT(LED_STRIP_NUM_PIXELS == 17U,
"LED strip key map expects 17 pixels");
struct led_strip_module_ctx {
struct module_lifecycle_ctx lc;
const struct device *strip;
struct gpio_dt_spec strip_en;
struct led_rgb pixels[LED_STRIP_NUM_PIXELS];
struct k_work_delayable effect_work;
struct led_effect *effect;
struct theme_rgb current_theme;
bool enabled;
};
static const struct led_key_map led_key_map[] = {
{ KEY_ID(0, 1), 0U },
{ KEY_ID(1, 1), 1U },
{ KEY_ID(2, 1), 2U },
{ KEY_ID(3, 1), 3U },
{ KEY_ID(0, 2), 4U },
{ KEY_ID(1, 2), 5U },
{ KEY_ID(2, 2), 6U },
{ KEY_ID(0, 3), 7U },
{ KEY_ID(1, 3), 8U },
{ KEY_ID(2, 3), 9U },
{ KEY_ID(3, 3), 10U },
{ KEY_ID(0, 4), 11U },
{ KEY_ID(1, 4), 12U },
{ KEY_ID(2, 4), 13U },
{ KEY_ID(0, 5), 14U },
{ KEY_ID(1, 5), 15U },
{ KEY_ID(3, 5), 16U },
};
static const struct led_effect_config effect_cfg = {
.key_map = led_key_map,
.key_map_len = ARRAY_SIZE(led_key_map),
.pixel_count = LED_STRIP_NUM_PIXELS,
.default_brightness = 0xFFU,
};
static int do_init(void);
static int do_start(void);
static int do_stop(void);
static const struct module_lifecycle_cfg lifecycle_cfg = {
.mode = ML_MODE_POWER,
.stopped_state = MODULE_STATE_STANDBY,
};
static const struct module_lifecycle_ops lifecycle_ops = {
.do_init = do_init,
.do_start = do_start,
.do_stop = do_stop,
};
static struct led_strip_module_ctx ctx = {
.lc = {
.state = LC_UNINIT,
.cfg = &lifecycle_cfg,
.ops = &lifecycle_ops,
},
.strip = DEVICE_DT_GET(LED_STRIP_NODE),
.strip_en = GPIO_DT_SPEC_GET(LED_STRIP_NODE, supply_gpios),
.current_theme = {
.r = BLINKY_THEME_DEFAULT_R,
.g = BLINKY_THEME_DEFAULT_G,
.b = BLINKY_THEME_DEFAULT_B,
},
.enabled = true,
};
static void clear_pixels(void)
{
memset(ctx.pixels, 0, sizeof(ctx.pixels));
}
static int submit_frame(void)
{
int err;
err = led_strip_update_rgb(ctx.strip, ctx.pixels, ARRAY_SIZE(ctx.pixels));
if (err) {
LOG_WRN("led_strip_update_rgb failed (%d)", err);
}
return err;
}
static int set_strip_power(bool on)
{
int err;
err = gpio_pin_set_dt(&ctx.strip_en, on ? 1 : 0);
if (err) {
LOG_WRN("LED strip EN set failed (%d)", err);
}
return err;
}
static int refresh_idle_frame(void)
{
clear_pixels();
return submit_frame();
}
static void stop_effect_work(void)
{
k_work_cancel_delayable(&ctx.effect_work);
}
static void schedule_effect_tick(k_timeout_t delay)
{
k_work_reschedule(&ctx.effect_work, delay);
}
static int enable_strip_output(void)
{
int err;
err = set_strip_power(true);
if (err) {
return err;
}
return refresh_idle_frame();
}
static void disable_strip_output(void)
{
stop_effect_work();
clear_pixels();
(void)submit_frame();
(void)set_strip_power(false);
}
static void effect_work_handler(struct k_work *work)
{
bool keep_running;
ARG_UNUSED(work);
if (!module_lifecycle_is_running(&ctx.lc) || !ctx.enabled ||
(ctx.effect == NULL)) {
return;
}
keep_running = ctx.effect->ops->tick(ctx.effect,
k_ticks_to_ms_floor32(
LED_STRIP_TICK_INTERVAL.ticks),
ctx.pixels, ARRAY_SIZE(ctx.pixels));
(void)submit_frame();
if (keep_running) {
schedule_effect_tick(LED_STRIP_TICK_INTERVAL);
}
}
static int do_init(void)
{
int err;
if (!device_is_ready(ctx.strip)) {
LOG_ERR("LED strip device %s not ready", ctx.strip->name);
return -ENODEV;
}
if (!gpio_is_ready_dt(&ctx.strip_en)) {
LOG_ERR("LED strip supply GPIO not ready");
return -ENODEV;
}
err = gpio_pin_configure_dt(&ctx.strip_en, GPIO_OUTPUT_INACTIVE);
if (err) {
LOG_ERR("Failed to configure LED strip supply GPIO (%d)", err);
return err;
}
k_work_init_delayable(&ctx.effect_work, effect_work_handler);
clear_pixels();
ctx.effect = led_effect_get_mutable(LED_EFFECT_ID_KEY_FADE);
if ((ctx.effect == NULL) || (ctx.effect->ops == NULL)) {
LOG_ERR("LED effect not available");
return -ENOENT;
}
err = ctx.effect->ops->init(ctx.effect, &effect_cfg);
if (err) {
LOG_ERR("LED effect init failed (%d)", err);
return err;
}
ctx.effect->ops->set_theme(ctx.effect, &ctx.current_theme);
LOG_INF("LED strip ready len:%u", (uint32_t)led_strip_length(ctx.strip));
return 0;
}
static int do_start(void)
{
int err;
if (module_lifecycle_is_running(&ctx.lc)) {
return 0;
}
if (!ctx.enabled) {
return 0;
}
err = enable_strip_output();
return err;
}
static int do_stop(void)
{
if (!module_lifecycle_is_running(&ctx.lc)) {
return 0;
}
if ((ctx.effect != NULL) && (ctx.effect->ops != NULL)) {
ctx.effect->ops->reset(ctx.effect);
}
disable_strip_output();
return 0;
}
static bool handle_button_event(const struct button_event *event)
{
if (!module_lifecycle_is_running(&ctx.lc) || !ctx.enabled ||
(ctx.effect == NULL) || !event->pressed) {
return false;
}
ctx.effect->ops->on_key_press(ctx.effect, event->key_id);
schedule_effect_tick(K_NO_WAIT);
return false;
}
static bool handle_led_strip_en_event(const struct led_strip_en_event *event)
{
ctx.enabled = event->enabled;
if (!module_lifecycle_is_running(&ctx.lc)) {
return false;
}
if (ctx.enabled) {
int err = enable_strip_output();
if (err) {
LOG_WRN("LED strip enable request failed (%d)", err);
ctx.enabled = false;
return false;
}
} else {
if ((ctx.effect != NULL) && (ctx.effect->ops != NULL)) {
ctx.effect->ops->reset(ctx.effect);
}
disable_strip_output();
}
return false;
}
static bool handle_theme_rgb_update_event(const struct theme_rgb_update_event *event)
{
ctx.current_theme = event->theme;
if ((ctx.effect != NULL) && (ctx.effect->ops != NULL)) {
ctx.effect->ops->set_theme(ctx.effect, &ctx.current_theme);
}
if (module_lifecycle_is_running(&ctx.lc) && ctx.enabled &&
(ctx.effect != NULL) && ctx.effect->ops->is_active(ctx.effect)) {
schedule_effect_tick(K_NO_WAIT);
}
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_led_strip_en_event(aeh)) {
return handle_led_strip_en_event(cast_led_strip_en_event(aeh));
}
if (is_theme_rgb_update_event(aeh)) {
return handle_theme_rgb_update_event(cast_theme_rgb_update_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)) {
(void)module_set_lifecycle(&ctx.lc, LC_RUNNING);
}
return false;
}
if (is_power_down_event(aeh)) {
if (module_lifecycle_is_initialized(&ctx.lc)) {
(void)module_set_lifecycle(&ctx.lc, LC_STOPPED);
}
return false;
}
if (is_wake_up_event(aeh)) {
if (module_lifecycle_is_initialized(&ctx.lc)) {
(void)module_set_lifecycle(&ctx.lc, LC_RUNNING);
}
return false;
}
return false;
}
APP_EVENT_LISTENER(MODULE, app_event_handler);
APP_EVENT_SUBSCRIBE_EARLY(MODULE, button_event);
APP_EVENT_SUBSCRIBE(MODULE, led_strip_en_event);
APP_EVENT_SUBSCRIBE(MODULE, module_state_event);
APP_EVENT_SUBSCRIBE(MODULE, theme_rgb_update_event);
APP_EVENT_SUBSCRIBE_EARLY(MODULE, power_down_event);
APP_EVENT_SUBSCRIBE(MODULE, wake_up_event);

202
src/mode_policy_module.c Normal file
View File

@@ -0,0 +1,202 @@
#include <stdbool.h>
#include <app_event_manager.h>
#define MODULE mode_policy_module
#include <caf/events/module_state_event.h>
#include <caf/events/module_suspend_event.h>
#include <zephyr/logging/log.h>
#include "module_lifecycle.h"
#include "mode_switch_event.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
struct mode_policy_module_ctx {
struct module_lifecycle_ctx lc;
enum mode_switch_mode active_mode;
};
static int do_init(void);
static int do_start(void);
static int do_stop(void);
static const struct module_lifecycle_cfg lifecycle_cfg = {
.mode = ML_MODE_NONE,
.stopped_state = MODULE_STATE_OFF,
};
static const struct module_lifecycle_ops lifecycle_ops = {
.do_init = do_init,
.do_start = do_start,
.do_stop = do_stop,
};
static struct mode_policy_module_ctx ctx = {
.lc = {
.state = LC_UNINIT,
.cfg = &lifecycle_cfg,
.ops = &lifecycle_ops,
},
.active_mode = MODE_SWITCH_USB,
};
static void mode_policy_set_ble(bool enable)
{
if (enable) {
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);
} else {
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);
}
}
static void mode_policy_set_usb(bool enable)
{
if (enable) {
struct module_resume_req_event *event = new_module_resume_req_event();
event->sink_module_id = MODULE_ID(usb_device_module);
event->src_module_id = MODULE_ID(MODULE);
APP_EVENT_SUBMIT(event);
} else {
struct module_suspend_req_event *event = new_module_suspend_req_event();
event->sink_module_id = MODULE_ID(usb_device_module);
event->src_module_id = MODULE_ID(MODULE);
APP_EVENT_SUBMIT(event);
}
}
static void apply_active_mode(void)
{
switch (ctx.active_mode) {
case MODE_SWITCH_BLE:
mode_policy_set_ble(true);
mode_policy_set_usb(false);
break;
case MODE_SWITCH_USB:
mode_policy_set_ble(false);
mode_policy_set_usb(true);
break;
case MODE_SWITCH_24G:
mode_policy_set_ble(false);
mode_policy_set_usb(false);
break;
default:
break;
}
}
static void apply_ble_mode_policy(void)
{
switch (ctx.active_mode) {
case MODE_SWITCH_BLE:
mode_policy_set_ble(true);
break;
case MODE_SWITCH_USB:
mode_policy_set_ble(false);
break;
case MODE_SWITCH_24G:
mode_policy_set_ble(false);
break;
default:
break;
}
}
static void apply_usb_mode_policy(void)
{
switch (ctx.active_mode) {
case MODE_SWITCH_BLE:
mode_policy_set_usb(false);
break;
case MODE_SWITCH_USB:
mode_policy_set_usb(true);
break;
case MODE_SWITCH_24G:
mode_policy_set_usb(false);
break;
default:
break;
}
}
static int do_init(void)
{
ctx.active_mode = MODE_SWITCH_USB;
return 0;
}
static int do_start(void)
{
apply_active_mode();
return 0;
}
static int do_stop(void)
{
return 0;
}
static bool app_event_handler(const struct app_event_header *aeh)
{
if (is_mode_switch_event(aeh)) {
const struct mode_switch_event *event = cast_mode_switch_event(aeh);
if (module_lifecycle_is_running(&ctx.lc)) {
ctx.active_mode = event->mode;
apply_active_mode();
}
return false;
}
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)) {
(void)module_set_lifecycle(&ctx.lc, LC_RUNNING);
return false;
}
if (check_state(event, MODULE_ID(ble_adv), MODULE_STATE_READY)) {
if (module_lifecycle_is_running(&ctx.lc)) {
apply_ble_mode_policy();
}
return false;
}
if (check_state(event, MODULE_ID(usb_device_module),
MODULE_STATE_READY)) {
if (module_lifecycle_is_running(&ctx.lc)) {
apply_usb_mode_policy();
}
}
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);

View File

@@ -14,6 +14,7 @@
#include <zephyr/logging/log.h>
#include <zephyr/pm/device.h>
#include "module_lifecycle.h"
#include "mode_switch_event.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
@@ -26,15 +27,36 @@ LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
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);
struct mode_switch_module_ctx {
struct module_lifecycle_ctx lc;
const struct device *mode_switch_adc_dev;
struct k_work_delayable mode_switch_sample_work;
enum mode_switch_mode last_mode;
};
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 int do_init(void);
static int do_start(void);
static int do_stop(void);
static const struct module_lifecycle_cfg lifecycle_cfg = {
.mode = ML_MODE_POWER,
.stopped_state = MODULE_STATE_STANDBY,
};
static const struct module_lifecycle_ops lifecycle_ops = {
.do_init = do_init,
.do_start = do_start,
.do_stop = do_stop,
};
static struct mode_switch_module_ctx ctx = {
.lc = {
.state = LC_UNINIT,
.cfg = &lifecycle_cfg,
.ops = &lifecycle_ops,
},
.mode_switch_adc_dev = DEVICE_DT_GET(MODE_SWITCH_ADC_NODE),
};
static enum mode_switch_mode detect_mode(uint16_t voltage_mv)
{
@@ -53,7 +75,7 @@ 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);
int err = pm_device_action_run(ctx.mode_switch_adc_dev, action);
if (err && (err != -EALREADY) && (err != -ENOTSUP)) {
LOG_ERR("Cannot %s mode switch ADC (%d)",
@@ -71,17 +93,18 @@ static void mode_switch_sample_fn(struct k_work *work)
ARG_UNUSED(work);
if (!running) {
if (!module_lifecycle_is_running(&ctx.lc)) {
return;
}
err = sensor_sample_fetch(mode_switch_adc_dev);
err = sensor_sample_fetch(ctx.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);
err = sensor_channel_get(ctx.mode_switch_adc_dev, SENSOR_CHAN_VOLTAGE,
&voltage);
if (err) {
LOG_WRN("Mode switch ADC channel get failed (%d)", err);
goto reschedule;
@@ -90,43 +113,37 @@ static void mode_switch_sample_fn(struct k_work *work)
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();
if ((ctx.last_mode == MODE_SWITCH_INVALID) || (mode != ctx.last_mode)) {
submit_mode_switch_event(mode, sample_mv);
event->mode = mode;
event->voltage_mv = sample_mv;
APP_EVENT_SUBMIT(event);
last_mode = mode;
mode_valid = true;
force_report = false;
ctx.last_mode = mode;
}
reschedule:
if (running) {
k_work_reschedule(&mode_switch_sample_work, MODE_SWITCH_SAMPLE_INTERVAL);
if (module_lifecycle_is_running(&ctx.lc)) {
k_work_reschedule(&ctx.mode_switch_sample_work,
MODE_SWITCH_SAMPLE_INTERVAL);
}
}
static int module_init(void)
static int do_init(void)
{
if (!device_is_ready(mode_switch_adc_dev)) {
if (!device_is_ready(ctx.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;
k_work_init_delayable(&ctx.mode_switch_sample_work, mode_switch_sample_fn);
ctx.last_mode = MODE_SWITCH_INVALID;
return 0;
}
static int module_start(void)
static int do_start(void)
{
int err;
if (running) {
if (module_lifecycle_is_running(&ctx.lc)) {
return 0;
}
@@ -135,22 +152,21 @@ static int module_start(void)
return err;
}
running = true;
force_report = true;
k_work_reschedule(&mode_switch_sample_work, K_NO_WAIT);
k_work_reschedule(&ctx.mode_switch_sample_work, K_NO_WAIT);
return 0;
}
static void module_pause(void)
static int do_stop(void)
{
if (!running) {
return;
if (!module_lifecycle_is_running(&ctx.lc)) {
return 0;
}
(void)k_work_cancel_delayable(&mode_switch_sample_work);
(void)k_work_cancel_delayable(&ctx.mode_switch_sample_work);
(void)mode_switch_enable(false);
running = false;
return 0;
}
static bool app_event_handler(const struct app_event_header *aeh)
@@ -159,46 +175,35 @@ static bool app_event_handler(const struct app_event_header *aeh)
const struct module_state_event *event = cast_module_state_event(aeh);
if (check_state(event, MODULE_ID(main), MODULE_STATE_READY)) {
int err;
(void)module_set_lifecycle(&ctx.lc, LC_RUNNING);
return false;
}
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);
if (check_state(event, MODULE_ID(mode_policy_module),
MODULE_STATE_READY)) {
if (ctx.last_mode != MODE_SWITCH_INVALID) {
submit_mode_switch_event(ctx.last_mode, 0U);
}
return false;
}
return false;
}
if (is_power_down_event(aeh)) {
if (initialized) {
module_pause();
module_set_state(MODULE_STATE_STANDBY);
if (module_lifecycle_is_initialized(&ctx.lc)) {
(void)module_set_lifecycle(&ctx.lc, LC_STOPPED);
}
return false;
}
if (is_wake_up_event(aeh)) {
if (initialized) {
int err = module_start();
if (module_lifecycle_is_initialized(&ctx.lc)) {
(void)module_set_lifecycle(&ctx.lc, LC_RUNNING);
if (err) {
module_set_state(MODULE_STATE_ERROR);
} else {
module_set_state(MODULE_STATE_READY);
if (ctx.last_mode != MODE_SWITCH_INVALID) {
submit_mode_switch_event(ctx.last_mode, 0U);
}
}

View File

@@ -2,34 +2,101 @@
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <app_event_manager.h>
#define MODULE protocol_module
#include <caf/events/module_state_event.h>
#include <zephyr/logging/log.h>
#include <zephyr/sys/util.h>
#include <pb_decode.h>
#include <pb_encode.h>
#include <proto/device_comm.pb.h>
#include "function_bitmap_state_event.h"
#include "function_bitmap_update_event.h"
#include "hid_led_event.h"
#include "module_lifecycle.h"
#include "proto_rx_event.h"
#include "proto_transport_state_event.h"
#include "proto_tx_event.h"
#include "protocol_module.h"
#include "theme_rgb_update_event.h"
#include "time_sync_event.h"
LOG_MODULE_REGISTER(protocol_module, LOG_LEVEL_INF);
LOG_MODULE_REGISTER(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
#define PROTOCOL_CAPABILITY_FLAGS (BIT(0) | BIT(1) | BIT(2) | BIT(3) | BIT(4))
#define PROTOCOL_MAX_MSG_LEN 128U
static bool type_matches_body(uint8_t type, const CdcPacketBody *body)
enum proto_session_state {
PROTO_SESSION_DOWN = 0,
PROTO_SESSION_WAIT_HELLO,
PROTO_SESSION_ACTIVE,
};
struct protocol_module_ctx {
struct module_lifecycle_ctx lc;
enum proto_session_state session_state[PROTO_TRANSPORT_COUNT];
};
static int do_init(void);
static int do_start(void);
static int do_stop(void);
static const struct module_lifecycle_cfg lifecycle_cfg = {
.mode = ML_MODE_NONE,
.stopped_state = MODULE_STATE_OFF,
};
static const struct module_lifecycle_ops lifecycle_ops = {
.do_init = do_init,
.do_start = do_start,
.do_stop = do_stop,
};
static struct protocol_module_ctx ctx = {
.lc = {
.state = LC_UNINIT,
.cfg = &lifecycle_cfg,
.ops = &lifecycle_ops,
},
};
#define session_state ctx.session_state
static const char *proto_session_name(enum proto_session_state state)
{
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;
switch (state) {
case PROTO_SESSION_DOWN:
return "DOWN";
case PROTO_SESSION_WAIT_HELLO:
return "WAIT_HELLO";
case PROTO_SESSION_ACTIVE:
return "ACTIVE";
default:
return false;
return "?";
}
}
static const char *proto_transport_name(enum proto_transport transport)
{
switch (transport) {
case PROTO_TRANSPORT_USB_CDC:
return "usb_cdc";
case PROTO_TRANSPORT_BLE_NUS:
return "ble_nus";
default:
return "?";
}
}
@@ -53,15 +120,29 @@ static int decode_body(const uint8_t *payload, size_t payload_len,
return 0;
}
static int encode_body(const CdcPacketBody *body, uint8_t *payload,
size_t payload_buf_size, size_t *payload_len)
{
pb_ostream_t stream;
if ((body == NULL) || (payload == NULL) || (payload_len == NULL)) {
return -EINVAL;
}
stream = pb_ostream_from_buffer(payload, payload_buf_size);
if (!pb_encode(&stream, CdcPacketBody_fields, body)) {
LOG_WRN("pb_encode failed: %s", PB_GET_ERROR(&stream));
return -EIO;
}
*payload_len = stream.bytes_written;
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;
@@ -71,63 +152,385 @@ static int encode_hello_rsp(uint8_t *rsp_payload, size_t rsp_payload_buf_size,
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);
return encode_body(&body, rsp_payload, rsp_payload_buf_size, rsp_payload_len);
}
if (!pb_encode(&stream, CdcPacketBody_fields, &body)) {
LOG_WRN("pb_encode failed: %s", PB_GET_ERROR(&stream));
return -EIO;
static int encode_ack(uint8_t acked_type, uint8_t *rsp_payload,
size_t rsp_payload_buf_size, size_t *rsp_payload_len)
{
CdcPacketBody body = CdcPacketBody_init_zero;
body.which_body = CdcPacketBody_ack_tag;
body.body.ack.acked_type = acked_type;
return encode_body(&body, rsp_payload, rsp_payload_buf_size, rsp_payload_len);
}
static int encode_error(uint8_t error_type, ErrorCode error_code,
uint8_t *rsp_payload, size_t rsp_payload_buf_size,
size_t *rsp_payload_len)
{
CdcPacketBody body = CdcPacketBody_init_zero;
body.which_body = CdcPacketBody_error_tag;
body.body.error.error_type = error_type;
body.body.error.error_code = error_code;
return encode_body(&body, rsp_payload, rsp_payload_buf_size, rsp_payload_len);
}
static int encode_led_state(uint32_t led_mask, uint8_t *payload,
size_t payload_buf_size, size_t *payload_len)
{
CdcPacketBody body = CdcPacketBody_init_zero;
body.which_body = CdcPacketBody_led_state_tag;
body.body.led_state.led_mask = led_mask;
return encode_body(&body, payload, payload_buf_size, payload_len);
}
static int encode_function_bitmap_state(const uint8_t *bitmap, uint8_t *payload,
size_t payload_buf_size,
size_t *payload_len)
{
CdcPacketBody body = CdcPacketBody_init_zero;
if (bitmap == NULL) {
return -EINVAL;
}
body.which_body = CdcPacketBody_function_key_event_tag;
body.body.function_key_event.usage_bitmap.size = KEYBOARD_PROTOCOL_BITMAP_BYTES;
memcpy(body.body.function_key_event.usage_bitmap.bytes, bitmap,
KEYBOARD_PROTOCOL_BITMAP_BYTES);
return encode_body(&body, payload, payload_buf_size, payload_len);
}
static int do_init(void)
{
for (size_t i = 0; i < ARRAY_SIZE(session_state); i++) {
session_state[i] = PROTO_SESSION_DOWN;
}
*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)
static int do_start(void)
{
if (module_lifecycle_is_running(&ctx.lc)) {
return 0;
}
return 0;
}
static int do_stop(void)
{
if (!module_lifecycle_is_running(&ctx.lc)) {
return 0;
}
for (size_t i = 0; i < ARRAY_SIZE(session_state); i++) {
session_state[i] = PROTO_SESSION_DOWN;
}
return 0;
}
int protocol_module_process_message(enum proto_transport transport,
const uint8_t *req_payload,
size_t req_payload_len,
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)) {
if ((transport >= PROTO_TRANSPORT_COUNT) ||
(rsp_payload == NULL) || (rsp_payload_len == NULL)) {
return -EINVAL;
}
if (!module_lifecycle_is_running(&ctx.lc)) {
LOG_WRN("Reject proto msg transport:%s len:%u lc:%s",
proto_transport_name(transport), (uint32_t)req_payload_len,
module_lifecycle_name(ctx.lc.state));
return -EAGAIN;
}
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 (body.which_body) {
case CdcPacketBody_hello_req_tag:
if (session_state[transport] == PROTO_SESSION_DOWN) {
LOG_WRN("Reject HelloReq transport:%s session:%s lc:%s",
proto_transport_name(transport),
proto_session_name(session_state[transport]),
module_lifecycle_name(ctx.lc.state));
return -EAGAIN;
}
switch (req_type) {
case CDC_PROTO_TYPE_HELLO_REQ:
LOG_INF("HelloReq protocol_version:%u",
body.body.hello_req.protocol_version);
LOG_INF("HelloReq transport:%u protocol_version:%u",
transport, 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;
session_state[transport] = PROTO_SESSION_ACTIVE;
return encode_hello_rsp(rsp_payload, rsp_payload_buf_size, rsp_payload_len);
case CdcPacketBody_bitmap_tag:
if (session_state[transport] != PROTO_SESSION_ACTIVE) {
return encode_error(CdcPacketBody_bitmap_tag,
ErrorCode_ERROR_CODE_NOT_READY,
rsp_payload, rsp_payload_buf_size,
rsp_payload_len);
}
*rsp_type = CDC_PROTO_TYPE_HELLO_RSP;
return 0;
if (body.body.bitmap.usage_bitmap.size != KEYBOARD_PROTOCOL_BITMAP_BYTES) {
return encode_error(CdcPacketBody_bitmap_tag,
ErrorCode_ERROR_CODE_INVALID_LENGTH,
rsp_payload, rsp_payload_buf_size,
rsp_payload_len);
}
err = submit_function_bitmap_update_event(
body.body.bitmap.usage_bitmap.bytes);
if (err) {
return encode_error(CdcPacketBody_bitmap_tag,
ErrorCode_ERROR_CODE_INVALID_PARAM,
rsp_payload, rsp_payload_buf_size,
rsp_payload_len);
}
return encode_ack(CdcPacketBody_bitmap_tag, rsp_payload,
rsp_payload_buf_size, rsp_payload_len);
case CdcPacketBody_time_sync_tag:
if (session_state[transport] != PROTO_SESSION_ACTIVE) {
return encode_error(CdcPacketBody_time_sync_tag,
ErrorCode_ERROR_CODE_NOT_READY,
rsp_payload, rsp_payload_buf_size,
rsp_payload_len);
}
if (body.body.time_sync.version != 1U) {
return encode_error(CdcPacketBody_time_sync_tag,
ErrorCode_ERROR_CODE_INVALID_PARAM,
rsp_payload, rsp_payload_buf_size,
rsp_payload_len);
}
submit_time_sync_event(body.body.time_sync.version,
body.body.time_sync.flags,
body.body.time_sync.timezone_min,
body.body.time_sync.utc_ms,
body.body.time_sync.accuracy_ms);
return encode_ack(CdcPacketBody_time_sync_tag, rsp_payload,
rsp_payload_buf_size, rsp_payload_len);
case CdcPacketBody_theme_rgb_tag:
if (session_state[transport] != PROTO_SESSION_ACTIVE) {
return encode_error(CdcPacketBody_theme_rgb_tag,
ErrorCode_ERROR_CODE_NOT_READY,
rsp_payload, rsp_payload_buf_size,
rsp_payload_len);
}
if ((body.body.theme_rgb.red > 255U) ||
(body.body.theme_rgb.green > 255U) ||
(body.body.theme_rgb.blue > 255U)) {
return encode_error(CdcPacketBody_theme_rgb_tag,
ErrorCode_ERROR_CODE_INVALID_PARAM,
rsp_payload, rsp_payload_buf_size,
rsp_payload_len);
}
submit_theme_rgb_update_event((struct theme_rgb) {
.r = (uint8_t)body.body.theme_rgb.red,
.g = (uint8_t)body.body.theme_rgb.green,
.b = (uint8_t)body.body.theme_rgb.blue,
});
return encode_ack(CdcPacketBody_theme_rgb_tag, rsp_payload,
rsp_payload_buf_size, rsp_payload_len);
default:
LOG_WRN("Unsupported CDC protocol type:0x%02x", req_type);
LOG_WRN("Unsupported protobuf body case %d", body.which_body);
return -ENOTSUP;
}
}
static bool handle_proto_rx_event(const struct proto_rx_event *event)
{
uint8_t rsp_payload[PROTOCOL_MAX_MSG_LEN];
size_t rsp_payload_len = 0U;
int err;
if (!module_lifecycle_is_running(&ctx.lc)) {
return false;
}
err = protocol_module_process_message(event->transport,
event->dyndata.data,
event->dyndata.size,
rsp_payload,
sizeof(rsp_payload),
&rsp_payload_len);
if (err) {
if (err != -ENOTSUP) {
LOG_WRN("Protocol processing failed (%d) transport:%s session:%s lc:%s len:%u",
err, proto_transport_name(event->transport),
proto_session_name(session_state[event->transport]),
module_lifecycle_name(ctx.lc.state),
(uint32_t)event->dyndata.size);
}
return false;
}
err = submit_proto_tx_event(event->transport, rsp_payload, rsp_payload_len);
if (err) {
LOG_WRN("Proto TX submit failed (%d)", err);
}
return false;
}
static bool handle_proto_transport_state_event(
const struct proto_transport_state_event *event)
{
if (event->transport >= PROTO_TRANSPORT_COUNT) {
return false;
}
switch (event->state) {
case PROTO_TRANSPORT_LINK_DOWN:
session_state[event->transport] = PROTO_SESSION_DOWN;
break;
case PROTO_TRANSPORT_LINK_READY:
session_state[event->transport] = PROTO_SESSION_WAIT_HELLO;
break;
default:
return false;
}
return false;
}
static bool handle_function_bitmap_state_event(
const struct function_bitmap_state_event *event)
{
uint8_t payload[PROTOCOL_MAX_MSG_LEN];
size_t payload_len;
int err;
if (!module_lifecycle_is_running(&ctx.lc)) {
return false;
}
for (enum proto_transport transport = 0; transport < PROTO_TRANSPORT_COUNT;
transport++) {
if (session_state[transport] != PROTO_SESSION_ACTIVE) {
continue;
}
err = encode_function_bitmap_state(event->bitmap, payload,
sizeof(payload), &payload_len);
if (err) {
LOG_WRN("FunctionKeyEvent encode failed (%d)", err);
return false;
}
err = submit_proto_tx_event(transport, payload, payload_len);
if (err) {
LOG_WRN("FunctionKeyEvent submit failed (%d)", err);
}
}
return false;
}
static bool handle_hid_led_event(const struct hid_led_event *event)
{
uint8_t payload[PROTOCOL_MAX_MSG_LEN];
size_t payload_len;
int err;
enum proto_transport transport;
if (!module_lifecycle_is_running(&ctx.lc)) {
return false;
}
transport = (event->transport == HID_TRANSPORT_USB) ?
PROTO_TRANSPORT_USB_CDC :
PROTO_TRANSPORT_BLE_NUS;
if (session_state[transport] != PROTO_SESSION_ACTIVE) {
return false;
}
err = encode_led_state(event->led_bm, payload, sizeof(payload), &payload_len);
if (err) {
LOG_WRN("LedState encode failed (%d)", err);
return false;
}
err = submit_proto_tx_event(transport, payload, payload_len);
if (err) {
LOG_WRN("LedState submit failed (%d)", err);
}
return false;
}
static bool app_event_handler(const struct app_event_header *aeh)
{
if (is_proto_rx_event(aeh)) {
return handle_proto_rx_event(cast_proto_rx_event(aeh));
}
if (is_proto_transport_state_event(aeh)) {
return handle_proto_transport_state_event(
cast_proto_transport_state_event(aeh));
}
if (is_function_bitmap_state_event(aeh)) {
return handle_function_bitmap_state_event(
cast_function_bitmap_state_event(aeh));
}
if (is_hid_led_event(aeh)) {
return handle_hid_led_event(cast_hid_led_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)) {
(void)module_set_lifecycle(&ctx.lc, LC_RUNNING);
return false;
}
return false;
}
return false;
}
APP_EVENT_LISTENER(MODULE, app_event_handler);
APP_EVENT_SUBSCRIBE(MODULE, function_bitmap_state_event);
APP_EVENT_SUBSCRIBE(MODULE, hid_led_event);
APP_EVENT_SUBSCRIBE(MODULE, module_state_event);
APP_EVENT_SUBSCRIBE(MODULE, proto_rx_event);
APP_EVENT_SUBSCRIBE(MODULE, proto_transport_state_event);

191
src/time_sync_module.c Normal file
View File

@@ -0,0 +1,191 @@
#include <stdbool.h>
#include <string.h>
#include <time.h>
#include <app_event_manager.h>
#define MODULE time_sync_module
#include <caf/events/module_state_event.h>
#include <caf/events/power_event.h>
#include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
#include <zephyr/sys/printk.h>
#include "datetime_event.h"
#include "module_lifecycle.h"
#include "time_sync_event.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
#define TIME_SYNC_REFRESH_PERIOD K_SECONDS(1)
struct time_sync_module_ctx {
struct module_lifecycle_ctx lc;
struct k_work_delayable refresh_work;
int32_t timezone_min;
uint64_t utc_ms_base;
int64_t uptime_ms_base;
};
static int do_init(void);
static int do_start(void);
static int do_stop(void);
static const struct module_lifecycle_cfg lifecycle_cfg = {
.mode = ML_MODE_POWER,
.stopped_state = MODULE_STATE_STANDBY,
};
static const struct module_lifecycle_ops lifecycle_ops = {
.do_init = do_init,
.do_start = do_start,
.do_stop = do_stop,
};
static struct time_sync_module_ctx ctx = {
.lc = {
.state = LC_UNINIT,
.cfg = &lifecycle_cfg,
.ops = &lifecycle_ops,
},
};
static void publish_datetime_event(void)
{
struct tm tm_buf;
time_t seconds;
int64_t local_ms;
char date_text[DATETIME_EVENT_DATE_TEXT_LEN];
char time_text[DATETIME_EVENT_TIME_TEXT_LEN];
local_ms = (int64_t)ctx.utc_ms_base +
(k_uptime_get() - ctx.uptime_ms_base) +
((int64_t)ctx.timezone_min * 60LL * 1000LL);
if (local_ms < 0) {
local_ms = 0;
}
seconds = (time_t)(local_ms / 1000LL);
if (gmtime_r(&seconds, &tm_buf) == NULL) {
strncpy(date_text, "1970/01/01", sizeof(date_text));
date_text[sizeof(date_text) - 1] = '\0';
strncpy(time_text, "00:00:00", sizeof(time_text));
time_text[sizeof(time_text) - 1] = '\0';
} else {
snprintk(date_text, sizeof(date_text),
"%04u/%02u/%02u",
(unsigned int)(tm_buf.tm_year + 1900),
(unsigned int)(tm_buf.tm_mon + 1),
(unsigned int)tm_buf.tm_mday);
snprintk(time_text, sizeof(time_text),
"%02u:%02u:%02u",
(unsigned int)tm_buf.tm_hour,
(unsigned int)tm_buf.tm_min,
(unsigned int)tm_buf.tm_sec);
}
(void)submit_datetime_event(date_text, time_text);
}
static void refresh_work_handler(struct k_work *work)
{
ARG_UNUSED(work);
if (!module_lifecycle_is_running(&ctx.lc)) {
return;
}
publish_datetime_event();
k_work_reschedule(&ctx.refresh_work, TIME_SYNC_REFRESH_PERIOD);
}
static int do_init(void)
{
ctx.timezone_min = 0;
ctx.utc_ms_base = 0U;
ctx.uptime_ms_base = k_uptime_get();
k_work_init_delayable(&ctx.refresh_work, refresh_work_handler);
return 0;
}
static int do_start(void)
{
if (module_lifecycle_is_running(&ctx.lc)) {
return 0;
}
k_work_reschedule(&ctx.refresh_work, K_NO_WAIT);
return 0;
}
static int do_stop(void)
{
if (!module_lifecycle_is_running(&ctx.lc)) {
return 0;
}
k_work_cancel_delayable(&ctx.refresh_work);
return 0;
}
static bool handle_time_sync_event(const struct time_sync_event *event)
{
if (event->version != 1U) {
LOG_WRN("Unexpected TimeSync version:%u", event->version);
return false;
}
ctx.timezone_min = event->timezone_min;
ctx.utc_ms_base = event->utc_ms;
ctx.uptime_ms_base = k_uptime_get();
if (module_lifecycle_is_running(&ctx.lc)) {
k_work_reschedule(&ctx.refresh_work, K_NO_WAIT);
}
return false;
}
static bool app_event_handler(const struct app_event_header *aeh)
{
if (is_time_sync_event(aeh)) {
return handle_time_sync_event(cast_time_sync_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)) {
(void)module_set_lifecycle(&ctx.lc, LC_RUNNING);
}
return false;
}
if (is_power_down_event(aeh)) {
if (module_lifecycle_is_initialized(&ctx.lc)) {
(void)module_set_lifecycle(&ctx.lc, LC_STOPPED);
}
return false;
}
if (is_wake_up_event(aeh)) {
if (module_lifecycle_is_initialized(&ctx.lc)) {
(void)module_set_lifecycle(&ctx.lc, LC_RUNNING);
}
return false;
}
return false;
}
APP_EVENT_LISTENER(MODULE, app_event_handler);
APP_EVENT_SUBSCRIBE(MODULE, module_state_event);
APP_EVENT_SUBSCRIBE(MODULE, time_sync_event);
APP_EVENT_SUBSCRIBE_EARLY(MODULE, power_down_event);
APP_EVENT_SUBSCRIBE(MODULE, wake_up_event);

View File

@@ -207,8 +207,6 @@ void ui_main_init(const struct ui_main_model *model,
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);

View File

@@ -16,78 +16,182 @@
#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"
#include "module_lifecycle.h"
#include "proto_rx_event.h"
#include "proto_transport_state_event.h"
#include "proto_tx_event.h"
#include "usb_control_event.h"
#include "usb_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_PROTO_RX_BUF_SIZE 128
#define USB_CDC_PROTO_RX_FLUSH_DELAY K_MSEC(3)
#define USB_CDC_EXPECTED_BAUDRATE 115200U
static const struct device *const cdc_dev = DEVICE_DT_GET_ONE(zephyr_cdc_acm_uart);
enum usb_cdc_business_state {
USB_CDC_BUS_OFFLINE = 0,
USB_CDC_WAIT_DTR,
USB_CDC_SESSION_READY,
};
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;
struct usb_cdc_ctx {
struct module_lifecycle_ctx lc;
enum usb_cdc_business_state business;
const struct device *cdc_dev;
uint8_t rx_ring_buffer[USB_CDC_RX_RING_BUF_SIZE];
uint8_t tx_ring_buffer[USB_CDC_TX_RING_BUF_SIZE];
struct ring_buf rx_ringbuf;
struct ring_buf tx_ringbuf;
struct k_work rx_work;
struct k_work_delayable rx_flush_work;
uint8_t proto_rx_buf[USB_CDC_PROTO_RX_BUF_SIZE];
bool usb_active;
size_t proto_rx_len;
};
static int do_init(void);
static int do_start(void);
static int do_stop(void);
static void submit_usb_cdc_rx_event(const uint8_t *data, size_t len)
static const struct module_lifecycle_cfg lifecycle_cfg = {
.mode = ML_MODE_POWER,
.stopped_state = MODULE_STATE_STANDBY,
};
static const struct module_lifecycle_ops lifecycle_ops = {
.do_init = do_init,
.do_start = do_start,
.do_stop = do_stop,
};
static struct usb_cdc_ctx ctx = {
.lc = {
.state = LC_UNINIT,
.cfg = &lifecycle_cfg,
.ops = &lifecycle_ops,
},
.business = USB_CDC_BUS_OFFLINE,
.cdc_dev = DEVICE_DT_GET_ONE(zephyr_cdc_acm_uart),
.usb_active = false,
.proto_rx_len = 0U,
};
#define proto_rx_buf ctx.proto_rx_buf
static void validate_line_coding(void);
static bool lifecycle_is_ready(void)
{
struct usb_cdc_rx_event *event = new_usb_cdc_rx_event(len);
memcpy(event->dyndata.data, data, len);
APP_EVENT_SUBMIT(event);
return module_lifecycle_is_running(&ctx.lc);
}
static void submit_usb_function_ready_event(void)
static enum proto_transport_link_state transport_link_state_get(void)
{
struct usb_function_ready_event *event = new_usb_function_ready_event();
event->function_mask = USB_FUNCTION_CDC_ACM;
APP_EVENT_SUBMIT(event);
return (lifecycle_is_ready() &&
(ctx.business == USB_CDC_SESSION_READY)) ?
PROTO_TRANSPORT_LINK_READY :
PROTO_TRANSPORT_LINK_DOWN;
}
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);
ring_buf_init(&ctx.rx_ringbuf, sizeof(ctx.rx_ring_buffer), ctx.rx_ring_buffer);
ring_buf_init(&ctx.tx_ringbuf, sizeof(ctx.tx_ring_buffer), ctx.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;
uart_irq_rx_disable(ctx.cdc_dev);
uart_irq_tx_disable(ctx.cdc_dev);
ctx.proto_rx_len = 0U;
k_work_cancel_delayable(&ctx.rx_flush_work);
reset_ring_buffers();
}
static void state_reconcile(enum module_lifecycle old_lifecycle,
enum usb_cdc_business_state old_business)
{
enum proto_transport_link_state old_link =
((old_lifecycle == LC_RUNNING) &&
(old_business == USB_CDC_SESSION_READY)) ?
PROTO_TRANSPORT_LINK_READY :
PROTO_TRANSPORT_LINK_DOWN;
enum proto_transport_link_state new_link = transport_link_state_get();
if ((old_lifecycle == LC_RUNNING) &&
(old_business == USB_CDC_SESSION_READY) &&
(new_link == PROTO_TRANSPORT_LINK_DOWN)) {
disable_uart_io();
}
if ((old_link == PROTO_TRANSPORT_LINK_DOWN) &&
(new_link == PROTO_TRANSPORT_LINK_READY)) {
int err;
validate_line_coding();
err = uart_line_ctrl_set(ctx.cdc_dev, UART_LINE_CTRL_DCD, 1);
if (err) {
LOG_WRN("Failed to set DCD (%d)", err);
}
err = uart_line_ctrl_set(ctx.cdc_dev, UART_LINE_CTRL_DSR, 1);
if (err) {
LOG_WRN("Failed to set DSR (%d)", err);
}
uart_irq_rx_enable(ctx.cdc_dev);
}
if (old_link != new_link) {
submit_proto_transport_state_event(PROTO_TRANSPORT_USB_CDC,
new_link);
}
}
static void business_state_set(enum usb_cdc_business_state new_state)
{
enum module_lifecycle old_lifecycle = ctx.lc.state;
enum usb_cdc_business_state old_business = ctx.business;
if (ctx.business == new_state) {
return;
}
ctx.business = new_state;
state_reconcile(old_lifecycle, old_business);
}
static void business_state_sync_from_usb(void)
{
if (!ctx.usb_active) {
business_state_set(USB_CDC_BUS_OFFLINE);
return;
}
if (!lifecycle_is_ready()) {
return;
}
if (ctx.business == USB_CDC_BUS_OFFLINE) {
business_state_set(USB_CDC_WAIT_DTR);
}
}
static void kick_tx(void)
{
if (!running || !usb_active || !dtr_ready) {
if (transport_link_state_get() != PROTO_TRANSPORT_LINK_READY) {
return;
}
uart_irq_tx_enable(cdc_dev);
uart_irq_tx_enable(ctx.cdc_dev);
}
static void validate_line_coding(void)
@@ -95,7 +199,7 @@ 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);
err = uart_line_ctrl_get(ctx.cdc_dev, UART_LINE_CTRL_BAUD_RATE, &baudrate);
if (err) {
LOG_WRN("Failed to get CDC baudrate (%d)", err);
} else {
@@ -110,7 +214,7 @@ static void validate_line_coding(void)
{
struct uart_config cfg;
err = uart_config_get(cdc_dev, &cfg);
err = uart_config_get(ctx.cdc_dev, &cfg);
if (err) {
LOG_WRN("uart_config_get failed (%d)", err);
} else {
@@ -138,62 +242,39 @@ static void rx_work_handler(struct k_work *work)
uint32_t len;
unsigned int key = irq_lock();
len = ring_buf_get(&rx_ringbuf, buffer, sizeof(buffer));
len = ring_buf_get(&ctx.rx_ringbuf, buffer, sizeof(buffer));
irq_unlock(key);
if (len == 0U) {
return;
}
submit_usb_cdc_rx_event(buffer, len);
if ((ctx.proto_rx_len + len) > sizeof(proto_rx_buf)) {
LOG_WRN("Drop oversized CDC protobuf message len:%u",
(uint32_t)(ctx.proto_rx_len + len));
ctx.proto_rx_len = 0U;
}
if (len > 0U) {
memcpy(&proto_rx_buf[ctx.proto_rx_len], buffer, len);
ctx.proto_rx_len += len;
k_work_reschedule(&ctx.rx_flush_work, USB_CDC_PROTO_RX_FLUSH_DELAY);
}
}
}
static void control_work_handler(struct k_work *work)
static void rx_flush_work_handler(struct k_work *work)
{
uint32_t dtr = 0U;
int err;
ARG_UNUSED(work);
if (!running || !usb_active) {
if ((transport_link_state_get() != PROTO_TRANSPORT_LINK_READY) ||
(ctx.proto_rx_len == 0U)) {
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);
(void)submit_proto_rx_event(PROTO_TRANSPORT_USB_CDC, proto_rx_buf,
ctx.proto_rx_len);
ctx.proto_rx_len = 0U;
}
static void cdc_interrupt_handler(const struct device *dev, void *user_data)
@@ -214,15 +295,16 @@ static void cdc_interrupt_handler(const struct device *dev, void *user_data)
uint32_t written;
unsigned int key = irq_lock();
written = ring_buf_put(&rx_ringbuf, buffer,
written = ring_buf_put(&ctx.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);
LOG_WRN("Drop %d CDC RX bytes",
recv_len - (int)written);
}
k_work_submit(&rx_work);
k_work_submit(&ctx.rx_work);
}
}
@@ -232,7 +314,7 @@ static void cdc_interrupt_handler(const struct device *dev, void *user_data)
int sent_len;
unsigned int key = irq_lock();
len = ring_buf_get(&tx_ringbuf, buffer, sizeof(buffer));
len = ring_buf_get(&ctx.tx_ringbuf, buffer, sizeof(buffer));
irq_unlock(key);
if (len == 0U) {
@@ -252,90 +334,136 @@ static void cdc_interrupt_handler(const struct device *dev, void *user_data)
}
}
static int module_init(void)
static int do_init(void)
{
if (!device_is_ready(cdc_dev)) {
if (!device_is_ready(ctx.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;
k_work_init(&ctx.rx_work, rx_work_handler);
k_work_init_delayable(&ctx.rx_flush_work, rx_flush_work_handler);
uart_irq_callback_set(ctx.cdc_dev, cdc_interrupt_handler);
ctx.business = USB_CDC_BUS_OFFLINE;
ctx.usb_active = false;
ctx.proto_rx_len = 0U;
return 0;
}
static int module_start(void)
static int do_start(void)
{
if (running) {
return 0;
return 0;
}
static int do_stop(void)
{
ctx.business = USB_CDC_BUS_OFFLINE;
return 0;
}
static int apply_lifecycle(enum module_lifecycle target)
{
enum module_lifecycle old_lifecycle = ctx.lc.state;
enum usb_cdc_business_state old_business = ctx.business;
int err = module_set_lifecycle(&ctx.lc, target);
if (err) {
return err;
}
running = true;
if (usb_active) {
k_work_reschedule(&control_work, K_NO_WAIT);
state_reconcile(old_lifecycle, old_business);
if (target == LC_RUNNING) {
business_state_sync_from_usb();
}
return 0;
}
static void module_pause(void)
static bool handle_usb_state_event(const struct usb_state_event *event)
{
if (!running) {
return;
}
bool new_usb_active = (event->state == USB_STATE_ACTIVE);
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) {
if (new_usb_active == ctx.usb_active) {
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);
}
ctx.usb_active = new_usb_active;
business_state_sync_from_usb();
return false;
}
static bool handle_usb_cdc_tx_event(const struct usb_cdc_tx_event *event)
static bool handle_usb_control_event(const struct usb_control_event *event)
{
if (event->dev != ctx.cdc_dev) {
return false;
}
switch (event->type) {
case USB_CONTROL_EVENT_CDC_LINE_STATE:
if (!ctx.usb_active || !lifecycle_is_ready()) {
return false;
}
if (event->data.cdc_line_state.dtr) {
LOG_INF("CDC DTR set");
business_state_set(USB_CDC_SESSION_READY);
kick_tx();
} else {
LOG_INF("CDC DTR cleared");
business_state_set(USB_CDC_WAIT_DTR);
}
return false;
case USB_CONTROL_EVENT_CDC_LINE_CODING:
if (event->data.cdc_line_coding.baudrate != 0U) {
LOG_INF("CDC baudrate %u",
event->data.cdc_line_coding.baudrate);
if (event->data.cdc_line_coding.baudrate !=
USB_CDC_EXPECTED_BAUDRATE) {
LOG_WRN("Expected CDC baudrate %u, got %u",
USB_CDC_EXPECTED_BAUDRATE,
event->data.cdc_line_coding.baudrate);
}
}
#ifdef CONFIG_UART_USE_RUNTIME_CONFIGURE
if ((event->data.cdc_line_coding.data_bits != 0U) ||
(event->data.cdc_line_coding.stop_bits != 0U) ||
(event->data.cdc_line_coding.parity != 0U) ||
(event->data.cdc_line_coding.flow_ctrl != 0U)) {
LOG_INF("CDC line coding data:%u stop:%u parity:%u flow:%u",
event->data.cdc_line_coding.data_bits,
event->data.cdc_line_coding.stop_bits,
event->data.cdc_line_coding.parity,
event->data.cdc_line_coding.flow_ctrl);
}
#endif
return false;
default:
return false;
}
}
static bool handle_proto_tx_event(const struct proto_tx_event *event)
{
uint32_t written;
unsigned int key;
if (!running || !usb_active || !dtr_ready) {
if (event->transport != PROTO_TRANSPORT_USB_CDC) {
return false;
}
if (transport_link_state_get() != PROTO_TRANSPORT_LINK_READY) {
return false;
}
key = irq_lock();
written = ring_buf_put(&tx_ringbuf, event->dyndata.data,
written = ring_buf_put(&ctx.tx_ringbuf, event->dyndata.data,
(uint32_t)event->dyndata.size);
irq_unlock(key);
@@ -352,63 +480,40 @@ static bool handle_usb_cdc_tx_event(const struct usb_cdc_tx_event *event)
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_state_event(aeh)) {
return handle_usb_state_event(cast_usb_state_event(aeh));
}
if (is_usb_prepare_event(aeh)) {
return handle_usb_prepare_event(cast_usb_prepare_event(aeh));
if (is_proto_tx_event(aeh)) {
return handle_proto_tx_event(cast_proto_tx_event(aeh));
}
if (is_usb_cdc_tx_event(aeh)) {
return handle_usb_cdc_tx_event(cast_usb_cdc_tx_event(aeh));
if (is_usb_control_event(aeh)) {
return handle_usb_control_event(cast_usb_control_event(aeh));
}
if (is_module_state_event(aeh)) {
const struct module_state_event *event = cast_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);
}
(void)apply_lifecycle(LC_RUNNING);
}
return false;
}
if (is_power_down_event(aeh)) {
if (initialized) {
module_pause();
module_set_state(MODULE_STATE_STANDBY);
if (module_lifecycle_is_initialized(&ctx.lc)) {
(void)apply_lifecycle(LC_STOPPED);
}
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);
}
if (module_lifecycle_is_initialized(&ctx.lc)) {
(void)apply_lifecycle(LC_RUNNING);
}
return false;
@@ -419,8 +524,8 @@ static bool app_event_handler(const struct app_event_header *aeh)
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(MODULE, proto_tx_event);
APP_EVENT_SUBSCRIBE(MODULE, usb_control_event);
APP_EVENT_SUBSCRIBE(MODULE, usb_state_event);
APP_EVENT_SUBSCRIBE_EARLY(MODULE, power_down_event);
APP_EVENT_SUBSCRIBE(MODULE, wake_up_event);

View File

@@ -1,164 +0,0 @@
#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);

View File

@@ -6,17 +6,19 @@
#define MODULE usb_device_module
#include <caf/events/module_state_event.h>
#include <caf/events/module_suspend_event.h>
#include <caf/events/power_event.h>
#include <zephyr/drivers/uart.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"
#include "module_lifecycle.h"
#include "usb_function_hook.h"
#include "usb_control_event.h"
#include "usb_state_event.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
@@ -24,7 +26,6 @@ LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
#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);
@@ -40,37 +41,85 @@ 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;
enum usb_stack_state {
USB_STACK_UNINITIALIZED = 0,
USB_STACK_READY,
USB_STACK_ENABLED,
};
static void submit_usb_device_state_event(enum usb_device_state state)
enum usb_bus_state {
USB_BUS_DISCONNECTED = 0,
USB_BUS_POWERED,
USB_BUS_ACTIVE,
USB_BUS_SUSPENDED,
};
struct usb_owner_ctx {
struct module_lifecycle_ctx lc;
enum usb_stack_state stack;
enum usb_bus_state bus;
};
static int do_init(void);
static int do_start(void);
static int do_stop(void);
/* Project exception: mode policy suspend/resume controls USB availability,
* while global power events still map to standby lifecycle transitions.
*/
static const struct module_lifecycle_cfg lifecycle_cfg = {
.mode = ML_MODE_SUSPEND,
.stopped_state = MODULE_STATE_STANDBY,
};
static const struct module_lifecycle_ops lifecycle_ops = {
.do_init = do_init,
.do_start = do_start,
.do_stop = do_stop,
};
static struct usb_owner_ctx usb_ctx = {
.lc = {
.state = LC_UNINIT,
.cfg = &lifecycle_cfg,
.ops = &lifecycle_ops,
},
.stack = USB_STACK_UNINITIALIZED,
.bus = USB_BUS_DISCONNECTED,
};
static inline enum usb_state usb_public_state_get(void)
{
struct usb_device_state_event *event = new_usb_device_state_event();
if (!module_lifecycle_is_running(&usb_ctx.lc) ||
(usb_ctx.stack == USB_STACK_UNINITIALIZED)) {
return USB_STATE_DISABLED;
}
event->state = state;
APP_EVENT_SUBMIT(event);
switch (usb_ctx.bus) {
case USB_BUS_DISCONNECTED:
return USB_STATE_DISCONNECTED;
case USB_BUS_POWERED:
return USB_STATE_POWERED;
case USB_BUS_ACTIVE:
return USB_STATE_ACTIVE;
case USB_BUS_SUSPENDED:
return USB_STATE_SUSPENDED;
default:
return USB_STATE_DISABLED;
}
}
static void submit_usb_prepare_event(void)
static inline void usb_bus_set(enum usb_bus_state state)
{
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) {
if (usb_ctx.bus == state) {
return;
}
device_state = state;
submit_usb_device_state_event(state);
usb_ctx.bus = state;
if (module_lifecycle_is_initialized(&usb_ctx.lc)) {
submit_usb_state(usb_public_state_get());
}
}
static void update_power_manager_restriction(bool vbus_present)
@@ -119,52 +168,104 @@ static void usbd_msg_cb(struct usbd_context *const usbd_ctx,
{
ARG_UNUSED(usbd_ctx);
if (msg->type == USBD_MSG_CDC_ACM_CONTROL_LINE_STATE) {
uint32_t dtr = 0U;
int err = uart_line_ctrl_get(msg->dev, UART_LINE_CTRL_DTR, &dtr);
if (err) {
LOG_WRN("Failed to get CDC DTR (%d)", err);
} else {
submit_usb_control_cdc_line_state_event(msg->dev, dtr != 0U);
}
return;
}
if (msg->type == USBD_MSG_CDC_ACM_LINE_CODING) {
uint32_t baudrate = 0U;
uint8_t data_bits = 0U;
uint8_t stop_bits = 0U;
uint8_t parity = 0U;
uint8_t flow_ctrl = 0U;
int err;
err = uart_line_ctrl_get(msg->dev, UART_LINE_CTRL_BAUD_RATE, &baudrate);
if (err) {
LOG_WRN("Failed to get CDC baudrate (%d)", err);
}
#ifdef CONFIG_UART_USE_RUNTIME_CONFIGURE
{
struct uart_config cfg;
err = uart_config_get(msg->dev, &cfg);
if (err) {
LOG_WRN("uart_config_get failed (%d)", err);
} else {
data_bits = (uint8_t)cfg.data_bits;
stop_bits = (uint8_t)cfg.stop_bits;
parity = (uint8_t)cfg.parity;
flow_ctrl = (uint8_t)cfg.flow_ctrl;
}
}
#endif
submit_usb_control_cdc_line_coding_event(msg->dev, baudrate,
data_bits, stop_bits,
parity, flow_ctrl);
return;
}
switch (msg->type) {
case USBD_MSG_VBUS_READY:
update_power_manager_restriction(true);
if (!usb_enabled) {
int err = usbd_enable(&blinky_usbd);
usb_bus_set(USB_BUS_POWERED);
if (module_lifecycle_is_running(&usb_ctx.lc) &&
(usb_ctx.stack == USB_STACK_READY)) {
int err = do_start();
if (err) {
LOG_ERR("usbd_enable failed (%d)", err);
} else {
usb_enabled = true;
update_usb_device_state(USB_DEVICE_STATE_POWERED);
LOG_ERR("USB start on VBUS ready failed (%d)", err);
}
}
break;
case USBD_MSG_VBUS_REMOVED:
update_power_manager_restriction(false);
if (usb_enabled) {
int err = usbd_disable(&blinky_usbd);
if (usb_ctx.stack == USB_STACK_ENABLED) {
int err = do_stop();
if (err) {
LOG_ERR("usbd_disable failed (%d)", err);
LOG_ERR("USB stop on VBUS removed failed (%d)", err);
}
} else {
update_power_manager_restriction(false);
}
usb_enabled = false;
update_usb_device_state(USB_DEVICE_STATE_DISCONNECTED);
if (usb_ctx.stack != USB_STACK_UNINITIALIZED) {
usb_ctx.stack = USB_STACK_READY;
}
usb_bus_set(USB_BUS_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);
usb_bus_set(USB_BUS_ACTIVE);
} else if (usb_ctx.stack == USB_STACK_ENABLED) {
usb_bus_set(USB_BUS_POWERED);
}
break;
case USBD_MSG_SUSPEND:
if (usb_enabled) {
update_usb_device_state(USB_DEVICE_STATE_SUSPENDED);
if (usb_ctx.stack == USB_STACK_ENABLED) {
usb_bus_set(USB_BUS_SUSPENDED);
}
break;
case USBD_MSG_RESUME:
if (usb_enabled) {
update_usb_device_state(USB_DEVICE_STATE_ACTIVE);
if (usb_ctx.stack == USB_STACK_ENABLED) {
usb_bus_set(USB_BUS_ACTIVE);
}
break;
@@ -173,10 +274,26 @@ static void usbd_msg_cb(struct usbd_context *const usbd_ctx,
}
}
static int usb_stack_init(void)
static int do_init(void)
{
int err;
usb_ctx.stack = USB_STACK_UNINITIALIZED;
usb_ctx.bus = USB_BUS_DISCONNECTED;
update_power_manager_restriction(false);
STRUCT_SECTION_FOREACH(usb_function_hook, hook) {
if (hook->pre_stack_init == NULL) {
continue;
}
err = hook->pre_stack_init();
if (err) {
LOG_ERR("USB function hook %s failed (%d)", hook->name, err);
return err;
}
}
err = usbd_msg_register_cb(&blinky_usbd, usbd_msg_cb);
if (err) {
LOG_ERR("usbd_msg_register_cb failed (%d)", err);
@@ -195,7 +312,18 @@ static int usb_stack_init(void)
return err;
}
usbd_initialized = true;
usb_ctx.stack = USB_STACK_READY;
return 0;
}
static int do_start(void)
{
int err;
if (usb_ctx.stack == USB_STACK_ENABLED) {
return 0;
}
if (!usbd_can_detect_vbus(&blinky_usbd)) {
err = usbd_enable(&blinky_usbd);
@@ -204,105 +332,84 @@ static int usb_stack_init(void)
return err;
}
usb_enabled = true;
update_usb_device_state(USB_DEVICE_STATE_POWERED);
usb_ctx.stack = USB_STACK_ENABLED;
usb_ctx.bus = USB_BUS_POWERED;
update_power_manager_restriction(true);
return 0;
}
if (usb_ctx.bus == USB_BUS_DISCONNECTED) {
return 0;
}
err = usbd_enable(&blinky_usbd);
if (err) {
LOG_ERR("usbd_enable failed (%d)", err);
return err;
}
usb_ctx.stack = USB_STACK_ENABLED;
update_power_manager_restriction(true);
return 0;
}
static int module_init(void)
static int do_stop(void)
{
device_state = USB_DEVICE_STATE_DISCONNECTED;
usb_enabled = false;
ready_function_mask = 0U;
prepare_broadcasted = false;
usbd_initialized = false;
int err;
if (usb_ctx.stack == USB_STACK_ENABLED) {
err = usbd_disable(&blinky_usbd);
if (err) {
LOG_ERR("usbd_disable failed (%d)", err);
return err;
}
}
usb_ctx.stack = USB_STACK_READY;
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);
}
if (module_set_lifecycle(&usb_ctx.lc, LC_RUNNING) == 0) {
submit_usb_state(usb_public_state_get());
}
return false;
}
static bool handle_usb_function_ready_event(const struct usb_function_ready_event *event)
static bool handle_module_suspend_req_event(
const struct module_suspend_req_event *event)
{
int err;
if (!running || !prepare_broadcasted || usbd_initialized) {
if ((event->sink_module_id != MODULE_ID(MODULE)) ||
(usb_ctx.lc.state != LC_RUNNING)) {
return false;
}
ready_function_mask |= event->function_mask;
if (module_set_lifecycle(&usb_ctx.lc, LC_STOPPED) == 0) {
submit_usb_state(usb_public_state_get());
}
if ((ready_function_mask & USB_REQUIRED_FUNCTION_MASK) !=
USB_REQUIRED_FUNCTION_MASK) {
return false;
}
static bool handle_module_resume_req_event(
const struct module_resume_req_event *event)
{
if ((event->sink_module_id != MODULE_ID(MODULE)) ||
(usb_ctx.lc.state != LC_STOPPED)) {
return false;
}
err = usb_stack_init();
if (err) {
module_set_state(MODULE_STATE_ERROR);
return false;
if (module_set_lifecycle(&usb_ctx.lc, LC_RUNNING) == 0) {
submit_usb_state(usb_public_state_get());
}
module_set_state(MODULE_STATE_READY);
return false;
}
@@ -312,27 +419,30 @@ static bool app_event_handler(const struct app_event_header *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_module_suspend_req_event(aeh)) {
return handle_module_suspend_req_event(
cast_module_suspend_req_event(aeh));
}
if (is_module_resume_req_event(aeh)) {
return handle_module_resume_req_event(
cast_module_resume_req_event(aeh));
}
if (is_power_down_event(aeh)) {
if (initialized) {
module_pause();
module_set_state(MODULE_STATE_STANDBY);
if (module_lifecycle_is_initialized(&usb_ctx.lc)) {
if (module_set_lifecycle(&usb_ctx.lc, LC_STOPPED) == 0) {
submit_usb_state(usb_public_state_get());
}
}
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);
if (module_lifecycle_is_initialized(&usb_ctx.lc)) {
if (module_set_lifecycle(&usb_ctx.lc, LC_RUNNING) == 0) {
submit_usb_state(usb_public_state_get());
}
}
@@ -344,6 +454,7 @@ static bool app_event_handler(const struct app_event_header *aeh)
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(MODULE, module_suspend_req_event);
APP_EVENT_SUBSCRIBE(MODULE, module_resume_req_event);
APP_EVENT_SUBSCRIBE_EARLY(MODULE, power_down_event);
APP_EVENT_SUBSCRIBE(MODULE, wake_up_event);

1
src/usb_function_hook.ld Normal file
View File

@@ -0,0 +1 @@
ITERABLE_SECTION_ROM(usb_function_hook, Z_LINK_ITERABLE_SUBALIGN)

View File

@@ -0,0 +1,315 @@
#include <errno.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <app_event_manager.h>
#define MODULE usb_hid_consumer_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/usb/class/usbd_hid.h>
#include "hid_channel_state_event.h"
#include "hid_report_sent_event.h"
#include "hid_tx_report_event.h"
#include "keyboard_core.h"
#include "module_lifecycle.h"
#include "usb_function_hook.h"
#include "usb_state_event.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
static const uint8_t consumer_report_desc[] = {
0x05, 0x0C, 0x09, 0x01, 0xA1, 0x01, 0x15, 0x00,
0x26, 0xFF, 0x03, 0x19, 0x00, 0x2A, 0xFF, 0x03,
0x75, 0x10, 0x95, 0x01, 0x81, 0x00, 0xC0
};
struct usb_hid_consumer_module_ctx {
struct module_lifecycle_ctx lc;
const struct device *hid_dev;
bool usb_active;
bool iface_ready;
bool report_in_flight;
uint16_t in_flight_sequence;
};
static int do_init(void);
static int do_start(void);
static int do_stop(void);
static const struct module_lifecycle_cfg lifecycle_cfg = {
.mode = ML_MODE_POWER,
.stopped_state = MODULE_STATE_STANDBY,
};
static const struct module_lifecycle_ops lifecycle_ops = {
.do_init = do_init,
.do_start = do_start,
.do_stop = do_stop,
};
static struct usb_hid_consumer_module_ctx ctx = {
.lc = {
.state = LC_UNINIT,
.cfg = &lifecycle_cfg,
.ops = &lifecycle_ops,
},
.hid_dev = DEVICE_DT_GET(DT_NODELABEL(hid_consumer)),
};
UDC_STATIC_BUF_DEFINE(consumer_tx_buf, KEYBOARD_CONSUMER_REPORT_SIZE);
static void publish_consumer_state(void)
{
bool ready = module_lifecycle_is_running(&ctx.lc) &&
ctx.usb_active && ctx.iface_ready;
submit_hid_channel_state_event(HID_SEND_CH_USB_CONSUMER,
ready ? BIT(KEYBOARD_REPORT_TYPE_CONSUMER) : 0U,
KEYBOARD_PROTOCOL_MODE_REPORT);
}
static void consumer_iface_ready(const struct device *dev, const bool ready)
{
ARG_UNUSED(dev);
ctx.iface_ready = ready;
if (!ready) {
ctx.report_in_flight = false;
}
LOG_INF("%s interface %s", ctx.hid_dev->name,
ready ? "ready" : "not ready");
publish_consumer_state();
}
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(dev);
ARG_UNUSED(report);
ctx.report_in_flight = false;
submit_hid_report_sent_event(HID_SEND_CH_USB_CONSUMER,
KEYBOARD_REPORT_TYPE_CONSUMER,
ctx.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_consumer_register_device(void)
{
if (!device_is_ready(ctx.hid_dev)) {
LOG_ERR("HID device %s not ready", ctx.hid_dev->name);
return -ENODEV;
}
return hid_device_register(ctx.hid_dev, consumer_report_desc,
sizeof(consumer_report_desc), &consumer_ops);
}
USB_FUNCTION_HOOK_DEFINE(usb_hid_consumer_hook, usb_hid_consumer_register_device);
static int do_init(void)
{
ctx.usb_active = false;
ctx.iface_ready = false;
ctx.report_in_flight = false;
return 0;
}
static int do_start(void)
{
if (module_lifecycle_is_running(&ctx.lc)) {
return 0;
}
publish_consumer_state();
return 0;
}
static int do_stop(void)
{
if (!module_lifecycle_is_running(&ctx.lc)) {
return 0;
}
ctx.report_in_flight = false;
publish_consumer_state();
return 0;
}
static bool handle_usb_state_event(const struct usb_state_event *event)
{
bool new_usb_active = (event->state == USB_STATE_ACTIVE);
if (new_usb_active == ctx.usb_active) {
return false;
}
ctx.usb_active = new_usb_active;
if (!ctx.usb_active) {
ctx.iface_ready = false;
ctx.report_in_flight = false;
}
publish_consumer_state();
return false;
}
static bool handle_hid_tx_report_event(const struct hid_tx_report_event *event)
{
int err;
if (!module_lifecycle_is_running(&ctx.lc) || !ctx.usb_active ||
(event->channel != HID_SEND_CH_USB_CONSUMER)) {
return false;
}
if (event->report_type != KEYBOARD_REPORT_TYPE_CONSUMER) {
return false;
}
if (!ctx.iface_ready) {
return false;
}
if (ctx.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(ctx.hid_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(HID_SEND_CH_USB_CONSUMER,
KEYBOARD_REPORT_TYPE_CONSUMER,
event->sequence, true);
} else {
ctx.report_in_flight = true;
ctx.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_state_event(aeh)) {
return handle_usb_state_event(cast_usb_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)) {
(void)module_set_lifecycle(&ctx.lc, LC_RUNNING);
}
return false;
}
if (is_power_down_event(aeh)) {
if (module_lifecycle_is_initialized(&ctx.lc)) {
(void)module_set_lifecycle(&ctx.lc, LC_STOPPED);
}
return false;
}
if (is_wake_up_event(aeh)) {
if (module_lifecycle_is_initialized(&ctx.lc)) {
(void)module_set_lifecycle(&ctx.lc, LC_RUNNING);
}
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_state_event);
APP_EVENT_SUBSCRIBE_EARLY(MODULE, power_down_event);
APP_EVENT_SUBSCRIBE(MODULE, wake_up_event);

View File

@@ -0,0 +1,388 @@
#include <errno.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <app_event_manager.h>
#define MODULE usb_hid_keyboard_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/usb/class/usbd_hid.h>
#include "hid_channel_state_event.h"
#include "hid_led_event.h"
#include "hid_report_sent_event.h"
#include "hid_tx_report_event.h"
#include "keyboard_core.h"
#include "module_lifecycle.h"
#include "set_protocol_event.h"
#include "usb_function_hook.h"
#include "usb_state_event.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
#define KBD_LED_REPORT_SIZE 1U
#define KBD_LED_REPORT_WITH_ID_SIZE (KBD_LED_REPORT_SIZE + 1U)
static const uint8_t keyboard_report_desc[] = {
0x05, 0x01, 0x09, 0x06, 0xA1, 0x01, 0x05, 0x07,
0x19, 0xE0, 0x29, 0xE7, 0x15, 0x00, 0x25, 0x01,
0x75, 0x01, 0x95, 0x08, 0x81, 0x02, 0x05, 0x07,
0x19, 0x00, 0x2A, 0xDF, 0x00, 0x15, 0x00, 0x25,
0x01, 0x75, 0x01, 0x96, 0xE0, 0x00, 0x81, 0x02,
0x05, 0x08, 0x19, 0x01, 0x29, 0x05, 0x15, 0x00,
0x25, 0x01, 0x75, 0x01, 0x95, 0x05, 0x91, 0x02,
0x75, 0x03, 0x95, 0x01, 0x91, 0x01, 0xC0
};
struct usb_hid_keyboard_module_ctx {
struct module_lifecycle_ctx lc;
const struct device *hid_dev;
enum keyboard_protocol_mode keyboard_protocol_mode;
bool usb_active;
bool iface_ready;
bool report_in_flight;
uint16_t in_flight_sequence;
};
static int do_init(void);
static int do_start(void);
static int do_stop(void);
static const struct module_lifecycle_cfg lifecycle_cfg = {
.mode = ML_MODE_POWER,
.stopped_state = MODULE_STATE_STANDBY,
};
static const struct module_lifecycle_ops lifecycle_ops = {
.do_init = do_init,
.do_start = do_start,
.do_stop = do_stop,
};
static struct usb_hid_keyboard_module_ctx ctx = {
.lc = {
.state = LC_UNINIT,
.cfg = &lifecycle_cfg,
.ops = &lifecycle_ops,
},
.hid_dev = DEVICE_DT_GET(DT_NODELABEL(hid_kbd)),
.keyboard_protocol_mode = KEYBOARD_PROTOCOL_MODE_REPORT,
};
UDC_STATIC_BUF_DEFINE(keyboard_tx_buf, KEYBOARD_NKRO_REPORT_SIZE);
static void publish_keyboard_state(void)
{
bool ready = module_lifecycle_is_running(&ctx.lc) &&
ctx.usb_active && ctx.iface_ready;
submit_hid_channel_state_event(HID_SEND_CH_USB_KEYS,
ready ? BIT(KEYBOARD_REPORT_TYPE_KEYS) : 0U,
ctx.keyboard_protocol_mode);
}
static void keyboard_iface_ready(const struct device *dev, const bool ready)
{
ARG_UNUSED(dev);
ctx.iface_ready = ready;
if (!ready) {
ctx.report_in_flight = false;
}
LOG_INF("%s interface %s", ctx.hid_dev->name,
ready ? "ready" : "not ready");
publish_keyboard_state();
}
static int keyboard_handle_led_report(const char *source, uint8_t type, uint8_t id,
uint16_t len, const uint8_t *buf)
{
uint8_t led_bm;
if (buf == NULL) {
LOG_WRN("%s invalid keyboard report", source);
return -EINVAL;
}
if (len == KBD_LED_REPORT_SIZE) {
led_bm = buf[0];
} else if (len == KBD_LED_REPORT_WITH_ID_SIZE) {
led_bm = buf[1];
} else {
LOG_WRN("%s unexpected len %u type %u id %u",
source, len, type, id);
if (len >= KBD_LED_REPORT_WITH_ID_SIZE) {
LOG_WRN("%s possible report_id=0x%02x led_bm=0x%02x",
source, buf[0], buf[1]);
}
return -EMSGSIZE;
}
submit_hid_led_event(HID_TRANSPORT_USB, led_bm);
return 0;
}
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);
if (type != HID_REPORT_TYPE_OUTPUT) {
LOG_WRN("USB keyboard set_report unsupported type %u id %u len %u",
type, id, len);
if (buf != NULL) {
LOG_HEXDUMP_INF(buf, len, "USB keyboard set_report raw");
}
return -ENOTSUP;
}
return keyboard_handle_led_report("USB keyboard set_report", type, id,
len, buf);
}
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 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 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 (ctx.keyboard_protocol_mode == new_mode) {
return;
}
ctx.keyboard_protocol_mode = new_mode;
LOG_INF("USB keyboard protocol -> %s",
(new_mode == KEYBOARD_PROTOCOL_MODE_BOOT) ? "boot" : "report");
submit_set_protocol_event(HID_TRANSPORT_USB, new_mode);
publish_keyboard_state();
}
static void keyboard_input_report_done(const struct device *dev,
const uint8_t *const report)
{
ARG_UNUSED(dev);
ARG_UNUSED(report);
ctx.report_in_flight = false;
submit_hid_report_sent_event(HID_SEND_CH_USB_KEYS,
KEYBOARD_REPORT_TYPE_KEYS,
ctx.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);
(void)keyboard_handle_led_report("USB keyboard output report",
HID_REPORT_TYPE_OUTPUT, 0U,
len, buf);
}
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 int usb_hid_keyboard_register_device(void)
{
if (!device_is_ready(ctx.hid_dev)) {
LOG_ERR("HID device %s not ready", ctx.hid_dev->name);
return -ENODEV;
}
return hid_device_register(ctx.hid_dev, keyboard_report_desc,
sizeof(keyboard_report_desc), &keyboard_ops);
}
USB_FUNCTION_HOOK_DEFINE(usb_hid_keyboard_hook, usb_hid_keyboard_register_device);
static int do_init(void)
{
ctx.keyboard_protocol_mode = KEYBOARD_PROTOCOL_MODE_REPORT;
ctx.usb_active = false;
ctx.iface_ready = false;
ctx.report_in_flight = false;
return 0;
}
static int do_start(void)
{
if (module_lifecycle_is_running(&ctx.lc)) {
return 0;
}
publish_keyboard_state();
return 0;
}
static int do_stop(void)
{
if (!module_lifecycle_is_running(&ctx.lc)) {
return 0;
}
ctx.report_in_flight = false;
publish_keyboard_state();
return 0;
}
static bool handle_usb_state_event(const struct usb_state_event *event)
{
bool new_usb_active = (event->state == USB_STATE_ACTIVE);
if (new_usb_active == ctx.usb_active) {
return false;
}
ctx.usb_active = new_usb_active;
if (!ctx.usb_active) {
ctx.iface_ready = false;
ctx.report_in_flight = false;
}
publish_keyboard_state();
return false;
}
static bool handle_hid_tx_report_event(const struct hid_tx_report_event *event)
{
int err;
if (!module_lifecycle_is_running(&ctx.lc) || !ctx.usb_active ||
(event->channel != HID_SEND_CH_USB_KEYS)) {
return false;
}
if (event->report_type != KEYBOARD_REPORT_TYPE_KEYS) {
return false;
}
if (event->protocol_mode != ctx.keyboard_protocol_mode) {
LOG_WRN("Drop USB keys report due to protocol mismatch");
return false;
}
if (!ctx.iface_ready) {
return false;
}
if (ctx.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(ctx.hid_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(HID_SEND_CH_USB_KEYS,
KEYBOARD_REPORT_TYPE_KEYS,
event->sequence, true);
} else {
ctx.report_in_flight = true;
ctx.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_state_event(aeh)) {
return handle_usb_state_event(cast_usb_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)) {
(void)module_set_lifecycle(&ctx.lc, LC_RUNNING);
}
return false;
}
if (is_power_down_event(aeh)) {
if (module_lifecycle_is_initialized(&ctx.lc)) {
(void)module_set_lifecycle(&ctx.lc, LC_STOPPED);
}
return false;
}
if (is_wake_up_event(aeh)) {
if (module_lifecycle_is_initialized(&ctx.lc)) {
(void)module_set_lifecycle(&ctx.lc, LC_RUNNING);
}
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_state_event);
APP_EVENT_SUBSCRIBE_EARLY(MODULE, power_down_event);
APP_EVENT_SUBSCRIBE(MODULE, wake_up_event);

View File

@@ -1,647 +0,0 @@
#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);