Remove old HAL components and refactored GPS-related code (#583)

- Added generic GPS/GNSS support with device detection, configuration, and persistent settings.
- Improved device and module lifecycle management.
- Added flexible filesystem locking support for displays and storage.
- Improved display-idle and keyboard backlight handling.
- Updated architecture, driver, module, testing, and licensing documentation.
- Removed old HAL device and related code.
This commit is contained in:
Ken Van Hoeylandt
2026-07-25 17:20:17 +02:00
committed by GitHub
parent 29e80cfd65
commit 2a2558b29a
173 changed files with 3855 additions and 5445 deletions
+2 -8
View File
@@ -19,14 +19,8 @@ jobs:
run: cmake -S ./ -B build run: cmake -S ./ -B build
- name: "Build Tests" - name: "Build Tests"
run: cmake --build build --target build-tests run: cmake --build build --target build-tests
- name: "Run TactilityFreeRtos Tests" - name: "Run Tests"
run: build/Tests/TactilityFreeRtos/TactilityFreeRtosTests run: ctest --test-dir build/Tests
- name: "Run Tactility Tests"
run: build/Tests/Tactility/TactilityTests
- name: "Run TactilityKernel Tests"
run: build/Tests/TactilityKernel/TactilityKernelTests
- name: "Run CryptModuleTests Tests"
run: build/Tests/crypt-module/CryptModuleTests
DevicetreeTests: DevicetreeTests:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
@@ -26,7 +26,7 @@ def get_device_node_name_safe(device: Device):
def get_device_type_name(device: Device, bindings: list[Binding]): def get_device_type_name(device: Device, bindings: list[Binding]):
device_binding = find_device_binding(device, bindings) device_binding = find_device_binding(device, bindings)
if device_binding is None: if device_binding is None:
raise DevicetreeException(f"Binding not found for {device.node_name}") raise DevicetreeException(f"Binding not found for {device.node_name}. Make sure that the driver name in the driver's yaml and driver code declarations matches with the device dts file.")
if device_binding.compatible is None: if device_binding.compatible is None:
raise DevicetreeException(f"Couldn't find compatible binding for {device.node_name}") raise DevicetreeException(f"Couldn't find compatible binding for {device.node_name}")
compatible_safe = device_binding.compatible.split(",")[-1] compatible_safe = device_binding.compatible.split(",")[-1]
@@ -282,6 +282,7 @@ def write_device_structs(file, device: Device, parent_device: Device, bindings:
file.write(f"\t.address = {address_value},\n") file.write(f"\t.address = {address_value},\n")
file.write(f"\t.name = \"{device.node_name}\",\n") # Use original name file.write(f"\t.name = \"{device.node_name}\",\n") # Use original name
file.write(f"\t.config = &{config_variable_name},\n") file.write(f"\t.config = &{config_variable_name},\n")
file.write("\t.flags = DEVICE_FLAG_DTS,\n")
file.write(f"\t.parent = {parent_value},\n") file.write(f"\t.parent = {parent_value},\n")
file.write("\t.internal = NULL\n") file.write("\t.internal = NULL\n")
file.write("};\n\n") file.write("};\n\n")
@@ -13,6 +13,7 @@ static struct Device root = {
.address = 0, .address = 0,
.name = "/", .name = "/",
.config = &root_config, .config = &root_config,
.flags = DEVICE_FLAG_DTS,
.parent = NULL, .parent = NULL,
.internal = NULL .internal = NULL
}; };
@@ -27,6 +28,7 @@ static struct Device test_device = {
.address = 0, .address = 0,
.name = "test-device", .name = "test-device",
.config = &test_device_config, .config = &test_device_config,
.flags = DEVICE_FLAG_DTS,
.parent = &root, .parent = &root,
.internal = NULL .internal = NULL
}; };
@@ -43,6 +45,7 @@ static struct Device bool_test_device = {
.address = 0, .address = 0,
.name = "bool-test-device", .name = "bool-test-device",
.config = &bool_test_device_config, .config = &bool_test_device_config,
.flags = DEVICE_FLAG_DTS,
.parent = &root, .parent = &root,
.internal = NULL .internal = NULL
}; };
+2 -1
View File
@@ -96,9 +96,10 @@ if (NOT DEFINED ENV{ESP_IDF_VERSION})
add_subdirectory(Libraries/QRCode) add_subdirectory(Libraries/QRCode)
add_subdirectory(Libraries/minitar) add_subdirectory(Libraries/minitar)
add_subdirectory(Libraries/minmea) add_subdirectory(Libraries/minmea)
add_subdirectory(Modules/hal-device-module)
add_subdirectory(Modules/lvgl-module) add_subdirectory(Modules/lvgl-module)
add_subdirectory(Modules/crypt-module) add_subdirectory(Modules/crypt-module)
add_subdirectory(Modules/gps-module)
add_subdirectory(Drivers/gps-generic-module)
# FreeRTOS # FreeRTOS
set(FREERTOS_CONFIG_FILE_DIRECTORY ${PROJECT_SOURCE_DIR}/Devices/simulator/Source CACHE STRING "") set(FREERTOS_CONFIG_FILE_DIRECTORY ${PROJECT_SOURCE_DIR}/Devices/simulator/Source CACHE STRING "")
@@ -1,5 +1,6 @@
dependencies: dependencies:
- Platforms/platform-esp32 - Platforms/platform-esp32
- Drivers/gps-generic-module
- Drivers/st7789-module - Drivers/st7789-module
- Drivers/gt911-module - Drivers/gt911-module
- Drivers/lilygo-module - Drivers/lilygo-module
@@ -20,6 +20,8 @@
#include <bindings/es7210.h> #include <bindings/es7210.h>
#include <bindings/dummy_i2s_amp.h> #include <bindings/dummy_i2s_amp.h>
#include <gps_generic/bindings.h>
#include <lilygo/bindings/tdeck_keyboard.h> #include <lilygo/bindings/tdeck_keyboard.h>
#include <lilygo/bindings/tdeck_keyboard_backlight.h> #include <lilygo/bindings/tdeck_keyboard_backlight.h>
#include <lilygo/bindings/tdeck_trackball.h> #include <lilygo/bindings/tdeck_trackball.h>
@@ -188,5 +190,12 @@
port = <UART_NUM_1>; port = <UART_NUM_1>;
pin-tx = <&gpio0 43 GPIO_FLAG_NONE>; pin-tx = <&gpio0 43 GPIO_FLAG_NONE>;
pin-rx = <&gpio0 44 GPIO_FLAG_NONE>; pin-rx = <&gpio0 44 GPIO_FLAG_NONE>;
gps {
compatible = "tactility,gps-generic";
status = "disabled";
baud-rate = <38400>;
model = <GPS_MODEL_UBLOX10>;
};
}; };
}; };
+22 -42
View File
@@ -1,75 +1,57 @@
#include <tactility/module.h> #include <tactility/delay.h>
#include <tactility/error.h> #include <tactility/error.h>
#include <tactility/log.h> #include <tactility/log.h>
#include <tactility/lvgl_module.h> #include <tactility/lvgl_module.h>
#include <tactility/module.h>
#include <Tactility/SystemEvents.h> #include <Tactility/SystemEvents.h>
#include <Tactility/LogMessages.h> #include <Tactility/LogMessages.h>
#include <Tactility/hal/Configuration.h>
#include <Tactility/hal/gps/GpsConfiguration.h>
#include <Tactility/kernel/Kernel.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/service/gps/GpsService.h>
#include <Tactility/settings/TrackballSettings.h> #include <Tactility/settings/TrackballSettings.h>
#include <lilygo/drivers/trackball.h> #include <lilygo/drivers/trackball.h>
#include <lilygo/drivers/tdeck_power_on.h> #include <lilygo/drivers/tdeck_power_on.h>
#include <driver/gpio.h>
constexpr auto* TAG = "tdeck-plus"; constexpr auto* TAG = "tdeck-plus";
extern "C" { extern "C" {
void subscribe_events() { static tt::kernel::SystemEventSubscription tdeck_boot_splash_subscription = tt::kernel::NoSystemEventSubscription;
tt::kernel::subscribeSystemEvent(tt::kernel::SystemEvent::BootSplash, [](tt::kernel::SystemEvent event) {
auto gps_service = tt::service::gps::findGpsService();
if (gps_service != nullptr) {
std::vector<tt::hal::gps::GpsConfiguration> gps_configurations;
gps_service->getGpsConfigurations(gps_configurations);
if (gps_configurations.empty()) {
if (gps_service->addGpsConfiguration(tt::hal::gps::GpsConfiguration {.uartName = "uart0", .baudRate = 38400, .model = tt::hal::gps::GpsModel::UBLOX10})) {
LOG_I(TAG, "Configured internal GPS");
} else {
LOG_E(TAG, "Failed to configure internal GPS");
}
}
}
});
// The kernel trackball device is already started by kernel_init(); this just registers it as an void init_trackball() {
// LVGL input device and applies persisted settings, both of which require LVGL to be up first. auto tbSettings = tt::settings::trackball::loadOrGetDefault();
tt::kernel::subscribeSystemEvent(tt::kernel::SystemEvent::BootSplash, [](tt::kernel::SystemEvent event) { lvgl_lock();
auto tbSettings = tt::settings::trackball::loadOrGetDefault(); if (trackball::init() != nullptr) {
lvgl_lock(); trackball::setMode(tbSettings.trackballMode == tt::settings::trackball::TrackballMode::Pointer
if (trackball::init() != nullptr) { ? trackball::Mode::Pointer
trackball::setMode(tbSettings.trackballMode == tt::settings::trackball::TrackballMode::Pointer : trackball::Mode::Encoder);
? trackball::Mode::Pointer trackball::setEncoderSensitivity(tbSettings.encoderSensitivity);
: trackball::Mode::Encoder); trackball::setPointerSensitivity(tbSettings.pointerSensitivity);
trackball::setEncoderSensitivity(tbSettings.encoderSensitivity); trackball::setEnabled(tbSettings.trackballEnabled);
trackball::setPointerSensitivity(tbSettings.pointerSensitivity); }
trackball::setEnabled(tbSettings.trackballEnabled); lvgl_unlock();
}
lvgl_unlock();
});
} }
static error_t start() { static error_t start() {
LOG_I(TAG, LOG_MESSAGE_POWER_ON_START); LOG_I(TAG, LOG_MESSAGE_POWER_ON_START);
if (!tdeck_power_on()) { if (!tdeck_power_on()) {
LOG_E(TAG, LOG_MESSAGE_POWER_ON_FAILED); LOG_E(TAG, LOG_MESSAGE_POWER_ON_FAILED);
return ERROR_RESOURCE; return ERROR_RESOURCE;
} }
// Avoids crash when no SD card is inserted. It's unknown why, but likely is related to power draw. // Avoids crash when no SD card is inserted. It's unknown why, but likely is related to power draw.
tt::kernel::delayMillis(100); delay_millis(100);
subscribe_events(); tdeck_boot_splash_subscription = tt::kernel::subscribeSystemEvent(tt::kernel::SystemEvent::BootSplash, [](tt::kernel::SystemEvent event) {
init_trackball();
});
return ERROR_NONE; return ERROR_NONE;
} }
static error_t stop() { static error_t stop() {
tt::kernel::unsubscribeSystemEvent(tdeck_boot_splash_subscription);
tdeck_boot_splash_subscription = tt::kernel::NoSystemEventSubscription;
return ERROR_NONE; return ERROR_NONE;
} }
@@ -77,8 +59,6 @@ Module lilygo_tdeck_plus_module = {
.name = "lilygo-tdeck-plus", .name = "lilygo-tdeck-plus",
.start = start, .start = start,
.stop = stop, .stop = stop,
.symbols = nullptr,
.internal = nullptr
}; };
} }
+2 -5
View File
@@ -1,20 +1,17 @@
#include <tactility/module.h> #include <tactility/module.h>
#include "lilygo/drivers/tdeck_power_on.h"
#include "tactility/lvgl_module.h"
#include <tactility/error.h> #include <tactility/error.h>
#include <tactility/log.h> #include <tactility/log.h>
#include <tactility/lvgl_module.h>
#include <Tactility/SystemEvents.h> #include <Tactility/SystemEvents.h>
#include <Tactility/LogMessages.h> #include <Tactility/LogMessages.h>
#include <Tactility/hal/Configuration.h>
#include <Tactility/kernel/Kernel.h> #include <Tactility/kernel/Kernel.h>
#include <Tactility/lvgl/LvglSync.h> #include <Tactility/lvgl/LvglSync.h>
#include <Tactility/service/gps/GpsService.h>
#include <Tactility/settings/TrackballSettings.h> #include <Tactility/settings/TrackballSettings.h>
#include <lilygo/drivers/trackball.h> #include <lilygo/drivers/trackball.h>
#include <lilygo/drivers/tdeck_power_on.h>
constexpr auto* TAG = "tdeck"; constexpr auto* TAG = "tdeck";
@@ -1,5 +1,6 @@
dependencies: dependencies:
- Platforms/platform-esp32 - Platforms/platform-esp32
- Drivers/gps-generic-module
- Drivers/st7796-module - Drivers/st7796-module
- Drivers/bq27220-module - Drivers/bq27220-module
- Drivers/tca8418-module - Drivers/tca8418-module
@@ -11,6 +11,7 @@
#include <tactility/bindings/esp32_sdspi.h> #include <tactility/bindings/esp32_sdspi.h>
#include <tactility/bindings/esp32_pwm_ledc.h> #include <tactility/bindings/esp32_pwm_ledc.h>
#include <tactility/bindings/pwm_backlight.h> #include <tactility/bindings/pwm_backlight.h>
#include <gps_generic/bindings.h>
#include <bindings/st7796.h> #include <bindings/st7796.h>
#include <bindings/bq27220.h> #include <bindings/bq27220.h>
#include <bindings/tca8418.h> #include <bindings/tca8418.h>
@@ -181,6 +182,13 @@
port = <UART_NUM_0>; port = <UART_NUM_0>;
pin-tx = <&gpio0 12 GPIO_FLAG_NONE>; pin-tx = <&gpio0 12 GPIO_FLAG_NONE>;
pin-rx = <&gpio0 4 GPIO_FLAG_NONE>; pin-rx = <&gpio0 4 GPIO_FLAG_NONE>;
gps {
compatible = "tactility,gps-generic";
status = "disabled";
baud-rate = <38400>;
model = <GPS_MODEL_UBLOX10>;
};
}; };
uart_external: uart1 { uart_external: uart1 {
+3 -29
View File
@@ -1,15 +1,8 @@
#include <tactility/check.h> #include <tactility/lvgl_module.h>
#include <tactility/driver.h>
#include <tactility/module.h> #include <tactility/module.h>
#include <Tactility/LogMessages.h>
#include <Tactility/SystemEvents.h> #include <Tactility/SystemEvents.h>
#include <Tactility/hal/Configuration.h>
#include <Tactility/hal/gps/GpsConfiguration.h>
#include <Tactility/kernel/Kernel.h> #include <Tactility/kernel/Kernel.h>
#include <Tactility/service/gps/GpsService.h>
#include <tactility/log.h>
#include <tactility/lvgl_module.h>
#include <lilygo/drivers/tpager_encoder_input.h> #include <lilygo/drivers/tpager_encoder_input.h>
@@ -17,41 +10,22 @@ constexpr auto* TAG = "T-Lora Pager";
extern "C" { extern "C" {
tt::kernel::SystemEventSubscription event_subscription; tt::kernel::SystemEventSubscription event_subscription = tt::kernel::NoSystemEventSubscription;
static error_t start() { static error_t start() {
LOG_I(TAG, LOG_MESSAGE_POWER_ON_START);
event_subscription = tt::kernel::subscribeSystemEvent(tt::kernel::SystemEvent::BootSplash, [](tt::kernel::SystemEvent) { event_subscription = tt::kernel::subscribeSystemEvent(tt::kernel::SystemEvent::BootSplash, [](tt::kernel::SystemEvent) {
// The kernel tpager_encoder device is already started by kernel_init(); this just // The kernel tpager_encoder device is already started by kernel_init(); this just
// registers it as an LVGL input device, which requires LVGL to be up first. // registers it as an LVGL input device, which requires LVGL to be up first.
lvgl_lock(); lvgl_lock();
tpager_encoder::init(); tpager_encoder::init();
lvgl_unlock(); lvgl_unlock();
auto gps_service = tt::service::gps::findGpsService();
if (gps_service != nullptr) {
std::vector<tt::hal::gps::GpsConfiguration> gps_configurations;
gps_service->getGpsConfigurations(gps_configurations);
if (gps_configurations.empty()) {
if (gps_service->addGpsConfiguration(tt::hal::gps::GpsConfiguration {
.uartName = "uart0",
.baudRate = 38400,
.model = tt::hal::gps::GpsModel::UBLOX10
})) {
LOG_I(TAG, "Configured internal GPS");
} else {
LOG_E(TAG, "Failed to configure internal GPS");
}
}
}
}); });
return ERROR_NONE; return ERROR_NONE;
} }
static error_t stop() { static error_t stop() {
tt::kernel::unsubscribeSystemEvent(event_subscription); tt::kernel::unsubscribeSystemEvent(event_subscription);
event_subscription = tt::kernel::NoSystemEventSubscription;
return ERROR_NONE; return ERROR_NONE;
} }
-1
View File
@@ -1,6 +1,5 @@
#include "Main.h" #include "Main.h"
#include <Tactility/Thread.h> #include <Tactility/Thread.h>
#include <Tactility/TactilityCore.h>
#include "FreeRTOS.h" #include "FreeRTOS.h"
#include "task.h" #include "task.h"
-22
View File
@@ -1,22 +0,0 @@
#include "hal/SdlDisplay.h"
#include "hal/SdlKeyboard.h"
#include "hal/SimulatorPower.h"
#include <Tactility/hal/Configuration.h>
#define TAG "hardware"
using namespace tt::hal;
static std::vector<std::shared_ptr<tt::hal::Device>> createDevices() {
return {
std::make_shared<SdlDisplay>(),
std::make_shared<SdlKeyboard>(),
std::make_shared<SimulatorPower>(),
};
}
extern const Configuration hardwareConfiguration = {
.initBoot = nullptr,
.createDevices = createDevices
};
@@ -0,0 +1,160 @@
// SPDX-License-Identifier: Apache-2.0
#include "sdl_display.h"
#include <tactility/device.h>
#include <tactility/driver.h>
#include <tactility/drivers/display.h>
#include <tactility/log.h>
#include <tactility/module.h>
#include <SDL2/SDL.h>
#include <cstdlib>
constexpr auto* TAG = "SdlDisplay";
#define GET_CONFIG(device) (static_cast<const SdlDisplayConfig*>((device)->config))
struct SdlDisplayInternal {
SDL_Window* window;
SDL_Renderer* renderer;
SDL_Texture* texture;
};
// region Driver lifecycle
static error_t start(Device* device) {
const auto* config = GET_CONFIG(device);
auto* internal = static_cast<SdlDisplayInternal*>(malloc(sizeof(SdlDisplayInternal)));
if (internal == nullptr) {
return ERROR_OUT_OF_MEMORY;
}
if (SDL_InitSubSystem(SDL_INIT_VIDEO) != 0) {
LOG_E(TAG, "SDL_InitSubSystem failed: %s", SDL_GetError());
free(internal);
return ERROR_RESOURCE;
}
internal->window = SDL_CreateWindow(
"Tactility",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
config->horizontal_resolution, config->vertical_resolution,
SDL_WINDOW_SHOWN
);
internal->renderer = internal->window != nullptr
? SDL_CreateRenderer(internal->window, -1, SDL_RENDERER_ACCELERATED)
: nullptr;
internal->texture = internal->renderer != nullptr
? SDL_CreateTexture(internal->renderer, SDL_PIXELFORMAT_RGB565, SDL_TEXTUREACCESS_STREAMING,
config->horizontal_resolution, config->vertical_resolution)
: nullptr;
if (internal->window == nullptr || internal->renderer == nullptr || internal->texture == nullptr) {
LOG_E(TAG, "Failed to create SDL window: %s", SDL_GetError());
if (internal->texture != nullptr) SDL_DestroyTexture(internal->texture);
if (internal->renderer != nullptr) SDL_DestroyRenderer(internal->renderer);
if (internal->window != nullptr) SDL_DestroyWindow(internal->window);
SDL_QuitSubSystem(SDL_INIT_VIDEO);
free(internal);
return ERROR_RESOURCE;
}
device_set_driver_data(device, internal);
return ERROR_NONE;
}
static error_t stop(Device* device) {
auto* internal = static_cast<SdlDisplayInternal*>(device_get_driver_data(device));
SDL_DestroyTexture(internal->texture);
SDL_DestroyRenderer(internal->renderer);
SDL_DestroyWindow(internal->window);
SDL_QuitSubSystem(SDL_INIT_VIDEO);
free(internal);
device_set_driver_data(device, nullptr);
return ERROR_NONE;
}
// endregion
// region DisplayApi
static error_t sdl_display_reset(Device*) { return ERROR_NONE; }
static error_t sdl_display_init(Device*) { return ERROR_NONE; }
static error_t sdl_display_draw_bitmap(Device* device, int32_t x_start, int32_t y_start, int32_t x_end, int32_t y_end, const void* color_data) {
auto* internal = static_cast<SdlDisplayInternal*>(device_get_driver_data(device));
SDL_Rect rect = { x_start, y_start, x_end - x_start, y_end - y_start };
// RGB565 = 2 bytes/pixel.
if (SDL_UpdateTexture(internal->texture, &rect, color_data, (x_end - x_start) * 2) != 0) {
return ERROR_RESOURCE;
}
SDL_RenderClear(internal->renderer);
SDL_RenderCopy(internal->renderer, internal->texture, nullptr, nullptr);
SDL_RenderPresent(internal->renderer);
return ERROR_NONE;
}
static enum DisplayColorFormat sdl_display_get_color_format(Device*) {
return DISPLAY_COLOR_FORMAT_RGB565;
}
static uint16_t sdl_display_get_resolution_x(Device* device) {
return GET_CONFIG(device)->horizontal_resolution;
}
static uint16_t sdl_display_get_resolution_y(Device* device) {
return GET_CONFIG(device)->vertical_resolution;
}
static void sdl_display_get_frame_buffer(Device*, uint8_t, void** out_buffer) {
*out_buffer = nullptr;
}
static uint8_t sdl_display_get_frame_buffer_count(Device*) {
return 0;
}
// endregion
static const DisplayApi sdl_display_api = {
.capabilities = 0,
.reset = sdl_display_reset,
.init = sdl_display_init,
.draw_bitmap = sdl_display_draw_bitmap,
.mirror = nullptr,
.swap_xy = nullptr,
.get_swap_xy = nullptr,
.get_mirror_x = nullptr,
.get_mirror_y = nullptr,
.set_gap = nullptr,
.get_gap_x = nullptr,
.get_gap_y = nullptr,
.invert_color = nullptr,
.disp_on_off = nullptr,
.disp_sleep = nullptr,
.get_color_format = sdl_display_get_color_format,
.get_resolution_x = sdl_display_get_resolution_x,
.get_resolution_y = sdl_display_get_resolution_y,
.get_frame_buffer = sdl_display_get_frame_buffer,
.get_frame_buffer_count = sdl_display_get_frame_buffer_count,
.get_backlight = nullptr,
.has_capability = nullptr,
};
extern Module simulator_module;
Driver sdl_display_driver = {
.name = "sdl-display",
.compatible = (const char*[]) { "tactility,sdl-display", nullptr },
.start_device = start,
.stop_device = stop,
.api = &sdl_display_api,
.device_type = &DISPLAY_TYPE,
.owner = &simulator_module,
.internal = nullptr
};
@@ -0,0 +1,17 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
struct SdlDisplayConfig {
uint16_t horizontal_resolution;
uint16_t vertical_resolution;
};
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,108 @@
// SPDX-License-Identifier: Apache-2.0
#include "sdl_input.h"
#include <lvgl.h>
#include <SDL2/SDL.h>
#include <cstdlib>
namespace {
constexpr size_t KEY_QUEUE_CAPACITY = 32;
SdlPointerState pointer_state = { 0, 0, false };
uint32_t key_queue[KEY_QUEUE_CAPACITY];
size_t key_queue_head = 0;
size_t key_queue_count = 0;
bool text_input_started = false;
void push_key(uint32_t key) {
if (key == 0 || key_queue_count >= KEY_QUEUE_CAPACITY) {
return;
}
key_queue[(key_queue_head + key_queue_count) % KEY_QUEUE_CAPACITY] = key;
key_queue_count++;
}
// Mirrors LVGL's own lv_sdl_keyboard.c keycode_to_ctrl_key(): maps navigation/control keys to
// LV_KEY_* constants. Printable characters arrive separately via SDL_TEXTINPUT.
uint32_t keycode_to_key(SDL_Keycode sdl_key) {
switch (sdl_key) {
case SDLK_RIGHT: return LV_KEY_RIGHT;
case SDLK_LEFT: return LV_KEY_LEFT;
case SDLK_UP: return LV_KEY_UP;
case SDLK_DOWN: return LV_KEY_DOWN;
case SDLK_ESCAPE: return LV_KEY_ESC;
case SDLK_BACKSPACE: return LV_KEY_BACKSPACE;
case SDLK_DELETE: return LV_KEY_DEL;
case SDLK_RETURN:
case SDLK_KP_ENTER: return LV_KEY_ENTER;
case SDLK_TAB: return LV_KEY_NEXT;
case SDLK_HOME: return LV_KEY_HOME;
case SDLK_END: return LV_KEY_END;
default: return 0;
}
}
}
void sdl_input_pump() {
if (!text_input_started) {
SDL_StartTextInput();
text_input_started = true;
}
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_MOUSEMOTION:
pointer_state.x = event.motion.x;
pointer_state.y = event.motion.y;
break;
case SDL_MOUSEBUTTONDOWN:
if (event.button.button == SDL_BUTTON_LEFT) {
pointer_state.x = event.button.x;
pointer_state.y = event.button.y;
pointer_state.pressed = true;
}
break;
case SDL_MOUSEBUTTONUP:
if (event.button.button == SDL_BUTTON_LEFT) {
pointer_state.pressed = false;
}
break;
case SDL_KEYDOWN:
push_key(keycode_to_key(event.key.keysym.sym));
break;
case SDL_TEXTINPUT:
// ASCII only (first byte of event.text.text) - sufficient for a simulator keyboard.
push_key(static_cast<uint8_t>(event.text.text[0]));
break;
case SDL_QUIT:
exit(0);
default:
break;
}
}
}
void sdl_input_get_pointer_state(SdlPointerState* out_state) {
*out_state = pointer_state;
}
bool sdl_input_pop_key(uint32_t* out_key) {
if (key_queue_count == 0) {
return false;
}
*out_key = key_queue[key_queue_head];
key_queue_head = (key_queue_head + 1) % KEY_QUEUE_CAPACITY;
key_queue_count--;
return true;
}
bool sdl_input_has_queued_key() {
return key_queue_count > 0;
}
@@ -0,0 +1,47 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include <stdbool.h>
#include <stdint.h>
/**
* @brief Latest pointer (mouse) state as tracked by sdl_input_pump().
*/
struct SdlPointerState {
int32_t x;
int32_t y;
bool pressed;
};
/**
* @brief Drains all pending SDL events exactly once, updating the pointer state and key queue
* below. Safe to call from both the sdl-pointer and sdl-keyboard drivers' polling functions:
* SDL_PollEvent() drains a single global queue, so whichever driver is polled first on a given
* LVGL indev tick pumps events for both.
*/
void sdl_input_pump(void);
/**
* @brief Gets the pointer state as of the most recent sdl_input_pump() call.
*/
void sdl_input_get_pointer_state(struct SdlPointerState* out_state);
/**
* @brief Pops the next queued key event (produced by SDL_KEYDOWN/SDL_TEXTINPUT during
* sdl_input_pump()).
* @retval false when no key event is pending
*/
bool sdl_input_pop_key(uint32_t* out_key);
/**
* @brief Returns true if another key event is queued after the one just popped.
*/
bool sdl_input_has_queued_key(void);
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,53 @@
// SPDX-License-Identifier: Apache-2.0
#include "sdl_input.h"
#include <tactility/device.h>
#include <tactility/driver.h>
#include <tactility/drivers/keyboard.h>
#include <tactility/module.h>
// region Driver lifecycle
static error_t start(Device*) { return ERROR_NONE; }
static error_t stop(Device*) { return ERROR_NONE; }
// endregion
// region KeyboardApi
static error_t sdl_keyboard_read_key(Device*, KeyboardKeyData* data) {
sdl_input_pump();
uint32_t key = 0;
if (sdl_input_pop_key(&key)) {
data->key = key;
data->pressed = true;
data->continue_reading = sdl_input_has_queued_key();
} else {
data->key = 0;
data->pressed = false;
data->continue_reading = false;
}
return ERROR_NONE;
}
// endregion
static const KeyboardApi sdl_keyboard_api = {
.read_key = sdl_keyboard_read_key,
.get_backlight = nullptr,
};
extern Module simulator_module;
Driver sdl_keyboard_driver = {
.name = "sdl-keyboard",
.compatible = (const char*[]) { "tactility,sdl-keyboard", nullptr },
.start_device = start,
.stop_device = stop,
.api = &sdl_keyboard_api,
.device_type = &KEYBOARD_TYPE,
.owner = &simulator_module,
.internal = nullptr
};
@@ -0,0 +1,67 @@
// SPDX-License-Identifier: Apache-2.0
#include "sdl_input.h"
#include <tactility/device.h>
#include <tactility/driver.h>
#include <tactility/drivers/pointer.h>
#include <tactility/module.h>
// region Driver lifecycle
static error_t start(Device*) { return ERROR_NONE; }
static error_t stop(Device*) { return ERROR_NONE; }
// endregion
// region PointerApi
static error_t sdl_pointer_read_data(Device*, TickType_t) {
sdl_input_pump();
return ERROR_NONE;
}
static bool sdl_pointer_get_touched_points(Device*, uint16_t* x, uint16_t* y, uint16_t* strength, uint8_t* point_count, uint8_t max_point_count) {
SdlPointerState state;
sdl_input_get_pointer_state(&state);
if (!state.pressed || max_point_count == 0) {
*point_count = 0;
return false;
}
x[0] = static_cast<uint16_t>(state.x);
y[0] = static_cast<uint16_t>(state.y);
if (strength != nullptr) {
strength[0] = 0xFFFF;
}
*point_count = 1;
return true;
}
// endregion
static const PointerApi sdl_pointer_api = {
.enter_sleep = nullptr,
.exit_sleep = nullptr,
.read_data = sdl_pointer_read_data,
.get_touched_points = sdl_pointer_get_touched_points,
.set_swap_xy = nullptr,
.get_swap_xy = nullptr,
.set_mirror_x = nullptr,
.get_mirror_x = nullptr,
.set_mirror_y = nullptr,
.get_mirror_y = nullptr,
};
extern Module simulator_module;
Driver sdl_pointer_driver = {
.name = "sdl-pointer",
.compatible = (const char*[]) { "tactility,sdl-pointer", nullptr },
.start_device = start,
.stop_device = stop,
.api = &sdl_pointer_api,
.device_type = &POINTER_TYPE,
.owner = &simulator_module,
.internal = nullptr
};
-42
View File
@@ -1,42 +0,0 @@
#pragma once
#include "SdlTouch.h"
#include <tactility/check.h>
#include <Tactility/hal/display/DisplayDevice.h>
class SdlDisplay final : public tt::hal::display::DisplayDevice {
lv_disp_t* displayHandle = nullptr;
public:
std::string getName() const override { return "SDL Display"; }
std::string getDescription() const override { return ""; }
bool start() override { return true; }
bool stop() override { return true; }
bool supportsLvgl() const override { return true; }
bool startLvgl() override {
if (displayHandle) return true; // already started
displayHandle = lv_sdl_window_create(320, 240);
lv_sdl_window_set_title(displayHandle, "Tactility");
return displayHandle != nullptr;
}
bool stopLvgl() override {
if (!displayHandle) return true;
lv_display_delete(displayHandle);
displayHandle = nullptr;
return true;
}
lv_display_t* getLvglDisplay() const override { return displayHandle; }
std::shared_ptr<tt::hal::touch::TouchDevice> getTouchDevice() override { return std::make_shared<SdlTouch>(); }
bool supportsDisplayDriver() const override { return false; }
std::shared_ptr<tt::hal::display::DisplayDriver> getDisplayDriver() override { return nullptr; }
};
@@ -1,26 +0,0 @@
#pragma once
#include <Tactility/TactilityCore.h>
#include <tactility/check.h>
#include <Tactility/hal/keyboard/KeyboardDevice.h>
class SdlKeyboard final : public tt::hal::keyboard::KeyboardDevice {
lv_indev_t* handle = nullptr;
public:
std::string getName() const override { return "SDL Keyboard"; }
std::string getDescription() const override { return "SDL keyboard device"; }
bool startLvgl(lv_display_t* display) override {
handle = lv_sdl_keyboard_create();
return handle != nullptr;
}
bool stopLvgl() override { check(false, "Not supported"); }
bool isAttached() const override { return true; }
lv_indev_t* getLvglIndev() override { return handle; }
};
-36
View File
@@ -1,36 +0,0 @@
#pragma once
#include "Tactility/hal/touch/TouchDevice.h"
#include <Tactility/TactilityCore.h>
#include <tactility/check.h>
class SdlTouch final : public tt::hal::touch::TouchDevice {
lv_indev_t* handle = nullptr;
public:
std::string getName() const override { return "SDL Mouse"; }
std::string getDescription() const override { return "SDL mouse/touch pointer device"; }
bool start() override { return true; }
bool stop() override { check(false, "Not supported"); }
bool supportsLvgl() const override { return true; }
bool startLvgl(lv_display_t* display) override {
handle = lv_sdl_mouse_create();
return handle != nullptr;
}
bool stopLvgl() override { check(false, "Not supported"); }
lv_indev_t* getLvglIndev() override { return handle; }
bool supportsTouchDriver() override { return false; }
std::shared_ptr<tt::hal::touch::TouchDriver> getTouchDriver() override { return nullptr; };
};
@@ -1,36 +0,0 @@
#include "SimulatorPower.h"
constexpr auto* TAG = "SimulatorPower";
bool SimulatorPower::supportsMetric(MetricType type) const {
switch (type) {
using enum MetricType;
case IsCharging:
case Current:
case BatteryVoltage:
case ChargeLevel:
return true;
}
return false; // Safety guard for when new enum values are introduced
}
bool SimulatorPower::getMetric(MetricType type, MetricData& data) {
switch (type) {
using enum MetricType;
case IsCharging:
data.valueAsBool = true;
return true;
case Current:
data.valueAsInt32 = 42;
return true;
case BatteryVoltage:
data.valueAsUint32 = 4032;
return true;
case ChargeLevel:
data.valueAsUint8 = 100;
return true;
}
return false; // Safety guard for when new enum values are introduced
}
@@ -1,26 +0,0 @@
#pragma once
#include <Tactility/hal/power/PowerDevice.h>
#include <memory>
using tt::hal::power::PowerDevice;
class SimulatorPower final : public PowerDevice {
bool allowedToCharge = false;
public:
SimulatorPower() = default;
~SimulatorPower() override = default;
std::string getName() const override { return "Power Mock"; }
std::string getDescription() const override { return ""; }
bool supportsMetric(MetricType type) const override;
bool getMetric(MetricType type, MetricData& data) override;
bool supportsChargeControl() const override { return true; }
bool isAllowedToCharge() const override { return allowedToCharge; }
void setAllowedToCharge(bool canCharge) override { allowedToCharge = canCharge; }
};
+90 -5
View File
@@ -1,23 +1,108 @@
#include "drivers/sdl_display.h"
#include <tactility/device.h>
#include <tactility/device_listener.h>
#include <tactility/driver.h>
#include <tactility/error.h>
#include <tactility/log.h>
#include <tactility/module.h> #include <tactility/module.h>
#include <cstring>
constexpr auto* TAG = "Simulator";
extern "C" {
extern Driver sdl_display_driver;
extern Driver sdl_pointer_driver;
extern Driver sdl_keyboard_driver;
static Driver* const simulator_drivers[] = {
&sdl_display_driver,
&sdl_pointer_driver,
&sdl_keyboard_driver,
nullptr
};
}
// These devices have no real bus to attach to (SDL has no notion of one), but every non-root
// device is still expected to have a parent (see Device::parent) - they're parented to root once
// it's available below.
static const SdlDisplayConfig sdl_display_config = { 320, 240 };
static Device sdl_display_device {};
static Device sdl_pointer_device {};
static Device sdl_keyboard_device {};
static bool construct_add_start(Device* device, Device* parent, const char* name, const void* config, const char* compatible) {
device->address = 0;
device->name = name;
device->config = config;
device->parent = nullptr;
device->internal = nullptr;
error_t error = device_construct(device);
if (error != ERROR_NONE) {
LOG_E(TAG, "Failed to construct %s: %s", name, error_to_string(error));
return false;
}
device_set_parent(device, parent);
Driver* driver = driver_find_compatible(compatible);
if (driver == nullptr) {
LOG_E(TAG, "No driver registered for %s", compatible);
device_destruct(device);
return false;
}
device_set_driver(device, driver);
if (device_add(device) != ERROR_NONE) {
LOG_E(TAG, "Failed to add %s", name);
device_destruct(device);
return false;
}
if (device_start(device) != ERROR_NONE) {
LOG_E(TAG, "Failed to start %s", name);
device_remove(device);
device_destruct(device);
return false;
}
return true;
}
// Root is only constructed/added/started after all dts_modules (including this one) have already
// started (see kernel_init()), so it can't be looked up by name from this module's own start() -
// wait for its DEVICE_EVENT_STARTED instead, same as e.g. m5stack-tab5's display/keyboard detection.
static void on_root_started(Device* device, DeviceEvent event, void* context) {
if (event != DEVICE_EVENT_STARTED || strcmp(device->name, "/") != 0) {
return;
}
construct_add_start(&sdl_display_device, device, "display0", &sdl_display_config, "tactility,sdl-display");
construct_add_start(&sdl_pointer_device, device, "pointer0", nullptr, "tactility,sdl-pointer");
construct_add_start(&sdl_keyboard_device, device, "keyboard0", nullptr, "tactility,sdl-keyboard");
}
extern "C" { extern "C" {
static error_t start() { static error_t start() {
// Empty for now device_listener_add(on_root_started, nullptr);
return ERROR_NONE; return ERROR_NONE;
} }
static error_t stop() { static error_t stop() {
// Empty for now device_listener_remove(on_root_started);
return ERROR_NONE; return ERROR_NONE;
} }
struct Module simulator_module = { Module simulator_module = {
.name = "simulator", .name = "simulator",
.start = start, .start = start,
.stop = stop, .stop = stop,
.symbols = nullptr, .drivers = simulator_drivers
.internal = nullptr
}; };
} }
+14 -24
View File
@@ -64,11 +64,7 @@ Tests use Doctest and run on simulator (POSIX) target only:
```bash ```bash
cmake -B buildsim -G Ninja cmake -B buildsim -G Ninja
ninja -C buildsim build-tests ninja -C buildsim build-tests
cd buildsim && ctest # run all tests cd buildsim && ctest --test-dir Tests
./buildsim/Tests/TactilityKernel/TactilityKernelTests
./buildsim/Tests/Tactility/TactilityTests
./buildsim/Tests/TactilityFreeRtos/TactilityFreeRtosTests
./buildsim/Tests/crypt-module/CryptModuleTests
``` ```
## Architecture ## Architecture
@@ -77,7 +73,7 @@ cd buildsim && ctest # run all tests
- **TactilityKernel** — C API kernel: device/driver/module lifecycle, concurrency primitives (thread, mutex, timer, dispatcher), filesystem, logging. Header convention: `<tactility/*.h>` (lowercase snake_case). - **TactilityKernel** — C API kernel: device/driver/module lifecycle, concurrency primitives (thread, mutex, timer, dispatcher), filesystem, logging. Header convention: `<tactility/*.h>` (lowercase snake_case).
- **TactilityFreeRtos** — Thin C++ wrappers around FreeRTOS primitives. - **TactilityFreeRtos** — Thin C++ wrappers around FreeRTOS primitives.
- **Tactility** — Main OS layer: app framework, service framework, HAL (deprecated, replaced by TactilityKernel), LVGL integration, networking and services (Wi-Fi, BLE, NTP, ESP-NOW), settings, i18n. - **Tactility** — Main OS layer: app framework, service framework, LVGL integration, networking and services (Wi-Fi, BLE, NTP, ESP-NOW), settings, i18n.
- **TactilityC** — C bindings (`tt_*.h`) for Tactility, used by side-loaded ELF apps on ESP32. Deprecated, replaced by TactilityKernel. - **TactilityC** — C bindings (`tt_*.h`) for Tactility, used by side-loaded ELF apps on ESP32. Deprecated, replaced by TactilityKernel.
- **Firmware** — Entry point (`app_main`). - **Firmware** — Entry point (`app_main`).
@@ -100,34 +96,28 @@ Apps implement `tt::app::App` (or just provide callbacks). Each app has an `AppM
Services implement `tt::service::Service` with a `ServiceManifest`. Services are long-running background processes (GUI, Wi-Fi, loader, statusbar, GPS, etc.). Services implement `tt::service::Service` with a `ServiceManifest`. Services are long-running background processes (GUI, Wi-Fi, loader, statusbar, GPS, etc.).
### HAL Layer ### Hardware Abstraction Layer
#### Deprecated HAL
Located in Tactility folder.
`tt::hal::Configuration` is declared per-device board (in `Devices/<id>/Source/Configuration.cpp`). It provides `initBoot` for early hardware setup and `createDevices` to instantiate HAL device wrappers (display, touch, power, keyboard, etc.).
#### Current HAL
Located in TactilityKernel. Based on Linux driver subsystems.
#### Driver #### Driver
A driver generally consists of: A driver generally consists of:
- Registration of driver in parent module (optional) - Registration of driver in parent module (optional, but desirable)
- YAML bindings in the `bindings/` folder - YAML bindings in the `bindings/` folder
- An `#include` that is used in the `.dts` file. The include is in `[projectname]/bindings/[drivername].h` - An `#include` that is used in the `.dts` file. The include is in `[projectname]/bindings/[drivername].h`
- The driver implementation: a `.cpp` and `.h` file. The implementation is C++, but the header exposes pure C functions. - The driver implementation: a `.cpp` and `.h` file. The implementation is C++, but the header exposes pure C functions. C implementations are allowed, but C++ is preferred.
Drivers can be stored in: Drivers are part of a kernel module.
Modules with drivers can be stored in:
- TactilityKernel - TactilityKernel
- A subproject in Platforms/ folder - A subproject in `Platforms` folder
- A subproject in Devices/ folder - A subproject in `Devices` folder
- A subproject in Drivers/ folder. This is a kernel module. Naming is lower case and postfixed with `-module` - A subproject in `Drivers` folder
#### Kernel Modules #### Kernel Modules
Kernel module names are lower case and postfixed with `-module`.
Projects that are kernel modules: Projects that are kernel modules:
1. Declare a `struct Module` 1. Declare a `struct Module`
@@ -169,6 +159,6 @@ Pointers are expected to be non-null unless documented otherwise.
- `#ifdef ESP_PLATFORM` guards ESP32-specific code; the simulator uses POSIX equivalents. - `#ifdef ESP_PLATFORM` guards ESP32-specific code; the simulator uses POSIX equivalents.
- The `Drivers/` directory contains hardware drivers (display controllers, touch controllers, PMICs, etc.) — each is its own CMake component. - The `Drivers/` directory contains hardware drivers (display controllers, touch controllers, PMICs, etc.) — each is its own CMake component.
- `Modules/` contains cross-cutting modules: `hal-device-module` (device lifecycle) and `lvgl-module` (LVGL task management). - `Modules/` contains cross-cutting modules. e.g.`lvgl-module` (LVGL task management).
- `Data/system/` and `Data/data/` are flashed as FAT filesystem images on ESP32. - `Data/system/` and `Data/data/` are flashed as FAT filesystem images on ESP32.
- Translations are in `Translations/` as CSV files, generated via `generate.py`. - Translations are in `Translations/` as CSV files, generated via `generate.py`.
+1
View File
@@ -13,6 +13,7 @@
## Higher Priority ## Higher Priority
- Remove and migrate `Include/Tactility/kernel/Kernel.h` into `tactility/delay.h`
- Drivers/audio-codec-module is not a module. Move it somewhere else. Or make it an actual module. - Drivers/audio-codec-module is not a module. Move it somewhere else. Or make it an actual module.
- LilyGO T-Dongle S3: 1 button control, stop auto-launching web server - LilyGO T-Dongle S3: 1 button control, stop auto-launching web server
- Core2: support power off via software - Core2: support power off via software
+12
View File
@@ -0,0 +1,12 @@
cmake_minimum_required(VERSION 3.20)
include("${CMAKE_CURRENT_LIST_DIR}/../../Buildscripts/module.cmake")
file(GLOB_RECURSE SOURCE_FILES "source/*.c*")
tactility_add_module(gps-generic-module
SRCS ${SOURCE_FILES}
PRIV_INCLUDE_DIRS private/
INCLUDE_DIRS include/
REQUIRES TactilityKernel gps-module minmea
)
@@ -0,0 +1,677 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices" to
the extent that it includes a convenient and prominently visible feature
that (1) displays an appropriate copyright notice, and (2) tells the
user that there is no warranty for the work (except to the extent that
warranties are provided), that licensees may convey the work under this
License, and how to view a copy of this License. If the interface
presents a list of user commands or options, such as a menu, a
prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work for
making modifications to it. "Object code" means any non-source form of
a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that is
widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system (if
any) on which the executable work runs, or a compiler used to produce
the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such
circumvention is effected by exercising rights under this License with
respect to the covered work, and you disclaim any intention to limit
operation or modification of the work as a means of enforcing, against
the work's users, your or third parties' legal rights to forbid
circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for
incorporation into a dwelling. In determining whether a product is a
consumer product, doubtful cases shall be resolved in favor of
coverage. For a particular product received by a particular user,
"normally used" refers to a typical or common use of that class of
product, regardless of the status of the particular user or of the way
in which the particular user actually uses, or expects or is expected
to use, the product. A product is a consumer product regardless of
whether the product has substantial commercial, industrial or
non-consumer uses, unless such uses represent the only significant
mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to
install and execute modified versions of a covered work in that User
Product from a modified version of its Corresponding Source. The
information must suffice to ensure that the continued functioning of
the modified object code is in no case prevented or interfered with
solely because modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include
a requirement to continue to provide support service, warranty, or
updates for a work that has been modified or installed by the
recipient, or for the User Product in which it has been modified or
installed. Access to a network may be denied when the modification
itself materially and adversely affects the operation of the network
or violates the rules and protocols for communication across the
network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders
of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not convey it at all. For example, if you agree to terms that
obligate you to collect a royalty for further conveying from those to
whom you convey the Program, the only way you could satisfy both those
terms and this License would be to refrain entirely from conveying the
Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your
program into proprietary programs. If your program is a subroutine
library, you may consider it more useful to permit linking proprietary
applications with the library. If this is what you want to do, use
the GNU Lesser General Public License instead of this License. But
first, please read <https://www.gnu.org/licenses/why-not-lgpl.html>.
+14
View File
@@ -0,0 +1,14 @@
# gps-generic-module
Kernel driver implementing the `GPS_TYPE`/`GpsApi` interface with for generic UART-connected GPS/GNSS receivers:
NMEA parsing for MTK, Airoha/AG33xx, ATGM336H/CASIC, Unicore UC6580 and u-blox 6/7/8/9/10 modules.
It is ported from [Meshtastic Firmware](https://github.com/MeshTastic/firmware), so it has a GPL v3.0 license.
## License
This module is licensed under **GPL-3.0-or-later** (see `LICENSE-GPL-3.0.md`), separately from
the rest of Tactility (Apache-2.0). The probing and initialization logic (`source/probe.cpp`,
`source/init.cpp`, `source/ublox.cpp` and their private headers) is ported from
[meshtastic/firmware](https://github.com/meshtastic/firmware) (GPL-3.0-or-later); see the
`From: <url>` comments in those files for the exact origin of each ported function.
@@ -0,0 +1,17 @@
description: >
Generic UART-connected GPS/GNSS receiver. Supports MTK, Airoha/AG33xx, ATGM336H/CASIC,
Unicore UC6580 and u-blox 6/7/8/9/10 chipsets, either auto-probed or fixed via 'model'.
compatible: "tactility,gps-generic"
properties:
baud-rate:
type: int
required: true
description: UART baud rate, e.g. 9600 or 38400
model:
type: int
default: 0
description: |
GpsModel enum value (see gps/gps.h, e.g. GPS_MODEL_UBLOX10 = 12). Defaults to
GPS_MODEL_UNKNOWN (0), which triggers an autoprobe on start().
@@ -0,0 +1,4 @@
dependencies:
- TactilityKernel
- Modules/gps-module
bindings: bindings
@@ -0,0 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <tactility/bindings/bindings.h>
#include <gps_generic/gps_generic.h>
DEFINE_DEVICETREE(gps_generic, struct GpsConfig)
@@ -0,0 +1,24 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <gps/gps.h>
#include <tactility/device.h>
/**
* @brief Devicetree configuration for a generic UART-connected GPS/GNSS receiver.
*/
struct GpsConfig {
uint32_t baud_rate;
/** GPS_MODEL_UNKNOWN triggers an autoprobe on start(); the detected model is then available via get_model(). */
enum GpsModel model;
};
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,12 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
extern struct Module gps_generic_module;
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,57 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <cstddef>
#include <cstdint>
// NEMA message IDs
constexpr uint8_t CAS_NEMA_GGA = 0x00;
constexpr uint8_t CAS_NEMA_GLL = 0x01;
constexpr uint8_t CAS_NEMA_GSA = 0x02;
constexpr uint8_t CAS_NEMA_GSV = 0x03;
constexpr uint8_t CAS_NEMA_RMC = 0x04;
constexpr uint8_t CAS_NEMA_VTG = 0x05;
constexpr uint8_t CAS_NEMA_GST = 0x07;
constexpr uint8_t CAS_NEMA_ZDA = 0x08;
constexpr uint8_t CAS_NEMA_DHV = 0x0D;
/** Size of a CAS-ACK-(N)ACK message */
constexpr size_t CAS_MESSAGE_ACK_NACK_SIZE = 0x0E; // 14 bytes
/** Factory reset message */
constexpr uint8_t CAS_MESSAGE_CFG_RST_FACTORY[] = {
0xFF, 0x03,
0x01,
0x03
};
/** Configure update rate to 1 Hz. */
constexpr uint8_t CAS_MESSAGE_CFG_RATE_1HZ[] = {
0xE8, 0x03, // 0x03E8 = 1000ms
0x00, 0x00
};
/** Config navx */
constexpr uint8_t CAS_MESSAGE_CFG_NAVX_CONF[] = {
0x03, 0x01, 0x00, 0x00,
0x03,
0x03,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x07,
0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
};
@@ -0,0 +1,11 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
// Internal-only result of waiting for a chip's ACK/NACK response during probing/initialization.
// Not part of the public API (see gps/gps.h) - callers only ever see GpsState/GpsModel.
enum class GpsResponse {
None,
NotAck,
FrameErrors,
Ok,
};
@@ -0,0 +1,11 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <gps/gps.h>
struct Device;
/**
* Sends the init sequence for a specific, already-probed GPS model over uart.
*/
bool gps_init(Device* uart, GpsModel model);
@@ -0,0 +1,12 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <gps/gps.h>
struct Device;
/**
* Attempts to auto-detect the GPS/GNSS chipset connected via uart.
* @return GPS_MODEL_UNKNOWN when no supported chipset responded
*/
GpsModel gps_probe(Device* uart);
@@ -0,0 +1,22 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <gps/gps.h>
#include <cstddef>
#include <cstdint>
struct Device;
namespace gps_ublox {
void checksum(uint8_t* message, size_t length);
// From https://github.com/meshtastic/firmware/blob/7648391f91f2b84e367ae2b38220b30936fb45b1/src/gps/GPS.cpp#L128
uint8_t make_packet(uint8_t class_id, uint8_t message_id, const uint8_t* payload, uint8_t payload_size, uint8_t* buffer_out);
GpsModel probe(Device* uart);
bool init(Device* uart, GpsModel model);
}
@@ -1,8 +1,9 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once #pragma once
#include <cstdint> #include <cstdint>
namespace tt::hal::gps::ublox { namespace gps_ublox {
// Power Management // Power Management
@@ -0,0 +1,343 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include <gps/gps.h>
#include <gps_generic/gps_generic.h>
#include <gps_generic/private/init.h>
#include <gps_generic/private/probe.h>
#include <tactility/check.h>
#include <tactility/concurrent/recursive_mutex.h>
#include <tactility/concurrent/thread.h>
#include <tactility/device.h>
#include <tactility/driver.h>
#include <tactility/drivers/uart_controller.h>
#include <tactility/error.h>
#include <tactility/log.h>
#include <tactility/module.h>
#include <tactility/time.h>
#include <minmea.h>
#include <cstdio>
#include <cstdlib> // For calloc() in PC builds
constexpr auto* TAG = "gps-generic";
#define GET_CONFIG(device) (static_cast<const GpsConfig*>((device)->config))
constexpr uint32_t GPS_UART_BUFFER_SIZE = 256;
constexpr TickType_t GPS_THREAD_STOP_TIMEOUT_TICKS = pdMS_TO_TICKS(5000);
constexpr TickType_t GPS_THREAD_STOP_POLL_TICKS = pdMS_TO_TICKS(1000);
struct GpsInternal {
RecursiveMutex mutex;
Thread* thread;
volatile bool interrupt_requested;
GpsState state;
// Mirrors GpsConfig::model, but overwritten with the autodetected model once probing succeeds.
GpsModel model;
// Singly-linked list of subscribers, guarded by `mutex`.
GpsSubscription* subscribers;
};
static const char* gpsModelToString(GpsModel model) {
switch (model) {
case GPS_MODEL_AG3335:
return "AG3335";
case GPS_MODEL_AG3352:
return "AG3352";
case GPS_MODEL_ATGM336H:
return "ATGM336H";
case GPS_MODEL_LS20031:
return "LS20031";
case GPS_MODEL_MTK:
return "MTK";
case GPS_MODEL_MTK_L76B:
return "MTK L76B";
case GPS_MODEL_MTK_PA1616S:
return "MTK PA1616S";
case GPS_MODEL_UBLOX6:
return "U-blox 6";
case GPS_MODEL_UBLOX7:
return "U-blox 7";
case GPS_MODEL_UBLOX8:
return "U-blox 8";
case GPS_MODEL_UBLOX9:
return "U-blox 9";
case GPS_MODEL_UBLOX10:
return "U-blox 10";
case GPS_MODEL_UC6580:
return "UC6580";
case GPS_MODEL_UNKNOWN:
return "Auto-detect";
default:
return "Unknown";
}
}
// Pushes `event` to every current subscriber and wakes their waiting task. Safe to call from the
// GPS thread's parsing loop.
static void notify_subscribers(GpsInternal* internal, const GpsEvent& event) {
recursive_mutex_lock(&internal->mutex);
for (GpsSubscription* sub = internal->subscribers; sub != nullptr; sub = sub->next) {
sub->event = event;
sub->sequence++;
xTaskNotifyGive(sub->task);
}
recursive_mutex_unlock(&internal->mutex);
}
static void set_state(GpsInternal* internal, GpsState state) {
recursive_mutex_lock(&internal->mutex);
internal->state = state;
recursive_mutex_unlock(&internal->mutex);
}
static bool is_interrupted(GpsInternal* internal) {
recursive_mutex_lock(&internal->mutex);
bool result = internal->interrupt_requested;
recursive_mutex_unlock(&internal->mutex);
return result;
}
// region Driver lifecycle
static int32_t gps_thread_main(void* context) {
auto* device = static_cast<Device*>(context);
auto* internal = static_cast<GpsInternal*>(device_get_driver_data(device));
const auto* config = GET_CONFIG(device);
auto* uart = device_get_parent(device);
check(uart);
check(device_get_type(uart) == &UART_CONTROLLER_TYPE);
const UartConfig uart_config = {
.baud_rate = config->baud_rate,
.data_bits = UART_CONTROLLER_DATA_8_BITS,
.parity = UART_CONTROLLER_PARITY_DISABLE,
.stop_bits = UART_CONTROLLER_STOP_BITS_1
};
if (uart_controller_set_config(uart, &uart_config) != ERROR_NONE) {
LOG_E(TAG, "Failed to configure UART %s", uart->name);
set_state(internal, GpsState::GPS_STATE_ERROR);
return -1;
}
if (uart_controller_open(uart) != ERROR_NONE) {
LOG_E(TAG, "Failed to open UART %s", uart->name);
set_state(internal, GpsState::GPS_STATE_ERROR);
return -1;
}
GpsModel model = internal->model;
if (model == GpsModel::GPS_MODEL_UNKNOWN) {
model = gps_probe(uart);
if (model == GpsModel::GPS_MODEL_UNKNOWN) {
LOG_E(TAG, "Probe failed");
set_state(internal, GpsState::GPS_STATE_ERROR);
return -1;
}
recursive_mutex_lock(&internal->mutex);
internal->model = model;
recursive_mutex_unlock(&internal->mutex);
}
if (!gps_init(uart, model)) {
LOG_E(TAG, "Init failed");
set_state(internal, GpsState::GPS_STATE_ERROR);
return -1;
}
set_state(internal, GpsState::GPS_STATE_ON);
// Reference: https://gpsd.gitlab.io/gpsd/NMEA.html
uint8_t buffer[GPS_UART_BUFFER_SIZE];
while (!is_interrupted(internal)) {
size_t bytes_read = 0;
uart_controller_read_until(uart, buffer, sizeof(buffer), '\n', true, &bytes_read, pdMS_TO_TICKS(100));
// Thread might've been interrupted in the meanwhile
if (is_interrupted(internal)) {
break;
}
if (bytes_read > 0U) {
switch (minmea_sentence_id(reinterpret_cast<char*>(buffer), false)) {
case MINMEA_SENTENCE_RMC: {
GpsEvent event { .type = GPS_EVENT_MESSAGE_RMC };
if (minmea_parse_rmc(&event.data.rmc, reinterpret_cast<char*>(buffer))) {
notify_subscribers(internal, event);
} else {
LOG_E(TAG, "RMC parse error: %s", reinterpret_cast<const char*>(buffer));
}
break;
}
case MINMEA_SENTENCE_GGA: {
GpsEvent event { .type = GPS_EVENT_MESSAGE_GGA };
if (minmea_parse_gga(&event.data.gga, reinterpret_cast<char*>(buffer))) {
notify_subscribers(internal, event);
} else {
LOG_E(TAG, "GGA parse error: %s", reinterpret_cast<const char*>(buffer));
}
break;
}
default:
break;
}
}
}
if (uart_controller_close(uart) != ERROR_NONE) {
LOG_W(TAG, "Failed to close UART %s", uart->name);
}
// Wake any subscribers still awaiting an event so they don't block forever on a device that's
// going away, then drop them - stop() is about to free `internal`.
notify_subscribers(internal, GpsEvent { .type = GPS_EVENT_UNSUBSCRIBED });
recursive_mutex_lock(&internal->mutex);
internal->subscribers = nullptr;
recursive_mutex_unlock(&internal->mutex);
set_state(internal, GPS_STATE_OFF);
return 0;
}
static error_t start(Device* device) {
const auto* config = GET_CONFIG(device);
auto* internal = static_cast<GpsInternal*>(calloc(1, sizeof(GpsInternal)));
if (internal == nullptr) {
return ERROR_OUT_OF_MEMORY;
}
recursive_mutex_construct(&internal->mutex);
internal->model = config->model;
internal->state = GPS_STATE_PENDING_ON;
internal->thread = thread_alloc_full("gps", 4096, gps_thread_main, device, -1);
if (internal->thread == nullptr) {
recursive_mutex_destruct(&internal->mutex);
free(internal);
return ERROR_OUT_OF_MEMORY;
}
thread_set_priority(internal->thread, THREAD_PRIORITY_HIGH);
device_set_driver_data(device, internal);
if (thread_start(internal->thread) != ERROR_NONE) {
thread_free(internal->thread);
recursive_mutex_destruct(&internal->mutex);
free(internal);
device_set_driver_data(device, nullptr);
return ERROR_RESOURCE;
}
return ERROR_NONE;
}
static error_t stop(Device* device) {
auto* internal = static_cast<GpsInternal*>(device_get_driver_data(device));
recursive_mutex_lock(&internal->mutex);
internal->interrupt_requested = true;
internal->state = GPS_STATE_PENDING_OFF;
recursive_mutex_unlock(&internal->mutex);
if (thread_join(internal->thread, GPS_THREAD_STOP_TIMEOUT_TICKS, GPS_THREAD_STOP_POLL_TICKS) != ERROR_NONE) {
LOG_E(TAG, "GPS thread for %s did not stop in time", device->name);
return ERROR_RESOURCE_BUSY;
}
thread_free(internal->thread);
recursive_mutex_destruct(&internal->mutex);
free(internal);
device_set_driver_data(device, nullptr);
return ERROR_NONE;
}
// endregion
// region GpsApi
static error_t gps_api_event_subscribe(Device* device, GpsSubscription* sub) {
auto* internal = static_cast<GpsInternal*>(device_get_driver_data(device));
sub->task = xTaskGetCurrentTaskHandle();
sub->sequence = 0;
sub->consumed_sequence = 0;
recursive_mutex_lock(&internal->mutex);
sub->next = internal->subscribers;
internal->subscribers = sub;
recursive_mutex_unlock(&internal->mutex);
return ERROR_NONE;
}
static error_t gps_api_event_unsubscribe(Device* device, GpsSubscription* sub) {
auto* internal = static_cast<GpsInternal*>(device_get_driver_data(device));
error_t result = ERROR_NOT_FOUND;
recursive_mutex_lock(&internal->mutex);
for (GpsSubscription** link = &internal->subscribers; *link != nullptr; link = &(*link)->next) {
if (*link == sub) {
*link = sub->next;
result = ERROR_NONE;
break;
}
}
recursive_mutex_unlock(&internal->mutex);
return result;
}
static error_t gps_api_event_await(Device*, GpsSubscription* sub, TickType_t timeout) {
uint32_t old_sequence = sub->sequence;
while (sub->sequence == old_sequence) {
if (ulTaskNotifyTake(pdTRUE, timeout) == 0) {
return ERROR_TIMEOUT;
}
}
sub->consumed_sequence = sub->sequence;
return ERROR_NONE;
}
static GpsState gps_api_get_state(Device* device) {
auto* internal = static_cast<GpsInternal*>(device_get_driver_data(device));
recursive_mutex_lock(&internal->mutex);
auto state = internal->state;
recursive_mutex_unlock(&internal->mutex);
return state;
}
static error_t gps_api_get_model_name(Device* device, char* model_name, size_t buffer_size) {
const auto* config = GET_CONFIG(device);
const char* name_to_set = gpsModelToString(config->model);
snprintf(model_name, buffer_size, "%s", name_to_set);
return ERROR_NONE;
}
// endregion
static const GpsApi generic_gps_api = {
.event_subscribe = gps_api_event_subscribe,
.event_unsubscribe = gps_api_event_unsubscribe,
.event_await = gps_api_event_await,
.get_state = gps_api_get_state,
.get_model_name = gps_api_get_model_name
};
extern Module gps_generic_module;
Driver generic_gps_driver = {
.name = "gps-generic",
.compatible = (const char*[]) { "tactility,gps-generic", nullptr },
.start_device = start,
.stop_device = stop,
.api = &generic_gps_api,
.device_type = &GPS_TYPE,
.owner = &gps_generic_module
};
@@ -1,31 +1,31 @@
#include <Tactility/hal/gps/Cas.h> // SPDX-License-Identifier: GPL-3.0-or-later
#include <Tactility/hal/gps/GpsDevice.h> #include <gps_generic/private/cas_messages.h>
#include <Tactility/hal/gps/Ublox.h> #include <gps_generic/private/init.h>
#include <Tactility/kernel/Kernel.h> #include <gps_generic/private/ublox.h>
#include <gps_generic/private/gps_response.h>
#include <tactility/check.h> #include <tactility/check.h>
#include <tactility/delay.h>
#include <tactility/device.h> #include <tactility/device.h>
#include <tactility/drivers/uart_controller.h> #include <tactility/drivers/uart_controller.h>
#include <tactility/log.h> #include <tactility/log.h>
#include <tactility/time.h>
#include <cstring> #include <cstring>
namespace tt::hal::gps { constexpr auto* TAG = "gps";
constexpr auto* TAG = "Gps"; bool init_mtk(Device* uart);
bool init_mtk_l76b(Device* uart);
bool initMtk(::Device* uart); bool init_mtk_pa1616s(Device* uart);
bool initMtkL76b(::Device* uart); bool init_atgm336h(Device* uart);
bool initMtkPa1616s(::Device* uart); bool init_uc6580(Device* uart);
bool initAtgm336h(::Device* uart); bool init_ag33xx(Device* uart);
bool initUc6580(::Device* uart);
bool initAg33xx(::Device* uart);
// region CAS // region CAS
// Calculate the checksum for a CAS packet // Calculate the checksum for a CAS packet
static void CASChecksum(uint8_t *message, size_t length) static void cas_checksum(uint8_t* message, size_t length) {
{
uint32_t cksum = ((uint32_t)message[5] << 24); // Message ID uint32_t cksum = ((uint32_t)message[5] << 24); // Message ID
cksum += ((uint32_t)message[4]) << 16; // Class cksum += ((uint32_t)message[4]) << 16; // Class
cksum += message[2]; // Payload Len cksum += message[2]; // Payload Len
@@ -46,8 +46,7 @@ static void CASChecksum(uint8_t *message, size_t length)
} }
// Function to create a CAS packet for editing in memory // Function to create a CAS packet for editing in memory
static uint8_t makeCASPacket(uint8_t* buffer, uint8_t class_id, uint8_t msg_id, uint8_t payload_size, const uint8_t *msg) static uint8_t make_cas_packet(uint8_t* buffer, uint8_t class_id, uint8_t msg_id, uint8_t payload_size, const uint8_t* msg) {
{
// General CAS structure // General CAS structure
// | H1 | H2 | payload_len | cls | msg | Payload ... | Checksum | // | H1 | H2 | payload_len | cls | msg | Payload ... | Checksum |
// Size: | 1 | 1 | 2 | 1 | 1 | payload_len | 4 | // Size: | 1 | 1 | 2 | 1 | 1 | payload_len | 4 |
@@ -71,17 +70,16 @@ static uint8_t makeCASPacket(uint8_t* buffer, uint8_t class_id, uint8_t msg_id,
for (int i = 0; i < payload_size; i++) { for (int i = 0; i < payload_size; i++) {
buffer[6 + i] = msg[i]; buffer[6 + i] = msg[i];
} }
CASChecksum(buffer, (payload_size + 10)); cas_checksum(buffer, (payload_size + 10));
return (payload_size + 10); return (payload_size + 10);
} }
GpsResponse getACKCas(::Device* uart, uint8_t class_id, uint8_t msg_id, uint32_t waitMillis) static GpsResponse get_ack_cas(Device* uart, uint8_t class_id, uint8_t msg_id, uint32_t wait_millis) {
{ uint32_t start_time = get_millis();
uint32_t startTime = kernel::getMillis(); uint8_t buffer[CAS_MESSAGE_ACK_NACK_SIZE] = {0};
uint8_t buffer[CAS_ACK_NACK_MSG_SIZE] = {0}; uint8_t buffer_pos = 0;
uint8_t bufferPos = 0; TickType_t wait_ticks = pdMS_TO_TICKS(wait_millis);
TickType_t waitTicks = pdMS_TO_TICKS(waitMillis);
// CAS-ACK-(N)ACK structure // CAS-ACK-(N)ACK structure
// | H1 | H2 | Payload Len | cls | msg | Payload | Checksum (4) | // | H1 | H2 | Payload Len | cls | msg | Payload | Checksum (4) |
@@ -90,26 +88,26 @@ GpsResponse getACKCas(::Device* uart, uint8_t class_id, uint8_t msg_id, uint32_t
// ACK-NACK| 0xBA | 0xCE | 0x04 | 0x00 | 0x05 | 0x00 | 0xXX | 0xXX | 0x00 | 0x00 | 0xXX | 0xXX | 0xXX | 0xXX | // ACK-NACK| 0xBA | 0xCE | 0x04 | 0x00 | 0x05 | 0x00 | 0xXX | 0xXX | 0x00 | 0x00 | 0xXX | 0xXX | 0xXX | 0xXX |
// ACK-ACK | 0xBA | 0xCE | 0x04 | 0x00 | 0x05 | 0x01 | 0xXX | 0xXX | 0x00 | 0x00 | 0xXX | 0xXX | 0xXX | 0xXX | // ACK-ACK | 0xBA | 0xCE | 0x04 | 0x00 | 0x05 | 0x01 | 0xXX | 0xXX | 0x00 | 0x00 | 0xXX | 0xXX | 0xXX | 0xXX |
while (kernel::getTicks() - startTime < waitTicks) { while (get_ticks() - start_time < wait_ticks) {
size_t available = 0; size_t available = 0;
uart_controller_get_available(uart, &available); uart_controller_get_available(uart, &available);
if (available > 0) { if (available > 0) {
uart_controller_read_byte(uart, &buffer[bufferPos++], 1); uart_controller_read_byte(uart, &buffer[buffer_pos++], 1);
// keep looking at the first two bytes of buffer until // keep looking at the first two bytes of buffer until
// we have found the CAS frame header (0xBA, 0xCE), if not // we have found the CAS frame header (0xBA, 0xCE), if not
// keep reading bytes until we find a frame header or we run // keep reading bytes until we find a frame header or we run
// out of time. // out of time.
if ((bufferPos == 2) && !(buffer[0] == 0xBA && buffer[1] == 0xCE)) { if ((buffer_pos == 2) && !(buffer[0] == 0xBA && buffer[1] == 0xCE)) {
buffer[0] = buffer[1]; buffer[0] = buffer[1];
buffer[1] = 0; buffer[1] = 0;
bufferPos = 1; buffer_pos = 1;
} }
} }
// we have read all the bytes required for the Ack/Nack (14-bytes) // we have read all the bytes required for the Ack/Nack (14-bytes)
// and we must have found a frame to get this far // and we must have found a frame to get this far
if (bufferPos == sizeof(buffer) - 1) { if (buffer_pos == sizeof(buffer) - 1) {
uint8_t msg_cls = buffer[4]; // message class should be 0x05 uint8_t msg_cls = buffer[4]; // message class should be 0x05
uint8_t msg_msg_id = buffer[5]; // message id should be 0x00 or 0x01 uint8_t msg_msg_id = buffer[5]; // message id should be 0x00 or 0x01
uint8_t payload_cls = buffer[6]; // payload class id uint8_t payload_cls = buffer[6]; // payload class id
@@ -117,24 +115,18 @@ GpsResponse getACKCas(::Device* uart, uint8_t class_id, uint8_t msg_id, uint32_t
// Check for an ACK-ACK for the specified class and message id // Check for an ACK-ACK for the specified class and message id
if ((msg_cls == 0x05) && (msg_msg_id == 0x01) && payload_cls == class_id && payload_msg == msg_id) { if ((msg_cls == 0x05) && (msg_msg_id == 0x01) && payload_cls == class_id && payload_msg == msg_id) {
#ifdef GPS_DEBUG
LOG_I(TAG, "Got ACK for class %02X message %02X in %zu ms", class_id, msg_id, kernel::getMillis() - startTime);
#endif
return GpsResponse::Ok; return GpsResponse::Ok;
} }
// Check for an ACK-NACK for the specified class and message id // Check for an ACK-NACK for the specified class and message id
if ((msg_cls == 0x05) && (msg_msg_id == 0x00) && payload_cls == class_id && payload_msg == msg_id) { if ((msg_cls == 0x05) && (msg_msg_id == 0x00) && payload_cls == class_id && payload_msg == msg_id) {
#ifdef GPS_DEBUG
LOG_W(TAG, "Got NACK for class %02X message %02X in %zu ms", class_id, msg_id, millis() - startTime);
#endif
return GpsResponse::NotAck; return GpsResponse::NotAck;
} }
// This isn't the frame we are looking for, clear the buffer // This isn't the frame we are looking for, clear the buffer
// and try again until we run out of time. // and try again until we run out of time.
memset(buffer, 0x0, sizeof(buffer)); memset(buffer, 0x0, sizeof(buffer));
bufferPos = 0; buffer_pos = 0;
} }
} }
return GpsResponse::None; return GpsResponse::None;
@@ -142,38 +134,38 @@ GpsResponse getACKCas(::Device* uart, uint8_t class_id, uint8_t msg_id, uint32_t
// endregion // endregion
bool init(::Device* uart, GpsModel type) { bool gps_init(Device* uart, GpsModel type) {
switch (type) { switch (type) {
case GpsModel::Unknown: case GPS_MODEL_UNKNOWN:
check(false); check(false);
case GpsModel::AG3335: case GPS_MODEL_AG3335:
case GpsModel::AG3352: case GPS_MODEL_AG3352:
return initAg33xx(uart); return init_ag33xx(uart);
case GpsModel::ATGM336H: case GPS_MODEL_ATGM336H:
return initAtgm336h(uart); return init_atgm336h(uart);
case GpsModel::LS20031: case GPS_MODEL_LS20031:
return true; return true;
case GpsModel::MTK: case GPS_MODEL_MTK:
return initMtk(uart); return init_mtk(uart);
case GpsModel::MTK_L76B: case GPS_MODEL_MTK_L76B:
return initMtkL76b(uart); return init_mtk_l76b(uart);
case GpsModel::MTK_PA1616S: case GPS_MODEL_MTK_PA1616S:
return initMtkPa1616s(uart); return init_mtk_pa1616s(uart);
case GpsModel::UBLOX6: case GPS_MODEL_UBLOX6:
case GpsModel::UBLOX7: case GPS_MODEL_UBLOX7:
case GpsModel::UBLOX8: case GPS_MODEL_UBLOX8:
case GpsModel::UBLOX9: case GPS_MODEL_UBLOX9:
case GpsModel::UBLOX10: case GPS_MODEL_UBLOX10:
return ublox::init(uart, type); return gps_ublox::init(uart, type);
case GpsModel::UC6580: case GPS_MODEL_UC6580:
return initUc6580(uart); return init_uc6580(uart);
} }
LOG_I(TAG, "Init not implemented %d", static_cast<int>(type)); LOG_I(TAG, "Init not implemented %d", static_cast<int>(type));
return false; return false;
} }
bool initAg33xx(::Device* uart) { bool init_ag33xx(Device* uart) {
uart_controller_write_bytes(uart, (const uint8_t*)"$PAIR066,1,0,1,0,0,1*3B\r\n", 25, 250); // Enable GPS+GALILEO+NAVIC uart_controller_write_bytes(uart, (const uint8_t*)"$PAIR066,1,0,1,0,0,1*3B\r\n", 25, 250); // Enable GPS+GALILEO+NAVIC
// Configure NMEA (sentences will output once per fix) // Configure NMEA (sentences will output once per fix)
@@ -185,47 +177,47 @@ bool initAg33xx(::Device* uart) {
uart_controller_write_bytes(uart, (const uint8_t*)"$PAIR062,5,0*3B\r\n", 17, 250); // VTG OFF uart_controller_write_bytes(uart, (const uint8_t*)"$PAIR062,5,0*3B\r\n", 17, 250); // VTG OFF
uart_controller_write_bytes(uart, (const uint8_t*)"$PAIR062,6,0*38\r\n", 17, 250); // ZDA ON uart_controller_write_bytes(uart, (const uint8_t*)"$PAIR062,6,0*38\r\n", 17, 250); // ZDA ON
kernel::delayMillis(250); delay_millis(250);
uart_controller_write_bytes(uart, (const uint8_t*)"$PAIR513*3D\r\n", 13, 250); // save configuration uart_controller_write_bytes(uart, (const uint8_t*)"$PAIR513*3D\r\n", 13, 250); // save configuration
return true; return true;
} }
bool initUc6580(::Device* uart) { bool init_uc6580(Device* uart) {
// The Unicore UC6580 can use a lot of sat systems, enable it to // The Unicore UC6580 can use a lot of sat systems, enable it to
// use GPS L1 & L5 + BDS B1I & B2a + GLONASS L1 + GALILEO E1 & E5a + SBAS + QZSS // use GPS L1 & L5 + BDS B1I & B2a + GLONASS L1 + GALILEO E1 & E5a + SBAS + QZSS
// This will reset the receiver, so wait a bit afterwards // This will reset the receiver, so wait a bit afterwards
// The paranoid will wait for the OK*04 confirmation response after each command. // The paranoid will wait for the OK*04 confirmation response after each command.
uart_controller_write_bytes(uart, (const uint8_t*)"$CFGSYS,h35155\r\n", 16, 250); uart_controller_write_bytes(uart, (const uint8_t*)"$CFGSYS,h35155\r\n", 16, 250);
kernel::delayMillis(750); delay_millis(750);
// Must be done after the CFGSYS command // Must be done after the CFGSYS command
// Turn off GSV messages, we don't really care about which and where the sats are, maybe someday. // Turn off GSV messages, we don't really care about which and where the sats are, maybe someday.
uart_controller_write_bytes(uart, (const uint8_t*)"$CFGMSG,0,3,0\r\n", 15, 250); uart_controller_write_bytes(uart, (const uint8_t*)"$CFGMSG,0,3,0\r\n", 15, 250);
kernel::delayMillis(250); delay_millis(250);
// Turn off GSA messages, TinyGPS++ doesn't use this message. // Turn off GSA messages, TinyGPS++ doesn't use this message.
uart_controller_write_bytes(uart, (const uint8_t*)"$CFGMSG,0,2,0\r\n", 15, 250); uart_controller_write_bytes(uart, (const uint8_t*)"$CFGMSG,0,2,0\r\n", 15, 250);
kernel::delayMillis(250); delay_millis(250);
// Turn off NOTICE __TXT messages, these may provide Unicore some info but we don't care. // Turn off NOTICE __TXT messages, these may provide Unicore some info but we don't care.
uart_controller_write_bytes(uart, (const uint8_t*)"$CFGMSG,6,0,0\r\n", 15, 250); uart_controller_write_bytes(uart, (const uint8_t*)"$CFGMSG,6,0,0\r\n", 15, 250);
kernel::delayMillis(250); delay_millis(250);
uart_controller_write_bytes(uart, (const uint8_t*)"$CFGMSG,6,1,0\r\n", 15, 250); uart_controller_write_bytes(uart, (const uint8_t*)"$CFGMSG,6,1,0\r\n", 15, 250);
kernel::delayMillis(250); delay_millis(250);
return true; return true;
} }
bool initAtgm336h(::Device* uart) { bool init_atgm336h(Device* uart) {
uint8_t buffer[256]; uint8_t buffer[256];
// Set the intial configuration of the device - these _should_ work for most AT6558 devices // Set the intial configuration of the device - these _should_ work for most AT6558 devices
int msglen = makeCASPacket(buffer, 0x06, 0x07, sizeof(_message_CAS_CFG_NAVX_CONF), _message_CAS_CFG_NAVX_CONF); int msglen = make_cas_packet(buffer, 0x06, 0x07, sizeof(CAS_MESSAGE_CFG_NAVX_CONF), CAS_MESSAGE_CFG_NAVX_CONF);
uart_controller_write_bytes(uart, buffer, msglen, 250); uart_controller_write_bytes(uart, buffer, msglen, 250);
if (getACKCas(uart, 0x06, 0x07, 250) != GpsResponse::Ok) { if (get_ack_cas(uart, 0x06, 0x07, 250) != GpsResponse::Ok) {
LOG_W(TAG, "ATGM336H: Could not set Config"); LOG_W(TAG, "ATGM336H: Could not set Config");
} }
// Set the update frequence to 1Hz // Set the update frequence to 1Hz
msglen = makeCASPacket(buffer, 0x06, 0x04, sizeof(_message_CAS_CFG_RATE_1HZ), _message_CAS_CFG_RATE_1HZ); msglen = make_cas_packet(buffer, 0x06, 0x04, sizeof(CAS_MESSAGE_CFG_RATE_1HZ), CAS_MESSAGE_CFG_RATE_1HZ);
uart_controller_write_bytes(uart, buffer, msglen, 250); uart_controller_write_bytes(uart, buffer, msglen, 250);
if (getACKCas(uart, 0x06, 0x04, 250) != GpsResponse::Ok) { if (get_ack_cas(uart, 0x06, 0x04, 250) != GpsResponse::Ok) {
LOG_W(TAG, "ATGM336H: Could not set Update Frequency"); LOG_W(TAG, "ATGM336H: Could not set Update Frequency");
} }
@@ -235,64 +227,62 @@ bool initAtgm336h(::Device* uart) {
for (unsigned int i = 0; i < sizeof(fields); i++) { for (unsigned int i = 0; i < sizeof(fields); i++) {
// Construct a CAS-CFG-MSG packet // Construct a CAS-CFG-MSG packet
uint8_t cas_cfg_msg_packet[] = {0x4e, fields[i], 0x01, 0x00}; uint8_t cas_cfg_msg_packet[] = {0x4e, fields[i], 0x01, 0x00};
msglen = makeCASPacket(buffer, 0x06, 0x01, sizeof(cas_cfg_msg_packet), cas_cfg_msg_packet); msglen = make_cas_packet(buffer, 0x06, 0x01, sizeof(cas_cfg_msg_packet), cas_cfg_msg_packet);
uart_controller_write_bytes(uart, buffer, msglen, 250); uart_controller_write_bytes(uart, buffer, msglen, 250);
if (getACKCas(uart, 0x06, 0x01, 250) != GpsResponse::Ok) { if (get_ack_cas(uart, 0x06, 0x01, 250) != GpsResponse::Ok) {
LOG_W(TAG, "ATGM336H: Could not enable NMEA MSG: %u", fields[i]); LOG_W(TAG, "ATGM336H: Could not enable NMEA MSG: %u", fields[i]);
} }
} }
return true; return true;
} }
bool initMtkPa1616s(::Device* uart) { bool init_mtk_pa1616s(Device* uart) {
// PA1616S is used in some GPS breakout boards from Adafruit // PA1616S is used in some GPS breakout boards from Adafruit
// PA1616S does not have GLONASS capability. PA1616D does, but is not implemented here. // PA1616S does not have GLONASS capability. PA1616D does, but is not implemented here.
uart_controller_write_bytes(uart, (const uint8_t*)"$PMTK353,1,0,0,0,0*2A\r\n", 23, 250); uart_controller_write_bytes(uart, (const uint8_t*)"$PMTK353,1,0,0,0,0*2A\r\n", 23, 250);
// Above command will reset the GPS and takes longer before it will accept new commands // Above command will reset the GPS and takes longer before it will accept new commands
kernel::delayMillis(1000); delay_millis(1000);
// Only ask for RMC and GGA (GNRMC and GNGGA) // Only ask for RMC and GGA (GNRMC and GNGGA)
uart_controller_write_bytes(uart, (const uint8_t*)"$PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*28\r\n", 51, 250); uart_controller_write_bytes(uart, (const uint8_t*)"$PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*28\r\n", 51, 250);
kernel::delayMillis(250); delay_millis(250);
// Enable SBAS / WAAS // Enable SBAS / WAAS
uart_controller_write_bytes(uart, (const uint8_t*)"$PMTK301,2*2E\r\n", 15, 250); uart_controller_write_bytes(uart, (const uint8_t*)"$PMTK301,2*2E\r\n", 15, 250);
kernel::delayMillis(250); delay_millis(250);
return true; return true;
} }
bool initMtkL76b(::Device* uart) { bool init_mtk_l76b(Device* uart) {
// Waveshare Pico-GPS hat uses the L76B with 9600 baud // Waveshare Pico-GPS hat uses the L76B with 9600 baud
// Initialize the L76B Chip, use GPS + GLONASS // Initialize the L76B Chip, use GPS + GLONASS
// See note in L76_Series_GNSS_Protocol_Specification, chapter 3.29 // See note in L76_Series_GNSS_Protocol_Specification, chapter 3.29
uart_controller_write_bytes(uart, (const uint8_t*)"$PMTK353,1,1,0,0,0*2B\r\n", 23, 250); uart_controller_write_bytes(uart, (const uint8_t*)"$PMTK353,1,1,0,0,0*2B\r\n", 23, 250);
// Above command will reset the GPS and takes longer before it will accept new commands // Above command will reset the GPS and takes longer before it will accept new commands
kernel::delayMillis(1000); delay_millis(1000);
// only ask for RMC and GGA (GNRMC and GNGGA) // only ask for RMC and GGA (GNRMC and GNGGA)
// See note in L76_Series_GNSS_Protocol_Specification, chapter 2.1 // See note in L76_Series_GNSS_Protocol_Specification, chapter 2.1
uart_controller_write_bytes(uart, (const uint8_t*)"$PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*28\r\n", 51, 250); uart_controller_write_bytes(uart, (const uint8_t*)"$PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*28\r\n", 51, 250);
kernel::delayMillis(250); delay_millis(250);
// Enable SBAS // Enable SBAS
uart_controller_write_bytes(uart, (const uint8_t*)"$PMTK301,2*2E\r\n", 15, 250); uart_controller_write_bytes(uart, (const uint8_t*)"$PMTK301,2*2E\r\n", 15, 250);
kernel::delayMillis(250); delay_millis(250);
// Enable PPS for 2D/3D fix only // Enable PPS for 2D/3D fix only
uart_controller_write_bytes(uart, (const uint8_t*)"$PMTK285,3,100*3F\r\n", 19, 250); uart_controller_write_bytes(uart, (const uint8_t*)"$PMTK285,3,100*3F\r\n", 19, 250);
kernel::delayMillis(250); delay_millis(250);
// Switch to Fitness Mode, for running and walking purpose with low speed (<5 m/s) // Switch to Fitness Mode, for running and walking purpose with low speed (<5 m/s)
uart_controller_write_bytes(uart, (const uint8_t*)"$PMTK886,1*29\r\n", 15, 250); uart_controller_write_bytes(uart, (const uint8_t*)"$PMTK886,1*29\r\n", 15, 250);
kernel::delayMillis(250); delay_millis(250);
return true; return true;
} }
bool initMtk(::Device* uart) { bool init_mtk(Device* uart) {
// Initialize the L76K Chip, use GPS + GLONASS + BEIDOU // Initialize the L76K Chip, use GPS + GLONASS + BEIDOU
uart_controller_write_bytes(uart, (const uint8_t*)"$PCAS04,7*1E\r\n", 14, 250); uart_controller_write_bytes(uart, (const uint8_t*)"$PCAS04,7*1E\r\n", 14, 250);
kernel::delayMillis(250); delay_millis(250);
// only ask for RMC and GGA // only ask for RMC and GGA
uart_controller_write_bytes(uart, (const uint8_t*)"$PCAS03,1,0,0,0,1,0,0,0,0,0,,,0,0*02\r\n", 38, 250); uart_controller_write_bytes(uart, (const uint8_t*)"$PCAS03,1,0,0,0,1,0,0,0,0,0,,,0,0*02\r\n", 38, 250);
kernel::delayMillis(250); delay_millis(250);
// Switch to Vehicle Mode, since SoftRF enables Aviation < 2g // Switch to Vehicle Mode, since SoftRF enables Aviation < 2g
uart_controller_write_bytes(uart, (const uint8_t*)"$PCAS11,3*1E\r\n", 14, 250); uart_controller_write_bytes(uart, (const uint8_t*)"$PCAS11,3*1E\r\n", 14, 250);
kernel::delayMillis(250); delay_millis(250);
return true; return true;
} }
} // namespace tt::hal::gps
@@ -0,0 +1,19 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include <tactility/driver.h>
#include <tactility/module.h>
extern "C" {
extern Driver generic_gps_driver;
static Driver* const gps_generic_drivers[] = {
&generic_gps_driver,
nullptr
};
Module gps_generic_module = {
.name = "gps-generic",
.drivers = gps_generic_drivers
};
}
+120
View File
@@ -0,0 +1,120 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include <gps_generic/private/gps_response.h>
#include <gps_generic/private/probe.h>
#include <gps_generic/private/ublox.h>
#include <tactility/delay.h>
#include <tactility/device.h>
#include <tactility/drivers/uart_controller.h>
#include <tactility/log.h>
#include <tactility/time.h>
#include <cstring>
constexpr auto* TAG = "Gps";
static char* probe_strnstr(const char* s, const char* find, size_t slen) {
char c;
if ((c = *find++) != '\0') {
char sc;
size_t len;
len = strlen(find);
do {
do {
if (slen-- < 1 || (sc = *s++) == '\0')
return (nullptr);
} while (sc != c);
if (len > slen)
return (nullptr);
} while (strncmp(s, find, len) != 0);
s--;
}
return ((char*)s);
}
static GpsResponse get_ack(Device* uart, const char* message, uint32_t wait_millis) {
uint8_t buffer[768] = {0};
uint8_t b;
int bytes_read = 0;
uint32_t start_timeout = get_millis() + wait_millis;
while (get_millis() < start_timeout) {
size_t available = 0;
uart_controller_get_available(uart, &available);
if (available > 0) {
uart_controller_read_byte(uart, &b, 1);
buffer[bytes_read] = b;
bytes_read++;
if ((bytes_read == 767) || (b == '\r')) {
if (probe_strnstr((char*)buffer, message, bytes_read) != nullptr) {
return GpsResponse::Ok;
} else {
bytes_read = 0;
}
}
}
}
return GpsResponse::None;
}
#define PROBE_SIMPLE(UART, CHIP, TOWRITE, RESPONSE, DRIVER, TIMEOUT, ...) \
do { \
LOG_I(TAG, "Probing for %s (%s)", CHIP, TOWRITE); \
uart_controller_flush_input(UART); \
uart_controller_write_bytes(UART, (const uint8_t*)(TOWRITE "\r\n"), strlen(TOWRITE "\r\n"), TIMEOUT); \
if (get_ack(UART, RESPONSE, TIMEOUT) == GpsResponse::Ok) { \
LOG_I(TAG, "Probe detected %s %s", CHIP, #DRIVER); \
return DRIVER; \
} \
} while (0)
GpsModel gps_probe(Device* uart) {
// Close all NMEA sentences
// Valid for L76K, ATGM336H and likely other AT6558 devices
uart_controller_write_bytes(uart, reinterpret_cast<const uint8_t*>("$PCAS03,0,0,0,0,0,0,0,0,0,0,,,0,0*02\r\n"), 40, 500);
delay_millis(20);
// Close NMEA sequences on Ublox
uart_controller_write_bytes(uart, reinterpret_cast<const uint8_t*>("$PUBX,40,GLL,0,0,0,0,0,0*5C\r\n"), 29, 500);
uart_controller_write_bytes(uart, reinterpret_cast<const uint8_t*>("$PUBX,40,GSV,0,0,0,0,0,0*59\r\n"), 29, 500);
uart_controller_write_bytes(uart, reinterpret_cast<const uint8_t*>("$PUBX,40,VTG,0,0,0,0,0,0*5E\r\n"), 29, 500);
delay_millis(20);
// Unicore UFirebirdII Series: UC6580, UM620, UM621, UM670A, UM680A, or UM681A
PROBE_SIMPLE(uart, "UC6580", "$PDTINFO", "UC6580", GpsModel::GPS_MODEL_UC6580, 500);
PROBE_SIMPLE(uart, "UM600", "$PDTINFO", "UM600", GpsModel::GPS_MODEL_UC6580, 500);
PROBE_SIMPLE(uart, "ATGM336H", "$PCAS06,1*1A", "$GPTXT,01,01,02,HW=ATGM336H", GpsModel::GPS_MODEL_ATGM336H, 500);
// ATGM332D series (-11(GPS), -21(BDS), -31(GPS+BDS), -51(GPS+GLONASS), -71-0(GPS+BDS+GLONASS)) based on AT6558
PROBE_SIMPLE(uart, "ATGM332D", "$PCAS06,1*1A", "$GPTXT,01,01,02,HW=ATGM332D", GpsModel::GPS_MODEL_ATGM336H, 500);
// Airoha (Mediatek) AG3335A/M/S, A3352Q, Quectel L89 2.0, SimCom SIM65M
// GSA OFF, reduce volume
uart_controller_write_bytes(uart, reinterpret_cast<const uint8_t*>("$PAIR062,2,0*3C\r\n"), 17, 500);
// GSV OFF, reduce volume
uart_controller_write_bytes(uart, reinterpret_cast<const uint8_t*>("$PAIR062,3,0*3D\r\n"), 17, 500);
// Save configuration
uart_controller_write_bytes(uart, reinterpret_cast<const uint8_t*>("$PAIR513*3D\r\n"), 13, 500);
PROBE_SIMPLE(uart, "AG3335", "$PAIR021*39", "$PAIR021,AG3335", GpsModel::GPS_MODEL_AG3335, 500);
PROBE_SIMPLE(uart, "AG3352", "$PAIR021*39", "$PAIR021,AG3352", GpsModel::GPS_MODEL_AG3352, 500);
PROBE_SIMPLE(uart, "LC86", "$PQTMVERNO*58", "$PQTMVERNO,LC86", GpsModel::GPS_MODEL_AG3352, 500);
PROBE_SIMPLE(uart, "L76K", "$PCAS06,0*1B", "$GPTXT,01,01,02,SW=", GpsModel::GPS_MODEL_MTK, 500);
// Close all NMEA sentences
// Valid for L76B MTK
uart_controller_write_bytes(uart, reinterpret_cast<const uint8_t*>("$PMTK514,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*2E\r\n"), 51, 500);
delay_millis(20);
PROBE_SIMPLE(uart, "L76B", "$PMTK605*31", "Quectel-L76B", GpsModel::GPS_MODEL_MTK_L76B, 500);
PROBE_SIMPLE(uart, "PA1616S", "$PMTK605*31", "1616S", GpsModel::GPS_MODEL_MTK_PA1616S, 500);
auto ublox_result = gps_ublox::probe(uart);
if (ublox_result != GPS_MODEL_UNKNOWN) {
return ublox_result;
} else {
LOG_W(TAG, "No GNSS Module");
return GPS_MODEL_UNKNOWN;
}
}
@@ -1,26 +1,32 @@
#include <Tactility/hal/gps/Ublox.h> // SPDX-License-Identifier: GPL-3.0-or-later
#include <Tactility/hal/gps/UbloxMessages.h> #include <gps_generic/private/ublox.h>
#include <Tactility/kernel/Kernel.h> #include <gps_generic/private/gps_response.h>
#include <gps_generic/private/ublox_messages.h>
#include <gps/gps.h>
#include <tactility/delay.h>
#include <tactility/device.h> #include <tactility/device.h>
#include <tactility/drivers/uart_controller.h> #include <tactility/drivers/uart_controller.h>
#include <tactility/log.h> #include <tactility/log.h>
#include <tactility/time.h>
#include <cstring> #include <cstring>
#include <cstdlib>
namespace tt::hal::gps::ublox { namespace gps_ublox {
constexpr auto* TAG = "Ublox"; constexpr auto* TAG = "Ublox";
bool initUblox6(::Device* uart); bool init_ublox_6(Device* uart);
bool initUblox789(::Device* uart, GpsModel model); bool init_ublox_789(Device* uart, GpsModel model);
bool initUblox10(::Device* uart); bool init_ublox_10(Device* uart);
#define SEND_UBX_PACKET(UART, BUFFER, TYPE, ID, DATA, ERRMSG, TIMEOUT_MILLIS) \ #define SEND_UBX_PACKET(UART, BUFFER, TYPE, ID, DATA, ERRMSG, TIMEOUT_MILLIS) \
do { \ do { \
auto msglen = makePacket(TYPE, ID, DATA, sizeof(DATA), BUFFER); \ auto msglen = make_packet(TYPE, ID, DATA, sizeof(DATA), BUFFER); \
uart_controller_write_bytes(UART, BUFFER, msglen, TIMEOUT_MILLIS / portTICK_PERIOD_MS); \ uart_controller_write_bytes(UART, BUFFER, msglen, TIMEOUT_MILLIS / portTICK_PERIOD_MS); \
if (getAck(UART, TYPE, ID, TIMEOUT_MILLIS) != GpsResponse::Ok) { \ if (get_ack(UART, TYPE, ID, TIMEOUT_MILLIS) != GpsResponse::Ok) { \
LOG_I(TAG, "Sending packet failed: %s", #ERRMSG); \ LOG_I(TAG, "Sending packet failed: %s", #ERRMSG); \
} \ } \
} while (0) } while (0)
@@ -39,37 +45,34 @@ void checksum(uint8_t* message, size_t length) {
message[length - 1] = CK_B; message[length - 1] = CK_B;
} }
uint8_t makePacket(uint8_t classId, uint8_t messageId, const uint8_t* payload, uint8_t payloadSize, uint8_t* bufferOut) { uint8_t make_packet(uint8_t class_id, uint8_t message_id, const uint8_t* payload, uint8_t payload_size, uint8_t* buffer_out) {
// Construct the UBX packet // Construct the UBX packet
bufferOut[0] = 0xB5U; // header buffer_out[0] = 0xB5U; // header
bufferOut[1] = 0x62U; // header buffer_out[1] = 0x62U; // header
bufferOut[2] = classId; // class buffer_out[2] = class_id; // class
bufferOut[3] = messageId; // id buffer_out[3] = message_id; // id
bufferOut[4] = payloadSize; // length buffer_out[4] = payload_size; // length
bufferOut[5] = 0x00U; buffer_out[5] = 0x00U;
bufferOut[6 + payloadSize] = 0x00U; // CK_A buffer_out[6 + payload_size] = 0x00U; // CK_A
bufferOut[7 + payloadSize] = 0x00U; // CK_B buffer_out[7 + payload_size] = 0x00U; // CK_B
for (int i = 0; i < payloadSize; i++) { for (int i = 0; i < payload_size; i++) {
bufferOut[6 + i] = payload[i]; buffer_out[6 + i] = payload[i];
} }
checksum(bufferOut, (payloadSize + 8U)); checksum(buffer_out, (payload_size + 8U));
return (payloadSize + 8U); return (payload_size + 8U);
} }
GpsResponse getAck(::Device* uart, uint8_t class_id, uint8_t msg_id, uint32_t waitMillis) { GpsResponse get_ack(Device* uart, uint8_t class_id, uint8_t msg_id, uint32_t wait_millis) {
uint8_t b; uint8_t b;
uint8_t ack = 0; uint8_t ack = 0;
const uint8_t ackP[2] = {class_id, msg_id}; const uint8_t ackP[2] = {class_id, msg_id};
uint8_t buf[10] = {0xB5, 0x62, 0x05, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00}; uint8_t buf[10] = {0xB5, 0x62, 0x05, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00};
uint32_t startTime = kernel::getTicks(); uint32_t start_time = get_ticks();
TickType_t waitTicks = pdMS_TO_TICKS(waitMillis); TickType_t wait_ticks = pdMS_TO_TICKS(wait_millis);
const char frame_errors[] = "More than 100 frame errors"; const char frame_errors[] = "More than 100 frame errors";
int sCounter = 0; int sCounter = 0;
#ifdef GPS_DEBUG
std::string debugmsg = "";
#endif
for (int j = 2; j < 6; j++) { for (int j = 2; j < 6; j++) {
buf[8] += buf[j]; buf[8] += buf[j];
@@ -82,11 +85,8 @@ GpsResponse getAck(::Device* uart, uint8_t class_id, uint8_t msg_id, uint32_t wa
buf[9] += buf[8]; buf[9] += buf[8];
} }
while (kernel::getTicks() - startTime < waitTicks) { while (get_ticks() - start_time < wait_ticks) {
if (ack > 9) { if (ack > 9) {
#ifdef GPS_DEBUG
LOG_I(TAG, "Got ACK for class %02X message %02X in %zums", class_id, msg_id, kernel::getMillis() - startTime);
#endif
return GpsResponse::Ok; // ACK received return GpsResponse::Ok; // ACK received
} }
size_t available = 0; size_t available = 0;
@@ -96,25 +96,15 @@ GpsResponse getAck(::Device* uart, uint8_t class_id, uint8_t msg_id, uint32_t wa
if (b == frame_errors[sCounter]) { if (b == frame_errors[sCounter]) {
sCounter++; sCounter++;
if (sCounter == 26) { if (sCounter == 26) {
#ifdef GPS_DEBUG
LOG_I(TAG, "%s", debugmsg.c_str());
#endif
return GpsResponse::FrameErrors; return GpsResponse::FrameErrors;
} }
} else { } else {
sCounter = 0; sCounter = 0;
} }
#ifdef GPS_DEBUG
debugmsg += std::format("%02X", b);
#endif
if (b == buf[ack]) { if (b == buf[ack]) {
ack++; ack++;
} else { } else {
if (ack == 3 && b == 0x00) { // UBX-ACK-NAK message if (ack == 3 && b == 0x00) { // UBX-ACK-NAK message
#ifdef GPS_DEBUG
LOG_I(TAG, "%s", debugmsg.c_str());
#endif
LOG_W(TAG, "Got NAK for class %02X message %02X", class_id, msg_id); LOG_W(TAG, "Got NAK for class %02X message %02X", class_id, msg_id);
return GpsResponse::NotAck; // NAK received return GpsResponse::NotAck; // NAK received
} }
@@ -122,20 +112,17 @@ GpsResponse getAck(::Device* uart, uint8_t class_id, uint8_t msg_id, uint32_t wa
} }
} }
} }
#ifdef GPS_DEBUG
LOG_I(TAG, "%s", debugmsg.c_str());
LOG_W(TAG, "No response for class %02X message %02X", class_id, msg_id); LOG_W(TAG, "No response for class %02X message %02X", class_id, msg_id);
#endif
return GpsResponse::None; // No response received within timeout return GpsResponse::None; // No response received within timeout
} }
static int getAck(::Device* uart, uint8_t* buffer, uint16_t size, uint8_t requestedClass, uint8_t requestedId, uint32_t timeoutMillis) { static int get_ack(Device* uart, uint8_t* buffer, uint16_t size, uint8_t requested_class, uint8_t requested_id, uint32_t timeout_millis) {
uint16_t ubxFrameCounter = 0; uint16_t ubx_frame_counter = 0;
TickType_t startTime = kernel::getTicks(); TickType_t start_time = get_ticks();
TickType_t timeoutTicks = pdMS_TO_TICKS(timeoutMillis); TickType_t timeout_ticks = pdMS_TO_TICKS(timeout_millis);
uint16_t needRead = 0; uint16_t need_read = 0;
while ((kernel::getTicks() - startTime) < timeoutTicks) { while ((get_ticks() - start_time) < timeout_ticks) {
size_t available = 0; size_t available = 0;
uart_controller_get_available(uart, &available); uart_controller_get_available(uart, &available);
while (available > 0) { while (available > 0) {
@@ -143,56 +130,53 @@ static int getAck(::Device* uart, uint8_t* buffer, uint16_t size, uint8_t reques
uart_controller_read_byte(uart, &c, 1); uart_controller_read_byte(uart, &c, 1);
available--; available--;
switch (ubxFrameCounter) { switch (ubx_frame_counter) {
case 0: case 0:
if (c == 0xB5) { if (c == 0xB5) {
ubxFrameCounter++; ubx_frame_counter++;
} }
break; break;
case 1: case 1:
if (c == 0x62) { if (c == 0x62) {
ubxFrameCounter++; ubx_frame_counter++;
} else { } else {
ubxFrameCounter = 0; ubx_frame_counter = 0;
} }
break; break;
case 2: case 2:
if (c == requestedClass) { if (c == requested_class) {
ubxFrameCounter++; ubx_frame_counter++;
} else { } else {
ubxFrameCounter = 0; ubx_frame_counter = 0;
} }
break; break;
case 3: case 3:
if (c == requestedId) { if (c == requested_id) {
ubxFrameCounter++; ubx_frame_counter++;
} else { } else {
ubxFrameCounter = 0; ubx_frame_counter = 0;
} }
break; break;
case 4: case 4:
needRead = c; need_read = c;
ubxFrameCounter++; ubx_frame_counter++;
break; break;
case 5: { case 5: {
// Payload length msb // Payload length msb
needRead |= (c << 8); need_read |= (c << 8);
ubxFrameCounter++; ubx_frame_counter++;
// Check for buffer overflow // Check for buffer overflow
if (needRead >= size) { if (need_read >= size) {
ubxFrameCounter = 0; ubx_frame_counter = 0;
break; break;
} }
auto read_bytes = 0U; auto read_bytes = 0U;
uart_controller_read_bytes(uart, buffer, needRead, 250 / portTICK_PERIOD_MS); uart_controller_read_bytes(uart, buffer, need_read, 250 / portTICK_PERIOD_MS);
if (read_bytes != needRead) { if (read_bytes != need_read) {
ubxFrameCounter = 0; ubx_frame_counter = 0;
} else { } else {
// return payload length // return payload length
#ifdef GPS_DEBUG return need_read;
LOG_I(TAG, "Got ACK for class %02X message %02X in %zums", requestedClass, requestedId, kernel::getMillis() - startTime);
#endif
return needRead;
} }
break; break;
} }
@@ -205,7 +189,7 @@ static int getAck(::Device* uart, uint8_t* buffer, uint16_t size, uint8_t reques
return 0; return 0;
} }
static struct uBloxGnssModelInfo { static struct UbloxGnssModelInfo {
char swVersion[30]; char swVersion[30];
char hwVersion[10]; char hwVersion[10];
uint8_t extensionNo; uint8_t extensionNo;
@@ -213,7 +197,7 @@ static struct uBloxGnssModelInfo {
uint8_t protocol_version; uint8_t protocol_version;
} ublox_info; } ublox_info;
GpsModel probe(::Device* uart) { GpsModel probe(Device* uart) {
LOG_I(TAG, "Probing for U-blox"); LOG_I(TAG, "Probing for U-blox");
uint8_t cfg_rate[] = {0xB5, 0x62, 0x06, 0x08, 0x00, 0x00, 0x00, 0x00}; uint8_t cfg_rate[] = {0xB5, 0x62, 0x06, 0x08, 0x00, 0x00, 0x00, 0x00};
@@ -221,28 +205,28 @@ GpsModel probe(::Device* uart) {
uart_controller_flush_input(uart); uart_controller_flush_input(uart);
uart_controller_write_bytes(uart, cfg_rate, sizeof(cfg_rate), 500 / portTICK_PERIOD_MS); uart_controller_write_bytes(uart, cfg_rate, sizeof(cfg_rate), 500 / portTICK_PERIOD_MS);
// Check that the returned response class and message ID are correct // Check that the returned response class and message ID are correct
GpsResponse response = getAck(uart, 0x06, 0x08, 750); GpsResponse response = get_ack(uart, 0x06, 0x08, 750);
if (response == GpsResponse::None) { if (response == GpsResponse::None) {
LOG_W(TAG, "No GNSS Module"); LOG_W(TAG, "No GNSS Module");
return GpsModel::Unknown; return GpsModel::GPS_MODEL_UNKNOWN;
} else if (response == GpsResponse::FrameErrors) { } else if (response == GpsResponse::FrameErrors) {
LOG_W(TAG, "UBlox Frame Errors"); LOG_W(TAG, "UBlox Frame Errors");
} }
uint8_t buffer[256]; uint8_t buffer[256];
memset(buffer, 0, sizeof(buffer)); memset(buffer, 0, sizeof(buffer));
uint8_t _message_MONVER[8] = { uint8_t message_monver[8] = {
0xB5, 0x62, // Sync message for UBX protocol 0xB5, 0x62, // Sync message for UBX protocol
0x0A, 0x04, // Message class and ID (UBX-MON-VER) 0x0A, 0x04, // Message class and ID (UBX-MON-VER)
0x00, 0x00, // Length of payload (we're asking for an answer, so no payload) 0x00, 0x00, // Length of payload (we're asking for an answer, so no payload)
0x00, 0x00 // Checksum 0x00, 0x00 // Checksum
}; };
// Get Ublox gnss module hardware and software info // Get Ublox gnss module hardware and software info
checksum(_message_MONVER, sizeof(_message_MONVER)); checksum(message_monver, sizeof(message_monver));
uart_controller_flush_input(uart); uart_controller_flush_input(uart);
uart_controller_write_bytes(uart, _message_MONVER, sizeof(_message_MONVER), 500); uart_controller_write_bytes(uart, message_monver, sizeof(message_monver), 500);
uint16_t ack_response_len = getAck(uart, buffer, sizeof(buffer), 0x0A, 0x04, 1200); uint16_t ack_response_len = get_ack(uart, buffer, sizeof(buffer), 0x0A, 0x04, 1200);
if (ack_response_len) { if (ack_response_len) {
uint16_t position = 0; uint16_t position = 0;
for (char& i: ublox_info.swVersion) { for (char& i: ublox_info.swVersion) {
@@ -294,86 +278,86 @@ GpsModel probe(::Device* uart) {
#define DETECTED_MESSAGE "%s detected, using %s Module" #define DETECTED_MESSAGE "%s detected, using %s Module"
if (strncmp(ublox_info.hwVersion, "00040007", 8) == 0) { if (strncmp(ublox_info.hwVersion, "00040007", 8) == 0) {
LOG_I(TAG, DETECTED_MESSAGE, "U-blox 6", "6"); LOG_I(TAG, DETECTED_MESSAGE, "U-blox 6", "6");
return GpsModel::UBLOX6; return GPS_MODEL_UBLOX6;
} else if (strncmp(ublox_info.hwVersion, "00070000", 8) == 0) { } else if (strncmp(ublox_info.hwVersion, "00070000", 8) == 0) {
LOG_I(TAG, DETECTED_MESSAGE, "U-blox 7", "7"); LOG_I(TAG, DETECTED_MESSAGE, "U-blox 7", "7");
return GpsModel::UBLOX7; return GPS_MODEL_UBLOX7;
} else if (strncmp(ublox_info.hwVersion, "00080000", 8) == 0) { } else if (strncmp(ublox_info.hwVersion, "00080000", 8) == 0) {
LOG_I(TAG, DETECTED_MESSAGE, "U-blox 8", "8"); LOG_I(TAG, DETECTED_MESSAGE, "U-blox 8", "8");
return GpsModel::UBLOX8; return GPS_MODEL_UBLOX8;
} else if (strncmp(ublox_info.hwVersion, "00190000", 8) == 0) { } else if (strncmp(ublox_info.hwVersion, "00190000", 8) == 0) {
LOG_I(TAG, DETECTED_MESSAGE, "U-blox 9", "9"); LOG_I(TAG, DETECTED_MESSAGE, "U-blox 9", "9");
return GpsModel::UBLOX9; return GPS_MODEL_UBLOX9;
} else if (strncmp(ublox_info.hwVersion, "000A0000", 8) == 0) { } else if (strncmp(ublox_info.hwVersion, "000A0000", 8) == 0) {
LOG_I(TAG, DETECTED_MESSAGE, "U-blox 10", "10"); LOG_I(TAG, DETECTED_MESSAGE, "U-blox 10", "10");
return GpsModel::UBLOX10; return GPS_MODEL_UBLOX10;
} }
} }
return GpsModel::Unknown; return GPS_MODEL_UNKNOWN;
} }
bool init(::Device* uart, GpsModel model) { bool init(Device* uart, GpsModel model) {
LOG_I(TAG, "U-blox init"); LOG_I(TAG, "U-blox init");
switch (model) { switch (model) {
case GpsModel::UBLOX6: case GPS_MODEL_UBLOX6:
return initUblox6(uart); return init_ublox_6(uart);
case GpsModel::UBLOX7: case GPS_MODEL_UBLOX7:
case GpsModel::UBLOX8: case GPS_MODEL_UBLOX8:
case GpsModel::UBLOX9: case GPS_MODEL_UBLOX9:
return initUblox789(uart, model); return init_ublox_789(uart, model);
case GpsModel::UBLOX10: case GPS_MODEL_UBLOX10:
return initUblox10(uart); return init_ublox_10(uart);
default: default:
LOG_E(TAG, "Unknown or unsupported U-blox model"); LOG_E(TAG, "Unknown or unsupported U-blox model");
return false; return false;
} }
} }
bool initUblox10(::Device* uart) { bool init_ublox_10(Device* uart) {
uint8_t buffer[256]; uint8_t buffer[256];
kernel::delayMillis(1000); delay_millis(1000);
uart_controller_flush_input(uart); uart_controller_flush_input(uart);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_DISABLE_NMEA_RAM, "disable NMEA messages in M10 RAM", 300); SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_DISABLE_NMEA_RAM, "disable NMEA messages in M10 RAM", 300);
kernel::delayMillis(750); delay_millis(750);
uart_controller_flush_input(uart); uart_controller_flush_input(uart);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_DISABLE_NMEA_BBR, "disable NMEA messages in M10 BBR", 300); SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_DISABLE_NMEA_BBR, "disable NMEA messages in M10 BBR", 300);
kernel::delayMillis(750); delay_millis(750);
uart_controller_flush_input(uart); uart_controller_flush_input(uart);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_DISABLE_TXT_INFO_RAM, "disable Info messages for M10 GPS RAM", 300); SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_DISABLE_TXT_INFO_RAM, "disable Info messages for M10 GPS RAM", 300);
kernel::delayMillis(750); delay_millis(750);
uart_controller_flush_input(uart); uart_controller_flush_input(uart);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_DISABLE_TXT_INFO_BBR, "disable Info messages for M10 GPS BBR", 300); SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_DISABLE_TXT_INFO_BBR, "disable Info messages for M10 GPS BBR", 300);
kernel::delayMillis(750); delay_millis(750);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_PM_RAM, "enable powersave for M10 GPS RAM", 300); SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_PM_RAM, "enable powersave for M10 GPS RAM", 300);
kernel::delayMillis(750); delay_millis(750);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_PM_BBR, "enable powersave for M10 GPS BBR", 300); SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_PM_BBR, "enable powersave for M10 GPS BBR", 300);
kernel::delayMillis(750); delay_millis(750);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_ITFM_RAM, "enable jam detection M10 GPS RAM", 300); SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_ITFM_RAM, "enable jam detection M10 GPS RAM", 300);
kernel::delayMillis(750); delay_millis(750);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_ITFM_BBR, "enable jam detection M10 GPS BBR", 300); SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_ITFM_BBR, "enable jam detection M10 GPS BBR", 300);
kernel::delayMillis(750); delay_millis(750);
// Here is where the init commands should go to do further M10 initialization. // Here is where the init commands should go to do further M10 initialization.
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_DISABLE_SBAS_RAM, "disable SBAS M10 GPS RAM", 300); SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_DISABLE_SBAS_RAM, "disable SBAS M10 GPS RAM", 300);
kernel::delayMillis(750); // will cause a receiver restart so wait a bit delay_millis(750); // will cause a receiver restart so wait a bit
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_DISABLE_SBAS_BBR, "disable SBAS M10 GPS BBR", 300); SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_DISABLE_SBAS_BBR, "disable SBAS M10 GPS BBR", 300);
kernel::delayMillis(750); // will cause a receiver restart so wait a bit delay_millis(750); // will cause a receiver restart so wait a bit
// Done with initialization // Done with initialization
// Enable wanted NMEA messages in BBR layer so they will survive a periodic sleep // Enable wanted NMEA messages in BBR layer so they will survive a periodic sleep
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_ENABLE_NMEA_BBR, "enable messages for M10 GPS BBR", 300); SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_ENABLE_NMEA_BBR, "enable messages for M10 GPS BBR", 300);
kernel::delayMillis(750); delay_millis(750);
// Enable wanted NMEA messages in RAM layer // Enable wanted NMEA messages in RAM layer
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_ENABLE_NMEA_RAM, "enable messages for M10 GPS RAM", 500); SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_ENABLE_NMEA_RAM, "enable messages for M10 GPS RAM", 500);
kernel::delayMillis(750); delay_millis(750);
// As the M10 has no flash, the best we can do to preserve the config is to set it in RAM and BBR. // As the M10 has no flash, the best we can do to preserve the config is to set it in RAM and BBR.
// BBR will survive a restart, and power off for a while, but modules with small backup // BBR will survive a restart, and power off for a while, but modules with small backup
// batteries or super caps will not retain the config for a long power off time. // batteries or super caps will not retain the config for a long power off time.
auto packet_size = makePacket(0x06, 0x09, _message_SAVE_10, sizeof(_message_SAVE_10), buffer); auto packet_size = make_packet(0x06, 0x09, _message_SAVE_10, sizeof(_message_SAVE_10), buffer);
uart_controller_write_bytes(uart, buffer, packet_size, 2000 / portTICK_PERIOD_MS); uart_controller_write_bytes(uart, buffer, packet_size, 2000 / portTICK_PERIOD_MS);
if (getAck(uart, 0x06, 0x09, 2000) != GpsResponse::Ok) { if (get_ack(uart, 0x06, 0x09, 2000) != GpsResponse::Ok) {
LOG_W(TAG, "Unable to save GNSS module config"); LOG_W(TAG, "Unable to save GNSS module config");
} else { } else {
LOG_I(TAG, "GNSS module configuration saved!"); LOG_I(TAG, "GNSS module configuration saved!");
@@ -381,36 +365,36 @@ bool initUblox10(::Device* uart) {
return true; return true;
} }
bool initUblox789(::Device* uart, GpsModel model) { bool init_ublox_789(Device* uart, GpsModel model) {
uint8_t buffer[256]; uint8_t buffer[256];
if (model == GpsModel::UBLOX7) { if (model == GpsModel::GPS_MODEL_UBLOX7) {
LOG_D(TAG, "Set GPS+SBAS"); LOG_D(TAG, "Set GPS+SBAS");
auto msglen = makePacket(0x06, 0x3e, _message_GNSS_7, sizeof(_message_GNSS_7), buffer); auto msglen = make_packet(0x06, 0x3e, _message_GNSS_7, sizeof(_message_GNSS_7), buffer);
uart_controller_write_bytes(uart, buffer, msglen, 800 / portTICK_PERIOD_MS); uart_controller_write_bytes(uart, buffer, msglen, 800 / portTICK_PERIOD_MS);
} else { // 8,9 } else { // 8,9
auto msglen = makePacket(0x06, 0x3e, _message_GNSS_8, sizeof(_message_GNSS_8), buffer); auto msglen = make_packet(0x06, 0x3e, _message_GNSS_8, sizeof(_message_GNSS_8), buffer);
uart_controller_write_bytes(uart, buffer, msglen, 800 / portTICK_PERIOD_MS); uart_controller_write_bytes(uart, buffer, msglen, 800 / portTICK_PERIOD_MS);
} }
if (getAck(uart, 0x06, 0x3e, 800) == GpsResponse::NotAck) { if (get_ack(uart, 0x06, 0x3e, 800) == GpsResponse::NotAck) {
// It's not critical if the module doesn't acknowledge this configuration. // It's not critical if the module doesn't acknowledge this configuration.
LOG_D(TAG, "reconfigure GNSS - defaults maintained. Is this module GPS-only?"); LOG_D(TAG, "reconfigure GNSS - defaults maintained. Is this module GPS-only?");
} else { } else {
if (model == GpsModel::UBLOX7) { if (model == GpsModel::GPS_MODEL_UBLOX7) {
LOG_I(TAG, "GPS+SBAS configured"); LOG_I(TAG, "GPS+SBAS configured");
} else { // 8,9 } else { // 8,9
LOG_I(TAG, "GPS+SBAS+GLONASS+Galileo configured"); LOG_I(TAG, "GPS+SBAS+GLONASS+Galileo configured");
} }
// Documentation say, we need wait at least 0.5s after reconfiguration of GNSS module, before sending next // Documentation say, we need wait at least 0.5s after reconfiguration of GNSS module, before sending next
// commands for the M8 it tends to be more. 1 sec should be enough // commands for the M8 it tends to be more. 1 sec should be enough
kernel::delayMillis(1000); delay_millis(1000);
} }
uart_controller_flush_input(uart); uart_controller_flush_input(uart);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x02, _message_DISABLE_TXT_INFO, "disable text info messages", 500); SEND_UBX_PACKET(uart, buffer, 0x06, 0x02, _message_DISABLE_TXT_INFO, "disable text info messages", 500);
if (model == GpsModel::UBLOX8) { // 8 if (model == GpsModel::GPS_MODEL_UBLOX8) { // 8
uart_controller_flush_input(uart); uart_controller_flush_input(uart);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x39, _message_JAM_8, "enable interference resistance", 500); SEND_UBX_PACKET(uart, buffer, 0x06, 0x39, _message_JAM_8, "enable interference resistance", 500);
@@ -436,7 +420,7 @@ bool initUblox789(::Device* uart, GpsModel model) {
SEND_UBX_PACKET(uart, buffer, 0x06, 0x3B, _message_CFG_PM2, "enable powersave details for GPS", 500); SEND_UBX_PACKET(uart, buffer, 0x06, 0x3B, _message_CFG_PM2, "enable powersave details for GPS", 500);
// For M8 we want to enable NMEA version 4.10 so we can see the additional satellites. // For M8 we want to enable NMEA version 4.10 so we can see the additional satellites.
if (model == GpsModel::UBLOX8) { if (model == GpsModel::GPS_MODEL_UBLOX8) {
uart_controller_flush_input(uart); uart_controller_flush_input(uart);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x17, _message_NMEA, "enable NMEA 4.10", 500); SEND_UBX_PACKET(uart, buffer, 0x06, 0x17, _message_NMEA, "enable NMEA 4.10", 500);
} }
@@ -445,9 +429,9 @@ bool initUblox789(::Device* uart, GpsModel model) {
SEND_UBX_PACKET(uart, buffer, 0x06, 0x3B, _message_CFG_PM2, "enable powersave details for GPS", 500); SEND_UBX_PACKET(uart, buffer, 0x06, 0x3B, _message_CFG_PM2, "enable powersave details for GPS", 500);
} }
auto packet_size = makePacket(0x06, 0x09, _message_SAVE, sizeof(_message_SAVE), buffer); auto packet_size = make_packet(0x06, 0x09, _message_SAVE, sizeof(_message_SAVE), buffer);
uart_controller_write_bytes(uart, buffer, packet_size, 2000 / portTICK_PERIOD_MS); uart_controller_write_bytes(uart, buffer, packet_size, 2000 / portTICK_PERIOD_MS);
if (getAck(uart, 0x06, 0x09, 2000) != GpsResponse::Ok) { if (get_ack(uart, 0x06, 0x09, 2000) != GpsResponse::Ok) {
LOG_W(TAG, "Unable to save GNSS module config"); LOG_W(TAG, "Unable to save GNSS module config");
} else { } else {
LOG_I(TAG, "GNSS module configuration saved!"); LOG_I(TAG, "GNSS module configuration saved!");
@@ -455,7 +439,7 @@ bool initUblox789(::Device* uart, GpsModel model) {
return true; return true;
} }
bool initUblox6(::Device* uart) { bool init_ublox_6(Device* uart) {
uint8_t buffer[256]; uint8_t buffer[256];
uart_controller_flush_input(uart); uart_controller_flush_input(uart);
@@ -479,9 +463,9 @@ bool initUblox6(::Device* uart) {
SEND_UBX_PACKET(uart, buffer, 0x06, 0x3B, _message_CFG_PM2, "enable powersave details for GPS", 500); SEND_UBX_PACKET(uart, buffer, 0x06, 0x3B, _message_CFG_PM2, "enable powersave details for GPS", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x01, _message_AID, "disable UBX-AID", 500); SEND_UBX_PACKET(uart, buffer, 0x06, 0x01, _message_AID, "disable UBX-AID", 500);
auto packet_size = makePacket(0x06, 0x09, _message_SAVE, sizeof(_message_SAVE), buffer); auto packet_size = make_packet(0x06, 0x09, _message_SAVE, sizeof(_message_SAVE), buffer);
uart_controller_write_bytes(uart, buffer, packet_size, 2000); uart_controller_write_bytes(uart, buffer, packet_size, 2000);
if (getAck(uart, 0x06, 0x09, 2000) != GpsResponse::Ok) { if (get_ack(uart, 0x06, 0x09, 2000) != GpsResponse::Ok) {
LOG_W(TAG, "Unable to save GNSS module config"); LOG_W(TAG, "Unable to save GNSS module config");
} else { } else {
LOG_I(TAG, "GNSS module config saved!"); LOG_I(TAG, "GNSS module config saved!");
@@ -489,4 +473,4 @@ bool initUblox6(::Device* uart) {
return true; return true;
} }
} // namespace tt::hal::gps::ublox }
+2 -1
View File
@@ -95,9 +95,10 @@ else ()
list(APPEND REQUIRES_LIST list(APPEND REQUIRES_LIST
Tactility Tactility
TactilityFreeRtos TactilityFreeRtos
hal-device-module
lvgl-module lvgl-module
crypt-module crypt-module
gps-module
gps-generic-module
SDL2::SDL2-static SDL2::SDL2-static
SDL2-static SDL2-static
) )
+1 -17
View File
@@ -1,6 +1,5 @@
#include <Tactility/Tactility.h> #include <Tactility/Tactility.h>
#include <tactility/driver.h>
#include <devicetree.h> #include <devicetree.h>
#ifdef ESP_PLATFORM #ifdef ESP_PLATFORM
@@ -9,30 +8,15 @@
#include <Simulator.h> #include <Simulator.h>
#endif #endif
#ifdef CONFIG_TT_USE_DEPRECATED_HAL
// Each board project declares this variable
extern const tt::hal::Configuration hardwareConfiguration;
#else
// Legacy placeholder (required until legacy HAL is cleaned up everywhere)
extern const tt::hal::Configuration hardwareConfiguration = {};
#endif
extern "C" { extern "C" {
void app_main() { void app_main() {
static const tt::Configuration config = {
/**
* Auto-select a board based on the ./sdkconfig.board.* file
* that you copied to ./sdkconfig before you opened this project.
*/
.hardware = &hardwareConfiguration
};
#ifdef ESP_PLATFORM #ifdef ESP_PLATFORM
tt_init_tactility_c(); // ELF bindings for side-loading on ESP32 tt_init_tactility_c(); // ELF bindings for side-loading on ESP32
#endif #endif
tt::run(config, dts_modules, dts_devices); tt::run(dts_modules, dts_devices);
} }
} // extern } // extern
+9 -6
View File
@@ -7,13 +7,16 @@ These applications are not part of the Tactility operating system's main firmwar
"end-users" refers to people who install and/or use Tactility software on their devices. "end-users" refers to people who install and/or use Tactility software on their devices.
## Past & Present ## Summary
Formerly, there was a mixed usage of [GPL v3.0](Documentation/LICENSE-GPL-3.0.md) for internal subprojects The main firmware projects (`Firmware/`, `Tactility/`) are licensed under [GPL v3.0](Documentation/LICENSE-GPL-3.0.md)
and [Apache License v2.0](Documentation/LICENSE-Apache-2.0.md) for subprojects that would be used in external apps.
For future subprojects, [Apache License v2.0](Documentation/LICENSE-Apache-2.0.md) will be chosen for internal subproject. Most drivers have an [Apache License v2.0](Documentation/LICENSE-Apache-2.0.md), with exceptions such as `Drivers/gps-generic-module/`.
Existing GPL-licensed projects will retain this license, as it cannot be changed to a more permissive license. Licensing may also differ for subprojects intended for use in external applications.
Specific aren't generally used directly in external app projects, but if they are, make sure to check their licenses.
All projects under `Modules/` have an [Apache License v2.0](Documentation/LICENSE-Apache-2.0.md).
## Overview ## Overview
@@ -22,13 +25,13 @@ Below is an overview of the licenses of some of the subprojects.
| Project | License | | Project | License |
|--------------------|-------------------------| |--------------------|-------------------------|
| Tactility | GNU Public License v3.0 | | Tactility | GNU Public License v3.0 |
| TactilityCore | GNU Public License v3.0 |
| TactilityC | Apache License v2.0 | | TactilityC | Apache License v2.0 |
| TactilityFreeRTOS | Apache License v2.0 | | TactilityFreeRTOS | Apache License v2.0 |
| TactilityKernel | Apache License v2.0 | | TactilityKernel | Apache License v2.0 |
| Tests | GNU Public License v3.0 | | Tests | GNU Public License v3.0 |
| Devices/* | GNU Public License v3.0 | | Devices/* | GNU Public License v3.0 |
| Drivers/* | (varies) | | Drivers/* | (varies) |
| Modules/* | Apache License v2.0 |
| DevicetreeCompiler | Apache License v2.0 | | DevicetreeCompiler | Apache License v2.0 |
| Platforms/* | Apache License v2.0 | | Platforms/* | Apache License v2.0 |
+12
View File
@@ -0,0 +1,12 @@
cmake_minimum_required(VERSION 3.20)
include("${CMAKE_CURRENT_LIST_DIR}/../../Buildscripts/module.cmake")
file(GLOB_RECURSE SOURCE_FILES "source/*.c*")
tactility_add_module(gps-module
SRCS ${SOURCE_FILES}
PRIV_INCLUDE_DIRS private/
INCLUDE_DIRS include/
REQUIRES TactilityKernel minmea
)
+195
View File
@@ -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.
+2
View File
@@ -0,0 +1,2 @@
dependencies:
- TactilityKernel
+137
View File
@@ -0,0 +1,137 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include <tactility/device.h>
#include <tactility/error.h>
#include <tactility/freertos/freertos.h>
#include <tactility/freertos/task.h>
#include <minmea.h>
/**
* @brief Supported GPS/GNSS receiver chipsets.
*/
enum GpsModel {
GPS_MODEL_UNKNOWN = 0,
GPS_MODEL_AG3335,
GPS_MODEL_AG3352,
// CASIC, might work with AT6558, Neoway N58 LTE Cat.1, Neoway G2 and Neoway G7A
GPS_MODEL_ATGM336H,
GPS_MODEL_LS20031,
GPS_MODEL_MTK,
GPS_MODEL_MTK_L76B,
GPS_MODEL_MTK_PA1616S,
GPS_MODEL_UBLOX6,
GPS_MODEL_UBLOX7,
GPS_MODEL_UBLOX8,
GPS_MODEL_UBLOX9,
GPS_MODEL_UBLOX10,
GPS_MODEL_UC6580,
};
/** @return a human-readable name for the model, e.g. "UBLOX8" or "Unknown" */
const char* gps_model_to_string(enum GpsModel model);
/**
* @brief Lifecycle state of a GPS_TYPE device.
*/
enum GpsState {
GPS_STATE_OFF,
GPS_STATE_PENDING_ON,
GPS_STATE_ON,
GPS_STATE_ERROR,
GPS_STATE_PENDING_OFF,
};
enum GpsEventType {
GPS_EVENT_UNSUBSCRIBED, // Last event, device wants to destroy itself and unsubscribed the subscriber.
GPS_EVENT_MESSAGE_RMC,
GPS_EVENT_MESSAGE_GGA,
};
struct GpsEvent {
enum GpsEventType type;
union {
struct minmea_sentence_rmc rmc;
struct minmea_sentence_gga gga;
} data;
};
struct GpsSubscription {
TaskHandle_t task;
struct GpsEvent event;
uint32_t sequence;
uint32_t consumed_sequence;
struct GpsSubscription* next;
};
/**
* @brief API for GPS/GNSS receiver drivers.
*/
struct GpsApi {
/**
* @brief Registers a subscriber for GPS events (e.g. RMC/GGA sentences).
* @param[in] device the GPS device
* @param[in,out] sub subscription to register; caller owns the storage and must keep it alive until unsubscribed
*/
error_t (*event_subscribe)(struct Device* device, struct GpsSubscription* sub);
/**
* @brief Removes a previously registered subscription.
* @param[in] device the GPS device
* @param[in] sub subscription to remove, as passed to event_subscribe
*/
error_t (*event_unsubscribe)(struct Device* device, struct GpsSubscription* sub);
/**
* @brief Blocks the calling task until a new event arrives for the subscription, or timeout elapses.
* @param[in] device the GPS device
* @param[in,out] sub subscription to wait on
* @param[in] timeout max ticks to wait
* @return ERROR_NONE if an event arrived, ERROR_TIMEOUT if the timeout elapsed
*/
error_t (*event_await)(struct Device* device, struct GpsSubscription* sub, TickType_t timeout);
/**
* @brief Gets the current lifecycle state.
* @param[in] device the GPS device
*/
enum GpsState (*get_state)(struct Device* device);
/**
* @brief Gets a human-readable model name for the device, e.g. "UBLOX8".
* @param[in] device the GPS device
* @param[out] model_name buffer to receive the NUL-terminated name
* @param[in] buffer_size size of model_name in bytes
* @return ERROR_NONE on success
*/
error_t (*get_model_name)(struct Device* device, char* model_name, size_t buffer_size);
};
/** @copydoc GpsApi::event_subscribe */
error_t gps_event_subscribe(struct Device* device, struct GpsSubscription* sub);
/** @copydoc GpsApi::event_unsubscribe */
error_t gps_event_unsubscribe(struct Device* device, struct GpsSubscription* sub);
/** @copydoc GpsApi::event_await */
error_t gps_event_await(struct Device* device, struct GpsSubscription* sub, TickType_t timeout);
/** @copydoc GpsApi::get_state */
enum GpsState gps_get_state(struct Device* device);
/** @copydoc GpsApi::get_model_name */
error_t gps_get_model_name(struct Device* device, char* model_name, size_t buffer_size);
extern const struct DeviceType GPS_TYPE;
#ifdef __cplusplus
}
#endif
@@ -5,7 +5,7 @@
extern "C" { extern "C" {
#endif #endif
extern struct Module hal_device_module; extern struct Module gps_module;
#ifdef __cplusplus #ifdef __cplusplus
} }
@@ -0,0 +1,51 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include <stddef.h>
#include <stdint.h>
#include <gps/gps.h>
#include <tactility/error.h>
/**
* @brief A persisted GPS receiver configuration.
*/
struct GpsConfiguration {
/** UART controller device name, e.g. "uart0" - resolved via device_get_by_name(). */
char uart_name[32];
uint32_t baud_rate;
/** GPS_MODEL_UNKNOWN triggers an autoprobe. */
enum GpsModel model;
};
/**
* @brief Persists a new GPS configuration and triggers the ledger to materialize a (not started)
* GPS_TYPE device for it in the device tree. Use device_start()/device_stop() on the resulting
* device to control whether it's actually running.
* @retval ERROR_RESOURCE if the configuration file could not be opened/written
*/
error_t gps_settings_add_configuration(const struct GpsConfiguration* configuration);
/**
* @brief Removes the persisted GPS configuration at `index` (as seen via
* gps_settings_for_each_configuration()), and triggers the ledger to stop, destruct and remove
* its corresponding GPS_TYPE device from the device tree.
* @retval ERROR_NOT_FOUND if index is out of range
* @retval ERROR_RESOURCE if the configuration file could not be read/written
*/
error_t gps_settings_remove_configuration_at(size_t index);
/**
* @brief Iterates over all persisted GPS configurations.
* @param[in] context passed through to on_configuration, can be NULL
* @param[in] on_configuration called once per configuration, in file order, with its index
*/
void gps_settings_for_each_configuration(void* context, void (*on_configuration)(const struct GpsConfiguration* configuration, size_t index, void* context));
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,20 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
/**
* @brief Reconciles the device tree against the persisted GPS configurations (see
* gps/gps_settings.h): constructs+adds (but does not start) a GPS_TYPE device for every
* configuration that doesn't have one yet, and stops+destructs+removes any ledger-owned device
* whose configuration has disappeared.
*
* Only ever touches devices the ledger itself created (tagged DEVICE_FLAG_DYNAMIC) - devicetree-
* declared GPS_TYPE devices (tagged DEVICE_FLAG_DTS) are never constructed, started, stopped, or
* destructed by the ledger.
*/
void gps_ledger_sync();
/**
* @brief Stops+destructs+removes every ledger-owned device. Devicetree-declared GPS_TYPE devices
* are left untouched.
*/
void gps_ledger_clear();
+57
View File
@@ -0,0 +1,57 @@
#include <gps/gps.h>
#ifdef __cplusplus
extern "C" {
#endif
const char* gps_model_to_string(GpsModel model) {
switch (model) {
case GPS_MODEL_AG3335: return "AG3335";
case GPS_MODEL_AG3352: return "AG3352";
case GPS_MODEL_ATGM336H: return "ATGM336H";
case GPS_MODEL_LS20031: return "LS20031";
case GPS_MODEL_MTK: return "MTK";
case GPS_MODEL_MTK_L76B: return "MTK_L76B";
case GPS_MODEL_MTK_PA1616S: return "MTK_PA1616S";
case GPS_MODEL_UBLOX6: return "UBLOX6";
case GPS_MODEL_UBLOX7: return "UBLOX7";
case GPS_MODEL_UBLOX8: return "UBLOX8";
case GPS_MODEL_UBLOX9: return "UBLOX9";
case GPS_MODEL_UBLOX10: return "UBLOX10";
case GPS_MODEL_UC6580: return "UC6580";
default: return "Unknown";
}
}
error_t gps_event_subscribe(Device* device, GpsSubscription* sub) {
const auto* driver = device_get_driver(device);
return static_cast<const GpsApi*>(driver->api)->event_subscribe(device, sub);
}
error_t gps_event_unsubscribe(Device* device, GpsSubscription* sub) {
const auto* driver = device_get_driver(device);
return static_cast<const GpsApi*>(driver->api)->event_unsubscribe(device, sub);
}
error_t gps_event_await(Device* device, GpsSubscription* sub, TickType_t timeout) {
const auto* driver = device_get_driver(device);
return static_cast<const GpsApi*>(driver->api)->event_await(device, sub, timeout);
}
GpsState gps_get_state(Device* device) {
const auto* driver = device_get_driver(device);
return static_cast<const GpsApi*>(driver->api)->get_state(device);
}
error_t gps_get_model_name(Device* device, char* model_name, size_t buffer_size) {
const auto* driver = device_get_driver(device);
return static_cast<const GpsApi*>(driver->api)->get_model_name(device, model_name, buffer_size);
}
const DeviceType GPS_TYPE {
.name = "gps"
};
#ifdef __cplusplus
}
#endif
+167
View File
@@ -0,0 +1,167 @@
// SPDX-License-Identifier: Apache-2.0
#include <gps/private/gps_ledger.h>
#include <gps/gps.h>
#include <gps/gps_settings.h>
#include <tactility/device.h>
#include <tactility/driver.h>
#include <tactility/log.h>
#include <cstdio>
#include <cstring>
#include <new>
#include <vector>
constexpr auto* TAG = "gps_ledger";
struct GpsConfig {
uint32_t baud_rate;
enum GpsModel model;
};
// A GPS_TYPE device the ledger constructed for a persisted GpsConfiguration. Device is the first
// member so `reinterpret_cast<GpsLedgerEntry*>(device)` is safe when a Device* obtained from the
// device tree needs to be freed.
struct GpsLedgerEntry {
Device device {};
GpsConfig config {};
// device->name points into this buffer - must outlive the device (device->name only stores a
// pointer, it doesn't copy).
char name[16] {};
};
// Unique across every device the ledger creates, so device names ("gpsN") never collide.
static uint32_t next_device_index = 0;
static bool device_matches_configuration(Device* device, const GpsConfiguration& configuration) {
auto* parent = device_get_parent(device);
if (parent == nullptr || strcmp(parent->name, configuration.uart_name) != 0) {
return false;
}
const auto* config = static_cast<const GpsConfig*>(device->config);
return config->baud_rate == configuration.baud_rate && config->model == configuration.model;
}
// Constructs+adds (not started) a GPS_TYPE device wired to `configuration`'s named UART, tagged
// DEVICE_FLAG_DYNAMIC so the ledger recognizes it as its own on a later sync.
static bool create_device(const GpsConfiguration& configuration) {
Device* uart = nullptr;
if (device_get_by_name(configuration.uart_name, &uart) != ERROR_NONE) {
LOG_E(TAG, "Failed to find device %s", configuration.uart_name);
return false;
}
auto* entry = new(std::nothrow) GpsLedgerEntry();
if (entry == nullptr) {
device_put(uart);
return false;
}
entry->config = GpsConfig { .baud_rate = configuration.baud_rate, .model = configuration.model };
snprintf(entry->name, sizeof(entry->name), "gps%u", (unsigned)next_device_index++);
auto* device = &entry->device;
device->address = 0;
device->name = entry->name;
device->config = &entry->config;
device->parent = nullptr;
device->flags = DEVICE_FLAG_DYNAMIC;
device->internal = nullptr;
bool ok = false;
if (device_construct(device) == ERROR_NONE) {
device_set_parent(device, uart);
Driver* driver = driver_find_compatible("tactility,gps-generic");
if (driver != nullptr) {
device_set_driver(device, driver);
ok = device_add(device) == ERROR_NONE;
if (!ok) {
LOG_E(TAG, "Failed to add %s", device->name);
}
} else {
LOG_E(TAG, "No driver registered for tactility,gps-generic");
}
if (!ok) {
device_destruct(device);
}
} else {
LOG_E(TAG, "Failed to construct %s", device->name);
}
device_put(uart);
if (!ok) {
delete entry;
}
return ok;
}
// Stops (if needed), removes and destructs a ledger-owned device, and frees its entry.
static void destroy_device(Device* device) {
if (device_is_ready(device)) {
device_stop(device);
}
device_remove(device);
device_destruct(device);
delete reinterpret_cast<GpsLedgerEntry*>(device);
}
static bool is_ledger_owned(const Device* device) {
return !(device->flags & DEVICE_FLAG_DTS) && (device->flags & DEVICE_FLAG_DYNAMIC);
}
// Collects the ledger-owned GPS_TYPE devices. device_remove()/device_stop() must not run while
// device_for_each_of_type() holds the device ledger lock, so callers process the result afterwards.
static std::vector<Device*> collect_owned_devices() {
std::vector<Device*> owned;
device_for_each_of_type(&GPS_TYPE, &owned, [](Device* device, void* context) {
if (is_ledger_owned(device)) {
static_cast<std::vector<Device*>*>(context)->push_back(device);
}
return true;
});
return owned;
}
void gps_ledger_sync() {
std::vector<GpsConfiguration> configurations;
gps_settings_for_each_configuration(&configurations, [](const GpsConfiguration* configuration, size_t, void* context) {
static_cast<std::vector<GpsConfiguration>*>(context)->push_back(*configuration);
});
std::vector<bool> matched(configurations.size(), false);
std::vector<Device*> stale;
for (auto* device : collect_owned_devices()) {
bool found = false;
for (size_t i = 0; i < configurations.size(); i++) {
if (!matched[i] && device_matches_configuration(device, configurations[i])) {
matched[i] = true;
found = true;
break;
}
}
if (!found) {
stale.push_back(device);
}
}
// Configuration disappeared - stop, destruct and drop the device that was created for it.
for (auto* device : stale) {
destroy_device(device);
}
// New configuration - create a (not started) device for it.
for (size_t i = 0; i < configurations.size(); i++) {
if (!matched[i]) {
create_device(configurations[i]);
}
}
}
void gps_ledger_clear() {
for (auto* device : collect_owned_devices()) {
destroy_device(device);
}
}
+169
View File
@@ -0,0 +1,169 @@
// SPDX-License-Identifier: Apache-2.0
#include <gps/gps_settings.h>
#include <gps/private/gps_ledger.h>
#include <tactility/filesystem/file_mutex.h>
#include <tactility/log.h>
#include <tactility/service/service_paths.h>
#include <sys/stat.h>
#include <cstdio>
#include <cstring>
#include <vector>
constexpr auto* TAG = "gps_settings";
// Storage key for the persisted configuration file (services would use their own service ID for
// this; gps_settings has no service backing it, so it defines its own).
constexpr auto* GPS_SETTINGS_STORAGE_ID = "gps";
// region Configuration persistence
// Recursively creates every missing directory component of `path` (best-effort - mkdir() failures
// other than "already exists" are surfaced later, when the actual config file open fails).
static void ensure_directory_exists(const char* path) {
char buffer[224];
std::strncpy(buffer, path, sizeof(buffer) - 1);
buffer[sizeof(buffer) - 1] = '\0';
for (char* p = buffer + 1; *p != '\0'; p++) {
if (*p == '/') {
*p = '\0';
mkdir(buffer, 0777);
*p = '/';
}
}
mkdir(buffer, 0777);
}
static bool get_configuration_path(char* out_path, size_t out_path_size) {
return service_paths_get_user_data_path(GPS_SETTINGS_STORAGE_ID, "config.bin", out_path, out_path_size) == ERROR_NONE;
}
// Holds the lock (if any) that `path` needs for the lifetime of the guard - see file_find_lock().
class FileLockGuard {
FileMutex mutex;
bool locked;
public:
explicit FileLockGuard(const char* path) {
file_mutex_get(&mutex, path);
file_mutex_lock(&mutex);
locked = true;
}
~FileLockGuard() {
unlock();
}
void unlock() {
if (locked) {
file_mutex_unlock(&mutex);
locked = false;
}
}
};
void gps_settings_for_each_configuration(void* context, void (*on_configuration)(const GpsConfiguration* configuration, size_t index, void* context)) {
char path[224];
if (!get_configuration_path(path, sizeof(path))) {
return;
}
FileLockGuard lock(path);
FILE* file = fopen(path, "rb");
if (file == nullptr) {
return; // No configurations saved yet
}
GpsConfiguration configuration;
size_t index = 0;
while (fread(&configuration, sizeof(configuration), 1, file) == 1) {
on_configuration(&configuration, index, context);
index++;
}
fclose(file);
}
static void collect_configuration(const GpsConfiguration* configuration, size_t, void* context) {
static_cast<std::vector<GpsConfiguration>*>(context)->push_back(*configuration);
}
static void load_configurations(std::vector<GpsConfiguration>& out) {
gps_settings_for_each_configuration(&out, collect_configuration);
}
static error_t write_configurations(const std::vector<GpsConfiguration>& configurations) {
char directory[224];
if (service_paths_get_user_data_directory(GPS_SETTINGS_STORAGE_ID, directory, sizeof(directory)) != ERROR_NONE) {
return ERROR_RESOURCE;
}
char path[256];
if (!get_configuration_path(path, sizeof(path))) {
return ERROR_RESOURCE;
}
FileLockGuard lock(path);
ensure_directory_exists(directory);
FILE* file = fopen(path, "wb");
if (file == nullptr) {
LOG_E(TAG, "Failed to open %s for writing", path);
return ERROR_RESOURCE;
}
bool ok = true;
for (auto& configuration : configurations) {
if (fwrite(&configuration, sizeof(configuration), 1, file) != 1) {
ok = false;
break;
}
}
fclose(file);
if (!ok) {
return ERROR_RESOURCE;
}
lock.unlock();
gps_ledger_sync();
return ERROR_NONE;
}
// endregion
error_t gps_settings_add_configuration(const GpsConfiguration* configuration) {
std::vector<GpsConfiguration> configurations;
load_configurations(configurations);
configurations.push_back(*configuration);
error_t error = write_configurations(configurations);
if (error != ERROR_NONE) {
return error;
}
return ERROR_NONE;
}
error_t gps_settings_remove_configuration_at(size_t index) {
std::vector<GpsConfiguration> configurations;
load_configurations(configurations);
if (index >= configurations.size()) {
return ERROR_NOT_FOUND;
}
configurations.erase(configurations.begin() + static_cast<ptrdiff_t>(index));
error_t error = write_configurations(configurations);
if (error != ERROR_NONE) {
return error;
}
return ERROR_NONE;
}
+30
View File
@@ -0,0 +1,30 @@
// SPDX-License-Identifier: Apache-2.0
#include <gps/gps_module.h>
#include <gps/private/gps_ledger.h>
#include <tactility/error.h>
#include <tactility/module.h>
extern "C" {
static error_t start() {
// Materializes devices for configurations persisted in previous sessions.
gps_ledger_sync();
return ERROR_NONE;
}
static error_t stop() {
gps_ledger_clear();
return ERROR_NONE;
}
Module gps_module = {
.name = "gps",
.start = start,
.stop = stop,
.drivers = nullptr,
.symbols = nullptr,
.internal = nullptr
};
}
-20
View File
@@ -1,20 +0,0 @@
cmake_minimum_required(VERSION 3.20)
include("${CMAKE_CURRENT_LIST_DIR}/../../Buildscripts/module.cmake")
file(GLOB_RECURSE SOURCE_FILES "source/*.c*")
list(APPEND REQUIRES_LIST
TactilityKernel
TactilityFreeRtos
)
if (NOT DEFINED ENV{ESP_IDF_VERSION})
list(APPEND REQUIRES_LIST freertos_kernel)
endif ()
tactility_add_module(hal-device-module
SRCS ${SOURCE_FILES}
INCLUDE_DIRS include/
REQUIRES ${REQUIRES_LIST}
)
-10
View File
@@ -1,10 +0,0 @@
# hal-device-module
**WARNING: This module contains deprecated code**
This module is the basis for the old Tactility HAL.
This HAL existed before TactilityKernel.
The C++ `tt::hal::Device` class is replaced by `struct Device` from TactilityKernel.
License: [Apache v2.0](LICENSE-Apache-2.0.md)
@@ -1,28 +0,0 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
enum class HalDeviceType {
HAL_DEVICE_TYPE_I2C,
HAL_DEVICE_TYPE_DISPLAY,
HAL_DEVICE_TYPE_TOUCH,
HAL_DEVICE_TYPE_SDCARD,
HAL_DEVICE_TYPE_KEYBOARD,
HAL_DEVICE_TYPE_ENCODER,
HAL_DEVICE_TYPE_POWER,
HAL_DEVICE_TYPE_GPS,
HAL_DEVICE_TYPE_OTHER
};
HalDeviceType hal_device_get_type(struct Device* device);
void hal_device_for_each_of_type(HalDeviceType type, void* context, bool(*onDevice)(struct Device* device, void* context));
extern const struct DeviceType HAL_DEVICE_TYPE;
#ifdef __cplusplus
}
#endif
@@ -1,21 +0,0 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "hal_device.h"
#include <memory>
#include <tactility/hal/Device.h>
namespace tt::hal {
/**
* @brief Get a tt::hal::Device object from a Kernel device.
* @warning The input device must be of type HAL_DEVICE_TYPE
* @param kernelDevice The kernel device
* @return std::shared_ptr<Device>
*/
std::shared_ptr<Device> hal_device_get_device(::Device* kernelDevice);
void hal_device_set_device(::Device* kernelDevice, std::shared_ptr<Device> halDevice);
}
@@ -1,144 +0,0 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <functional>
#include <memory>
#include <ranges>
#include <string>
#include <vector>
#include <cassert>
#include <tactility/device.h>
typedef ::Device KernelDevice;
namespace tt::hal {
/** Base class for HAL-related devices. */
class Device {
public:
enum class Type {
I2c,
Display,
Touch,
SdCard,
Keyboard,
Encoder,
Power,
Gps,
Other
};
typedef uint32_t Id;
struct KernelDeviceHolder {
const std::string name;
std::shared_ptr<KernelDevice> device = std::make_shared<KernelDevice>();
explicit KernelDeviceHolder(std::string name) : name(name) {
device->name = this->name.c_str();
}
};
private:
Id id;
std::shared_ptr<KernelDeviceHolder> kernelDeviceHolder;
public:
Device();
virtual ~Device() = default;
/** Unique identifier */
Id getId() const { return id; }
/** The type of device */
virtual Type getType() const = 0;
/** The part number or hardware name e.g. TdeckTouch, TdeckDisplay, BQ24295, etc. */
virtual std::string getName() const = 0;
/** A short description of what this device does.
* e.g. "USB charging controller with I2C interface."
*/
virtual std::string getDescription() const = 0;
void setKernelDeviceHolder(std::shared_ptr<KernelDeviceHolder> kernelDeviceHolder) { this->kernelDeviceHolder = kernelDeviceHolder; }
std::shared_ptr<KernelDeviceHolder> getKernelDeviceHolder() const { return kernelDeviceHolder; }
};
/**
* Adds a device to the registry.
* @warning This will leak memory if you want to destroy a device and don't call deregisterDevice()!
*/
void registerDevice(const std::shared_ptr<Device>& device);
/** Remove a device from the registry. */
void deregisterDevice(const std::shared_ptr<Device>& device);
/** Find a single device with a custom filter. Could return nullptr if not found. */
std::shared_ptr<Device> findDevice(const std::function<bool(const std::shared_ptr<Device>&)>& filterFunction);
/** Find devices with a custom filter */
std::vector<std::shared_ptr<Device>> findDevices(const std::function<bool(const std::shared_ptr<Device>&)>& filterFunction);
/** Find a device in the registry by its name. Could return nullptr if not found. */
std::shared_ptr<Device> findDevice(std::string name);
/** Find a device in the registry by its identifier. Could return nullptr if not found.*/
std::shared_ptr<Device> findDevice(Device::Id id);
/** Find 0, 1 or more devices in the registry by type. */
std::vector<std::shared_ptr<Device>> findDevices(Device::Type type);
/** Get a copy of the entire device registry in its current state. */
std::vector<std::shared_ptr<Device>> getDevices();
/** Find devices of a certain type and cast them to the specified class */
template<class DeviceType>
std::vector<std::shared_ptr<DeviceType>> findDevices(Device::Type type) {
auto devices = findDevices(type);
if (devices.empty()) {
return {};
} else {
std::vector<std::shared_ptr<DeviceType>> result;
result.reserve(devices.size());
for (auto& device : devices) {
auto target_device = std::static_pointer_cast<DeviceType>(device);
assert(target_device != nullptr);
result.push_back(target_device);
}
return result;
}
}
template<class DeviceType>
void findDevices(Device::Type type, std::function<bool(const std::shared_ptr<DeviceType>&)> onDeviceFound) {
auto devices_view = findDevices(type);
for (auto& device : devices_view) {
auto typed_device = std::static_pointer_cast<DeviceType>(device);
if (!onDeviceFound(typed_device)) {
break;
}
}
}
/** Find the first device of the specified type and cast it to the specified class */
template<class DeviceType>
std::shared_ptr<DeviceType> findFirstDevice(Device::Type type) {
auto devices = findDevices(type);
if (devices.empty()) {
return {};
} else {
auto& first = devices[0];
return std::static_pointer_cast<DeviceType>(first);
}
}
/** @return true if there are 1 or more devices of the specified type */
bool hasDevice(Device::Type type);
}
@@ -1,130 +0,0 @@
// SPDX-License-Identifier: Apache-2.0
#include <tactility/drivers/hal_device.h>
#include <tactility/device.h>
#include <tactility/driver.h>
#include <tactility/log.h>
#include <tactility/hal/Device.h>
#include <memory>
#include <utility>
#define TAG "HalDevice"
struct HalDevicePrivate {
std::shared_ptr<tt::hal::Device> halDevice;
};
#define GET_DATA(device) ((HalDevicePrivate*)device_get_driver_data(device))
static enum HalDeviceType getHalDeviceType(tt::hal::Device::Type type) {
switch (type) {
case tt::hal::Device::Type::I2c:
return HalDeviceType::HAL_DEVICE_TYPE_I2C;
case tt::hal::Device::Type::Display:
return HalDeviceType::HAL_DEVICE_TYPE_DISPLAY;
case tt::hal::Device::Type::Touch:
return HalDeviceType::HAL_DEVICE_TYPE_TOUCH;
case tt::hal::Device::Type::SdCard:
return HalDeviceType::HAL_DEVICE_TYPE_SDCARD;
case tt::hal::Device::Type::Keyboard:
return HalDeviceType::HAL_DEVICE_TYPE_KEYBOARD;
case tt::hal::Device::Type::Encoder:
return HalDeviceType::HAL_DEVICE_TYPE_ENCODER;
case tt::hal::Device::Type::Power:
return HalDeviceType::HAL_DEVICE_TYPE_POWER;
case tt::hal::Device::Type::Gps:
return HalDeviceType::HAL_DEVICE_TYPE_GPS;
case tt::hal::Device::Type::Other:
return HalDeviceType::HAL_DEVICE_TYPE_OTHER;
default:
LOG_W(TAG, "Device type %d is not implemented", static_cast<int>(type));
return HalDeviceType::HAL_DEVICE_TYPE_OTHER;
}
}
extern "C" {
HalDeviceType hal_device_get_type(struct Device* device) {
auto type = GET_DATA(device)->halDevice->getType();
return getHalDeviceType(type);
}
void hal_device_for_each_of_type(HalDeviceType type, void* context, bool(*onDevice)(struct Device* device, void* context)) {
struct InternalContext {
HalDeviceType typeParam;
void* contextParam;
bool(*onDeviceParam)(struct Device* device, void* context);
};
InternalContext internal_context = {
.typeParam = type,
.contextParam = context,
.onDeviceParam = onDevice
};
device_for_each_of_type(&HAL_DEVICE_TYPE, &internal_context, [](Device* device, void* context){
auto* hal_device_private = GET_DATA(device);
auto* internal_context = static_cast<InternalContext*>(context);
auto hal_device_type = getHalDeviceType(hal_device_private->halDevice->getType());
if (hal_device_type == internal_context->typeParam) {
if (!internal_context->onDeviceParam(device, internal_context->contextParam)) {
return false;
}
}
return true;
});
}
}
namespace tt::hal {
std::shared_ptr<Device> hal_device_get_device(::Device* device) {
auto* hal_device_private = GET_DATA(device);
return hal_device_private->halDevice;
}
void hal_device_set_device(::Device* kernelDevice, std::shared_ptr<Device> halDevice) {
GET_DATA(kernelDevice)->halDevice = std::move(halDevice);
}
}
#pragma region Lifecycle
static error_t start(Device* device) {
LOG_I(TAG, "start %s", device->name);
auto hal_device_data = new(std::nothrow) HalDevicePrivate();
if (hal_device_data == nullptr) return ERROR_OUT_OF_MEMORY;
device_set_driver_data(device, hal_device_data);
return ERROR_NONE;
}
static error_t stop(Device* device) {
LOG_I(TAG, "stop %s", device->name);
delete GET_DATA(device);
return ERROR_NONE;
}
#pragma endregion
extern "C" {
const struct DeviceType HAL_DEVICE_TYPE {
"hal-device"
};
extern struct Module hal_device_module;
Driver hal_device_driver = {
.name = "hal-device",
.compatible = (const char*[]) {"hal-device", nullptr},
.start_device = start,
.stop_device = stop,
.api = nullptr,
.device_type = &HAL_DEVICE_TYPE,
.owner = &hal_device_module,
.internal = nullptr
};
}
@@ -1,145 +0,0 @@
// SPDX-License-Identifier: Apache-2.0
#include <tactility/driver.h>
#include <tactility/drivers/hal_device.hpp>
#include <tactility/hal/Device.h>
#include <tactility/log.h>
#include <Tactility/RecursiveMutex.h>
#include <algorithm>
#include <format>
namespace tt::hal {
RecursiveMutex mutex;
static Device::Id nextId = 0;
constexpr auto* TAG = "Devices";
Device::Device() : id(nextId++) {}
static std::shared_ptr<Device::KernelDeviceHolder> createKernelDeviceHolder(const std::shared_ptr<Device>& device) {
auto kernel_device_name = std::format("hal-device-{}", device->getId());
LOG_I(TAG, "Registering %s with id %u as kernel device %s", device->getName().c_str(), (unsigned)device->getId(), kernel_device_name.c_str());
auto kernel_device_holder = std::make_shared<Device::KernelDeviceHolder>(kernel_device_name);
auto* kernel_device = kernel_device_holder->device.get();
check(device_construct(kernel_device) == ERROR_NONE);
check(device_add(kernel_device) == ERROR_NONE);
auto* driver = driver_find_compatible("hal-device");
check(driver);
device_set_driver(kernel_device, driver);
check(device_start(kernel_device) == ERROR_NONE);
hal_device_set_device(kernel_device, device);
return kernel_device_holder;
}
static void destroyKernelDeviceHolder(std::shared_ptr<Device::KernelDeviceHolder>& holder) {
auto kernel_device = holder->device.get();
hal_device_set_device(kernel_device, nullptr);
check(device_stop(kernel_device) == ERROR_NONE);
check(device_remove(kernel_device) == ERROR_NONE);
check(device_destruct(kernel_device) == ERROR_NONE);
holder->device = nullptr;
}
void registerDevice(const std::shared_ptr<Device>& device) {
auto scoped_mutex = mutex.asScopedLock();
scoped_mutex.lock();
if (device->getKernelDeviceHolder() == nullptr) {
// Kernel device
auto kernel_device_holder = createKernelDeviceHolder(device);
device->setKernelDeviceHolder(kernel_device_holder);
} else {
LOG_W(TAG, "Device %s with id %u was already registered", device->getName().c_str(), (unsigned)device->getId());
}
}
void deregisterDevice(const std::shared_ptr<Device>& device) {
auto scoped_mutex = mutex.asScopedLock();
scoped_mutex.lock();
// Kernel device
auto kernel_device_holder = device->getKernelDeviceHolder();
if (kernel_device_holder) {
destroyKernelDeviceHolder(kernel_device_holder);
device->setKernelDeviceHolder(nullptr);
} else {
LOG_W(TAG, "Device %s with id %u was not registered", device->getName().c_str(), (unsigned)device->getId());
}
}
template<typename R>
auto toVector(R&& range) {
using T = std::ranges::range_value_t<R>;
std::vector<T> result;
if constexpr (std::ranges::common_range<R>) {
result.reserve(std::ranges::distance(range));
}
std::ranges::copy(range, std::back_inserter(result));
return result;
}
std::vector<std::shared_ptr<Device>> findDevices(const std::function<bool(const std::shared_ptr<Device>&)>& filterFunction) {
auto scoped_mutex = mutex.asScopedLock();
scoped_mutex.lock();
auto devices_view = getDevices() | std::views::filter([&filterFunction](auto& device) {
return filterFunction(device);
});
return toVector(devices_view);
}
std::shared_ptr<Device> findDevice(const std::function<bool(const std::shared_ptr<Device>&)>& filterFunction) {
auto scoped_mutex = mutex.asScopedLock();
scoped_mutex.lock();
auto result_set = getDevices() | std::views::filter([&filterFunction](auto& device) {
return filterFunction(device);
});
if (!result_set.empty()) {
return result_set.front();
} else {
return nullptr;
}
}
std::shared_ptr<Device> findDevice(std::string name) {
return findDevice([&name](auto& device){
return device->getName() == name;
});
}
std::shared_ptr<Device> findDevice(Device::Id id) {
return findDevice([id](auto& device){
return device->getId() == id;
});
}
std::vector<std::shared_ptr<Device>> findDevices(Device::Type type) {
return findDevices([type](auto& device) {
return device->getType() == type;
});
}
std::vector<std::shared_ptr<Device>> getDevices() {
std::vector<std::shared_ptr<Device>> devices;
device_for_each_of_type(&HAL_DEVICE_TYPE, &devices ,[](auto* kernelDevice, auto* context) {
auto devices_ptr = static_cast<std::vector<std::shared_ptr<Device>>*>(context);
auto hal_device = hal_device_get_device(kernelDevice);
(*devices_ptr).push_back(hal_device);
return true;
});
return devices;
}
bool hasDevice(Device::Type type) {
auto scoped_mutex = mutex.asScopedLock();
scoped_mutex.lock();
auto result_set = getDevices() | std::views::filter([&type](auto& device) {
return device->getType() == type;
});
return !result_set.empty();
}
}
@@ -1,19 +0,0 @@
// SPDX-License-Identifier: Apache-2.0
#include <tactility/driver.h>
#include <tactility/module.h>
extern "C" {
extern Driver hal_device_driver;
static Driver* const hal_device_drivers[] = {
&hal_device_driver,
nullptr
};
Module hal_device_module = {
.name = "hal-device",
.drivers = hal_device_drivers
};
}
@@ -72,7 +72,7 @@ void lvgl_module_configure(struct LvglModuleConfig config);
* It is a recursive mutex. * It is a recursive mutex.
* @retval true when a lock was acquired, false otherwise * @retval true when a lock was acquired, false otherwise
*/ */
bool lvgl_lock(void); void lvgl_lock(void);
/** /**
* @brief Tries to lock the LVGL mutex with a timeout. * @brief Tries to lock the LVGL mutex with a timeout.
+5 -5
View File
@@ -13,19 +13,19 @@ extern void lvgl_devices_detach();
static bool initialized = false; static bool initialized = false;
bool lvgl_lock(void) { void lvgl_lock(void) {
if (!initialized) return true; // We allow (fake) locking because it's safe to do so as LVGL is not running yet if (!initialized) { return; }
return lvgl_port_lock(portMAX_DELAY); lvgl_port_lock(portMAX_DELAY);
} }
bool lvgl_try_lock(uint32_t timeoutTicks) { bool lvgl_try_lock(uint32_t timeoutTicks) {
if (!initialized) return true; // We allow (fake) locking because it's safe to do so as LVGL is not running yet if (!initialized) { return false; }
// lvgl_port_lock expects milliseconds // lvgl_port_lock expects milliseconds
return lvgl_port_lock(timeoutTicks * portTICK_PERIOD_MS); return lvgl_port_lock(timeoutTicks * portTICK_PERIOD_MS);
} }
void lvgl_unlock(void) { void lvgl_unlock(void) {
if (!initialized) return; if (!initialized) { return; }
lvgl_port_unlock(); lvgl_port_unlock();
} }
+9 -3
View File
@@ -13,6 +13,8 @@
#include <tactility/lvgl_module.h> #include <tactility/lvgl_module.h>
extern struct LvglModuleConfig lvgl_module_config; extern struct LvglModuleConfig lvgl_module_config;
extern void lvgl_devices_attach();
extern void lvgl_devices_detach();
// Mutex for LVGL drawing // Mutex for LVGL drawing
static struct RecursiveMutex lvgl_mutex; static struct RecursiveMutex lvgl_mutex;
@@ -37,10 +39,9 @@ static void task_unlock(void) {
recursive_mutex_unlock(&task_mutex); recursive_mutex_unlock(&task_mutex);
} }
bool lvgl_lock(void) { void lvgl_lock(void) {
if (!lvgl_mutex_initialised) return false; if (!lvgl_mutex_initialised) return;
recursive_mutex_lock(&lvgl_mutex); recursive_mutex_lock(&lvgl_mutex);
return true;
} }
bool lvgl_try_lock(uint32_t timeout) { bool lvgl_try_lock(uint32_t timeout) {
@@ -71,6 +72,9 @@ static void lvgl_task(void* arg) {
check(!lvgl_task_is_interrupt_requested()); check(!lvgl_task_is_interrupt_requested());
// Must run from this task (like on_start below), otherwise the display doesn't work.
lvgl_devices_attach();
// on_start must be called from the task, otherwise the display doesn't work // on_start must be called from the task, otherwise the display doesn't work
if (lvgl_module_config.on_start) lvgl_module_config.on_start(); if (lvgl_module_config.on_start) lvgl_module_config.on_start();
@@ -89,6 +93,8 @@ static void lvgl_task(void* arg) {
if (lvgl_module_config.on_stop) lvgl_module_config.on_stop(); if (lvgl_module_config.on_stop) lvgl_module_config.on_stop();
lvgl_devices_detach();
task_lock(); task_lock();
lvgl_task_handle = NULL; lvgl_task_handle = NULL;
task_unlock(); task_unlock();
+2 -2
View File
@@ -7,12 +7,12 @@ file(GLOB_RECURSE SOURCE_FILES Source/*.c*)
list(APPEND REQUIRES_LIST list(APPEND REQUIRES_LIST
TactilityKernel TactilityKernel
TactilityFreeRtos TactilityFreeRtos
hal-device-module
lvgl-module lvgl-module
crypt-module crypt-module
gps-module
gps-generic-module
lv_screenshot lv_screenshot
minitar minitar
minmea
) )
if (DEFINED ENV{ESP_IDF_VERSION}) if (DEFINED ENV{ESP_IDF_VERSION})
@@ -6,8 +6,6 @@
namespace tt::kernel { namespace tt::kernel {
enum class SystemEvent { enum class SystemEvent {
BootInitHalBegin,
BootInitHalEnd,
BootSplash, BootSplash,
/** Gained IP address */ /** Gained IP address */
NetworkConnected, NetworkConnected,
+4 -28
View File
@@ -1,11 +1,9 @@
#pragma once #pragma once
#include "tactility/concurrent/dispatcher.h" #include <tactility/concurrent/dispatcher.h>
#include "tactility/device.h" #include <tactility/device.h>
#include "tactility/module.h" #include <tactility/module.h>
#include <Tactility/app/AppManifest.h> #include <Tactility/app/AppManifest.h>
#include <Tactility/hal/Configuration.h>
#include <Tactility/service/ServiceManifest.h>
#include <functional> #include <functional>
@@ -40,27 +38,12 @@ private:
DispatcherHandle_t handle; DispatcherHandle_t handle;
}; };
/** @brief The configuration for the operating system
* It contains the hardware configuration, apps and services
*/
struct Configuration {
/** HAL configuration (drivers) */
const hal::Configuration* hardware = nullptr;
};
/** /**
* @brief Main entry point for Tactility. * @brief Main entry point for Tactility.
* @param dtsModules List of modules from devicetree, null-terminated, non-null parameter * @param dtsModules List of modules from devicetree, null-terminated, non-null parameter
* @param dtsDevices Array that is terminated with DTS_DEVICE_TERMINATOR * @param dtsDevices Array that is terminated with DTS_DEVICE_TERMINATOR
*/ */
void run(const Configuration& config, Module* dtsModules[], DtsDevice dtsDevices[]); void run(Module* dtsModules[], DtsDevice dtsDevices[]);
/**
* While technically nullable, this instance is always set if tt_init() succeeds.
* Could return nullptr if init was not called.
* @return the Configuration instance that was passed on to tt_init() if init is successful
*/
const Configuration* getConfiguration();
/** Provides access to the dispatcher that runs on the main task. /** Provides access to the dispatcher that runs on the main task.
* @warning This dispatcher is used for WiFi and might block for some time during WiFi connection. * @warning This dispatcher is used for WiFi and might block for some time during WiFi connection.
@@ -68,11 +51,4 @@ const Configuration* getConfiguration();
*/ */
MainDispatcher getMainDispatcher(); MainDispatcher getMainDispatcher();
namespace hal {
/** While technically this configuration is nullable, it's never null after initHeadless() is called. */
const Configuration* getConfiguration();
} // namespace hal
} // namespace tt } // namespace tt
+1 -5
View File
@@ -45,15 +45,11 @@ struct FileCloser {
} }
}; };
typedef std::function<std::shared_ptr<Lock>(const std::string&)> FindLockFunction;
/** /**
* @param[in] path the path to get a lock for * @param[in] path the path to get a lock for
* @return a lock instance (never null) * @return a lock instance (never null)
*/ */
std::shared_ptr<Lock> getLock(const std::string& path); std::shared_ptr<Lock> getLock(const std::string& path) __attribute__((deprecated("Use file_mutex.h from TactilityKernel")));
void setFindLockFunction(const FindLockFunction& function);
long getSize(FILE* file); long getSize(FILE* file);
+2 -1
View File
@@ -13,8 +13,9 @@ namespace tt::file {
/** /**
* @param[in] path the path to find a lock for * @param[in] path the path to find a lock for
* @deprecated
* @return a lock instance when a lock was found, otherwise nullptr * @return a lock instance when a lock was found, otherwise nullptr
*/ */
std::shared_ptr<Lock> findLock(const std::string& path); std::shared_ptr<Lock> findLock(const std::string& path) __attribute__((deprecated("Use file_get_mutex() from TactilityKernel")));
} }
@@ -1,24 +0,0 @@
#pragma once
#include <memory>
#include <tactility/hal/Device.h>
#include <vector>
namespace tt::hal {
typedef bool (*InitBoot)();
typedef std::vector<std::shared_ptr<Device>> DeviceVector;
typedef std::shared_ptr<Device> (*CreateDevice)();
struct Configuration {
/**
* Used for powering on the peripherals manually.
*/
const InitBoot initBoot = nullptr;
const std::function<DeviceVector()> createDevices = [] { return DeviceVector(); };
};
} // namespace
@@ -1,63 +0,0 @@
#pragma once
#include <tactility/hal/Device.h>
#include <lvgl.h>
namespace tt::hal::touch {
class TouchDevice;
}
namespace tt::hal::display {
class DisplayDriver;
class DisplayDevice : public Device {
public:
Type getType() const override { return Type::Display; }
/** Starts the internal driver */
virtual bool start() = 0;
virtual bool stop() = 0;
virtual void setPowerOn(bool turnOn) {}
virtual bool isPoweredOn() const { return true; }
virtual bool supportsPowerControl() const { return false; }
/** For e-paper screens */
virtual void requestFullRefresh() {}
/** Blocks until any frame already handed to this display has physically
* finished drawing. Displays that draw synchronously within their flush
* callback can rely on the default no-op; displays with an asynchronous
* refresh pipeline (e.g. e-paper, where a full refresh can take seconds)
* should override this so callers can safely do something irreversible
* (like cutting power) right after a screen update. */
virtual void waitForFlushComplete() {}
/** Could return nullptr if not started */
virtual std::shared_ptr<touch::TouchDevice> getTouchDevice() = 0;
/** Set a value in the range [0, 255] */
virtual void setBacklightDuty(uint8_t backlightDuty) { /* NO-OP */ }
virtual bool supportsBacklightDuty() const { return false; }
/** Set a value in the range [0, 255] */
virtual void setGammaCurve(uint8_t index) { /* NO-OP */ }
virtual uint8_t getGammaCurveCount() const { return 0; }
virtual bool supportsLvgl() const = 0;
virtual bool startLvgl() = 0;
virtual bool stopLvgl() = 0;
/** Could return nullptr if not started */
virtual lv_display_t* getLvglDisplay() const = 0;
virtual bool supportsDisplayDriver() const = 0;
/** Could return nullptr if not supported */
virtual std::shared_ptr<DisplayDriver> getDisplayDriver() = 0;
};
} // namespace tt::hal::display
@@ -1,37 +0,0 @@
#pragma once
#include <Tactility/Lock.h>
#include <cstdint>
namespace tt::hal::display {
enum class ColorFormat {
Monochrome, // 1 bpp
BGR565,
BGR565Swapped,
RGB565,
RGB565Swapped,
RGB888
};
class DisplayDriver {
public:
virtual ~DisplayDriver() = default;
virtual ColorFormat getColorFormat() const = 0;
virtual uint16_t getPixelWidth() const = 0;
virtual uint16_t getPixelHeight() const = 0;
virtual bool drawBitmap(int xStart, int yStart, int xEnd, int yEnd, const void* pixelData) = 0;
/**
* Returns direct pointers to the panel's hardware frame buffer(s), if the
* underlying driver supports it (DPI/MIPI-DSI panels only).
* @param[out] outBuffers receives up to 2 frame buffer pointers
* @return number of buffers written to outBuffers (0 if unsupported)
*/
virtual uint8_t getFrameBuffers(void* outBuffers[2]) const { return 0; }
};
}
@@ -1,26 +0,0 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <Tactility/hal/display/DisplayDriver.h>
#include <tactility/device.h>
namespace tt::hal::display {
/** Wraps a TactilityKernel Device of type DISPLAY_TYPE as a DisplayDriver. */
class KernelDisplayDriver final : public DisplayDriver {
::Device* device;
public:
explicit KernelDisplayDriver(::Device* device);
ColorFormat getColorFormat() const override;
uint16_t getPixelWidth() const override;
uint16_t getPixelHeight() const override;
bool drawBitmap(int xStart, int yStart, int xEnd, int yEnd, const void* pixelData) override;
uint8_t getFrameBuffers(void* outBuffers[2]) const override;
};
}
@@ -1,24 +0,0 @@
#pragma once
#include <tactility/hal/Device.h>
#include <lvgl.h>
namespace tt::hal::encoder {
class Display;
class EncoderDevice : public Device {
public:
Type getType() const override { return Type::Encoder; }
virtual bool startLvgl(lv_display_t* display) = 0;
virtual bool stopLvgl() = 0;
/** Could return nullptr if not started */
virtual lv_indev_t* getLvglIndev() = 0;
};
}
@@ -1,34 +0,0 @@
#pragma once
#include <cstdint>
namespace tt::hal::gpio {
typedef unsigned int Pin;
constexpr Pin NO_PIN = -1;
/** @warning The order must match GpioMode from tt_hal_gpio.h */
enum class Mode {
Disable = 0,
Input,
Output,
OutputOpenDrain,
InputOutput,
InputOutputOpenDrain
};
/** Configure a single pin */
bool configure(Pin pin, Mode mode, bool pullUp, bool pullDown);
/** Configure a set of pins defined by their bit index */
bool configureWithPinBitmask(uint64_t pinBitMask, Mode mode, bool pullUp, bool pullDown);
bool setMode(Pin pin, Mode mode);
bool getLevel(Pin pin);
bool setLevel(Pin pin, bool level);
int getPinCount();
}
@@ -1,36 +0,0 @@
#pragma once
#include <cstdint>
#include <vector>
#include <string>
namespace tt::hal::gps {
enum class GpsModel {
Unknown = 0,
AG3335,
AG3352,
ATGM336H, // Casic (might work with AT6558, Neoway N58 LTE Cat.1, Neoway G2, Neoway G7A)
LS20031,
MTK,
MTK_L76B,
MTK_PA1616S,
UBLOX6,
UBLOX7,
UBLOX8,
UBLOX9,
UBLOX10,
UC6580,
};
const char* toString(GpsModel model);
std::vector<std::string> getModels();
struct GpsConfiguration {
char uartName[32]; // e.g. "Internal" or "/dev/ttyUSB0"
uint32_t baudRate;
GpsModel model; // Choosing "Unknown" will result in a probe
};
}
@@ -1,124 +0,0 @@
#pragma once
#include <tactility/hal/Device.h>
#include "GpsConfiguration.h"
#include "Satellites.h"
#include <Tactility/Thread.h>
#include <Tactility/RecursiveMutex.h>
#include <minmea.h>
#include <utility>
namespace tt::hal::gps {
enum class GpsResponse {
None,
NotAck,
FrameErrors,
Ok,
};
class GpsDevice : public Device {
public:
typedef int GgaSubscriptionId;
typedef int RmcSubscriptionId;
enum class State {
PendingOn,
On,
Error,
PendingOff,
Off
};
private:
struct GgaSubscription {
GgaSubscriptionId id;
std::shared_ptr<std::function<void(Device::Id id, const minmea_sentence_gga&)>> onData;
};
struct RmcSubscription {
RmcSubscriptionId id;
std::shared_ptr<std::function<void(Device::Id id, const minmea_sentence_rmc&)>> onData;
};
const GpsConfiguration configuration;
RecursiveMutex mutex;
std::unique_ptr<Thread> thread;
bool threadInterrupted = false;
std::vector<GgaSubscription> ggaSubscriptions;
std::vector<RmcSubscription> rmcSubscriptions;
GgaSubscriptionId lastSatelliteSubscriptionId = 0;
RmcSubscriptionId lastRmcSubscriptionId = 0;
GpsModel model = GpsModel::Unknown;
State state = State::Off;
int32_t threadMain();
bool isThreadInterrupted() const;
void setState(State newState);
public:
explicit GpsDevice(GpsConfiguration configuration) : configuration(std::move(configuration)) {}
~GpsDevice() override = default;
Type getType() const override { return Type::Gps; }
std::string getName() const override {
if (model != GpsModel::Unknown) {
return toString(model);
} else {
return "Unknown GPS";
}
}
std::string getDescription() const override { return ""; }
bool start();
bool stop();
GgaSubscriptionId subscribeGga(const std::function<void(Device::Id deviceId, const minmea_sentence_gga&)>& onData) {
auto lock = mutex.asScopedLock();
lock.lock();
ggaSubscriptions.push_back({
.id = ++lastSatelliteSubscriptionId,
.onData = std::make_shared<std::function<void(Device::Id, const minmea_sentence_gga&)>>(onData)
});
return lastSatelliteSubscriptionId;
}
void unsubscribeGga(GgaSubscriptionId subscriptionId) {
auto lock = mutex.asScopedLock();
lock.lock();
std::erase_if(ggaSubscriptions, [subscriptionId](auto& subscription) { return subscription.id == subscriptionId; });
}
RmcSubscriptionId subscribeRmc(const std::function<void(Device::Id deviceId, const minmea_sentence_rmc&)>& onData) {
auto lock = mutex.asScopedLock();
lock.lock();
rmcSubscriptions.push_back({
.id = ++lastRmcSubscriptionId,
.onData = std::make_shared<std::function<void(Device::Id, const minmea_sentence_rmc&)>>(onData)
});
return lastRmcSubscriptionId;
}
void unsubscribeRmc(RmcSubscriptionId subscriptionId) {
auto lock = mutex.asScopedLock();
lock.lock();
std::erase_if(rmcSubscriptions, [subscriptionId](auto& subscription) { return subscription.id == subscriptionId; });
}
GpsModel getModel() const;
State getState() const;
};
}
@@ -1,59 +0,0 @@
#pragma once
#include <Tactility/freertoscompat/RTOS.h>
#include <Tactility/RecursiveMutex.h>
#include <minmea.h>
#include <ranges>
#include <memory>
namespace tt::hal::gps {
/** Thread-safe storage of recent satellites */
class SatelliteStorage {
public:
static constexpr size_t recordCount = 32;
private:
struct SatelliteRecord {
minmea_sat_info data {
.nr = 0,
.elevation = 0,
.azimuth = 0,
.snr = 0
};
TickType_t lastUpdated = 0;
bool inUse = false;
};
RecursiveMutex mutex;
std::array<SatelliteRecord, recordCount> records;
uint16_t recycleTimeSeconds;
uint16_t recentTimeSeconds;
SatelliteRecord* findRecord(int number);
SatelliteRecord* findUnusedRecord();
SatelliteRecord* findRecordToRecycle();
/** Tries to find an existing record, otherwise return a free one, otherwise return the oldest active one */
SatelliteRecord* findWithFallback(int number);
public:
explicit SatelliteStorage(
uint16_t recycleTimeSeconds = 120,
uint16_t recentTimeSeconds = 60
) : recycleTimeSeconds(recycleTimeSeconds), recentTimeSeconds(recentTimeSeconds) {}
void notify(const minmea_sat_info& info);
void getRecords(const std::function<void(const minmea_sat_info&)>& onRecord) const;
};
} // namespace tt::hal::gps
@@ -1,49 +0,0 @@
#pragma once
#include <tactility/hal/Device.h>
#include <tactility/drivers/i2c_controller.h>
namespace tt::hal::i2c {
/**
* Represents an I2C peripheral at a specific port and address.
* It helps to read and write registers.
*
* All read and write calls are thread-safe.
* @deprecated Use the device API from the Kernel project
*/
class I2cDevice : public Device {
protected:
::Device* controller;
uint8_t address;
static constexpr TickType_t DEFAULT_TIMEOUT = 1000 / portTICK_PERIOD_MS;
bool read(uint8_t* data, size_t dataSize, TickType_t timeout = DEFAULT_TIMEOUT);
bool write(const uint8_t* data, uint16_t dataSize, TickType_t timeout = DEFAULT_TIMEOUT);
bool writeRead(const uint8_t* writeData, size_t writeDataSize, uint8_t* readData, size_t readDataSize, TickType_t timeout = DEFAULT_TIMEOUT);
bool readRegister8(uint8_t reg, uint8_t& result) const;
bool writeRegister(uint8_t reg, const uint8_t* data, uint16_t dataSize, TickType_t timeout = DEFAULT_TIMEOUT);
bool writeRegister8(uint8_t reg, uint8_t value) const;
bool readRegister12(uint8_t reg, float& out) const;
bool readRegister14(uint8_t reg, float& out) const;
bool readRegister16(uint8_t reg, uint16_t& out) const;
bool bitOn(uint8_t reg, uint8_t bitmask) const;
bool bitOff(uint8_t reg, uint8_t bitmask) const;
bool bitOnByIndex(uint8_t reg, uint8_t index) const { return bitOn(reg, 1 << index); }
bool bitOffByIndex(uint8_t reg, uint8_t index) const { return bitOff(reg, 1 << index); }
public:
explicit I2cDevice(::Device* controller, uint32_t address) : controller(controller), address(address) {}
Type getType() const override { return Type::I2c; }
::Device* getController() const { return controller; }
uint8_t getAddress() const { return address; }
};
} // namespace tt::hal::i2c
@@ -1,27 +0,0 @@
#pragma once
#include <tactility/hal/Device.h>
#include <lvgl.h>
namespace tt::hal::keyboard {
class Display;
class KeyboardDevice : public Device {
public:
Type getType() const override { return Type::Keyboard; }
virtual bool startLvgl(lv_display_t* display) = 0;
virtual bool stopLvgl() = 0;
/** @return true when the keyboard currently is physically attached */
virtual bool isAttached() const = 0;
/** Could return nullptr if not started */
virtual lv_indev_t* getLvglIndev() = 0;
};
}
@@ -1,63 +0,0 @@
#pragma once
#include <tactility/hal/Device.h>
#include <cstdint>
#include <string>
namespace tt::hal::power {
class PowerDevice : public Device {
public:
PowerDevice();
~PowerDevice() override;
Type getType() const override { return Type::Power; }
enum class MetricType {
IsCharging, // bool
Current, // int32_t, mAh - battery current: either during charging (positive value) or discharging (negative value)
BatteryVoltage, // uint32_t, mV
ChargeLevel, // uint8_t [0, 100]
};
union MetricData {
int32_t valueAsInt32 = 0;
uint32_t valueAsUint32;
uint8_t valueAsUint8;
float valueAsFloat;
bool valueAsBool;
};
virtual bool supportsMetric(MetricType type) const = 0;
/**
* @return false when metric is not supported or (temporarily) not available.
*/
virtual bool getMetric(MetricType type, MetricData& data) = 0;
virtual bool supportsChargeControl() const { return false; }
virtual bool isAllowedToCharge() const { return false; }
virtual void setAllowedToCharge(bool canCharge) { /* NO-OP*/ }
virtual bool supportsQuickCharge() const { return false; }
virtual bool isQuickChargeEnabled() const { return false; }
virtual void setQuickChargeEnabled(bool enabled) { /* NO-OP */ }
virtual bool supportsPowerOff() const { return false; }
virtual void powerOff() { /* NO-OP*/ }
private:
/** Creates the kernel-level power_supply device that exposes this instance to TactilityKernel. */
void createPowerSupplyDevice();
/** Destroys the kernel-level power_supply device created by createPowerSupplyDevice(). */
void destroyPowerSupplyDevice();
std::string kernelDeviceName;
KernelDevice kernelDevice {};
};
}
@@ -1,22 +0,0 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <Tactility/hal/touch/TouchDriver.h>
#include <tactility/device.h>
namespace tt::hal::touch {
/** Wraps a TactilityKernel Device of type POINTER_TYPE as a TouchDriver. */
class KernelTouchDriver final : public TouchDriver {
::Device* device;
public:
explicit KernelTouchDriver(::Device* device);
bool getTouchedPoints(uint16_t* x, uint16_t* y, uint16_t* strength, uint8_t* pointCount, uint8_t maxPointCount) override;
};
}
@@ -1,36 +0,0 @@
#pragma once
#include <tactility/hal/Device.h>
#include "TouchDriver.h"
#include <lvgl.h>
namespace tt::hal::touch {
class Display;
class TouchDevice : public Device {
public:
Type getType() const override { return Type::Touch; }
virtual bool start() = 0;
virtual bool stop() = 0;
virtual bool supportsLvgl() const = 0;
virtual bool startLvgl(lv_display_t* display) = 0;
virtual bool stopLvgl() = 0;
/** Could return nullptr if not started */
virtual lv_indev_t* getLvglIndev() = 0;
virtual bool supportsTouchDriver() = 0;
virtual bool supportsCalibration() const { return false; }
/** Could return nullptr if not supported */
virtual std::shared_ptr<TouchDriver> getTouchDriver() = 0;
};
}
@@ -1,25 +0,0 @@
#pragma once
#include <cstdint>
namespace tt::hal::touch {
class TouchDriver {
public:
/**
* Get the coordinates for the currently touched points on the screen.
*
* @param[in] x array of X coordinates
* @param[in] y array of Y coordinates
* @param[in] strength optional array of strengths (nullable)
* @param[in] pointCount the number of points currently touched on the screen
* @param[in] maxPointCount the maximum number of points that can be touched at once
*
* @return true when touched and coordinates are available
*/
virtual bool getTouchedPoints(uint16_t* x, uint16_t* y, uint16_t* strength, uint8_t* pointCount, uint8_t maxPointCount) = 0;
};
}
+3 -3
View File
@@ -14,11 +14,11 @@ constexpr TickType_t defaultLockTime = 500 / portTICK_PERIOD_MS;
* @warning when passing zero, we wait forever, as this is the default behaviour for esp_lvgl_port, and we want it to remain consistent * @warning when passing zero, we wait forever, as this is the default behaviour for esp_lvgl_port, and we want it to remain consistent
* @deprecated Use lvgl_lock() or lvgl_try_lock() from lvgl-module instead. * @deprecated Use lvgl_lock() or lvgl_try_lock() from lvgl-module instead.
*/ */
bool lock(TickType_t timeout = portMAX_DELAY); bool lock(TickType_t timeout = portMAX_DELAY) __attribute__((deprecated("Use lvgl_lock() from lvgl-module")));
/** @deprecated Use lvgl_unlock() from lvgl-module instead. */ /** @deprecated Use lvgl_unlock() from lvgl-module instead. */
void unlock(); void unlock() __attribute__((deprecated("Use lvgl_unlock() from lvgl-module")));
std::shared_ptr<Lock> getSyncLock(); std::shared_ptr<Lock> getSyncLock() __attribute__((deprecated("Use lvgl locking functions from lvgl-module")));
} // namespace } // namespace
@@ -1,73 +0,0 @@
#pragma once
#include <Tactility/PubSub.h>
#include <Tactility/Mutex.h>
#include <Tactility/RecursiveMutex.h>
#include <Tactility/hal/gps/GpsDevice.h>
#include <Tactility/service/Service.h>
#include <Tactility/service/ServiceContext.h>
#include <Tactility/service/gps/GpsState.h>
namespace tt::service::gps {
class GpsService final : public Service {
struct GpsDeviceRecord {
std::shared_ptr<hal::gps::GpsDevice> device = nullptr;
hal::gps::GpsDevice::GgaSubscriptionId satelliteSubscriptionId = -1;
hal::gps::GpsDevice::RmcSubscriptionId rmcSubscriptionId = -1;
};
minmea_sentence_rmc rmcRecord;
TickType_t rmcTime = 0;
minmea_sentence_gga ggaRecord;
TickType_t ggaTime = 0;
RecursiveMutex mutex;
Mutex stateMutex;
std::vector<GpsDeviceRecord> deviceRecords;
std::shared_ptr<PubSub<State>> statePubSub = std::make_shared<PubSub<State>>();
std::unique_ptr<ServicePaths> paths;
State state = State::Off;
bool startGpsDevice(GpsDeviceRecord& deviceRecord);
static bool stopGpsDevice(GpsDeviceRecord& deviceRecord);
/** return nullptr when not found */
GpsDeviceRecord* findGpsRecord(const std::shared_ptr<hal::gps::GpsDevice>& record);
void onGgaSentence(hal::Device::Id deviceId, const minmea_sentence_gga& gga);
void onRmcSentence(hal::Device::Id deviceId, const minmea_sentence_rmc& rmc);
void setState(State newState);
void addGpsDevice(const std::shared_ptr<hal::gps::GpsDevice>& device);
void removeGpsDevice(const std::shared_ptr<hal::gps::GpsDevice>& device);
bool getConfigurationFilePath(std::string& output) const;
public:
bool onStart(ServiceContext &serviceContext) override;
void onStop(ServiceContext &serviceContext) override;
bool addGpsConfiguration(hal::gps::GpsConfiguration configuration);
bool removeGpsConfiguration(hal::gps::GpsConfiguration configuration);
bool getGpsConfigurations(std::vector<hal::gps::GpsConfiguration>& configurations) const;
bool startReceiving();
void stopReceiving();
State getState() const;
bool hasCoordinates() const;
bool getCoordinates(minmea_sentence_rmc& rmc) const;
bool getGga(minmea_sentence_gga& gga) const;
/** @return GPS service pubsub that broadcasts State* objects */
std::shared_ptr<PubSub<State>> getStatePubsub() const { return statePubSub; }
};
std::shared_ptr<GpsService> findGpsService();
} // tt::service::gps
@@ -1,12 +0,0 @@
#pragma once
namespace tt::service::gps {
enum class State {
OnPending,
On,
OffPending,
Off
};
}
@@ -1,10 +0,0 @@
#pragma once
#include <minmea.h>
namespace tt::hal::gps {
/** @return true when the input float is valid (contains non-zero values) */
inline bool isValid(const minmea_float& inFloat) { return inFloat.value != 0 && inFloat.scale != 0; }
}
@@ -1,9 +0,0 @@
#pragma once
#include "Tactility/hal/Configuration.h"
namespace tt::hal {
void init(const Configuration& configuration);
} // namespace
+1 -9
View File
@@ -7,14 +7,6 @@
namespace tt::hal::sdcard { namespace tt::hal::sdcard {
/** void startAll();
* Attempt to find an SD card that the specified belongs to,
* and returns its lock if the SD card is mounted. Otherwise it returns nullptr.
* @param[in] a path on a file system (e.g. file, directory, etc.)
* @return the lock of a mounted SD card or otherwise null
*/
std::shared_ptr<Lock> findSdCardLock(const std::string& path);
void mountAll();
} }
-68
View File
@@ -1,68 +0,0 @@
/**
* Source: https://raw.githubusercontent.com/meshtastic/firmware/3b0232de1b6282eacfbff6e50b68fca7e67b8511/src/gps/cas.h
*/
#pragma once
#include <cstdint>
// CASIC binary message definitions
// Reference: https://www.icofchina.com/d/file/xiazai/2020-09-22/20f1b42b3a11ac52089caf3603b43fb5.pdf
// ATGM33H-5N: https://www.icofchina.com/pro/mokuai/2016-08-01/4.html
// (https://www.icofchina.com/d/file/xiazai/2016-12-05/b5c57074f4b1fcc62ba8c7868548d18a.pdf)
// NEMA (Class ID - 0x4e) message IDs
#define CAS_NEMA_GGA 0x00
#define CAS_NEMA_GLL 0x01
#define CAS_NEMA_GSA 0x02
#define CAS_NEMA_GSV 0x03
#define CAS_NEMA_RMC 0x04
#define CAS_NEMA_VTG 0x05
#define CAS_NEMA_GST 0x07
#define CAS_NEMA_ZDA 0x08
#define CAS_NEMA_DHV 0x0D
// Size of a CAS-ACK-(N)ACK message (14 bytes)
#define CAS_ACK_NACK_MSG_SIZE 0x0E
// CFG-RST (0x06, 0x02)
// Factory reset
constexpr uint8_t _message_CAS_CFG_RST_FACTORY[] = {
0xFF, 0x03, // Fields to clear
0x01, // Reset Mode: Controlled Software reset
0x03 // Startup Mode: Factory
};
// CFG_RATE (0x06, 0x01)
// 1HZ update rate, this should always be the case after
// factory reset but update it regardless
constexpr uint8_t _message_CAS_CFG_RATE_1HZ[] = {
0xE8, 0x03, // Update Rate: 0x03E8 = 1000ms
0x00, 0x00 // Reserved
};
// CFG-NAVX (0x06, 0x07)
// Initial ATGM33H-5N configuration, Updates for Dynamic Mode, Fix Mode, and SV system
// Qwirk: The ATGM33H-5N-31 should only support GPS+BDS, however it will happily enable
// and use GPS+BDS+GLONASS iff the correct CFG_NAVX command is used.
constexpr uint8_t _message_CAS_CFG_NAVX_CONF[] = {
0x03, 0x01, 0x00, 0x00, // Update Mask: Dynamic Mode, Fix Mode, Nav Settings
0x03, // Dynamic Mode: Automotive
0x03, // Fix Mode: Auto 2D/3D
0x00, // Min SV
0x00, // Max SVs
0x00, // Min CNO
0x00, // Reserved1
0x00, // Init 3D fix
0x00, // Min Elevation
0x00, // Dr Limit
0x07, // Nav System: 2^0 = GPS, 2^1 = BDS 2^2 = GLONASS: 2^3
// 3=GPS+BDS, 7=GPS+BDS+GLONASS
0x00, 0x00, // Rollover Week
0x00, 0x00, 0x00, 0x00, // Fix Altitude
0x00, 0x00, 0x00, 0x00, // Fix Height Error
0x00, 0x00, 0x00, 0x00, // PDOP Maximum
0x00, 0x00, 0x00, 0x00, // TDOP Maximum
0x00, 0x00, 0x00, 0x00, // Position Accuracy Max
0x00, 0x00, 0x00, 0x00, // Time Accuracy Max
0x00, 0x00, 0x00, 0x00 // Static Hold Threshold
};
@@ -1,14 +0,0 @@
#pragma once
#include "Tactility/hal/gps/GpsDevice.h"
struct Device;
namespace tt::hal::gps {
/**
* Init sequence on UART for a specific GPS model.
*/
bool init(::Device* uart, GpsModel type);
}

Some files were not shown because too many files have changed in this diff Show More