Compare commits

...

7 Commits

Author SHA1 Message Date
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
39 changed files with 2558 additions and 52 deletions

View File

@@ -10,6 +10,7 @@ include(nanopb)
zephyr_include_directories(
inc
inc/events
src
)
add_subdirectory(drivers)
@@ -24,10 +25,15 @@ target_sources(app PRIVATE
src/ble_adv_uuid16.c
src/ble_bas_module.c
src/ble_hid_module.c
src/ble_serial_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/time_sync_module.c
src/ui/ui_main.c
src/cdc_wrapper_module.c
src/protocol_module.c
@@ -35,15 +41,24 @@ target_sources(app PRIVATE
src/usb_device_module.c
src/usb_hid_module.c
src/events/bat_state_event.c
src/events/ble_serial_rx_event.c
src/events/ble_serial_tx_event.c
src/events/cdc_proto_tx_event.c
src/events/datetime_event.c
src/events/encoder_event.c
src/events/function_bitmap_update_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/events/key_function_event.c
src/mode_switch_module.c
src/events/keyboard_hid_report_event.c
src/events/mode_switch_event.c
src/events/set_protocol_event.c
src/events/theme_rgb_update_event.c
src/events/time_sync_event.c
src/events/usb_cdc_rx_event.c
src/events/usb_cdc_tx_event.c
src/events/usb_device_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;
};
@@ -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

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

View File

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

View File

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

View File

@@ -0,0 +1,26 @@
#ifndef BLINKY_DATETIME_EVENT_H_
#define BLINKY_DATETIME_EVENT_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);
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_DATETIME_EVENT_H_ */

View File

@@ -0,0 +1,24 @@
#ifndef BLINKY_FUNCTION_BITMAP_UPDATE_EVENT_H_
#define BLINKY_FUNCTION_BITMAP_UPDATE_EVENT_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);
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_FUNCTION_BITMAP_UPDATE_EVENT_H_ */

View File

@@ -0,0 +1,28 @@
#ifndef BLINKY_KEY_FUNCTION_EVENT_H_
#define BLINKY_KEY_FUNCTION_EVENT_H_
#include <app_event_manager.h>
#include <app_event_manager_profiler_tracer.h>
#ifdef __cplusplus
extern "C" {
#endif
enum key_function_action {
KEY_FUNCTION_ACTION_RELEASE = 0U,
KEY_FUNCTION_ACTION_PRESS = 1U,
};
struct key_function_event {
struct app_event_header header;
uint16_t usage;
uint8_t action;
};
APP_EVENT_TYPE_DECLARE(key_function_event);
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_KEY_FUNCTION_EVENT_H_ */

View File

@@ -0,0 +1,24 @@
#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);
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_LED_STRIP_EN_EVENT_H_ */

View File

@@ -0,0 +1,24 @@
#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);
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_THEME_RGB_UPDATE_EVENT_H_ */

View File

@@ -0,0 +1,26 @@
#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);
#ifdef __cplusplus
}
#endif
#endif /* BLINKY_TIME_SYNC_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)

View File

@@ -10,6 +10,13 @@ extern "C" {
#define CDC_PROTO_TYPE_HELLO_REQ 0x01U
#define CDC_PROTO_TYPE_HELLO_RSP 0x02U
#define CDC_PROTO_TYPE_BITMAP 0x10U
#define CDC_PROTO_TYPE_FUNCTION_KEY_EVENT 0x20U
#define CDC_PROTO_TYPE_LED_STATE 0x21U
#define CDC_PROTO_TYPE_TIME_SYNC 0x30U
#define CDC_PROTO_TYPE_THEME_RGB 0x31U
#define CDC_PROTO_TYPE_ACK 0x7EU
#define CDC_PROTO_TYPE_ERROR 0x7FU
int protocol_module_process_cdc_packet(uint8_t req_type,
const uint8_t *req_payload,

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

@@ -27,6 +27,9 @@ CONFIG_NVS=y
CONFIG_HEAP_MEM_POOL_SIZE=4096
CONFIG_LOG=y
CONFIG_ASSERT=y
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
@@ -48,6 +51,9 @@ 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_CONN_CTX=y
CONFIG_BT_DEVICE_NAME="WH Mini Keyboard"
CONFIG_BT_DEVICE_APPEARANCE=961

View File

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

View File

@@ -13,9 +13,65 @@ message HelloRsp {
uint32 capability_flags = 6;
}
message Bitmap {
bytes usage_bitmap = 1;
}
enum KeyAction {
KEY_ACTION_RELEASE = 0;
KEY_ACTION_PRESS = 1;
}
message FunctionKeyEvent {
uint32 usage = 1;
KeyAction action = 2;
}
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;
}
}

308
src/ble_serial_module.c Normal file
View File

@@ -0,0 +1,308 @@
#include <errno.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <app_event_manager.h>
#define MODULE ble_serial_module
#include <caf/events/module_state_event.h>
#include <caf/events/power_event.h>
#include <caf/events/ble_common_event.h>
#include <zephyr/bluetooth/att.h>
#include <zephyr/bluetooth/conn.h>
#include <zephyr/bluetooth/gatt.h>
#include <zephyr/bluetooth/uuid.h>
#include <zephyr/logging/log.h>
#include "ble_serial_rx_event.h"
#include "ble_serial_tx_event.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
#define BLE_SERIAL_RX_MAX_LEN 64U
#define BLE_SERIAL_MIN_PAYLOAD_LEN 32U
#define BLE_SERIAL_NOTIFY_OVERHEAD 3U
#define BLE_SERIAL_SERVICE_UUID_VAL \
BT_UUID_128_ENCODE(0x0b7f6000, 0x38d2, 0x4f62, 0x8f6f, 0x36c4fd73a110)
#define BLE_SERIAL_RX_UUID_VAL \
BT_UUID_128_ENCODE(0x0b7f6001, 0x38d2, 0x4f62, 0x8f6f, 0x36c4fd73a110)
#define BLE_SERIAL_TX_UUID_VAL \
BT_UUID_128_ENCODE(0x0b7f6002, 0x38d2, 0x4f62, 0x8f6f, 0x36c4fd73a110)
static struct bt_conn *active_conn;
static bool initialized;
static bool running;
static bool ble_ready;
static bool secured;
static bool tx_notify_enabled;
static const struct bt_uuid_128 ble_serial_service_uuid =
BT_UUID_INIT_128(BLE_SERIAL_SERVICE_UUID_VAL);
static const struct bt_uuid_128 ble_serial_rx_uuid =
BT_UUID_INIT_128(BLE_SERIAL_RX_UUID_VAL);
static const struct bt_uuid_128 ble_serial_tx_uuid =
BT_UUID_INIT_128(BLE_SERIAL_TX_UUID_VAL);
static void submit_ble_serial_rx_event(const uint8_t *data, size_t len)
{
struct ble_serial_rx_event *event = new_ble_serial_rx_event(len);
memcpy(event->dyndata.data, data, len);
APP_EVENT_SUBMIT(event);
}
static void tx_ccc_cfg_changed(const struct bt_gatt_attr *attr, uint16_t value)
{
ARG_UNUSED(attr);
tx_notify_enabled = (value == BT_GATT_CCC_NOTIFY);
LOG_INF("BLE serial TX notify %s", tx_notify_enabled ? "enabled" : "disabled");
}
static ssize_t rx_write_handler(struct bt_conn *conn,
const struct bt_gatt_attr *attr,
const void *buf,
uint16_t len,
uint16_t offset,
uint8_t flags)
{
ARG_UNUSED(attr);
ARG_UNUSED(flags);
if (!running || !ble_ready || !secured || (conn != active_conn)) {
return BT_GATT_ERR(BT_ATT_ERR_WRITE_REQ_REJECTED);
}
if (offset != 0U) {
return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
}
if ((buf == NULL) || (len == 0U) || (len > BLE_SERIAL_RX_MAX_LEN)) {
return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
}
submit_ble_serial_rx_event(buf, len);
return len;
}
BT_GATT_SERVICE_DEFINE(ble_serial_svc,
BT_GATT_PRIMARY_SERVICE(&ble_serial_service_uuid.uuid),
BT_GATT_CHARACTERISTIC(&ble_serial_rx_uuid.uuid,
BT_GATT_CHRC_WRITE | BT_GATT_CHRC_WRITE_WITHOUT_RESP,
BT_GATT_PERM_WRITE_ENCRYPT,
NULL, rx_write_handler, NULL),
BT_GATT_CHARACTERISTIC(&ble_serial_tx_uuid.uuid,
BT_GATT_CHRC_NOTIFY,
BT_GATT_PERM_NONE,
NULL, NULL, NULL),
BT_GATT_CCC(tx_ccc_cfg_changed,
BT_GATT_PERM_READ | BT_GATT_PERM_WRITE_ENCRYPT)
);
static void mtu_updated(struct bt_conn *conn, uint16_t tx, uint16_t rx)
{
if (conn != active_conn) {
return;
}
LOG_INF("BLE serial MTU updated tx:%u rx:%u", tx, rx);
}
static struct bt_gatt_cb gatt_callbacks = {
.att_mtu_updated = mtu_updated,
};
static size_t notify_payload_max(void)
{
uint16_t mtu;
if (active_conn == NULL) {
return 0U;
}
mtu = bt_gatt_get_mtu(active_conn);
if (mtu <= BLE_SERIAL_NOTIFY_OVERHEAD) {
return 0U;
}
return (size_t)(mtu - BLE_SERIAL_NOTIFY_OVERHEAD);
}
static void reset_connection_state(void)
{
active_conn = NULL;
secured = false;
tx_notify_enabled = false;
}
static int module_init(void)
{
bt_gatt_cb_register(&gatt_callbacks);
reset_connection_state();
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;
tx_notify_enabled = false;
}
static bool handle_ble_peer_event(const struct ble_peer_event *event)
{
switch (event->state) {
case PEER_STATE_CONNECTED:
if (active_conn != NULL) {
return false;
}
active_conn = event->id;
secured = false;
tx_notify_enabled = false;
return false;
case PEER_STATE_SECURED:
if (active_conn != event->id) {
return false;
}
secured = true;
return false;
case PEER_STATE_DISCONNECTED:
if (active_conn != event->id) {
return false;
}
reset_connection_state();
return false;
default:
return false;
}
}
static bool handle_ble_serial_tx_event(const struct ble_serial_tx_event *event)
{
size_t payload_max;
int err;
if (!running || !ble_ready || (active_conn == NULL) || !secured || !tx_notify_enabled) {
return false;
}
payload_max = notify_payload_max();
if (payload_max < BLE_SERIAL_MIN_PAYLOAD_LEN) {
LOG_WRN("BLE serial MTU payload too small:%u", (uint32_t)payload_max);
return false;
}
if (event->dyndata.size > payload_max) {
LOG_WRN("BLE serial TX too large len:%u max:%u",
(uint32_t)event->dyndata.size, (uint32_t)payload_max);
return false;
}
err = bt_gatt_notify(active_conn, &ble_serial_svc.attrs[4],
event->dyndata.data,
(uint16_t)event->dyndata.size);
if (err) {
LOG_WRN("bt_gatt_notify failed (%d)", err);
}
return false;
}
static bool app_event_handler(const struct app_event_header *aeh)
{
if (is_ble_serial_tx_event(aeh)) {
return handle_ble_serial_tx_event(cast_ble_serial_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);
int err;
if (check_state(event, MODULE_ID(main), MODULE_STATE_READY)) {
if (!initialized) {
err = module_init();
if (err) {
module_set_state(MODULE_STATE_ERROR);
return false;
}
initialized = true;
}
err = module_start();
if (err) {
module_set_state(MODULE_STATE_ERROR);
}
return false;
}
if (check_state(event, MODULE_ID(ble_state), MODULE_STATE_READY)) {
ble_ready = true;
if (running) {
module_set_state(MODULE_STATE_READY);
}
return false;
}
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 if (ble_ready) {
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, ble_serial_tx_event);
APP_EVENT_SUBSCRIBE_EARLY(MODULE, ble_peer_event);
APP_EVENT_SUBSCRIBE_EARLY(MODULE, power_down_event);
APP_EVENT_SUBSCRIBE(MODULE, wake_up_event);

View File

@@ -12,6 +12,7 @@
#include <zephyr/logging/log.h>
#include "cdc_proto_tx_event.h"
#include "protocol_module.h"
#include "usb_cdc_rx_event.h"
#include "usb_cdc_tx_event.h"
@@ -106,7 +107,8 @@ static void process_complete_frame(void)
return;
}
LOG_INF("CDC HelloRsp encoded len:%u", (uint32_t)rsp_payload_len);
LOG_INF("CDC response type:0x%02x len:%u",
rsp_type, (uint32_t)rsp_payload_len);
submit_tx_frame(rsp_type, rsp_payload, rsp_payload_len);
}
@@ -183,6 +185,23 @@ static bool handle_usb_cdc_rx_event(const struct usb_cdc_rx_event *event)
return false;
}
static bool handle_cdc_proto_tx_event(const struct cdc_proto_tx_event *event)
{
if (!running) {
return false;
}
if (event->dyndata.size > CDC_WRAPPER_MAX_PAYLOAD_LEN) {
LOG_WRN("Drop CDC proto TX len:%u max:%u",
(uint32_t)event->dyndata.size,
(uint32_t)CDC_WRAPPER_MAX_PAYLOAD_LEN);
return false;
}
submit_tx_frame(event->type, event->dyndata.data, event->dyndata.size);
return false;
}
static int module_init(void)
{
parser_reset();
@@ -215,6 +234,10 @@ static bool app_event_handler(const struct app_event_header *aeh)
return handle_usb_cdc_rx_event(cast_usb_cdc_rx_event(aeh));
}
if (is_cdc_proto_tx_event(aeh)) {
return handle_cdc_proto_tx_event(cast_cdc_proto_tx_event(aeh));
}
if (is_module_state_event(aeh)) {
const struct module_state_event *event = cast_module_state_event(aeh);
@@ -269,6 +292,7 @@ static bool app_event_handler(const struct app_event_header *aeh)
}
APP_EVENT_LISTENER(MODULE, app_event_handler);
APP_EVENT_SUBSCRIBE(MODULE, cdc_proto_tx_event);
APP_EVENT_SUBSCRIBE(MODULE, module_state_event);
APP_EVENT_SUBSCRIBE(MODULE, usb_cdc_rx_event);
APP_EVENT_SUBSCRIBE_EARLY(MODULE, power_down_event);

