Files
zmk/app/src/behaviors/behavior_input_two_axis.c
Pete Johanson c06fa48ce5 feat!: Move to zephyr v4.1 (#3060)
refactor: Move to Zephyr v4.1.0

Move to Zephyr v4.1.0, with various build/compilation fixes needed for
basic use.

refactor(tests): Move to native_sim for tests.

feat(core): (Optionally) use Zephyr keyboard input devices

Add ability to assign a keyboard `input` device to a physical layout,
or use a chosen `zmk,matrix-input`.

fix(pointing): Refactor for changes to input API

Pass NULL user_data to input callbacks.

fix(tests): Fix BLE test to account for Zephyr changes

Handle additional read callback invocation once all matching
characteristic have been read.

fix(sensors): Initialize sensor data to 0 before fetching.

Be sure we don't get back any uninitialized data by initializing
the channel data to 0 before calling into the sensor API.

refactor(input): Adjust split input to input API changes.

Input callbacks now have a user_data parameter, adjust accordingly.

chore(bluetooth): Minor cleanup of split BT code after refactor

Small fixes and remove commented dead code left after the split
refactor.

refactor: Fix up BLE tests after Zephyr upgrade.

Minor changes to snapshots based on newer Zephyr version.

refactor(boards): Move to upstream xiao_ble board ID.

Move to official upstream board definition for the Seeed XIAO BLE.

refactor: Adjust metadata schema for HWMv2 board IDs w/ qualifiers

Adjust our ZMK metadata to allow for board IDs that include qualifiers
with slash delimeters.

refactor!(boards): Move nice!nano to HWMv2, and proper revisioning

Upgrade the nice!nano board to HWMv2, under the proper nicekeyboards
vendor directory, and with proper revisions. Includes a breaking change
to default the `2.0.0` version instead of the much older v1 (`1.0.0`).

fix: Disable Nordic dt-bindings header checks.

Disable the recently added Nordic dt-bindings header checks, which cause
issues for our HID related headers.

fix(studio): Correct `memset` usage.

Use the correct memset call to clear our RPC memory.

fix: Refactor for new Zephyr PM API

Adjustments to our PM code to match Zephyr PM APIs.

refactor(ble): Use correct BT opt for connectable.

Adjust for upstream Zephyr BT API changes for advertising options.

refactor(boards): Move MakerDiary M2 board to HWMv2.

Run the HWMv2 script to convert the MakerDiary M2 board.

fix(studio): Correct usage of thread analyzer API

Fix up the RPC code that invoke the thread analyzer API to account for
API changes.

chore: Remove nanopb module override.

Leverage nanopb version that's used by Zephyr.

feat(core): mapper for magic bootloader values.

To trigger bootloaders that use a magic value in RAM to trigger
bootloader mode, add a mapping retained memory driver that maps
write/read of boot mode values to a special magic value stored
in the actually backing RAM.

feat(behaviors): Add retention boot mode to reset.

Support new generic Zephyr retention boot mode API in the reset
behavior.

feat: Add double tap to enter bootloader functionality

Add ability to enter the bootloader if double tapping reset within the
specified window.

refactor(CI): Move to 4.1 container tags.

Move to the new 4.1 tagged container, to ensure updated SDK, Python
packages, etc.

refactor(boards): Move nRFMicro to HWMv2

Refactor nRFMicro to HWMv2, using proper SoC, revisions, and variants
(for flipped). Also move to devicetree setup of DCDC/HV DCDC.

refactor(boards): Move QMK Proton-C to HWMv2

Move Proton-C to HWMv2 for use with Zephyr 4.1.

chore(ci): Adjust core coverage for new board IDs.

Use correct board IDs, with qualifiers, for our core coverage testing.

refactor(boards): Move BDN9 to HWMv2

Move BDN9 to HWMv2, using the base `bdn9` ID, no longer including the
`_rev2` suffix in the ID.

refactor(boards): Move nice!60 to HWMv2

Migrate nice!60 to HWMv2.

refactor: Adjust how we're searching/loading keymap files

Use new post_boards_shields extension point for loading keymap files
from board/shield directories.

refactor(boards): Move planck rev6 to HWMv2.

Move Planck board definition to HWMv2, including versioning tweaks.

refactor(boards): Move OLKB Preonic to HWMv2

Move Preonic board definition to HWMv2 and remove `_rev3` variant
suffix in favor of board versioning with `3.0.0` as the default.

chore(deps): Pull in Zephyr optional group for nanopb.

Ensure we enable nanopb by adding +optional group filter.

fix(ci): Prevent slash characters in artifact names.

Move to HWMv2 means board IDs often include slashes, so replace those
with underscores when doing file uploads.

fix(usb): Adjust Kconfig settings for USB.

* Ensure USB isn't initialized automatically before we do, which can
  happen if USB CDC logging is used/enabled for a given board.
* Adjust USB HID to initialize the USB class/interface before we enable
  the USB device itself.

fix(display): Fix setting the small font for the mono theme.

Adjust for modified mono theme init function to pass the small font.

chore(ci): Fix changed board IDs for core coverage.

Adjust board IDs for our core coverage after move to HWMv2 and board
versioning consistently.

* planck_rev6 -> planck
* bdn9_rev2 -> bdn9

fix(underglow): Remove use of removed Kconfig WS2812 symbol

refactor(boards): Move PW CKP boards to HWMv2

Migrate the bt60, bt65, and bt75 to HWMv2.

refactor(boards): Move Puchi BLE to HWMv2

Migrate the Puchi BLE to HWMv2.

refactor(boards): Migrate Ferris rev02 to HWMv2.

Move Ferris rev02 to HMWv2, and remove the revision from the ID.

refactor(boards): Move Pillbug to HWMv2

Migrate the MechWild PillBug board to HWMv2.

refactor(boards): Migrate s40nc to HWMv2

Move the ShortyFortyNoCordy (s40nc) to HWMv2.

refactor(boards): Move bluemicro840 board to HWMv2.

Migrate bluemicro840 board to HWMv2, set up boot mode retention.

fix(boards): Retore bootloader support on XIAO BLE.

Set up necessary boot mode/retention to properly set GPREGRET to trigger
Adafruit bootloader to run on the XIAO BLE.

refactor(boards): Move Adv360 Pro to HWMv2.

Migrate Adv360 Pro left/right to HWMv2.

refactor(boards): Move Glove80 to HMWv2

Refactor the MoErgo Glove80 left/right to HWMv2.

refactor(boards): Move Mikoto to HMWv2.

Migrate Mikoto to HWMv2, with non-exact matching, tweaks to I2C
selection to imply it for the 7.2.0 revision for the fuel gauge.

refactor(boards): Move kbdfans Tofu65 2.0 to HMWv2

Move Tofu65 2.0 to HMWv2, with ID of just `tofu65`.

refactor(boards): Remove dz60rgb board

Remove dz60rgb, it's no longer readily available and we have other
current stm32 reference designs for testing.

refactor(boards): Move Corneish Zen to HMWv2

Move Corneish Zen to HMWv2, with IDs of
`corneish_zen_left`/`corneish_zen_right`.

refactor(boards): Migrate Corne-ish Zen status screen

* refactor(boards): Add boot mode to the nice!nano using common dtsi

* Add a new .dtsi for setting up nRF52 boot mode/retained memory
  settings
* Adjust XIAO BLE to use the new include file
* Add boot mode to to the nice!nano

refactor(boards): Add boot mode support to nice!60 board

Enable boot mode for nice!60 board.

refactor(boards): Adjust Zephyr board metadata file locations

Move the ZMK metadata files for upstream Zephyr boards to align with the
HWMv2 directory structure that uses the vendor ID for the parent
directory for a board directory.

fix: Don't enable ZMK Display by default for a few shields

By convention, avoid enabling ZMK Display by default on shields that may
be built with under-resourced controllers (e.g. nRF52833 based ones).

fix: Remove usage of renamed Kconfig from core coverage.

Avoid using WS2812_LED_STRIP, since that Kconfig was renamed/split into
SPI/GPIO/I2S symbols.

refactor(boards): Adjust XIAO RP2040 override names, bootloader support

Adjust the .conf/.overlay files to match the proper naming for the
XIAO rp2040 board. Also add the necessary Kconfig/DTS bits for
supporting bootloader using retained memory/boot mode retention.

fix(display): Adjust stack sizes for display usage.

Updated LVGL is bumping our stack size, so adjust the system work queue
and dedicated display queue stack sizes as needed to account for this.

feat(display): Add thread name to dedicated display queue.

When thread names are enabled, pass a name to the dedicated display
queue for better tracibility when using the thread analyzer.

docs(blog): Add Zephyr upgrade post

docs: Add bootloader integration page

Add a dedicated page to outline steps to set up bootloader integration
using the boot retention mechanism in newer Zephyr versions.

fix(display): port nice!view display code

* remove `lv_` prefix from old LVGL methods

doc: Update local setup docs to use `west packages pip`

Install Zephyr deps using the newer `west packages pip --install`.

Signed-off-by: Peter Johanson <peter@peterjohanson.com>

refactor(split): Adjust BT split code for newer Zephyr APIs.

refactor(boards): Adjust upstream RP2040 boards for boot mode retention

Add necessary DTS/Kconfig settings to upstream RP2040 boards so they can
use the ZMK bootloader functionality using the boot mode retention
infrastructure.

docs: Update Zephyr docs links to 4.1.0 version.

Update all links to the Zephyr docs to the 4.1.0 versions to match our
Zephyr version in use.

docs: Add a note about using CMake v3 for maximum compatibility.

Some optional modules, like libmetal, which is used on nRF5340,
specifically require CMake v3, so add a note in the native toolchain
setup about this.

feat(pointing): Handle INPUT_BTN_TOUCH codes for mouse buttons

Translate INPUT_BTN_TOUCH input codes into button 0 press/release for
HID layer.

chore(pointing): Clean up some warning messages.

Properly check return code from queue-ing messages, and fix up some type
warnings in our logging calls.

* Fix input event codes line numbers

fix(studio): Properly serialize GATT RPC indications.

fix(core): Set a system work queue stack size of 2048 by default

We use a fair amount of stack even without BLE or RP2040, so default to
2048 by default everywhere, and constrained platforms can lowes this if
they really need.

refactor(core): Move away from deprecated DIS Kconfig symbols

Use the correct Device Information Service Kconfig symbols for our model
number and manufacturer.

refactor: Move upstream Zephyr board overrides to extensions dirs

Newer Zephyr supports "board extensions" to formally do what we've added
in ourselves via some hacks, so move all our board overlay/config file
overrides for upstream Zephyr boards into that correct structure.

fix(boards): Add xiao_ble sd_partition label for nosd snippet compat

Upstream xiao_ble uses different naming convention for the partition
labels, so add an additional label for the SD range, so the existing
nrf52840-nosd snippet will still work with the board.

fix(core): Don't force CBPRINTF_NANO, for proper formatting.

The nano CBPRINTF implementation lacks some padded formatting needed to
ensure consistent formatting of BLE addresses, which we use to store
keys as strings in a few places, so use the complete CBPRINTF by default
now.

fix(boards): Remove some references to old nice_nano_v2 board ID.

The nice!nano board definition now properly uses versioning, so avoid
referring to it with old `nice_nano_v2` board ID.

fix(boards): Remove nano overlays for old nice_nano_v2 board ID.

With board versioning in place, we can remove the unused
`nice_nano_v2.overlay` files from shields.

---------

Signed-off-by: Peter Johanson <peter@peterjohanson.com>
Co-authored-by: Cem Aksoylar <caksoylar@users.noreply.github.com>
Co-authored-by: Nicolas Munnich <munnich@lipn.univ-paris13.fr>
Co-authored-by: snoyer <noyer.stephane@gmail.com>
2025-12-09 19:43:22 -05:00

305 lines
10 KiB
C

/*
* Copyright (c) 2024 The ZMK Contributors
*
* SPDX-License-Identifier: MIT
*/
#define DT_DRV_COMPAT zmk_behavior_input_two_axis
#include <zephyr/device.h>
#include <drivers/behavior.h>
#include <zephyr/input/input.h>
#include <zephyr/logging/log.h>
#include <zephyr/sys/util.h> // CLAMP
#include <zmk/behavior.h>
#include <dt-bindings/zmk/pointing.h>
#if IS_ENABLED(CONFIG_ZMK_POINTING_SMOOTH_SCROLLING)
#include <zmk/pointing/resolution_multipliers.h>
#endif // IS_ENABLED(CONFIG_ZMK_POINTING_SMOOTH_SCROLLING)
LOG_MODULE_DECLARE(zmk, CONFIG_ZMK_LOG_LEVEL);
struct vector2d {
float x;
float y;
};
struct movement_state_1d {
float remainder;
int16_t speed;
int64_t start_time;
};
struct movement_state_2d {
struct movement_state_1d x;
struct movement_state_1d y;
};
struct behavior_input_two_axis_data {
struct k_work_delayable tick_work;
const struct device *dev;
struct movement_state_2d state;
};
struct behavior_input_two_axis_config {
int16_t x_code;
int16_t y_code;
uint16_t delay_ms;
uint16_t time_to_max_speed_ms;
uint8_t trigger_period_ms;
// acceleration exponent 0: uniform speed
// acceleration exponent 1: uniform acceleration
// acceleration exponent 2: uniform jerk
uint8_t acceleration_exponent;
};
#if CONFIG_MINIMAL_LIBC
static float powf(float base, float exponent) {
// poor man's power implementation rounds the exponent down to the nearest integer.
float power = 1.0f;
for (; exponent >= 1.0f; exponent--) {
power = power * base;
}
return power;
}
#else
#include <math.h>
#endif
static int64_t ticks_since_start(int64_t start, int64_t now, int64_t delay) {
if (start == 0) {
return 0;
}
int64_t move_duration = now - (start + delay);
// start can be in the future if there's a delay
if (move_duration < 0) {
move_duration = 0;
}
return move_duration;
}
#if IS_ENABLED(CONFIG_ZMK_POINTING_SMOOTH_SCROLLING)
static uint8_t get_acceleration_exponent(const struct behavior_input_two_axis_config *config,
uint16_t code) {
switch (code) {
case INPUT_REL_WHEEL:
return (zmk_pointing_resolution_multipliers_get_current_profile().wheel > 0)
? 0
: config->acceleration_exponent;
case INPUT_REL_HWHEEL:
return (zmk_pointing_resolution_multipliers_get_current_profile().hor_wheel > 0)
? 0
: config->acceleration_exponent;
default:
return config->acceleration_exponent;
}
}
#else
static inline uint8_t get_acceleration_exponent(const struct behavior_input_two_axis_config *config,
uint16_t code) {
return config->acceleration_exponent;
}
#endif // IS_ENABLED(CONFIG_ZMK_POINTING_SMOOTH_SCROLLING)
static float speed(const struct behavior_input_two_axis_config *config, uint16_t code,
float max_speed, int64_t duration_ticks) {
uint8_t accel_exp = get_acceleration_exponent(config, code);
if ((1000 * duration_ticks / CONFIG_SYS_CLOCK_TICKS_PER_SEC) > config->time_to_max_speed_ms ||
config->time_to_max_speed_ms == 0 || accel_exp == 0) {
return max_speed;
}
// Calculate the speed based on MouseKeysAccel
// See https://en.wikipedia.org/wiki/Mouse_keys
if (duration_ticks == 0) {
return 0;
}
float time_fraction = (float)(1000 * duration_ticks / CONFIG_SYS_CLOCK_TICKS_PER_SEC) /
config->time_to_max_speed_ms;
return max_speed * powf(time_fraction, accel_exp);
}
static void track_remainder(float *move, float *remainder) {
float new_move = *move + *remainder;
*remainder = new_move - (int)new_move;
*move = (int)new_move;
}
static float update_movement_1d(const struct behavior_input_two_axis_config *config, uint16_t code,
struct movement_state_1d *state, int64_t now) {
float move = 0;
if (state->speed == 0) {
state->remainder = 0;
return move;
}
int64_t move_duration = ticks_since_start(state->start_time, now, config->delay_ms);
LOG_DBG("Calculated speed: %f", (double)speed(config, code, state->speed, move_duration));
move =
(move_duration > 0)
? (speed(config, code, state->speed, move_duration) * config->trigger_period_ms / 1000)
: 0;
track_remainder(&(move), &(state->remainder));
return move;
}
static struct vector2d update_movement_2d(const struct behavior_input_two_axis_config *config,
struct movement_state_2d *state, int64_t now) {
struct vector2d move = {0};
move = (struct vector2d){
.x = update_movement_1d(config, config->x_code, &state->x, now),
.y = update_movement_1d(config, config->y_code, &state->y, now),
};
return move;
}
static bool is_non_zero_1d_movement(int16_t speed) { return speed != 0; }
static bool is_non_zero_2d_movement(struct movement_state_2d *state) {
return is_non_zero_1d_movement(state->x.speed) || is_non_zero_1d_movement(state->y.speed);
}
static bool should_be_working(struct behavior_input_two_axis_data *data) {
return is_non_zero_2d_movement(&data->state);
}
static void tick_work_cb(struct k_work *work) {
struct k_work_delayable *d_work = k_work_delayable_from_work(work);
struct behavior_input_two_axis_data *data =
CONTAINER_OF(d_work, struct behavior_input_two_axis_data, tick_work);
const struct device *dev = data->dev;
const struct behavior_input_two_axis_config *cfg = dev->config;
uint64_t timestamp = k_uptime_ticks();
// LOG_INF("x start: %llu, y start: %llu, current timestamp: %llu", data->state.x.start_time,
// data->state.y.start_time, timestamp);
struct vector2d move = update_movement_2d(cfg, &data->state, timestamp);
int ret = 0;
bool have_x = is_non_zero_1d_movement(move.x);
bool have_y = is_non_zero_1d_movement(move.y);
if (have_x) {
ret = input_report_rel(dev, cfg->x_code, (int16_t)CLAMP(move.x, INT16_MIN, INT16_MAX),
!have_y, K_NO_WAIT);
}
if (have_y) {
ret = input_report_rel(dev, cfg->y_code, (int16_t)CLAMP(move.y, INT16_MIN, INT16_MAX), true,
K_NO_WAIT);
}
if (should_be_working(data)) {
k_work_schedule(&data->tick_work, K_MSEC(cfg->trigger_period_ms));
}
}
static void set_start_times_for_activity_1d(struct movement_state_1d *state) {
if (state->speed != 0 && state->start_time == 0) {
state->start_time = k_uptime_ticks();
} else if (state->speed == 0) {
state->start_time = 0;
}
}
static void set_start_times_for_activity(struct movement_state_2d *state) {
set_start_times_for_activity_1d(&state->x);
set_start_times_for_activity_1d(&state->y);
}
static void update_work_scheduling(const struct device *dev) {
struct behavior_input_two_axis_data *data = dev->data;
const struct behavior_input_two_axis_config *cfg = dev->config;
set_start_times_for_activity(&data->state);
if (should_be_working(data)) {
k_work_schedule(&data->tick_work, K_MSEC(cfg->trigger_period_ms));
} else {
k_work_cancel_delayable(&data->tick_work);
data->state.y.remainder = 0;
data->state.x.remainder = 0;
}
}
int behavior_input_two_axis_adjust_speed(const struct device *dev, int16_t dx, int16_t dy) {
struct behavior_input_two_axis_data *data = dev->data;
LOG_DBG("Adjusting: %d %d", dx, dy);
data->state.x.speed += dx;
data->state.y.speed += dy;
LOG_DBG("After: %d %d", data->state.x.speed, data->state.y.speed);
update_work_scheduling(dev);
return 0;
}
static int behavior_input_two_axis_init(const struct device *dev) {
struct behavior_input_two_axis_data *data = dev->data;
data->dev = dev;
k_work_init_delayable(&data->tick_work, tick_work_cb);
return 0;
};
static int on_keymap_binding_pressed(struct zmk_behavior_binding *binding,
struct zmk_behavior_binding_event event) {
const struct device *behavior_dev = zmk_behavior_get_binding(binding->behavior_dev);
LOG_DBG("position %d keycode 0x%02X", event.position, binding->param1);
int16_t x = MOVE_X_DECODE(binding->param1);
int16_t y = MOVE_Y_DECODE(binding->param1);
behavior_input_two_axis_adjust_speed(behavior_dev, x, y);
return 0;
}
static int on_keymap_binding_released(struct zmk_behavior_binding *binding,
struct zmk_behavior_binding_event event) {
const struct device *behavior_dev = zmk_behavior_get_binding(binding->behavior_dev);
LOG_DBG("position %d keycode 0x%02X", event.position, binding->param1);
int16_t x = MOVE_X_DECODE(binding->param1);
int16_t y = MOVE_Y_DECODE(binding->param1);
behavior_input_two_axis_adjust_speed(behavior_dev, -x, -y);
return 0;
}
static const struct behavior_driver_api behavior_input_two_axis_driver_api = {
.binding_pressed = on_keymap_binding_pressed, .binding_released = on_keymap_binding_released};
#define ITA_INST(n) \
static struct behavior_input_two_axis_data behavior_input_two_axis_data_##n = {}; \
static struct behavior_input_two_axis_config behavior_input_two_axis_config_##n = { \
.x_code = DT_INST_PROP(n, x_input_code), \
.y_code = DT_INST_PROP(n, y_input_code), \
.trigger_period_ms = DT_INST_PROP(n, trigger_period_ms), \
.delay_ms = DT_INST_PROP_OR(n, delay_ms, 0), \
.time_to_max_speed_ms = DT_INST_PROP(n, time_to_max_speed_ms), \
.acceleration_exponent = DT_INST_PROP_OR(n, acceleration_exponent, 1), \
}; \
BEHAVIOR_DT_INST_DEFINE( \
n, behavior_input_two_axis_init, NULL, &behavior_input_two_axis_data_##n, \
&behavior_input_two_axis_config_##n, POST_KERNEL, CONFIG_KERNEL_INIT_PRIORITY_DEFAULT, \
&behavior_input_two_axis_driver_api);
DT_INST_FOREACH_STATUS_OKAY(ITA_INST)