New kernel drivers and device implementation updates (#561)

- Added modular device support and devicetree bindings for ILI9341, ILI9488, CST816S, XPT2046, and GPIO button input, updating several board configurations for display/touch/backlight/keyboard/battery.
- Added a setting to control deprecated HAL usage (device property + Kconfig).
This commit is contained in:
Ken Van Hoeylandt
2026-07-12 23:54:55 +02:00
committed by GitHub
parent 50c0a14a93
commit fa4a6e255c
148 changed files with 5837 additions and 2145 deletions
+11
View File
@@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 3.20)
include("${CMAKE_CURRENT_LIST_DIR}/../../Buildscripts/module.cmake")
file(GLOB_RECURSE SOURCE_FILES "source/*.c*")
tactility_add_module(m5stack-module
SRCS ${SOURCE_FILES}
INCLUDE_DIRS include/
REQUIRES TactilityKernel platform-esp32 lvgl driver
)
@@ -0,0 +1,195 @@
Apache License
==============
_Version 2.0, January 2004_
_&lt;<http://www.apache.org/licenses/>&gt;_
### Terms and Conditions for use, reproduction, and distribution
#### 1. Definitions
“License” shall mean the terms and conditions for use, reproduction, and
distribution as defined by Sections 1 through 9 of this document.
“Licensor” shall mean the copyright owner or entity authorized by the copyright
owner that is granting the License.
“Legal Entity” shall mean the union of the acting entity and all other entities
that control, are controlled by, or are under common control with that entity.
For the purposes of this definition, “control” means **(i)** the power, direct or
indirect, to cause the direction or management of such entity, whether by
contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the
outstanding shares, or **(iii)** beneficial ownership of such entity.
“You” (or “Your”) shall mean an individual or Legal Entity exercising
permissions granted by this License.
“Source” form shall mean the preferred form for making modifications, including
but not limited to software source code, documentation source, and configuration
files.
“Object” form shall mean any form resulting from mechanical transformation or
translation of a Source form, including but not limited to compiled object code,
generated documentation, and conversions to other media types.
“Work” shall mean the work of authorship, whether in Source or Object form, made
available under the License, as indicated by a copyright notice that is included
in or attached to the work (an example is provided in the Appendix below).
“Derivative Works” shall mean any work, whether in Source or Object form, that
is based on (or derived from) the Work and for which the editorial revisions,
annotations, elaborations, or other modifications represent, as a whole, an
original work of authorship. For the purposes of this License, Derivative Works
shall not include works that remain separable from, or merely link (or bind by
name) to the interfaces of, the Work and Derivative Works thereof.
“Contribution” shall mean any work of authorship, including the original version
of the Work and any modifications or additions to that Work or Derivative Works
thereof, that is intentionally submitted to Licensor for inclusion in the Work
by the copyright owner or by an individual or Legal Entity authorized to submit
on behalf of the copyright owner. For the purposes of this definition,
“submitted” means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems, and
issue tracking systems that are managed by, or on behalf of, the Licensor for
the purpose of discussing and improving the Work, but excluding communication
that is conspicuously marked or otherwise designated in writing by the copyright
owner as “Not a Contribution.”
“Contributor” shall mean Licensor and any individual or Legal Entity on behalf
of whom a Contribution has been received by Licensor and subsequently
incorporated within the Work.
#### 2. Grant of Copyright License
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the Work and such
Derivative Works in Source or Object form.
#### 3. Grant of Patent License
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable (except as stated in this section) patent license to make, have
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
such license applies only to those patent claims licensable by such Contributor
that are necessarily infringed by their Contribution(s) alone or by combination
of their Contribution(s) with the Work to which such Contribution(s) was
submitted. If You institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
Contribution incorporated within the Work constitutes direct or contributory
patent infringement, then any patent licenses granted to You under this License
for that Work shall terminate as of the date such litigation is filed.
#### 4. Redistribution
You may reproduce and distribute copies of the Work or Derivative Works thereof
in any medium, with or without modifications, and in Source or Object form,
provided that You meet the following conditions:
* **(a)** You must give any other recipients of the Work or Derivative Works a copy of
this License; and
* **(b)** You must cause any modified files to carry prominent notices stating that You
changed the files; and
* **(c)** You must retain, in the Source form of any Derivative Works that You distribute,
all copyright, patent, trademark, and attribution notices from the Source form
of the Work, excluding those notices that do not pertain to any part of the
Derivative Works; and
* **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any
Derivative Works that You distribute must include a readable copy of the
attribution notices contained within such NOTICE file, excluding those notices
that do not pertain to any part of the Derivative Works, in at least one of the
following places: within a NOTICE text file distributed as part of the
Derivative Works; within the Source form or documentation, if provided along
with the Derivative Works; or, within a display generated by the Derivative
Works, if and wherever such third-party notices normally appear. The contents of
the NOTICE file are for informational purposes only and do not modify the
License. You may add Your own attribution notices within Derivative Works that
You distribute, alongside or as an addendum to the NOTICE text from the Work,
provided that such additional attribution notices cannot be construed as
modifying the License.
You may add Your own copyright statement to Your modifications and may provide
additional or different license terms and conditions for use, reproduction, or
distribution of Your modifications, or for any such Derivative Works as a whole,
provided Your use, reproduction, and distribution of the Work otherwise complies
with the conditions stated in this License.
#### 5. Submission of Contributions
Unless You explicitly state otherwise, any Contribution intentionally submitted
for inclusion in the Work by You to the Licensor shall be under the terms and
conditions of this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify the terms of
any separate license agreement you may have executed with Licensor regarding
such Contributions.
#### 6. Trademarks
This License does not grant permission to use the trade names, trademarks,
service marks, or product names of the Licensor, except as required for
reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE file.
#### 7. Disclaimer of Warranty
Unless required by applicable law or agreed to in writing, Licensor provides the
Work (and each Contributor provides its Contributions) on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
including, without limitation, any warranties or conditions of TITLE,
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
solely responsible for determining the appropriateness of using or
redistributing the Work and assume any risks associated with Your exercise of
permissions under this License.
#### 8. Limitation of Liability
In no event and under no legal theory, whether in tort (including negligence),
contract, or otherwise, unless required by applicable law (such as deliberate
and grossly negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special, incidental,
or consequential damages of any character arising as a result of this License or
out of the use or inability to use the Work (including but not limited to
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
any and all other commercial damages or losses), even if such Contributor has
been advised of the possibility of such damages.
#### 9. Accepting Warranty or Additional Liability
While redistributing the Work or Derivative Works thereof, You may choose to
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
other liability obligations and/or rights consistent with this License. However,
in accepting such obligations, You may act only on Your own behalf and on Your
sole responsibility, not on behalf of any other Contributor, and only if You
agree to indemnify, defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason of your
accepting any such warranty or additional liability.
_END OF TERMS AND CONDITIONS_
### APPENDIX: How to apply the Apache License to your work
To apply the Apache License to your work, attach the following boilerplate
notice, with the fields enclosed by brackets `[]` replaced with your own
identifying information. (Don't include the brackets!) The text should be
enclosed in the appropriate comment syntax for the file format. We also
recommend that a file or class name and description of purpose be included on
the same “printed page” as the copyright notice for easier identification within
third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -0,0 +1,12 @@
description: >
M5Stack Cardputer Adv keyboard, a TCA8418 I2C keypad-scan IC wired as a 7x8 matrix behind
a 4x14 key grid identical to the base Cardputer's. Exposes a KEYBOARD_TYPE device.
Sym (fn) and shift are consumed internally and never emitted as their own key events;
sym+shift together toggles caps lock. Regular keys emit their lowercase/uppercase/sym-layer
ASCII character or LVGL navigation key depending on which layer is active.
include: ["i2c-device.yaml"]
compatible: "m5stack,cardputer-adv-keyboard"
bus: i2c
@@ -0,0 +1,21 @@
description: >
M5Stack Cardputer internal GPIO matrix keyboard: 4 rows x 14 columns, scanned via 3
binary-encoded column-select output pins and 7 row input pins. Exposes a KEYBOARD_TYPE
device. Modifier keys (fn/shift/ctrl/opt/alt/tab) are consumed internally and never emitted
as their own key events. Regular keys emit their ASCII character (shifted variant when
shift or ctrl is held). With fn held: del -> forward delete, enter -> enter, ` -> escape,
, -> left, / -> right, ; -> previous (group navigation), . -> next (group navigation).
compatible: "m5stack,cardputer-keyboard"
properties:
pins-output:
type: phandle-array
element-type: "struct GpioPinSpec"
required: true
description: 3 GPIO pins driving the binary-encoded column-select lines, in scan-bit order
pins-input:
type: phandle-array
element-type: "struct GpioPinSpec"
required: true
description: 7 GPIO pins reading the row lines, in scan-bit order
+3
View File
@@ -0,0 +1,3 @@
dependencies:
- TactilityKernel
bindings: bindings
@@ -0,0 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <tactility/bindings/bindings.h>
#include <drivers/cardputer_adv_keyboard.h>
DEFINE_DEVICETREE(cardputer_adv_keyboard, struct M5stackCardputerAdvKeyboardConfig)
@@ -0,0 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <tactility/bindings/bindings.h>
#include <drivers/cardputer_keyboard.h>
DEFINE_DEVICETREE(cardputer_keyboard, struct M5stackCardputerKeyboardConfig)
@@ -0,0 +1,19 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
struct M5stackCardputerAdvKeyboardConfig {
// Devicetree address hint. The TCA8418 has a fixed I2C address (0x34), but the field is
// still populated from the standard i2c-device "reg" property for consistency with other
// I2C child device bindings.
uint8_t address;
};
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,21 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <tactility/drivers/gpio.h>
struct M5stackCardputerKeyboardConfig {
struct GpioPinSpec* pins_output;
uint8_t pins_output_count;
struct GpioPinSpec* pins_input;
uint8_t pins_input_count;
};
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,14 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <tactility/module.h>
#ifdef __cplusplus
extern "C" {
#endif
extern struct Module m5stack_module;
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,283 @@
// SPDX-License-Identifier: Apache-2.0
// TCA8418 register protocol and Cardputer Adv row/col remap ported from
// Devices/m5stack-cardputer-adv/source/devices/CardputerKeyboard.cpp and
// Drivers/TCA8418/Source/Tca8418.cpp (itself ported from
// https://github.com/adafruit/Adafruit_TCA8418, MIT licensed).
#include <drivers/cardputer_adv_keyboard.h>
#include <m5stack_module.h>
#include <tactility/check.h>
#include <tactility/device.h>
#include <tactility/driver.h>
#include <tactility/drivers/i2c_controller.h>
#include <tactility/drivers/keyboard.h>
#include <tactility/error.h>
#include <tactility/log.h>
#include <lvgl.h>
#include <cstdlib>
static constexpr const char* TAG = "CardputerAdvKeyboard";
#define GET_CONFIG(device) (static_cast<const M5stackCardputerAdvKeyboardConfig*>((device)->config))
static constexpr TickType_t I2C_TIMEOUT = pdMS_TO_TICKS(100);
// Fixed by the board's wiring (see Tca8418::init(7, 8) in the pre-kernel driver).
static constexpr int TCA8418_ROWS = 7;
static constexpr int TCA8418_COLS = 8;
static constexpr uint8_t TCA8418_REG_CFG = 0x01U;
static constexpr uint8_t TCA8418_REG_KEY_EVENT_A = 0x04U;
static constexpr uint8_t TCA8418_REG_KP_GPIO1 = 0x1DU;
static constexpr uint8_t TCA8418_REG_KP_GPIO2 = 0x1EU;
// AI=1, GPI_E_CFG=0, OVR_FLOW_M=0 (overflow disabled), INT_CFG=1, *_IEN=0 except KE_IEN=1.
static constexpr uint8_t TCA8418_CFG_VALUE = 0x99U;
// Worst case per read_key() call: drain this many queued chip events in one go.
static constexpr int CARDPUTER_ADV_MAX_EVENTS_PER_SCAN = 10;
static constexpr int CARDPUTER_ADV_PENDING_CAPACITY = 10;
static constexpr int CARDPUTER_ADV_ACTIVE_KEY_CAPACITY = 4;
static constexpr int CARDPUTER_ADV_ROWS = 4;
static constexpr int CARDPUTER_ADV_COLS = 14;
// [row][col] on the 4x14 grid, matching the base Cardputer's physical layout. 0 means the cell
// emits nothing (used for the sym/shift cells themselves, and unwired cells on this board).
static const uint32_t cardputer_adv_keymap_lc[CARDPUTER_ADV_ROWS][CARDPUTER_ADV_COLS] = {
{ '`', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', LV_KEY_BACKSPACE },
{ '\t', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', '\\' },
{ 0, 0, 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', '\'', LV_KEY_ENTER },
{ 0, 0, 0, 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/', ' ' },
};
static const uint32_t cardputer_adv_keymap_uc[CARDPUTER_ADV_ROWS][CARDPUTER_ADV_COLS] = {
{ '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', LV_KEY_DEL },
{ '\t', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '{', '}', '|' },
{ 0, 0, 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ':', '"', LV_KEY_ENTER },
{ 0, 0, 0, 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '<', '>', '?', ' ' },
};
static const uint32_t cardputer_adv_keymap_sym[CARDPUTER_ADV_ROWS][CARDPUTER_ADV_COLS] = {
{ LV_KEY_ESC, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ '\t', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, LV_KEY_PREV, 0, LV_KEY_ENTER },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, LV_KEY_LEFT, LV_KEY_NEXT, LV_KEY_RIGHT, 0 },
};
struct CardputerAdvActiveKey {
bool in_use;
uint8_t row;
uint8_t col;
uint32_t key;
};
struct CardputerAdvPendingEvent {
uint32_t key;
bool pressed;
};
struct CardputerAdvKeyboardInternal {
bool sym_pressed;
bool shift_pressed;
bool caps_lock;
// Only allows one caps-lock toggle per sym+shift co-press, requiring both to be released
// before it can be toggled again.
bool caps_lock_armed;
CardputerAdvActiveKey active_keys[CARDPUTER_ADV_ACTIVE_KEY_CAPACITY];
CardputerAdvPendingEvent pending[CARDPUTER_ADV_PENDING_CAPACITY];
uint8_t pending_head;
uint8_t pending_count;
};
static void push_pending(CardputerAdvKeyboardInternal* internal, uint32_t key, bool pressed) {
if (internal->pending_count >= CARDPUTER_ADV_PENDING_CAPACITY) {
LOG_W(TAG, "Pending event queue full, dropping event");
return;
}
uint8_t tail = (internal->pending_head + internal->pending_count) % CARDPUTER_ADV_PENDING_CAPACITY;
internal->pending[tail] = { .key = key, .pressed = pressed };
internal->pending_count++;
}
static bool pop_pending(CardputerAdvKeyboardInternal* internal, CardputerAdvPendingEvent* out_event) {
if (internal->pending_count == 0) {
return false;
}
*out_event = internal->pending[internal->pending_head];
internal->pending_head = (internal->pending_head + 1) % CARDPUTER_ADV_PENDING_CAPACITY;
internal->pending_count--;
return true;
}
// region Driver lifecycle
static error_t start(Device* device) {
auto* parent = device_get_parent(device);
check(device_get_type(parent) == &I2C_CONTROLLER_TYPE);
const auto* config = GET_CONFIG(device);
if (i2c_controller_has_device_at_address(parent, config->address, I2C_TIMEOUT) != ERROR_NONE) {
LOG_E(TAG, "No device found on I2C bus at address 0x%02X", config->address);
return ERROR_RESOURCE;
}
auto* internal = static_cast<CardputerAdvKeyboardInternal*>(malloc(sizeof(CardputerAdvKeyboardInternal)));
if (internal == nullptr) {
return ERROR_OUT_OF_MEMORY;
}
*internal = {};
internal->caps_lock_armed = true;
// KP_GPIO1/2: mark all TCA8418_ROWS rows and TCA8418_COLS columns as keypad matrix pins.
uint8_t row_mask = (1U << TCA8418_ROWS) - 1;
uint8_t col_mask = (1U << TCA8418_COLS) - 1;
bool ok =
i2c_controller_register8_set(parent, config->address, TCA8418_REG_KP_GPIO1, row_mask, I2C_TIMEOUT) == ERROR_NONE &&
i2c_controller_register8_set(parent, config->address, TCA8418_REG_KP_GPIO2, col_mask, I2C_TIMEOUT) == ERROR_NONE &&
i2c_controller_register8_set(parent, config->address, TCA8418_REG_CFG, TCA8418_CFG_VALUE, I2C_TIMEOUT) == ERROR_NONE;
if (!ok) {
LOG_E(TAG, "Failed to configure TCA8418");
free(internal);
return ERROR_RESOURCE;
}
device_set_driver_data(device, internal);
return ERROR_NONE;
}
static error_t stop(Device* device) {
auto* internal = static_cast<CardputerAdvKeyboardInternal*>(device_get_driver_data(device));
free(internal);
return ERROR_NONE;
}
// endregion
// region KeyboardApi
// Wiring is a 7x8 matrix, but the keymap tables are laid out as a 4x14 grid (matching the base
// Cardputer's physical key positions).
static void remap_to_grid(uint8_t wiring_row, uint8_t wiring_col, uint8_t* grid_row, uint8_t* grid_col) {
uint8_t col = wiring_row * 2;
if (wiring_col > 3) {
col++;
}
*grid_row = (wiring_col + 4) % 4;
*grid_col = col;
}
static uint32_t resolve_key(const CardputerAdvKeyboardInternal* internal, uint8_t row, uint8_t col) {
if (internal->sym_pressed) {
return cardputer_adv_keymap_sym[row][col];
}
if (internal->shift_pressed || internal->caps_lock) {
return cardputer_adv_keymap_uc[row][col];
}
return cardputer_adv_keymap_lc[row][col];
}
static void handle_key_event(CardputerAdvKeyboardInternal* internal, uint8_t row, uint8_t col, bool pressed) {
// Sym and shift are modifiers: tracked as state, never emitted as their own key events.
if (row == 2 && col == 0) {
internal->sym_pressed = pressed;
} else if (row == 2 && col == 1) {
internal->shift_pressed = pressed;
} else if (pressed) {
if (internal->sym_pressed && internal->shift_pressed && internal->caps_lock_armed) {
internal->caps_lock = !internal->caps_lock;
internal->caps_lock_armed = false;
}
uint32_t key = resolve_key(internal, row, col);
if (key != 0) {
for (auto& active_key : internal->active_keys) {
if (!active_key.in_use) {
active_key = { .in_use = true, .row = row, .col = col, .key = key };
push_pending(internal, key, true);
break;
}
}
}
} else {
// Release: report the key that was actually pressed, even if the active modifier layer
// changed while it was held.
for (auto& active_key : internal->active_keys) {
if (active_key.in_use && active_key.row == row && active_key.col == col) {
push_pending(internal, active_key.key, false);
active_key.in_use = false;
break;
}
}
}
if (!internal->sym_pressed && !internal->shift_pressed) {
internal->caps_lock_armed = true;
}
}
static error_t cardputer_adv_keyboard_read_key(Device* device, KeyboardKeyData* data) {
auto* parent = device_get_parent(device);
const auto* config = GET_CONFIG(device);
auto* internal = static_cast<CardputerAdvKeyboardInternal*>(device_get_driver_data(device));
for (int i = 0; i < CARDPUTER_ADV_MAX_EVENTS_PER_SCAN; i++) {
uint8_t key_event = 0;
if (i2c_controller_register8_get(parent, config->address, TCA8418_REG_KEY_EVENT_A, &key_event, I2C_TIMEOUT) != ERROR_NONE) {
break;
}
if (key_event == 0) {
break; // Chip event FIFO is empty.
}
bool pressed = (key_event & 0x80) != 0;
uint8_t raw_code = key_event & 0x7F;
if (raw_code == 0) {
continue; // Invalid: code 0 underflows below when decremented.
}
uint8_t code = raw_code - 1;
uint8_t wiring_row = code / 10;
uint8_t wiring_col = code % 10;
if (wiring_row >= TCA8418_ROWS || wiring_col >= TCA8418_COLS) {
continue; // Out of range for the physical matrix: would index the keymaps out of bounds.
}
uint8_t grid_row, grid_col;
remap_to_grid(wiring_row, wiring_col, &grid_row, &grid_col);
handle_key_event(internal, grid_row, grid_col, pressed);
}
CardputerAdvPendingEvent event;
if (pop_pending(internal, &event)) {
data->key = event.key;
data->pressed = event.pressed;
data->continue_reading = internal->pending_count > 0;
} else {
data->key = 0;
data->pressed = false;
data->continue_reading = false;
}
return ERROR_NONE;
}
// endregion
static const KeyboardApi cardputer_adv_keyboard_api = {
.read_key = cardputer_adv_keyboard_read_key,
};
Driver cardputer_adv_keyboard_driver = {
.name = "cardputer_adv_keyboard",
.compatible = (const char*[]) { "m5stack,cardputer-adv-keyboard", nullptr },
.start_device = start,
.stop_device = stop,
.api = &cardputer_adv_keyboard_api,
.device_type = &KEYBOARD_TYPE,
.owner = &m5stack_module,
.internal = nullptr
};
@@ -0,0 +1,330 @@
// SPDX-License-Identifier: Apache-2.0
// Matrix-scan and keymap logic ported from the M5Stack Cardputer keyboard driver at
// https://github.com/m5stack/M5Cardputer-UserDemo/tree/main/main/hal/keyboard (MIT licensed).
#include <drivers/cardputer_keyboard.h>
#include <m5stack_module.h>
#include <tactility/check.h>
#include <tactility/device.h>
#include <tactility/driver.h>
#include <tactility/drivers/gpio_controller.h>
#include <tactility/drivers/keyboard.h>
#include <tactility/error.h>
#include <tactility/log.h>
#include <lvgl.h>
#include <cstdlib>
static constexpr const char* TAG = "CardputerKeyboard";
#define GET_CONFIG(device) (static_cast<const M5stackCardputerKeyboardConfig*>((device)->config))
static constexpr int CARDPUTER_OUTPUT_COUNT = 3;
static constexpr int CARDPUTER_INPUT_COUNT = 7;
static constexpr int CARDPUTER_ROWS = 4;
static constexpr int CARDPUTER_COLS = 14;
// Worst case per scan: the previously active key releases and a different key is now active,
// i.e. one release event and one press event.
static constexpr int CARDPUTER_PENDING_CAPACITY = 2;
enum CardputerKeyRole {
CARDPUTER_KEY_CHAR,
CARDPUTER_KEY_TAB,
CARDPUTER_KEY_FN,
CARDPUTER_KEY_SHIFT,
CARDPUTER_KEY_CTRL,
CARDPUTER_KEY_OPT,
CARDPUTER_KEY_ALT,
CARDPUTER_KEY_DEL,
CARDPUTER_KEY_ENTER,
CARDPUTER_KEY_SPACE,
};
struct CardputerKeyDef {
CardputerKeyRole role;
// Only meaningful when role == CARDPUTER_KEY_CHAR.
char normal;
char shifted;
};
#define K(normal, shifted) { CARDPUTER_KEY_CHAR, normal, shifted }
// [row][col], matching the physical key grid. Modifier/action cells carry a role instead of
// a character; their normal/shifted fields are unused.
static const CardputerKeyDef cardputer_key_map[CARDPUTER_ROWS][CARDPUTER_COLS] = {
{ K('`', '~'), K('1', '!'), K('2', '@'), K('3', '#'), K('4', '$'), K('5', '%'), K('6', '^'),
K('7', '&'), K('8', '*'), K('9', '('), K('0', ')'), K('-', '_'), K('=', '+'), { CARDPUTER_KEY_DEL, 0, 0 } },
{ { CARDPUTER_KEY_TAB, 0, 0 }, K('q', 'Q'), K('w', 'W'), K('e', 'E'), K('r', 'R'), K('t', 'T'), K('y', 'Y'),
K('u', 'U'), K('i', 'I'), K('o', 'O'), K('p', 'P'), K('[', '{'), K(']', '}'), K('\\', '|') },
{ { CARDPUTER_KEY_FN, 0, 0 }, { CARDPUTER_KEY_SHIFT, 0, 0 }, K('a', 'A'), K('s', 'S'), K('d', 'D'), K('f', 'F'), K('g', 'G'),
K('h', 'H'), K('j', 'J'), K('k', 'K'), K('l', 'L'), K(';', ':'), K('\'', '"'), { CARDPUTER_KEY_ENTER, 0, 0 } },
{ { CARDPUTER_KEY_CTRL, 0, 0 }, { CARDPUTER_KEY_OPT, 0, 0 }, { CARDPUTER_KEY_ALT, 0, 0 }, K('z', 'Z'), K('x', 'X'), K('c', 'C'), K('v', 'V'),
K('b', 'B'), K('n', 'N'), K('m', 'M'), K(',', '<'), K('.', '>'), K('/', '?'), { CARDPUTER_KEY_SPACE, 0, 0 } },
};
#undef K
struct CardputerKeyboardPendingEvent {
uint32_t key;
bool pressed;
};
struct CardputerKeyboardInternal {
GpioDescriptor* output_descriptors[CARDPUTER_OUTPUT_COUNT];
GpioDescriptor* input_descriptors[CARDPUTER_INPUT_COUNT];
// 0 when no actionable key is currently held; otherwise the LVGL key code last reported
// via read_key(). Only ever one actionable key at a time (matches original hardware driver:
// modifier keys are consumed internally, and only the first non-modifier key found in a
// scan is reported).
uint32_t active_key;
CardputerKeyboardPendingEvent pending[CARDPUTER_PENDING_CAPACITY];
uint8_t pending_head;
uint8_t pending_count;
};
static void push_pending(CardputerKeyboardInternal* internal, uint32_t key, bool pressed) {
if (internal->pending_count >= CARDPUTER_PENDING_CAPACITY) {
LOG_W(TAG, "Pending event queue full, dropping event");
return;
}
uint8_t tail = (internal->pending_head + internal->pending_count) % CARDPUTER_PENDING_CAPACITY;
internal->pending[tail] = { .key = key, .pressed = pressed };
internal->pending_count++;
}
static bool pop_pending(CardputerKeyboardInternal* internal, CardputerKeyboardPendingEvent* out_event) {
if (internal->pending_count == 0) {
return false;
}
*out_event = internal->pending[internal->pending_head];
internal->pending_head = (internal->pending_head + 1) % CARDPUTER_PENDING_CAPACITY;
internal->pending_count--;
return true;
}
// region Driver lifecycle
static error_t start(Device* device) {
const auto* config = GET_CONFIG(device);
if (config->pins_output_count != CARDPUTER_OUTPUT_COUNT || config->pins_input_count != CARDPUTER_INPUT_COUNT) {
LOG_E(TAG, "Expected %d output pins and %d input pins", CARDPUTER_OUTPUT_COUNT, CARDPUTER_INPUT_COUNT);
return ERROR_INVALID_ARGUMENT;
}
auto* internal = static_cast<CardputerKeyboardInternal*>(malloc(sizeof(CardputerKeyboardInternal)));
if (internal == nullptr) {
return ERROR_OUT_OF_MEMORY;
}
*internal = {};
for (int i = 0; i < CARDPUTER_OUTPUT_COUNT; i++) {
const auto& pin = config->pins_output[i];
auto* descriptor = gpio_descriptor_acquire(pin.gpio_controller, pin.pin, GPIO_OWNER_GPIO);
if (descriptor != nullptr && gpio_descriptor_set_flags(descriptor, pin.flags | GPIO_FLAG_DIRECTION_OUTPUT) != ERROR_NONE) {
gpio_descriptor_release(descriptor);
descriptor = nullptr;
}
if (descriptor == nullptr) {
LOG_E(TAG, "Failed to configure output pin %d", i);
for (int j = 0; j < i; j++) {
gpio_descriptor_release(internal->output_descriptors[j]);
}
free(internal);
return ERROR_RESOURCE;
}
gpio_descriptor_set_level(descriptor, false);
internal->output_descriptors[i] = descriptor;
}
for (int i = 0; i < CARDPUTER_INPUT_COUNT; i++) {
const auto& pin = config->pins_input[i];
// Rows float high and are pulled low through a pressed key by the active output line,
// so an internal pull-up is required regardless of what the devicetree pin flags say.
auto* descriptor = gpio_descriptor_acquire(pin.gpio_controller, pin.pin, GPIO_OWNER_GPIO);
if (descriptor == nullptr || gpio_descriptor_set_flags(descriptor, pin.flags | GPIO_FLAG_DIRECTION_INPUT | GPIO_FLAG_PULL_UP) != ERROR_NONE) {
LOG_E(TAG, "Failed to configure input pin %d", i);
for (int j = 0; j < CARDPUTER_OUTPUT_COUNT; j++) {
gpio_descriptor_release(internal->output_descriptors[j]);
}
for (int j = 0; j < i; j++) {
gpio_descriptor_release(internal->input_descriptors[j]);
}
free(internal);
return ERROR_RESOURCE;
}
internal->input_descriptors[i] = descriptor;
}
device_set_driver_data(device, internal);
return ERROR_NONE;
}
static error_t stop(Device* device) {
auto* internal = static_cast<CardputerKeyboardInternal*>(device_get_driver_data(device));
for (auto* descriptor : internal->output_descriptors) {
gpio_descriptor_release(descriptor);
}
for (auto* descriptor : internal->input_descriptors) {
gpio_descriptor_release(descriptor);
}
free(internal);
return ERROR_NONE;
}
// endregion
// region KeyboardApi
static void set_output(CardputerKeyboardInternal* internal, uint8_t value) {
for (int i = 0; i < CARDPUTER_OUTPUT_COUNT; i++) {
gpio_descriptor_set_level(internal->output_descriptors[i], ((value >> i) & 0x01) != 0);
}
}
static uint8_t read_input(CardputerKeyboardInternal* internal) {
uint8_t mask = 0;
for (int j = 0; j < CARDPUTER_INPUT_COUNT; j++) {
bool high = true;
gpio_descriptor_get_level(internal->input_descriptors[j], &high);
if (!high) { // active-low: LOW means pressed
mask |= (1 << j);
}
}
return mask;
}
// Scans the full matrix and resolves it to a single LVGL key code (0 if none), applying the
// same priority as the original driver: enter > space > backspace > first regular character
// found in scan order, with fn changing the interpretation of backspace/enter/punctuation.
// Modifier keys (fn/shift/ctrl/opt/alt/tab) are never reported themselves.
static uint32_t scan_key(CardputerKeyboardInternal* internal) {
bool fn = false, shift = false, ctrl = false;
bool del_flag = false, enter_flag = false, space_flag = false;
bool has_regular = false;
char regular_normal = 0, regular_shifted = 0;
// 8 binary-encoded column-select codes x 7 row inputs = 4 rows x 14 columns.
for (uint8_t i = 0; i < 8; i++) {
set_output(internal, i);
uint8_t input_mask = read_input(internal);
if (input_mask == 0) {
continue;
}
for (int j = 0; j < CARDPUTER_INPUT_COUNT; j++) {
if ((input_mask & (1 << j)) == 0) {
continue;
}
int row = 3 - (i % 4);
int col = (i >= 4) ? (2 * j) : (2 * j + 1);
const auto& def = cardputer_key_map[row][col];
switch (def.role) {
case CARDPUTER_KEY_TAB:
case CARDPUTER_KEY_OPT:
case CARDPUTER_KEY_ALT:
break; // consumed, never affects output
case CARDPUTER_KEY_FN:
fn = true;
break;
case CARDPUTER_KEY_SHIFT:
shift = true;
break;
case CARDPUTER_KEY_CTRL:
ctrl = true;
break;
case CARDPUTER_KEY_DEL:
del_flag = true;
break;
case CARDPUTER_KEY_ENTER:
enter_flag = true;
break;
case CARDPUTER_KEY_SPACE:
space_flag = true;
break;
case CARDPUTER_KEY_CHAR:
if (!has_regular) {
has_regular = true;
regular_normal = def.normal;
regular_shifted = def.shifted;
}
break;
}
}
}
char resolved_char = has_regular ? ((ctrl || shift) ? regular_shifted : regular_normal) : 0;
if (!fn) {
if (enter_flag) return LV_KEY_ENTER;
if (space_flag) return (uint32_t)' ';
if (del_flag) return LV_KEY_BACKSPACE;
if (has_regular) return (uint32_t)(uint8_t)resolved_char;
return 0;
}
// fn combos: forward-delete, enter, and group navigation (using PREV/NEXT rather than
// UP/DOWN so widgets like lv_switch that toggle on arrow keys aren't affected).
if (del_flag) return LV_KEY_DEL;
if (enter_flag) return LV_KEY_ENTER;
if (has_regular) {
switch (resolved_char) {
case '`': return LV_KEY_ESC;
case ',': return LV_KEY_LEFT;
case '/': return LV_KEY_RIGHT;
case ';': return LV_KEY_PREV;
case '.': return LV_KEY_NEXT;
default: return 0;
}
}
return 0;
}
static error_t cardputer_keyboard_read_key(Device* device, KeyboardKeyData* data) {
auto* internal = static_cast<CardputerKeyboardInternal*>(device_get_driver_data(device));
uint32_t new_key = scan_key(internal);
if (new_key != internal->active_key) {
if (internal->active_key != 0) {
push_pending(internal, internal->active_key, false);
}
if (new_key != 0) {
push_pending(internal, new_key, true);
}
internal->active_key = new_key;
}
CardputerKeyboardPendingEvent event;
if (pop_pending(internal, &event)) {
data->key = event.key;
data->pressed = event.pressed;
data->continue_reading = internal->pending_count > 0;
} else {
data->key = 0;
data->pressed = false;
data->continue_reading = false;
}
return ERROR_NONE;
}
// endregion
static const KeyboardApi cardputer_keyboard_api = {
.read_key = cardputer_keyboard_read_key,
};
Driver cardputer_keyboard_driver = {
.name = "cardputer_keyboard",
.compatible = (const char*[]) { "m5stack,cardputer-keyboard", nullptr },
.start_device = start,
.stop_device = stop,
.api = &cardputer_keyboard_api,
.device_type = &KEYBOARD_TYPE,
.owner = &m5stack_module,
.internal = nullptr
};
+35
View File
@@ -0,0 +1,35 @@
// SPDX-License-Identifier: Apache-2.0
#include <tactility/check.h>
#include <tactility/driver.h>
#include <tactility/module.h>
extern "C" {
extern Driver cardputer_keyboard_driver;
extern Driver cardputer_adv_keyboard_driver;
static error_t start() {
/* We crash when construct fails, because if a single driver fails to construct,
* there is no guarantee that the previously constructed drivers can be destroyed */
check(driver_construct_add(&cardputer_keyboard_driver) == ERROR_NONE);
check(driver_construct_add(&cardputer_adv_keyboard_driver) == ERROR_NONE);
return ERROR_NONE;
}
static error_t stop() {
/* We crash when destruct fails, because if a single driver fails to destruct,
* there is no guarantee that the previously destroyed drivers can be recovered */
check(driver_remove_destruct(&cardputer_keyboard_driver) == ERROR_NONE);
check(driver_remove_destruct(&cardputer_adv_keyboard_driver) == ERROR_NONE);
return ERROR_NONE;
}
Module m5stack_module = {
.name = "m5stack",
.start = start,
.stop = stop,
.symbols = nullptr,
.internal = nullptr
};
} // extern "C"