View File

@@ -14,8 +14,11 @@
#include <zephyr/logging/log.h>
#include "bat_state_event.h"
#include "datetime_event.h"
#include "hid_led_event.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);
@@ -30,13 +33,17 @@ 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),
.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,
};
static bool initialized;
static bool running;
static bool lvgl_initialized;
static char date_text[DATETIME_EVENT_DATE_TEXT_LEN] = "1970/01/01";
static char time_text[DATETIME_EVENT_TIME_TEXT_LEN] = "00:00:00";
static int backlight_set(bool on)
{
@@ -90,7 +97,7 @@ static int module_start(void)
lvgl_initialized = true;
lvgl_lock();
ui_main_init(&ui_model, "WH Mini", "Hello World");
ui_main_init(&ui_model, date_text, time_text);
lvgl_unlock();
}
@@ -132,7 +139,7 @@ static void refresh_ui(void)
}
lvgl_lock();
ui_main_refresh_all(&ui_model, "WH Mini", "Hello World");
ui_main_refresh_all(&ui_model, date_text, time_text);
lvgl_unlock();
}
@@ -164,6 +171,28 @@ static bool app_event_handler(const struct app_event_header *aeh)
return false;
}
if (is_theme_rgb_update_event(aeh)) {
const struct theme_rgb_update_event *event =
cast_theme_rgb_update_event(aeh);
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(date_text, event->date_text, sizeof(date_text));
date_text[sizeof(date_text) - 1] = '\0';
strncpy(time_text, event->time_text, sizeof(time_text));
time_text[sizeof(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;
@@ -218,8 +247,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

@@ -0,0 +1,73 @@
#include <ctype.h>
#include <stdio.h>
#include "ble_serial_rx_event.h"
#define BLE_SERIAL_RX_EVENT_LOG_BUF_LEN 384
static void log_ble_serial_rx_event(const struct app_event_header *aeh)
{
const struct ble_serial_rx_event *event = cast_ble_serial_rx_event(aeh);
char log_buf[BLE_SERIAL_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_ble_serial_rx_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
const struct ble_serial_rx_event *event = cast_ble_serial_rx_event(aeh);
nrf_profiler_log_encode_uint8(buf, (uint8_t)event->dyndata.size);
}
APP_EVENT_INFO_DEFINE(ble_serial_rx_event,
ENCODE(NRF_PROFILER_ARG_U8),
ENCODE("len"),
profile_ble_serial_rx_event);
APP_EVENT_TYPE_DEFINE(ble_serial_rx_event,
log_ble_serial_rx_event,
&ble_serial_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 "ble_serial_tx_event.h"
#define BLE_SERIAL_TX_EVENT_LOG_BUF_LEN 256
static void log_ble_serial_tx_event(const struct app_event_header *aeh)
{
const struct ble_serial_tx_event *event = cast_ble_serial_tx_event(aeh);
char log_buf[BLE_SERIAL_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_ble_serial_tx_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
const struct ble_serial_tx_event *event = cast_ble_serial_tx_event(aeh);
nrf_profiler_log_encode_uint8(buf, (uint8_t)event->dyndata.size);
}
APP_EVENT_INFO_DEFINE(ble_serial_tx_event,
ENCODE(NRF_PROFILER_ARG_U8),
ENCODE("len"),
profile_ble_serial_tx_event);
APP_EVENT_TYPE_DEFINE(ble_serial_tx_event,
log_ble_serial_tx_event,
&ble_serial_tx_event_info,
APP_EVENT_FLAGS_CREATE(
APP_EVENT_TYPE_FLAGS_INIT_LOG_ENABLE));

View File

@@ -0,0 +1,29 @@
#include "cdc_proto_tx_event.h"
static void log_cdc_proto_tx_event(const struct app_event_header *aeh)
{
const struct cdc_proto_tx_event *event = cast_cdc_proto_tx_event(aeh);
APP_EVENT_MANAGER_LOG(aeh, "type:0x%02x len:%zu",
event->type, event->dyndata.size);
}
static void profile_cdc_proto_tx_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
const struct cdc_proto_tx_event *event = cast_cdc_proto_tx_event(aeh);
nrf_profiler_log_encode_uint8(buf, event->type);
nrf_profiler_log_encode_uint8(buf, (uint8_t)event->dyndata.size);
}
APP_EVENT_INFO_DEFINE(cdc_proto_tx_event,
ENCODE(NRF_PROFILER_ARG_U8, NRF_PROFILER_ARG_U8),
ENCODE("type", "len"),
profile_cdc_proto_tx_event);
APP_EVENT_TYPE_DEFINE(cdc_proto_tx_event,
log_cdc_proto_tx_event,
&cdc_proto_tx_event_info,
APP_EVENT_FLAGS_CREATE(
APP_EVENT_TYPE_FLAGS_INIT_LOG_ENABLE));

View File

@@ -0,0 +1,27 @@
#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(
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,43 @@
#include "key_function_event.h"
static const char *action_name(uint8_t action)
{
switch (action) {
case KEY_FUNCTION_ACTION_RELEASE:
return "release";
case KEY_FUNCTION_ACTION_PRESS:
return "press";
default:
return "unknown";
}
}
static void log_key_function_event(const struct app_event_header *aeh)
{
const struct key_function_event *event = cast_key_function_event(aeh);
APP_EVENT_MANAGER_LOG(aeh, "usage:0x%04x action:%s",
event->usage, action_name(event->action));
}
static void profile_key_function_event(struct log_event_buf *buf,
const struct app_event_header *aeh)
{
const struct key_function_event *event = cast_key_function_event(aeh);
nrf_profiler_log_encode_uint16(buf, event->usage);
nrf_profiler_log_encode_uint8(buf, event->action);
}
APP_EVENT_INFO_DEFINE(key_function_event,
ENCODE(NRF_PROFILER_ARG_U16, NRF_PROFILER_ARG_U8),
ENCODE("usage", "action"),
profile_key_function_event);
APP_EVENT_TYPE_DEFINE(key_function_event,
log_key_function_event,
&key_function_event_info,
APP_EVENT_FLAGS_CREATE(
APP_EVENT_TYPE_FLAGS_INIT_LOG_ENABLE));

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

@@ -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

@@ -15,8 +15,10 @@
#include <zephyr/sys/util.h>
#include "encoder_event.h"
#include "function_bitmap_update_event.h"
#include "keyboard_core.h"
#include "keyboard_hid_report_event.h"
#include "key_function_event.h"
#include "mode_switch_event.h"
#include "set_protocol_event.h"
@@ -39,8 +41,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;
};
@@ -85,6 +87,7 @@ static const uint16_t consumer_usage_map[KEYBOARD_CONSUMER_CTRL_COUNT] = {
static struct keyboard_state keyboard_state;
static struct keyboard_reports_cache reports_cache;
static uint8_t function_usage_mask[KEYBOARD_PROTOCOL_BITMAP_BYTES];
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,
@@ -143,40 +146,35 @@ 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_bitmap_test(const uint8_t *bitmap, uint16_t usage_id)
{
return IN_RANGE(usage_id, KEYBOARD_USAGE_FIRST_MODIFIER,
KEYBOARD_USAGE_LAST_MODIFIER);
}
static bool keyboard_key_update(uint16_t usage_id, bool pressed)
{
if (usage_is_modifier(usage_id)) {
uint8_t new_modifiers = keyboard_state.modifiers;
WRITE_BIT(new_modifiers, usage_id - KEYBOARD_USAGE_FIRST_MODIFIER, pressed);
if (new_modifiers == keyboard_state.modifiers) {
if ((bitmap == NULL) || (usage_id > KEYBOARD_PROTOCOL_USAGE_MAX)) {
return false;
}
keyboard_state.modifiers = new_modifiers;
return true;
return (bitmap[usage_id / 8U] & BIT(usage_id % 8U)) != 0U;
}
if (usage_id > KEYBOARD_NKRO_USAGE_MAX) {
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_id > KEYBOARD_PROTOCOL_USAGE_MAX)) {
LOG_WRN("Unsupported keyboard usage 0x%04x", usage_id);
return false;
}
uint8_t byte_idx = usage_id / 8U;
uint8_t bit_idx = usage_id % 8U;
bool was_pressed = (keyboard_state.keys_bitmap[byte_idx] & BIT(bit_idx)) != 0U;
byte_idx = usage_id / 8U;
bit_idx = usage_id % 8U;
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 +200,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 +212,29 @@ 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[KEYBOARD_PROTOCOL_BITMAP_BYTES - 1U];
report[1] = KEYBOARD_BOOT_RESERVED_BYTE;
for (uint16_t usage_id = 0; usage_id <= KEYBOARD_NKRO_USAGE_MAX; usage_id++) {
uint8_t byte_idx = usage_id / 8U;
uint8_t bit_idx = usage_id % 8U;
if ((keyboard_state.keys_bitmap[byte_idx] & BIT(bit_idx)) == 0U) {
if ((effective_hid_bitmap[byte_idx] & BIT(bit_idx)) == 0U) {
continue;
}
@@ -238,8 +251,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[KEYBOARD_PROTOCOL_BITMAP_BYTES - 1U];
memcpy(&report[1], effective_hid_bitmap, KEYBOARD_NKRO_BITMAP_BYTES);
}
static uint16_t active_consumer_usage_get(void)
@@ -275,6 +291,15 @@ static void submit_keyboard_report_event(enum keyboard_report_type report_type,
APP_EVENT_SUBMIT(event);
}
static void submit_key_function_event(uint16_t usage_id, uint8_t action)
{
struct key_function_event *event = new_key_function_event();
event->usage = usage_id;
event->action = action;
APP_EVENT_SUBMIT(event);
}
static void submit_consumer_fifo_frame(uint16_t usage_id)
{
uint8_t report_buf[KEYBOARD_CONSUMER_REPORT_SIZE];
@@ -389,6 +414,17 @@ static void emit_all_reports(bool force)
}
}
static void emit_function_release_events(void)
{
for (uint16_t usage_id = 0; usage_id <= KEYBOARD_PROTOCOL_USAGE_MAX; usage_id++) {
if (!usage_bitmap_test(keyboard_state.function_pressed_bitmap, usage_id)) {
continue;
}
submit_key_function_event(usage_id, KEY_FUNCTION_ACTION_RELEASE);
}
}
static void emit_release_reports(enum mode_switch_mode mode)
{
struct keyboard_hid_report_event *event;
@@ -421,6 +457,7 @@ static int module_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;
@@ -449,6 +486,7 @@ static void module_pause(void)
if (mode_valid) {
emit_release_reports(current_mode);
}
emit_function_release_events();
keyboard_state_clear();
reports_cache_invalidate();
@@ -472,8 +510,33 @@ 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) {
submit_key_function_event(entry->usage_id,
event->pressed ?
KEY_FUNCTION_ACTION_PRESS :
KEY_FUNCTION_ACTION_RELEASE);
} else {
emit_keys_report(false);
}
} else {
@@ -498,6 +561,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_release_events();
keyboard_state_clear();
reports_cache_invalidate();
}
@@ -526,6 +590,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 +607,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;
@@ -623,6 +699,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_ */

368
src/led_strip_module.c Normal file
View File

@@ -0,0 +1,368 @@
#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 "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");
static const struct device *const strip = DEVICE_DT_GET(LED_STRIP_NODE);
static const struct gpio_dt_spec strip_en =
GPIO_DT_SPEC_GET(LED_STRIP_NODE, supply_gpios);
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 struct led_rgb pixels[LED_STRIP_NUM_PIXELS];
static struct k_work_delayable effect_work;
static struct led_effect *effect;
static struct theme_rgb current_theme = {
.r = BLINKY_THEME_DEFAULT_R,
.g = BLINKY_THEME_DEFAULT_G,
.b = BLINKY_THEME_DEFAULT_B,
};
static bool initialized;
static bool running;
static bool enabled = true;
static void clear_pixels(void)
{
memset(pixels, 0, sizeof(pixels));
}
static int submit_frame(void)
{
int err;
err = led_strip_update_rgb(strip, pixels, ARRAY_SIZE(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(&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(&effect_work);
}
static void schedule_effect_tick(k_timeout_t delay)
{
k_work_reschedule(&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 (!running || !enabled || (effect == NULL)) {
return;
}
keep_running = effect->ops->tick(effect, k_ticks_to_ms_floor32(
LED_STRIP_TICK_INTERVAL.ticks),
pixels, ARRAY_SIZE(pixels));
(void)submit_frame();
if (keep_running) {
schedule_effect_tick(LED_STRIP_TICK_INTERVAL);
}
}
static int module_init(void)
{
int err;
if (!device_is_ready(strip)) {
LOG_ERR("LED strip device %s not ready", strip->name);
return -ENODEV;
}
if (!gpio_is_ready_dt(&strip_en)) {
LOG_ERR("LED strip supply GPIO not ready");
return -ENODEV;
}
err = gpio_pin_configure_dt(&strip_en, GPIO_OUTPUT_INACTIVE);
if (err) {
LOG_ERR("Failed to configure LED strip supply GPIO (%d)", err);
return err;
}
k_work_init_delayable(&effect_work, effect_work_handler);
clear_pixels();
effect = led_effect_get_mutable(LED_EFFECT_ID_KEY_FADE);
if ((effect == NULL) || (effect->ops == NULL)) {
LOG_ERR("LED effect not available");
return -ENOENT;
}
err = effect->ops->init(effect, &effect_cfg);
if (err) {
LOG_ERR("LED effect init failed (%d)", err);
return err;
}
effect->ops->set_theme(effect, &current_theme);
LOG_INF("LED strip ready len:%u", (uint32_t)led_strip_length(strip));
return 0;
}
static int module_start(void)
{
int err;
if (running) {
return 0;
}
running = true;
if (!enabled) {
return 0;
}
err = enable_strip_output();
if (err) {
running = false;
}
return err;
}
static void module_pause(void)
{
if (!running) {
return;
}
if ((effect != NULL) && (effect->ops != NULL)) {
effect->ops->reset(effect);
}
disable_strip_output();
running = false;
}
static bool handle_button_event(const struct button_event *event)
{
if (!running || !enabled || (effect == NULL) || !event->pressed) {
return false;
}
effect->ops->on_key_press(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)
{
enabled = event->enabled;
if (!running) {
return false;
}
if (enabled) {
int err = enable_strip_output();
if (err) {
module_set_state(MODULE_STATE_ERROR);
return false;
}
} else {
if ((effect != NULL) && (effect->ops != NULL)) {
effect->ops->reset(effect);
}
disable_strip_output();
}
return false;
}
static bool handle_theme_rgb_update_event(const struct theme_rgb_update_event *event)
{
current_theme = event->theme;
if ((effect != NULL) && (effect->ops != NULL)) {
effect->ops->set_theme(effect, &current_theme);
}
if (running && enabled && (effect != NULL) && effect->ops->is_active(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)) {
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_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);

View File

@@ -2,24 +2,45 @@
#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 <caf/events/power_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 "theme_rgb_update_event.h"
#include "time_sync_event.h"
#include "cdc_proto_tx_event.h"
#include "function_bitmap_update_event.h"
#include "hid_led_event.h"
#include "key_function_event.h"
#include "protocol_module.h"
#include "usb_device_state_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))
static bool initialized;
static bool running;
static bool keyboard_core_ready;
static bool usb_active;
static bool hello_done;
static bool type_matches_body(uint8_t type, const CdcPacketBody *body)
{
@@ -28,6 +49,20 @@ static bool type_matches_body(uint8_t type, const CdcPacketBody *body)
return body->which_body == CdcPacketBody_hello_req_tag;
case CDC_PROTO_TYPE_HELLO_RSP:
return body->which_body == CdcPacketBody_hello_rsp_tag;
case CDC_PROTO_TYPE_BITMAP:
return body->which_body == CdcPacketBody_bitmap_tag;
case CDC_PROTO_TYPE_FUNCTION_KEY_EVENT:
return body->which_body == CdcPacketBody_function_key_event_tag;
case CDC_PROTO_TYPE_LED_STATE:
return body->which_body == CdcPacketBody_led_state_tag;
case CDC_PROTO_TYPE_TIME_SYNC:
return body->which_body == CdcPacketBody_time_sync_tag;
case CDC_PROTO_TYPE_THEME_RGB:
return body->which_body == CdcPacketBody_theme_rgb_tag;
case CDC_PROTO_TYPE_ACK:
return body->which_body == CdcPacketBody_ack_tag;
case CDC_PROTO_TYPE_ERROR:
return body->which_body == CdcPacketBody_error_tag;
default:
return false;
}
@@ -53,15 +88,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,17 +120,195 @@ 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);
if (!pb_encode(&stream, CdcPacketBody_fields, &body)) {
LOG_WRN("pb_encode failed: %s", PB_GET_ERROR(&stream));
return -EIO;
return encode_body(&body, rsp_payload, rsp_payload_buf_size, rsp_payload_len);
}
*rsp_payload_len = stream.bytes_written;
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_function_key_event(uint16_t usage, uint8_t action,
uint8_t *payload,
size_t payload_buf_size,
size_t *payload_len)
{
CdcPacketBody body = CdcPacketBody_init_zero;
body.which_body = CdcPacketBody_function_key_event_tag;
body.body.function_key_event.usage = usage;
body.body.function_key_event.action = (KeyAction)action;
return encode_body(&body, payload, payload_buf_size, 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 submit_cdc_proto_tx_event(uint8_t type, const uint8_t *payload,
size_t payload_len)
{
struct cdc_proto_tx_event *event;
if ((payload == NULL) && (payload_len > 0U)) {
return -EINVAL;
}
event = new_cdc_proto_tx_event(payload_len);
event->type = type;
if (payload_len > 0U) {
memcpy(event->dyndata.data, payload, payload_len);
}
APP_EVENT_SUBMIT(event);
return 0;
}
static int submit_function_bitmap_update_event(const Bitmap *bitmap)
{
struct function_bitmap_update_event *event;
if ((bitmap == NULL) ||
(bitmap->usage_bitmap.size != KEYBOARD_PROTOCOL_BITMAP_BYTES)) {
return -EINVAL;
}
event = new_function_bitmap_update_event();
memcpy(event->bitmap, bitmap->usage_bitmap.bytes,
KEYBOARD_PROTOCOL_BITMAP_BYTES);
APP_EVENT_SUBMIT(event);
return 0;
}
static int submit_theme_rgb_update_event(const ThemeRgb *theme_rgb)
{
struct theme_rgb_update_event *event;
if ((theme_rgb == NULL) ||
(theme_rgb->red > 255U) ||
(theme_rgb->green > 255U) ||
(theme_rgb->blue > 255U)) {
return -EINVAL;
}
event = new_theme_rgb_update_event();
event->theme.r = (uint8_t)theme_rgb->red;
event->theme.g = (uint8_t)theme_rgb->green;
event->theme.b = (uint8_t)theme_rgb->blue;
APP_EVENT_SUBMIT(event);
return 0;
}
static int submit_time_sync_event(const TimeSync *time_sync)
{
struct time_sync_event *event;
if (time_sync == NULL) {
return -EINVAL;
}
event = new_time_sync_event();
event->version = time_sync->version;
event->flags = time_sync->flags;
event->timezone_min = time_sync->timezone_min;
event->utc_ms = time_sync->utc_ms;
event->accuracy_ms = time_sync->accuracy_ms;
APP_EVENT_SUBMIT(event);
return 0;
}
static int encode_error_response(uint8_t req_type, ErrorCode error_code,
uint8_t *rsp_type, uint8_t *rsp_payload,
size_t rsp_payload_buf_size,
size_t *rsp_payload_len)
{
int err;
err = encode_error(req_type, error_code, rsp_payload,
rsp_payload_buf_size, rsp_payload_len);
if (err) {
return err;
}
*rsp_type = CDC_PROTO_TYPE_ERROR;
return 0;
}
static int encode_ack_response(uint8_t acked_type, uint8_t *rsp_type,
uint8_t *rsp_payload,
size_t rsp_payload_buf_size,
size_t *rsp_payload_len)
{
int err;
err = encode_ack(acked_type, rsp_payload, rsp_payload_buf_size,
rsp_payload_len);
if (err) {
return err;
}
*rsp_type = CDC_PROTO_TYPE_ACK;
return 0;
}
static int module_init(void)
{
keyboard_core_ready = false;
usb_active = false;
hello_done = false;
return 0;
}
static int module_start(void)
{
if (running) {
return 0;
}
running = true;
return 0;
}
static void module_pause(void)
{
if (!running) {
return;
}
hello_done = false;
running = false;
}
int protocol_module_process_cdc_packet(uint8_t req_type,
const uint8_t *req_payload,
size_t req_payload_len,
@@ -97,15 +324,23 @@ int protocol_module_process_cdc_packet(uint8_t req_type,
return -EINVAL;
}
if (!running) {
return -EAGAIN;
}
err = decode_body(req_payload, req_payload_len, &body);
if (err) {
return err;
return encode_error_response(req_type, ErrorCode_ERROR_CODE_INVALID_LENGTH,
rsp_type, rsp_payload,
rsp_payload_buf_size, rsp_payload_len);
}
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;
return encode_error_response(req_type, ErrorCode_ERROR_CODE_INVALID_PARAM,
rsp_type, rsp_payload,
rsp_payload_buf_size, rsp_payload_len);
}
switch (req_type) {
@@ -118,6 +353,7 @@ int protocol_module_process_cdc_packet(uint8_t req_type,
body.body.hello_req.protocol_version);
}
hello_done = true;
err = encode_hello_rsp(rsp_payload, rsp_payload_buf_size, rsp_payload_len);
if (err) {
return err;
@@ -126,8 +362,232 @@ int protocol_module_process_cdc_packet(uint8_t req_type,
*rsp_type = CDC_PROTO_TYPE_HELLO_RSP;
return 0;
case CDC_PROTO_TYPE_BITMAP:
if (!hello_done) {
return encode_error_response(req_type, ErrorCode_ERROR_CODE_NOT_READY,
rsp_type, rsp_payload,
rsp_payload_buf_size,
rsp_payload_len);
}
if (!keyboard_core_ready) {
return encode_error_response(req_type, ErrorCode_ERROR_CODE_NOT_READY,
rsp_type, rsp_payload,
rsp_payload_buf_size,
rsp_payload_len);
}
if (body.body.bitmap.usage_bitmap.size != KEYBOARD_PROTOCOL_BITMAP_BYTES) {
LOG_WRN("Bitmap len:%u expected:%u",
(unsigned int)body.body.bitmap.usage_bitmap.size,
KEYBOARD_PROTOCOL_BITMAP_BYTES);
return encode_error_response(req_type, ErrorCode_ERROR_CODE_INVALID_LENGTH,
rsp_type, rsp_payload,
rsp_payload_buf_size,
rsp_payload_len);
}
err = submit_function_bitmap_update_event(&body.body.bitmap);
if (err) {
return encode_error_response(req_type, ErrorCode_ERROR_CODE_INVALID_PARAM,
rsp_type, rsp_payload,
rsp_payload_buf_size,
rsp_payload_len);
}
return encode_ack_response(req_type, rsp_type, rsp_payload,
rsp_payload_buf_size, rsp_payload_len);
case CDC_PROTO_TYPE_TIME_SYNC:
if (!hello_done) {
return encode_error_response(req_type, ErrorCode_ERROR_CODE_NOT_READY,
rsp_type, rsp_payload,
rsp_payload_buf_size,
rsp_payload_len);
}
if (body.body.time_sync.version != 1U) {
return encode_error_response(req_type, ErrorCode_ERROR_CODE_INVALID_PARAM,
rsp_type, rsp_payload,
rsp_payload_buf_size,
rsp_payload_len);
}
err = submit_time_sync_event(&body.body.time_sync);
if (err) {
return encode_error_response(req_type, ErrorCode_ERROR_CODE_INVALID_PARAM,
rsp_type, rsp_payload,
rsp_payload_buf_size,
rsp_payload_len);
}
return encode_ack_response(req_type, rsp_type, rsp_payload,
rsp_payload_buf_size, rsp_payload_len);
case CDC_PROTO_TYPE_THEME_RGB:
if (!hello_done) {
return encode_error_response(req_type, ErrorCode_ERROR_CODE_NOT_READY,
rsp_type, rsp_payload,
rsp_payload_buf_size,
rsp_payload_len);
}
err = submit_theme_rgb_update_event(&body.body.theme_rgb);
if (err) {
return encode_error_response(req_type, ErrorCode_ERROR_CODE_INVALID_PARAM,
rsp_type, rsp_payload,
rsp_payload_buf_size,
rsp_payload_len);
}
return encode_ack_response(req_type, rsp_type, rsp_payload,
rsp_payload_buf_size, rsp_payload_len);
default:
LOG_WRN("Unsupported CDC protocol type:0x%02x", req_type);
return -ENOTSUP;
return encode_error_response(req_type, ErrorCode_ERROR_CODE_UNKNOWN_TYPE,
rsp_type, rsp_payload,
rsp_payload_buf_size, rsp_payload_len);
}
}
static bool handle_key_function_event(const struct key_function_event *event)
{
uint8_t payload[64];
size_t payload_len;
int err;
if (!running || !usb_active || !hello_done) {
return false;
}
err = encode_function_key_event(event->usage, event->action, payload,
sizeof(payload), &payload_len);
if (err) {
LOG_WRN("FunctionKeyEvent encode failed (%d)", err);
return false;
}
err = submit_cdc_proto_tx_event(CDC_PROTO_TYPE_FUNCTION_KEY_EVENT,
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[64];
size_t payload_len;
int err;
if (!running || !usb_active || !hello_done) {
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_cdc_proto_tx_event(CDC_PROTO_TYPE_LED_STATE, payload, payload_len);
if (err) {
LOG_WRN("LedState submit failed (%d)", err);
}
return false;
}
static bool handle_usb_device_state_event(const struct usb_device_state_event *event)
{
usb_active = (event->state == USB_DEVICE_STATE_ACTIVE);
if (!usb_active) {
hello_done = false;
}
return false;
}
static bool app_event_handler(const struct app_event_header *aeh)
{
if (is_key_function_event(aeh)) {
return handle_key_function_event(cast_key_function_event(aeh));
}
if (is_hid_led_event(aeh)) {
return handle_hid_led_event(cast_hid_led_event(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);
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 (check_state(event, MODULE_ID(keyboard_core_module), MODULE_STATE_READY)) {
keyboard_core_ready = true;
return false;
}
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, hid_led_event);
APP_EVENT_SUBSCRIBE(MODULE, key_function_event);
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);

186
src/time_sync_module.c Normal file
View File

@@ -0,0 +1,186 @@
#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 "time_sync_event.h"
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
#define TIME_SYNC_REFRESH_PERIOD K_SECONDS(1)
static struct k_work_delayable refresh_work;
static bool initialized;
static bool running;
static int32_t timezone_min;
static uint64_t utc_ms_base;
static int64_t uptime_ms_base;
static void submit_datetime_event(void)
{
struct datetime_event *event = new_datetime_event();
struct tm tm_buf;
time_t seconds;
int64_t local_ms;
local_ms = (int64_t)utc_ms_base +
(k_uptime_get() - uptime_ms_base) +
((int64_t)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(event->date_text, "1970/01/01", sizeof(event->date_text));
strncpy(event->time_text, "00:00:00", sizeof(event->time_text));
} else {
snprintk(event->date_text, sizeof(event->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(event->time_text, sizeof(event->time_text),
"%02u:%02u:%02u",
(unsigned int)tm_buf.tm_hour,
(unsigned int)tm_buf.tm_min,
(unsigned int)tm_buf.tm_sec);
}
APP_EVENT_SUBMIT(event);
}
static void refresh_work_handler(struct k_work *work)
{
ARG_UNUSED(work);
if (!running) {
return;
}
submit_datetime_event();
k_work_reschedule(&refresh_work, TIME_SYNC_REFRESH_PERIOD);
}
static int module_init(void)
{
timezone_min = 0;
utc_ms_base = 0U;
uptime_ms_base = k_uptime_get();
k_work_init_delayable(&refresh_work, refresh_work_handler);
return 0;
}
static int module_start(void)
{
if (running) {
return 0;
}
running = true;
k_work_reschedule(&refresh_work, K_NO_WAIT);
return 0;
}
static void module_pause(void)
{
if (!running) {
return;
}
k_work_cancel_delayable(&refresh_work);
running = false;
}
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;
}
timezone_min = event->timezone_min;
utc_ms_base = event->utc_ms;
uptime_ms_base = k_uptime_get();
if (running) {
k_work_reschedule(&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);
int err;
if (check_state(event, MODULE_ID(main), MODULE_STATE_READY)) {
if (!initialized) {
err = module_init();
if (err) {
module_set_state(MODULE_STATE_ERROR);
return false;
}
initialized = true;
}
err = module_start();
if (err) {
module_set_state(MODULE_STATE_ERROR);
} else {
module_set_state(MODULE_STATE_READY);
}
}
return false;
}
if (is_power_down_event(aeh)) {
if (initialized) {
module_pause();
module_set_state(MODULE_STATE_STANDBY);
}
return false;
}
if (is_wake_up_event(aeh)) {
if (initialized) {
int err = module_start();
if (err) {
module_set_state(MODULE_STATE_ERROR);
} else {
module_set_state(MODULE_STATE_READY);
}
}
return false;
}
return false;
}
APP_EVENT_LISTENER(MODULE, app_event_handler);
APP_EVENT_SUBSCRIBE(MODULE, 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

@@ -7,9 +7,12 @@
#include <caf/events/module_state_event.h>
#include <caf/events/power_event.h>
#include <caf/events/ble_common_event.h>
#include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
#include "ble_serial_tx_event.h"
#include "usb_cdc_tx_event.h"
#include "usb_device_state_event.h"
@@ -18,11 +21,13 @@ 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 const uint8_t ble_hello_message[] = "ble_hello\r\n";
static struct k_work_delayable hello_work;
static bool initialized;
static bool running;
static bool usb_active;
static bool ble_active;
static void submit_hello_message(void)
{
@@ -33,15 +38,31 @@ static void submit_hello_message(void)
APP_EVENT_SUBMIT(event);
}
static void submit_ble_hello_message(void)
{
struct ble_serial_tx_event *event =
new_ble_serial_tx_event(sizeof(ble_hello_message) - 1U);
memcpy(event->dyndata.data, ble_hello_message, sizeof(ble_hello_message) - 1U);
APP_EVENT_SUBMIT(event);
}
static void hello_work_handler(struct k_work *work)
{
ARG_UNUSED(work);
if (!running || !usb_active) {
if (!running) {
return;
}
if (usb_active) {
submit_hello_message();
}
if (ble_active) {
submit_ble_hello_message();
}
k_work_reschedule(&hello_work, USB_CDC_TEST_PERIOD);
}
@@ -58,7 +79,7 @@ static int module_start(void)
}
running = true;
if (usb_active) {
if (usb_active || ble_active) {
k_work_reschedule(&hello_work, USB_CDC_TEST_PERIOD);
}
@@ -98,12 +119,56 @@ static bool handle_usb_device_state_event(const struct usb_device_state_event *e
return false;
}
static bool handle_ble_peer_event(const struct ble_peer_event *event)
{
bool new_ble_active = ble_active;
switch (event->state) {
case PEER_STATE_CONNECTED:
new_ble_active = false;
break;
case PEER_STATE_SECURED:
new_ble_active = true;
break;
case PEER_STATE_DISCONNECTED:
new_ble_active = false;
break;
default:
return false;
}
if (new_ble_active == ble_active) {
return false;
}
ble_active = new_ble_active;
if (!running) {
return false;
}
if (usb_active || ble_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_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);
@@ -159,6 +224,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, ble_peer_event);
APP_EVENT_SUBSCRIBE(MODULE, usb_device_state_event);
APP_EVENT_SUBSCRIBE_EARLY(MODULE, power_down_event);
APP_EVENT_SUBSCRIBE(MODULE, wake_up_event);