New kernel drivers and device migrations (#563)

This commit is contained in:
Ken Van Hoeylandt
2026-07-14 20:26:57 +02:00
committed by GitHub
parent 955416dac8
commit 8af6204ba1
215 changed files with 6359 additions and 3633 deletions
@@ -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(xpt2046-softspi-module
SRCS ${SOURCE_FILES}
INCLUDE_DIRS include/
REQUIRES TactilityKernel platform-esp32 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.
+9
View File
@@ -0,0 +1,9 @@
# XPT2046 Software SPI Touch Driver
A kernel driver for the `XPT2046` resistive touch controller, bit-banged over plain GPIO pins instead of a hardware SPI peripheral. Use this instead of `xpt2046-module` when no SPI host is free for touch (e.g. both `SPI2_HOST` and `SPI3_HOST` are already claimed by the display and an SD card).
No reset or interrupt pin support (matches the controller's typical wiring: polled, no dedicated IRQ line wired on most panels using it).
See https://grobotronics.com/images/datasheets/xpt2046-datasheet.pdf
License: [Apache v2.0](LICENSE-Apache-2.0.md)
@@ -0,0 +1,52 @@
description: >
XPT2046 resistive touch controller driven over bit-banged (software) SPI on plain GPIO
pins, for boards where no hardware SPI peripheral is available for touch (e.g. both
SPI2_HOST and SPI3_HOST are already claimed by the display and SD card).
compatible: "xptek,xpt2046-softspi"
properties:
pin-mosi:
type: phandles
required: true
description: MOSI (controller-out, peripheral-in) GPIO pin
pin-miso:
type: phandles
required: true
description: MISO (controller-in, peripheral-out) GPIO pin
pin-sck:
type: phandles
required: true
description: Clock GPIO pin
pin-cs:
type: phandles
required: true
description: Chip-select GPIO pin
x-max:
type: int
required: true
description: Maximum X coordinate reported by the controller (typically the panel's horizontal resolution)
y-max:
type: int
required: true
description: Maximum Y coordinate reported by the controller (typically the panel's vertical resolution)
swap-xy:
type: boolean
default: false
description: Swap the X and Y axes
mirror-x:
type: boolean
default: false
description: Mirror the X axis
mirror-y:
type: boolean
default: false
description: Mirror the Y axis
power-supply:
type: boolean
default: false
description: Expose a power-supply device that reports battery voltage/capacity read from the XPT2046's v-bat input
power-supply-reference-voltage-mv:
type: int
default: 4200
description: Battery voltage (in mV) considered 100% capacity, used to compute POWER_SUPPLY_PROP_CAPACITY
@@ -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/xpt2046_softspi.h>
DEFINE_DEVICETREE(xpt2046_softspi, struct Xpt2046SoftSpiConfig)
@@ -0,0 +1,31 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stdbool.h>
#include <tactility/drivers/gpio.h>
struct Xpt2046SoftSpiConfig {
struct GpioPinSpec pin_mosi;
struct GpioPinSpec pin_miso;
struct GpioPinSpec pin_sck;
struct GpioPinSpec pin_cs;
uint16_t x_max;
uint16_t y_max;
bool swap_xy;
bool mirror_x;
bool mirror_y;
/** Expose a power-supply child device that reads battery voltage/capacity off the chip's v-bat input */
bool power_supply;
/** Battery voltage (mV) considered 100% capacity, used to derive POWER_SUPPLY_PROP_CAPACITY */
uint32_t power_supply_reference_voltage_mv;
};
#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 xpt2046_softspi_module;
#ifdef __cplusplus
}
#endif
@@ -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 xpt2046_softspi_driver;
extern Driver xpt2046_softspi_power_supply_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(&xpt2046_softspi_driver) == ERROR_NONE);
check(driver_construct_add(&xpt2046_softspi_power_supply_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(&xpt2046_softspi_power_supply_driver) == ERROR_NONE);
check(driver_remove_destruct(&xpt2046_softspi_driver) == ERROR_NONE);
return ERROR_NONE;
}
Module xpt2046_softspi_module = {
.name = "xpt2046_softspi",
.start = start,
.stop = stop,
.symbols = nullptr,
.internal = nullptr
};
} // extern "C"
@@ -0,0 +1,444 @@
// SPDX-License-Identifier: Apache-2.0
#include <drivers/xpt2046_softspi.h>
#include <xpt2046_softspi_module.h>
#include <tactility/check.h>
#include <tactility/device.h>
#include <tactility/driver.h>
#include <tactility/drivers/gpio_controller.h>
#include <tactility/drivers/pointer.h>
#include <tactility/drivers/power_supply.h>
#include <tactility/delay.h>
#include <tactility/error.h>
#include <tactility/log.h>
#include <cstdlib>
#include <new>
#define TAG "XPT2046SoftSPI"
#define GET_CONFIG(device) (static_cast<const Xpt2046SoftSpiConfig*>((device)->config))
// Rough LiPo discharge curve floor, used together with the configured reference voltage
// (the 100% point) to estimate a charge percentage from the sensed v-bat voltage.
#define POWER_SUPPLY_MIN_MV 3200
namespace {
constexpr uint8_t CMD_READ_X = 0xD0;
constexpr uint8_t CMD_READ_Y = 0x90;
// BATTERY register (start=1, addr=010, 12-bit mode, single-ended, PD1=0/PD0=1 i.e. IRQ disabled
// between conversions), same encoding as the hardware-SPI XPT2046 driver's default mode.
constexpr uint8_t CMD_READ_BATTERY = 0xA7;
constexpr int RAW_MIN_DEFAULT = 100;
constexpr int RAW_MAX_DEFAULT = 1900;
constexpr int RAW_VALID_MIN = 100;
constexpr int RAW_VALID_MAX = 3900;
constexpr int SAMPLE_COUNT = 8;
} // namespace
struct Xpt2046SoftSpiInternal {
GpioDescriptor* mosi;
GpioDescriptor* miso;
GpioDescriptor* sck;
GpioDescriptor* cs;
bool swap_xy;
bool mirror_x;
bool mirror_y;
bool touched;
uint16_t x;
uint16_t y;
Device* power_supply_device;
};
static error_t create_power_supply_child(Device* parent, Device*& out_child);
static void destroy_power_supply_child(Device* child);
// region Driver lifecycle
static void release_descriptors(Xpt2046SoftSpiInternal* internal) {
if (internal->mosi != nullptr) gpio_descriptor_release(internal->mosi);
if (internal->miso != nullptr) gpio_descriptor_release(internal->miso);
if (internal->sck != nullptr) gpio_descriptor_release(internal->sck);
if (internal->cs != nullptr) gpio_descriptor_release(internal->cs);
}
static error_t start(Device* device) {
const auto* config = GET_CONFIG(device);
auto* internal = static_cast<Xpt2046SoftSpiInternal*>(malloc(sizeof(Xpt2046SoftSpiInternal)));
if (internal == nullptr) {
return ERROR_OUT_OF_MEMORY;
}
*internal = {};
internal->mosi = gpio_descriptor_acquire(config->pin_mosi.gpio_controller, config->pin_mosi.pin, GPIO_OWNER_GPIO);
internal->miso = gpio_descriptor_acquire(config->pin_miso.gpio_controller, config->pin_miso.pin, GPIO_OWNER_GPIO);
internal->sck = gpio_descriptor_acquire(config->pin_sck.gpio_controller, config->pin_sck.pin, GPIO_OWNER_GPIO);
internal->cs = gpio_descriptor_acquire(config->pin_cs.gpio_controller, config->pin_cs.pin, GPIO_OWNER_GPIO);
if (internal->mosi == nullptr || internal->miso == nullptr || internal->sck == nullptr || internal->cs == nullptr) {
LOG_E(TAG, "Failed to acquire GPIO descriptors");
release_descriptors(internal);
free(internal);
return ERROR_RESOURCE;
}
bool ok =
gpio_descriptor_set_flags(internal->mosi, GPIO_FLAG_DIRECTION_OUTPUT) == ERROR_NONE &&
gpio_descriptor_set_flags(internal->sck, GPIO_FLAG_DIRECTION_OUTPUT) == ERROR_NONE &&
gpio_descriptor_set_flags(internal->cs, GPIO_FLAG_DIRECTION_OUTPUT) == ERROR_NONE &&
gpio_descriptor_set_flags(internal->miso, GPIO_FLAG_DIRECTION_INPUT | GPIO_FLAG_PULL_UP) == ERROR_NONE;
// Idle state: CS high (deselected), SCK/MOSI low.
ok = ok &&
gpio_descriptor_set_level(internal->cs, true) == ERROR_NONE &&
gpio_descriptor_set_level(internal->sck, false) == ERROR_NONE &&
gpio_descriptor_set_level(internal->mosi, false) == ERROR_NONE;
if (!ok) {
LOG_E(TAG, "Failed to configure GPIO pins");
release_descriptors(internal);
free(internal);
return ERROR_RESOURCE;
}
internal->swap_xy = config->swap_xy;
internal->mirror_x = config->mirror_x;
internal->mirror_y = config->mirror_y;
device_set_driver_data(device, internal);
if (config->power_supply) {
error_t error = create_power_supply_child(device, internal->power_supply_device);
if (error != ERROR_NONE) {
LOG_E(TAG, "Failed to create power-supply device");
release_descriptors(internal);
free(internal);
return error;
}
}
return ERROR_NONE;
}
static error_t stop(Device* device) {
auto* internal = static_cast<Xpt2046SoftSpiInternal*>(device_get_driver_data(device));
if (internal->power_supply_device != nullptr) {
destroy_power_supply_child(internal->power_supply_device);
}
release_descriptors(internal);
free(internal);
return ERROR_NONE;
}
// endregion
// region Bit-banged SPI
// XPT2046 protocol: 8-bit command out, 12-bit conversion result back (MSB first), clocked
// manually since no hardware SPI peripheral is available for this pin set (see the binding's
// description). 1us clock half-period is well within the XPT2046's timing budget (it's rated
// for a multi-MHz SPI clock; this bit-bang loop runs orders of magnitude slower).
static int read_spi_command(Xpt2046SoftSpiInternal* internal, uint8_t command) {
int result = 0;
gpio_descriptor_set_level(internal->cs, false);
delay_micros(1);
for (int i = 7; i >= 0; i--) {
gpio_descriptor_set_level(internal->mosi, (command & (1 << i)) != 0);
gpio_descriptor_set_level(internal->sck, true);
delay_micros(1);
gpio_descriptor_set_level(internal->sck, false);
delay_micros(1);
}
for (int i = 11; i >= 0; i--) {
gpio_descriptor_set_level(internal->sck, true);
delay_micros(1);
bool level = false;
gpio_descriptor_get_level(internal->miso, &level);
if (level) {
result |= (1 << i);
}
gpio_descriptor_set_level(internal->sck, false);
delay_micros(1);
}
gpio_descriptor_set_level(internal->cs, true);
return result;
}
// endregion
// region Power supply
// The v-bat reading is noisy (bit-banged SPI, no dedicated sample/hold), so it's smoothed by
// averaging over several samples rather than trusting a single conversion.
#define POWER_SUPPLY_SAMPLE_COUNT 20
// Same scaling as the hardware-SPI XPT2046 driver's esp_lcd_touch_xpt2046_read_battery_level():
// the chip halves the v-bat voltage internally, and the raw code is relative to its internal
// 2.507V reference over 12 bits.
static int read_battery_mv(Xpt2046SoftSpiInternal* internal) {
int64_t raw_sum = 0;
for (int i = 0; i < POWER_SUPPLY_SAMPLE_COUNT; i++) {
raw_sum += read_spi_command(internal, CMD_READ_BATTERY);
}
int64_t raw_avg = raw_sum / POWER_SUPPLY_SAMPLE_COUNT;
return (int)((raw_avg * 4 * 2507) / 4096);
}
static bool ps_supports_property(Device*, PowerSupplyProperty property) {
return property == POWER_SUPPLY_PROP_VOLTAGE || property == POWER_SUPPLY_PROP_CAPACITY;
}
static int estimate_capacity_from_mv(int battery_mv, uint32_t reference_mv) {
if (battery_mv <= POWER_SUPPLY_MIN_MV) return 0;
if ((uint32_t)battery_mv >= reference_mv) return 100;
return (battery_mv - POWER_SUPPLY_MIN_MV) * 100 / ((int)reference_mv - POWER_SUPPLY_MIN_MV);
}
static error_t ps_get_property(Device* device, PowerSupplyProperty property, PowerSupplyPropertyValue* out_value) {
if (property != POWER_SUPPLY_PROP_VOLTAGE && property != POWER_SUPPLY_PROP_CAPACITY) {
return ERROR_NOT_SUPPORTED;
}
auto* parent = device_get_parent(device);
const auto* parent_config = GET_CONFIG(parent);
auto* parent_internal = static_cast<Xpt2046SoftSpiInternal*>(device_get_driver_data(parent));
int battery_mv = read_battery_mv(parent_internal);
out_value->int_value = (property == POWER_SUPPLY_PROP_VOLTAGE) ? battery_mv : estimate_capacity_from_mv(battery_mv, parent_config->power_supply_reference_voltage_mv);
return ERROR_NONE;
}
static bool ps_supports_charge_control(Device*) { return false; }
static bool ps_is_allowed_to_charge(Device*) { return false; }
static error_t ps_set_allowed_to_charge(Device*, bool) { return ERROR_NOT_SUPPORTED; }
static bool ps_supports_quick_charge(Device*) { return false; }
static bool ps_is_quick_charge_enabled(Device*) { return false; }
static error_t ps_set_quick_charge_enabled(Device*, bool) { return ERROR_NOT_SUPPORTED; }
static bool ps_supports_power_off(Device*) { return false; }
static error_t ps_power_off(Device*) { return ERROR_NOT_SUPPORTED; }
static constexpr PowerSupplyApi XPT2046_SOFTSPI_POWER_SUPPLY_API = {
.supports_property = ps_supports_property,
.get_property = ps_get_property,
.supports_charge_control = ps_supports_charge_control,
.is_allowed_to_charge = ps_is_allowed_to_charge,
.set_allowed_to_charge = ps_set_allowed_to_charge,
.supports_quick_charge = ps_supports_quick_charge,
.is_quick_charge_enabled = ps_is_quick_charge_enabled,
.set_quick_charge_enabled = ps_set_quick_charge_enabled,
.supports_power_off = ps_supports_power_off,
.power_off = ps_power_off,
};
// Registered (driver_construct_add() in module.cpp) so driver_bind() has a valid ->internal,
// but never matched against a devicetree node: xpt2046_softspi wires it up directly by pointer.
Driver xpt2046_softspi_power_supply_driver = {
.name = "xpt2046-softspi-power-supply",
.compatible = (const char*[]) { "xpt2046-softspi-power-supply", nullptr },
.start_device = nullptr,
.stop_device = nullptr,
.api = &XPT2046_SOFTSPI_POWER_SUPPLY_API,
.device_type = &POWER_SUPPLY_TYPE,
.owner = &xpt2046_softspi_module,
.internal = nullptr
};
static error_t create_power_supply_child(Device* parent, Device*& out_child) {
auto* child = new(std::nothrow) Device { .address = 0, .name = "xpt2046-softspi-power-supply", .config = nullptr, .parent = nullptr, .internal = nullptr };
if (child == nullptr) {
return ERROR_OUT_OF_MEMORY;
}
error_t error = device_construct(child);
if (error != ERROR_NONE) {
delete child;
return error;
}
device_set_parent(child, parent);
device_set_driver(child, &xpt2046_softspi_power_supply_driver);
error = device_add(child);
if (error != ERROR_NONE) {
device_destruct(child);
delete child;
return error;
}
error = device_start(child);
if (error != ERROR_NONE) {
device_remove(child);
device_destruct(child);
delete child;
return error;
}
out_child = child;
return ERROR_NONE;
}
static void destroy_power_supply_child(Device* child) {
check(device_stop(child) == ERROR_NONE);
check(device_remove(child) == ERROR_NONE);
check(device_destruct(child) == ERROR_NONE);
delete child;
}
// endregion
// region PointerApi
static error_t xpt2046_softspi_enter_sleep(Device*) {
// No software-controlled power-down for this bit-banged variant; nothing to do.
return ERROR_NONE;
}
static error_t xpt2046_softspi_exit_sleep(Device*) {
return ERROR_NONE;
}
// Takes and averages several raw samples (rejecting out-of-range noise) then maps them onto
// [0, x_max]/[0, y_max], applying swap/mirror. Mirrors the deprecated HAL's Xpt2046SoftSpi driver.
static error_t xpt2046_softspi_read_data(Device* device, TickType_t timeout) {
(void)timeout;
auto* internal = static_cast<Xpt2046SoftSpiInternal*>(device_get_driver_data(device));
const auto* config = GET_CONFIG(device);
int total_x = 0;
int total_y = 0;
int valid_samples = 0;
for (int i = 0; i < SAMPLE_COUNT; i++) {
const int raw_x = read_spi_command(internal, CMD_READ_X);
const int raw_y = read_spi_command(internal, CMD_READ_Y);
if (raw_x > RAW_VALID_MIN && raw_x < RAW_VALID_MAX && raw_y > RAW_VALID_MIN && raw_y < RAW_VALID_MAX) {
total_x += raw_x;
total_y += raw_y;
valid_samples++;
}
delay_millis(1);
}
if (valid_samples < 3) {
internal->touched = false;
return ERROR_NONE;
}
const int raw_x = total_x / valid_samples;
const int raw_y = total_y / valid_samples;
int mapped_x = (raw_x - RAW_MIN_DEFAULT) * static_cast<int>(config->x_max) / (RAW_MAX_DEFAULT - RAW_MIN_DEFAULT);
int mapped_y = (raw_y - RAW_MIN_DEFAULT) * static_cast<int>(config->y_max) / (RAW_MAX_DEFAULT - RAW_MIN_DEFAULT);
if (internal->swap_xy) {
const int swapped = mapped_x;
mapped_x = mapped_y;
mapped_y = swapped;
}
if (internal->mirror_x) {
mapped_x = static_cast<int>(config->x_max) - mapped_x;
}
if (internal->mirror_y) {
mapped_y = static_cast<int>(config->y_max) - mapped_y;
}
if (mapped_x < 0) mapped_x = 0;
if (mapped_x > static_cast<int>(config->x_max)) mapped_x = static_cast<int>(config->x_max);
if (mapped_y < 0) mapped_y = 0;
if (mapped_y > static_cast<int>(config->y_max)) mapped_y = static_cast<int>(config->y_max);
internal->x = static_cast<uint16_t>(mapped_x);
internal->y = static_cast<uint16_t>(mapped_y);
internal->touched = true;
return ERROR_NONE;
}
static bool xpt2046_softspi_get_touched_points(Device* device, uint16_t* x, uint16_t* y, uint16_t* strength, uint8_t* point_count, uint8_t max_point_count) {
(void)strength;
auto* internal = static_cast<Xpt2046SoftSpiInternal*>(device_get_driver_data(device));
if (!internal->touched || max_point_count < 1) {
*point_count = 0;
return false;
}
*x = internal->x;
*y = internal->y;
*point_count = 1;
return true;
}
static error_t xpt2046_softspi_set_swap_xy(Device* device, bool swap) {
auto* internal = static_cast<Xpt2046SoftSpiInternal*>(device_get_driver_data(device));
internal->swap_xy = swap;
return ERROR_NONE;
}
static error_t xpt2046_softspi_get_swap_xy(Device* device, bool* swap) {
auto* internal = static_cast<Xpt2046SoftSpiInternal*>(device_get_driver_data(device));
*swap = internal->swap_xy;
return ERROR_NONE;
}
static error_t xpt2046_softspi_set_mirror_x(Device* device, bool mirror) {
auto* internal = static_cast<Xpt2046SoftSpiInternal*>(device_get_driver_data(device));
internal->mirror_x = mirror;
return ERROR_NONE;
}
static error_t xpt2046_softspi_get_mirror_x(Device* device, bool* mirror) {
auto* internal = static_cast<Xpt2046SoftSpiInternal*>(device_get_driver_data(device));
*mirror = internal->mirror_x;
return ERROR_NONE;
}
static error_t xpt2046_softspi_set_mirror_y(Device* device, bool mirror) {
auto* internal = static_cast<Xpt2046SoftSpiInternal*>(device_get_driver_data(device));
internal->mirror_y = mirror;
return ERROR_NONE;
}
static error_t xpt2046_softspi_get_mirror_y(Device* device, bool* mirror) {
auto* internal = static_cast<Xpt2046SoftSpiInternal*>(device_get_driver_data(device));
*mirror = internal->mirror_y;
return ERROR_NONE;
}
// endregion
static const PointerApi xpt2046_softspi_pointer_api = {
.enter_sleep = xpt2046_softspi_enter_sleep,
.exit_sleep = xpt2046_softspi_exit_sleep,
.read_data = xpt2046_softspi_read_data,
.get_touched_points = xpt2046_softspi_get_touched_points,
.set_swap_xy = xpt2046_softspi_set_swap_xy,
.get_swap_xy = xpt2046_softspi_get_swap_xy,
.set_mirror_x = xpt2046_softspi_set_mirror_x,
.get_mirror_x = xpt2046_softspi_get_mirror_x,
.set_mirror_y = xpt2046_softspi_set_mirror_y,
.get_mirror_y = xpt2046_softspi_get_mirror_y,
};
Driver xpt2046_softspi_driver = {
.name = "xpt2046_softspi",
.compatible = (const char*[]) { "xptek,xpt2046-softspi", nullptr },
.start_device = start,
.stop_device = stop,
.api = &xpt2046_softspi_pointer_api,
.device_type = &POINTER_TYPE,
.owner = &xpt2046_softspi_module,
.internal = nullptr
};