Compare commits

...

4 Commits

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

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

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

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

- 启用串口和UART中断驱动配置
- 添加USB CDC ACM类和HID支持
- 增加LVGL工作队列栈大小到16KB
- 添加蒙特赛拉特32号字体支持
2026-04-11 16:40:54 +08:00
26 changed files with 2261 additions and 163 deletions

View File

@@ -4,12 +4,19 @@ cmake_minimum_required(VERSION 3.20.0)
find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})
project(blinky)
list(APPEND CMAKE_MODULE_PATH ${ZEPHYR_BASE}/modules/nanopb)
include(nanopb)
zephyr_include_directories(
inc
inc/events
)
add_subdirectory(drivers)
zephyr_nanopb_sources(app
proto/device_comm.proto
)
target_sources(app PRIVATE
src/main.c
src/battery_module.c
@@ -22,6 +29,10 @@ target_sources(app PRIVATE
src/hid_flowctrl_module.c
src/keyboard_core_module.c
src/ui/ui_main.c
src/cdc_wrapper_module.c
src/protocol_module.c
src/usb_cdc_module.c
src/usb_device_module.c
src/usb_hid_module.c
src/events/bat_state_event.c
src/events/encoder_event.c
@@ -33,4 +44,9 @@ target_sources(app PRIVATE
src/events/keyboard_hid_report_event.c
src/events/mode_switch_event.c
src/events/set_protocol_event.c
src/events/usb_cdc_rx_event.c
src/events/usb_cdc_tx_event.c
src/events/usb_device_state_event.c
src/events/usb_function_ready_event.c
src/events/usb_prepare_event.c
)

View File

@@ -225,9 +225,14 @@
&usbd {
status = "okay";
num-bidir-endpoints = <0>;
num-in-endpoints = <2>;
num-out-endpoints = <1>;
num-bidir-endpoints = <1>;
num-in-endpoints = <7>;
num-out-endpoints = <7>;
num-isoin-endpoints = <0>;
num-isoout-endpoints = <0>;
cdc_acm_uart0: cdc_acm_uart0 {
compatible = "zephyr,cdc-acm-uart";
label = "CDC_ACM_0";
};
};

12
inc/cdc_wrapper_module.h Normal file
View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

26
inc/protocol_module.h Normal file
View File

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

26
inc/usb_device_module.h Normal file
View File

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

View File

@@ -30,7 +30,14 @@ CONFIG_ASSERT=y
# USB HID next stack
CONFIG_USB_DEVICE_STACK_NEXT=y
CONFIG_SERIAL=y
CONFIG_UART_INTERRUPT_DRIVEN=y
CONFIG_UART_LINE_CTRL=y
CONFIG_UART_USE_RUNTIME_CONFIGURE=y
CONFIG_NANOPB=y
CONFIG_USBD_HID_SUPPORT=y
CONFIG_USBD_CDC_ACM_CLASS=y
CONFIG_CDC_ACM_SERIAL_INITIALIZE_AT_BOOT=n
# BLE
CONFIG_BT=y
@@ -100,6 +107,7 @@ CONFIG_BT_ADV_PROV_DEVICE_NAME_SD=y
CONFIG_LVGL=y
CONFIG_LV_Z_AUTO_INIT=n
CONFIG_LV_Z_RUN_LVGL_ON_WORKQUEUE=y
CONFIG_LV_Z_LVGL_WORKQUEUE_STACK_SIZE=16384
CONFIG_LV_Z_LVGL_MUTEX=y
CONFIG_LV_COLOR_DEPTH_16=y
CONFIG_LV_COLOR_16_SWAP=y
@@ -109,4 +117,5 @@ CONFIG_LV_Z_DOUBLE_VDB=y
CONFIG_LV_Z_MEM_POOL_SIZE=16384
CONFIG_LV_USE_LABEL=y
CONFIG_LV_FONT_MONTSERRAT_14=y
CONFIG_LV_FONT_MONTSERRAT_32=y
CONFIG_MAIN_STACK_SIZE=4096

21
proto/device_comm.proto Normal file
View File

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

275
src/cdc_wrapper_module.c Normal file
View File

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

View File

@@ -13,6 +13,9 @@
#include <zephyr/drivers/led.h>
#include <zephyr/logging/log.h>
#include "bat_state_event.h"
#include "hid_led_event.h"
#include "mode_switch_event.h"
#include "ui/ui_main.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
@@ -26,6 +29,11 @@ static const struct device *const display_dev =
static const struct device *const backlight_dev =
DEVICE_DT_GET(DT_PARENT(DT_ALIAS(backlight)));
static const uint32_t backlight_idx = DT_NODE_CHILD_IDX(DT_ALIAS(backlight));
static struct ui_main_model ui_model = {
.theme_color = LV_COLOR_MAKE(0x4C, 0x9E, 0xF5),
.inactive_border_color = LV_COLOR_MAKE(0x3A, 0x44, 0x52),
.mode = MODE_SWITCH_BLE,
};
static bool initialized;
static bool running;
static bool lvgl_initialized;
@@ -82,7 +90,7 @@ static int module_start(void)
lvgl_initialized = true;
lvgl_lock();
ui_main_init();
ui_main_init(&ui_model, "WH Mini", "Hello World");
lvgl_unlock();
}
@@ -117,8 +125,45 @@ static void module_pause(void)
LOG_INF("LVGL display paused");
}
static void refresh_ui(void)
{
if (!lvgl_initialized) {
return;
}
lvgl_lock();
ui_main_refresh_all(&ui_model, "WH Mini", "Hello World");
lvgl_unlock();
}
static bool app_event_handler(const struct app_event_header *aeh)
{
if (is_bat_state_event(aeh)) {
const struct bat_state_event *event = cast_bat_state_event(aeh);
ui_model.battery_level = event->soc;
ui_model.charging = event->charging;
ui_model.full = event->full;
refresh_ui();
return false;
}
if (is_mode_switch_event(aeh)) {
const struct mode_switch_event *event = cast_mode_switch_event(aeh);
ui_model.mode = event->mode;
refresh_ui();
return false;
}
if (is_hid_led_event(aeh)) {
const struct hid_led_event *event = cast_hid_led_event(aeh);
ui_model.led_mask = event->led_bm;
refresh_ui();
return false;
}
if (is_module_state_event(aeh)) {
const struct module_state_event *event = cast_module_state_event(aeh);
int err;
@@ -172,6 +217,9 @@ 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, hid_led_event);
APP_EVENT_SUBSCRIBE(MODULE, module_state_event);
APP_EVENT_SUBSCRIBE(MODULE, mode_switch_event);
APP_EVENT_SUBSCRIBE_EARLY(MODULE, power_down_event);
APP_EVENT_SUBSCRIBE(MODULE, wake_up_event);

View File

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

View File

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

View File

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

View File

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

View File

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

133
src/protocol_module.c Normal file
View File

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

View File

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

View File

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

426
src/usb_cdc_module.c Normal file
View File

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

164
src/usb_cdc_test_module.c Normal file
View File

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

349
src/usb_device_module.c Normal file
View File

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

View File

@@ -12,10 +12,8 @@
#include <zephyr/device.h>
#include <zephyr/drivers/usb/udc_buf.h>
#include <zephyr/logging/log.h>
#include <zephyr/sys/byteorder.h>
#include <zephyr/sys/util.h>
#include <zephyr/usb/class/usbd_hid.h>
#include <zephyr/usb/usbd.h>
#include "hid_led_event.h"
#include "hid_report_sent_event.h"
@@ -23,15 +21,13 @@
#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 USB_HID_VID 0x1915
#define USB_HID_PID 0x52F0
#define USB_HID_MANUFACTURER "Atguigu"
#define USB_HID_PRODUCT "WH Mini Keyboard"
#define USB_HID_POLLING_US 1000U
#define KBD_LED_REPORT_SIZE 1U
enum usb_hid_interface {
@@ -106,7 +102,8 @@ static enum keyboard_protocol_mode keyboard_protocol_mode =
KEYBOARD_PROTOCOL_MODE_REPORT;
static bool initialized;
static bool running;
static bool usb_enabled;
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;
@@ -115,20 +112,6 @@ 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);
USBD_DEVICE_DEFINE(blinky_usbd, DEVICE_DT_GET(DT_NODELABEL(usbd)),
USB_HID_VID, USB_HID_PID);
USBD_DESC_LANG_DEFINE(blinky_lang);
USBD_DESC_MANUFACTURER_DEFINE(blinky_mfr, USB_HID_MANUFACTURER);
USBD_DESC_PRODUCT_DEFINE(blinky_product, USB_HID_PRODUCT);
USBD_DESC_CONFIG_DEFINE(blinky_fs_cfg_desc, "FS Configuration");
USBD_CONFIGURATION_DEFINE(blinky_fs_config, 0, 250, &blinky_fs_cfg_desc);
static const char *const class_blocklist[] = {
NULL,
};
static struct usb_hid_interface_state *iface_from_dev(const struct device *dev)
{
for (size_t i = 0; i < ARRAY_SIZE(hid_ifaces); i++) {
@@ -146,6 +129,17 @@ static enum keyboard_protocol_mode usb_proto_to_keyboard_proto(uint8_t proto)
: 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();
@@ -167,12 +161,13 @@ static void submit_hid_led_event(uint8_t led_bm)
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 = usb_enabled;
event->keys_ready = usb_enabled &&
event->ready = ready;
event->keys_ready = ready &&
hid_ifaces[USB_HID_INTERFACE_KEYBOARD].ready;
event->consumer_ready = usb_enabled &&
event->consumer_ready = ready &&
hid_ifaces[USB_HID_INTERFACE_CONSUMER].ready;
event->protocol_mode = keyboard_protocol_mode;
@@ -192,6 +187,14 @@ static void submit_hid_report_sent_event(enum keyboard_report_type report_type,
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);
@@ -204,8 +207,8 @@ static void keyboard_iface_ready(const struct device *dev, const bool ready)
if (!ready) {
keyboard_report_in_flight = false;
}
LOG_INF("%s interface %s",
dev->name, ready ? "ready" : "not ready");
LOG_INF("%s interface %s", dev->name, ready ? "ready" : "not ready");
submit_transport_state_event();
}
@@ -316,8 +319,8 @@ static void consumer_iface_ready(const struct device *dev, const bool ready)
if (!ready) {
consumer_report_in_flight = false;
}
LOG_INF("%s interface %s",
dev->name, ready ? "ready" : "not ready");
LOG_INF("%s interface %s", dev->name, ready ? "ready" : "not ready");
submit_transport_state_event();
}
@@ -400,81 +403,6 @@ static const struct hid_device_ops consumer_ops = {
.output_report = consumer_output_report,
};
static void usbd_msg_cb(struct usbd_context *const usbd_ctx,
const struct usbd_msg *const msg)
{
ARG_UNUSED(usbd_ctx);
if (msg->type == USBD_MSG_VBUS_READY) {
if (!usb_enabled) {
int err = usbd_enable(&blinky_usbd);
if (err) {
LOG_ERR("usbd_enable failed (%d)", err);
} else {
usb_enabled = true;
submit_transport_state_event();
}
}
return;
}
if (msg->type == USBD_MSG_VBUS_REMOVED) {
if (usb_enabled) {
int err = usbd_disable(&blinky_usbd);
if (err) {
LOG_ERR("usbd_disable failed (%d)", err);
} else {
usb_enabled = false;
for (size_t i = 0; i < ARRAY_SIZE(hid_ifaces); i++) {
hid_ifaces[i].ready = false;
}
keyboard_report_in_flight = false;
consumer_report_in_flight = false;
submit_transport_state_event();
}
}
return;
}
}
static int usb_descriptors_init(void)
{
int err;
err = usbd_add_descriptor(&blinky_usbd, &blinky_lang);
if (err) {
return err;
}
err = usbd_add_descriptor(&blinky_usbd, &blinky_mfr);
if (err) {
return err;
}
err = usbd_add_descriptor(&blinky_usbd, &blinky_product);
if (err) {
return err;
}
err = usbd_add_configuration(&blinky_usbd, USBD_SPEED_FS, &blinky_fs_config);
if (err) {
return err;
}
err = usbd_register_all_classes(&blinky_usbd, USBD_SPEED_FS, 1, class_blocklist);
if (err) {
return err;
}
usbd_device_set_code_triple(&blinky_usbd, USBD_SPEED_FS, 0, 0, 0);
return 0;
}
static int usb_hid_register_devices(void)
{
int err;
@@ -507,41 +435,9 @@ static int usb_hid_register_devices(void)
static int module_init(void)
{
int err;
err = usb_hid_register_devices();
if (err) {
LOG_ERR("hid_device_register failed (%d)", err);
return err;
}
err = usbd_msg_register_cb(&blinky_usbd, usbd_msg_cb);
if (err) {
LOG_ERR("usbd_msg_register_cb failed (%d)", err);
return err;
}
err = usb_descriptors_init();
if (err) {
LOG_ERR("usb descriptor init failed (%d)", err);
return err;
}
err = usbd_init(&blinky_usbd);
if (err) {
LOG_ERR("usbd_init failed (%d)", err);
return err;
}
if (!usbd_can_detect_vbus(&blinky_usbd)) {
err = usbd_enable(&blinky_usbd);
if (err) {
LOG_ERR("usbd_enable failed (%d)", err);
return err;
}
usb_enabled = true;
}
reset_usb_runtime_state();
keyboard_protocol_mode = KEYBOARD_PROTOCOL_MODE_REPORT;
usb_function_prepared = false;
return 0;
}
@@ -560,13 +456,54 @@ static int module_start(void)
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 || (event->transport != HID_TRANSPORT_USB)) {
if (!running || !usb_active || (event->transport != HID_TRANSPORT_USB)) {
return false;
}
@@ -640,6 +577,14 @@ static bool app_event_handler(const struct app_event_header *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);
@@ -690,12 +635,13 @@ static bool app_event_handler(const struct app_event_header *aeh)
return false;
}
__ASSERT_NO_MSG(false);
return false;
}
APP_EVENT_LISTENER(MODULE, app_event_handler);
APP_EVENT_SUBSCRIBE(MODULE, module_state_event);
APP_EVENT_SUBSCRIBE(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);