From f086465294a94adce9859648750bb863676b9b97 Mon Sep 17 00:00:00 2001 From: Ken Van Hoeylandt Date: Sat, 25 Jul 2026 01:37:53 +0200 Subject: [PATCH] Work in progress --- .github/workflows/tests.yml | 10 +- .../DevicetreeCompiler/source/generator.py | 3 +- CMakeLists.txt | 3 +- Devices/lilygo-tdeck-plus/devicetree.yaml | 1 + .../lilygo-tdeck-plus/lilygo,tdeck-plus.dts | 9 + Devices/lilygo-tdeck-plus/source/module.cpp | 28 +- Devices/lilygo-tlora-pager/devicetree.yaml | 1 + .../lilygo-tlora-pager/lilygo,tlora-pager.dts | 7 + Devices/lilygo-tlora-pager/source/module.cpp | 31 +- Documentation/README.md | 6 +- Drivers/gps-generic-module/CMakeLists.txt | 12 + Drivers/gps-generic-module/LICENSE-GPL-3.0.md | 677 ++++++++++++++++++ Drivers/gps-generic-module/README.md | 13 + .../bindings/tactility,gps-generic.yaml | 17 + Drivers/gps-generic-module/devicetree.yaml | 4 + .../include/gps_generic/bindings.h | 7 + .../include/gps_generic/gps_generic.h | 24 + .../include/gps_generic/gps_generic_module.h | 12 + .../gps_generic/private/cas_messages.h | 57 ++ .../gps_generic/private}/gps_response.h | 4 +- .../private/gps_generic/private}/init.h | 4 +- .../private/gps_generic/private}/probe.h | 4 +- .../private/gps_generic/private}/ublox.h | 6 +- .../gps_generic/private}/ublox_messages.h | 2 +- .../source/gps_generic.cpp} | 249 ++++--- .../source/init.cpp | 18 +- Drivers/gps-generic-module/source/module.cpp | 19 + .../source/probe.cpp | 54 +- .../source/ublox.cpp | 10 +- .../include/tactility/drivers/gps.h | 112 --- .../include/tactility/gps_service.h | 92 --- Drivers/gps-module/source/cas_messages.h | 68 -- Drivers/gps-module/source/gps_service.cpp | 398 ---------- .../gps-module/source/gps_service_internal.h | 8 - Drivers/gps-module/source/module.cpp | 39 - Firmware/CMakeLists.txt | 1 + Modules/crypt-module/LICENSE-Apache-2.0.md | 195 +++++ .../gps-module/CMakeLists.txt | 1 + Modules/gps-module/LICENSE-Apache-2.0.md | 195 +++++ .../gps-module/devicetree.yaml | 0 Modules/gps-module/include/gps/gps.h | 113 +++ Modules/gps-module/include/gps/gps_module.h | 12 + Modules/gps-module/include/gps/gps_settings.h | 51 ++ .../private/gps/private/gps_ledger.h | 20 + Modules/gps-module/source/gps.cpp | 57 ++ Modules/gps-module/source/gps_ledger.cpp | 175 +++++ Modules/gps-module/source/gps_settings.cpp | 159 ++++ Modules/gps-module/source/module.cpp | 30 + .../include/tactility/lvgl_module.h | 2 +- Modules/lvgl-module/source/arch/lvgl_esp32.c | 10 +- Tactility/CMakeLists.txt | 1 + Tactility/Include/Tactility/file/FileLock.h | 3 +- Tactility/Include/Tactility/lvgl/LvglSync.h | 6 +- Tactility/Private/Tactility/hal/SdCard.h | 3 +- Tactility/Source/Tactility.cpp | 17 +- Tactility/Source/app/addgps/AddGps.cpp | 34 +- .../Source/app/gpssettings/GpsSettings.cpp | 536 ++++++-------- Tactility/Source/file/FileLvglLock.cpp | 69 ++ .../Source/service/statusbar/Statusbar.cpp | 13 +- TactilityKernel/include/tactility/device.h | 15 + .../include/tactility/filesystem/file_lock.h | 28 + .../source/filesystem/file_lock.cpp | 67 ++ Tests/Tactility/CMakeLists.txt | 1 + 63 files changed, 2493 insertions(+), 1330 deletions(-) create mode 100644 Drivers/gps-generic-module/CMakeLists.txt create mode 100644 Drivers/gps-generic-module/LICENSE-GPL-3.0.md create mode 100644 Drivers/gps-generic-module/README.md create mode 100644 Drivers/gps-generic-module/bindings/tactility,gps-generic.yaml create mode 100644 Drivers/gps-generic-module/devicetree.yaml create mode 100644 Drivers/gps-generic-module/include/gps_generic/bindings.h create mode 100644 Drivers/gps-generic-module/include/gps_generic/gps_generic.h create mode 100644 Drivers/gps-generic-module/include/gps_generic/gps_generic_module.h create mode 100644 Drivers/gps-generic-module/private/gps_generic/private/cas_messages.h rename Drivers/{gps-module/source => gps-generic-module/private/gps_generic/private}/gps_response.h (56%) rename Drivers/{gps-module/source => gps-generic-module/private/gps_generic/private}/init.h (68%) rename Drivers/{gps-module/source => gps-generic-module/private/gps_generic/private}/probe.h (73%) rename Drivers/{gps-module/source => gps-generic-module/private/gps_generic/private}/ublox.h (86%) rename Drivers/{gps-module/source => gps-generic-module/private/gps_generic/private}/ublox_messages.h (99%) rename Drivers/{gps-module/source/gps.cpp => gps-generic-module/source/gps_generic.cpp} (58%) rename Drivers/{gps-module => gps-generic-module}/source/init.cpp (95%) create mode 100644 Drivers/gps-generic-module/source/module.cpp rename Drivers/{gps-module => gps-generic-module}/source/probe.cpp (65%) rename Drivers/{gps-module => gps-generic-module}/source/ublox.cpp (98%) delete mode 100644 Drivers/gps-module/include/tactility/drivers/gps.h delete mode 100644 Drivers/gps-module/include/tactility/gps_service.h delete mode 100644 Drivers/gps-module/source/cas_messages.h delete mode 100644 Drivers/gps-module/source/gps_service.cpp delete mode 100644 Drivers/gps-module/source/gps_service_internal.h delete mode 100644 Drivers/gps-module/source/module.cpp create mode 100644 Modules/crypt-module/LICENSE-Apache-2.0.md rename {Drivers => Modules}/gps-module/CMakeLists.txt (89%) create mode 100644 Modules/gps-module/LICENSE-Apache-2.0.md rename {Drivers => Modules}/gps-module/devicetree.yaml (100%) create mode 100644 Modules/gps-module/include/gps/gps.h create mode 100644 Modules/gps-module/include/gps/gps_module.h create mode 100644 Modules/gps-module/include/gps/gps_settings.h create mode 100644 Modules/gps-module/private/gps/private/gps_ledger.h create mode 100644 Modules/gps-module/source/gps.cpp create mode 100644 Modules/gps-module/source/gps_ledger.cpp create mode 100644 Modules/gps-module/source/gps_settings.cpp create mode 100644 Modules/gps-module/source/module.cpp create mode 100644 Tactility/Source/file/FileLvglLock.cpp create mode 100644 TactilityKernel/include/tactility/filesystem/file_lock.h create mode 100644 TactilityKernel/source/filesystem/file_lock.cpp diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 78ab3c9a9..8d5bb88e6 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -19,14 +19,8 @@ jobs: run: cmake -S ./ -B build - name: "Build Tests" run: cmake --build build --target build-tests - - name: "Run TactilityFreeRtos Tests" - run: build/Tests/TactilityFreeRtos/TactilityFreeRtosTests - - 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 + - name: "Run Tests" + run: ctest --build-dir build/Tests DevicetreeTests: runs-on: ubuntu-latest steps: diff --git a/Buildscripts/DevicetreeCompiler/source/generator.py b/Buildscripts/DevicetreeCompiler/source/generator.py index 4a45cce72..c8f41f838 100644 --- a/Buildscripts/DevicetreeCompiler/source/generator.py +++ b/Buildscripts/DevicetreeCompiler/source/generator.py @@ -26,7 +26,7 @@ def get_device_node_name_safe(device: Device): def get_device_type_name(device: Device, bindings: list[Binding]): device_binding = find_device_binding(device, bindings) 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: raise DevicetreeException(f"Couldn't find compatible binding for {device.node_name}") 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.name = \"{device.node_name}\",\n") # Use original name file.write(f"\t.config = &{config_variable_name},\n") + file.write(f"\t.flags = DEVICE_FLAG_DTS,\n") file.write(f"\t.parent = {parent_value},\n") file.write("\t.internal = NULL\n") file.write("};\n\n") diff --git a/CMakeLists.txt b/CMakeLists.txt index e558fec3c..0ab914383 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -98,7 +98,8 @@ if (NOT DEFINED ENV{ESP_IDF_VERSION}) add_subdirectory(Libraries/minmea) add_subdirectory(Modules/lvgl-module) add_subdirectory(Modules/crypt-module) - add_subdirectory(Drivers/gps-module) + add_subdirectory(Modules/gps-module) + add_subdirectory(Drivers/gps-generic-module) # FreeRTOS set(FREERTOS_CONFIG_FILE_DIRECTORY ${PROJECT_SOURCE_DIR}/Devices/simulator/Source CACHE STRING "") diff --git a/Devices/lilygo-tdeck-plus/devicetree.yaml b/Devices/lilygo-tdeck-plus/devicetree.yaml index 805ca1eaa..8634f22b4 100644 --- a/Devices/lilygo-tdeck-plus/devicetree.yaml +++ b/Devices/lilygo-tdeck-plus/devicetree.yaml @@ -1,5 +1,6 @@ dependencies: - Platforms/platform-esp32 + - Drivers/gps-generic-module - Drivers/st7789-module - Drivers/gt911-module - Drivers/lilygo-module diff --git a/Devices/lilygo-tdeck-plus/lilygo,tdeck-plus.dts b/Devices/lilygo-tdeck-plus/lilygo,tdeck-plus.dts index 1cfc2c93d..f9bd97d01 100644 --- a/Devices/lilygo-tdeck-plus/lilygo,tdeck-plus.dts +++ b/Devices/lilygo-tdeck-plus/lilygo,tdeck-plus.dts @@ -20,6 +20,8 @@ #include #include +#include + #include #include #include @@ -188,5 +190,12 @@ port = ; pin-tx = <&gpio0 43 GPIO_FLAG_NONE>; pin-rx = <&gpio0 44 GPIO_FLAG_NONE>; + + gps { + compatible = "tactility,gps-generic"; + status = "disabled"; + baud-rate = <38400>; + model = ; + }; }; }; diff --git a/Devices/lilygo-tdeck-plus/source/module.cpp b/Devices/lilygo-tdeck-plus/source/module.cpp index f03d41e5b..ea51abaa0 100644 --- a/Devices/lilygo-tdeck-plus/source/module.cpp +++ b/Devices/lilygo-tdeck-plus/source/module.cpp @@ -1,6 +1,5 @@ +#include #include -#include -#include #include #include #include @@ -12,31 +11,11 @@ #include #include -#include - -#include - constexpr auto* TAG = "tdeck-plus"; extern "C" { -static tt::kernel::SystemEventSubscription tdeck_boot_splash_subscription = 0; - -void init_gps_configuration() { - bool has_configuration = false; - gps_service_for_each_configuration(&has_configuration, [](const GpsConfiguration*, size_t, void* context) { - *static_cast(context) = true; - }); - - if (!has_configuration) { - GpsConfiguration configuration = { .uart_name = "uart0", .baud_rate = 38400, .model = GpsModel::GPS_MODEL_UBLOX10 }; - if (gps_service_add_configuration(&configuration) == ERROR_NONE) { - LOG_I(TAG, "Configured internal GPS"); - } else { - LOG_E(TAG, "Failed to configure internal GPS"); - } - } -} +static tt::kernel::SystemEventSubscription tdeck_boot_splash_subscription = tt::kernel::NoSystemEventSubscription; void init_trackball() { auto tbSettings = tt::settings::trackball::loadOrGetDefault(); @@ -64,7 +43,6 @@ static error_t start() { delay_millis(100); tdeck_boot_splash_subscription = tt::kernel::subscribeSystemEvent(tt::kernel::SystemEvent::BootSplash, [](tt::kernel::SystemEvent event) { - init_gps_configuration(); init_trackball(); }); @@ -73,7 +51,7 @@ static error_t start() { static error_t stop() { tt::kernel::unsubscribeSystemEvent(tdeck_boot_splash_subscription); - tdeck_boot_splash_subscription = 0; + tdeck_boot_splash_subscription = tt::kernel::NoSystemEventSubscription; return ERROR_NONE; } diff --git a/Devices/lilygo-tlora-pager/devicetree.yaml b/Devices/lilygo-tlora-pager/devicetree.yaml index 82ada517d..d38da1a52 100644 --- a/Devices/lilygo-tlora-pager/devicetree.yaml +++ b/Devices/lilygo-tlora-pager/devicetree.yaml @@ -1,5 +1,6 @@ dependencies: - Platforms/platform-esp32 + - Drivers/gps-generic-module - Drivers/st7796-module - Drivers/bq27220-module - Drivers/tca8418-module diff --git a/Devices/lilygo-tlora-pager/lilygo,tlora-pager.dts b/Devices/lilygo-tlora-pager/lilygo,tlora-pager.dts index f3343fb59..618c80caa 100644 --- a/Devices/lilygo-tlora-pager/lilygo,tlora-pager.dts +++ b/Devices/lilygo-tlora-pager/lilygo,tlora-pager.dts @@ -181,6 +181,13 @@ port = ; pin-tx = <&gpio0 12 GPIO_FLAG_NONE>; pin-rx = <&gpio0 4 GPIO_FLAG_NONE>; + + gps { + compatible = "tactility,gps-generic"; + status = "disabled"; + baud-rate = <38400>; + model = ; + }; }; uart_external: uart1 { diff --git a/Devices/lilygo-tlora-pager/source/module.cpp b/Devices/lilygo-tlora-pager/source/module.cpp index 7b4b60683..81f331b26 100644 --- a/Devices/lilygo-tlora-pager/source/module.cpp +++ b/Devices/lilygo-tlora-pager/source/module.cpp @@ -1,14 +1,8 @@ -#include -#include +#include #include -#include #include -#include #include -#include -#include -#include #include @@ -16,41 +10,22 @@ constexpr auto* TAG = "T-Lora Pager"; extern "C" { -tt::kernel::SystemEventSubscription event_subscription; +tt::kernel::SystemEventSubscription event_subscription = tt::kernel::NoSystemEventSubscription; static error_t start() { - - LOG_I(TAG, LOG_MESSAGE_POWER_ON_START); - 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 // registers it as an LVGL input device, which requires LVGL to be up first. lvgl_lock(); tpager_encoder::init(); lvgl_unlock(); - - auto gps_service = tt::service::gps::findGpsService(); - if (gps_service != nullptr) { - std::vector 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; } static error_t stop() { tt::kernel::unsubscribeSystemEvent(event_subscription); + event_subscription = tt::kernel::NoSystemEventSubscription; return ERROR_NONE; } diff --git a/Documentation/README.md b/Documentation/README.md index 172d58124..628acd143 100644 --- a/Documentation/README.md +++ b/Documentation/README.md @@ -64,11 +64,7 @@ Tests use Doctest and run on simulator (POSIX) target only: ```bash cmake -B buildsim -G Ninja ninja -C buildsim build-tests -cd buildsim && ctest # run all tests -./buildsim/Tests/TactilityKernel/TactilityKernelTests -./buildsim/Tests/Tactility/TactilityTests -./buildsim/Tests/TactilityFreeRtos/TactilityFreeRtosTests -./buildsim/Tests/crypt-module/CryptModuleTests +cd buildsim && ctest --test-dir Tests ``` ## Architecture diff --git a/Drivers/gps-generic-module/CMakeLists.txt b/Drivers/gps-generic-module/CMakeLists.txt new file mode 100644 index 000000000..828c12977 --- /dev/null +++ b/Drivers/gps-generic-module/CMakeLists.txt @@ -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 +) diff --git a/Drivers/gps-generic-module/LICENSE-GPL-3.0.md b/Drivers/gps-generic-module/LICENSE-GPL-3.0.md new file mode 100644 index 000000000..5a9d38ddf --- /dev/null +++ b/Drivers/gps-generic-module/LICENSE-GPL-3.0.md @@ -0,0 +1,677 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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. + + + Copyright (C) + + 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 . + +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: + + Copyright (C) + 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 +. + + 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 . diff --git a/Drivers/gps-generic-module/README.md b/Drivers/gps-generic-module/README.md new file mode 100644 index 000000000..af7923579 --- /dev/null +++ b/Drivers/gps-generic-module/README.md @@ -0,0 +1,13 @@ +# gps-generic-module + +Kernel driver implementing the `GPS_TYPE`/`GpsApi` interface (declared by `Drivers/gps-module`, +Apache-2.0) for generic UART-connected GPS/GNSS receivers: chipset probing, init sequences, and +NMEA parsing for MTK, Airoha/AG33xx, ATGM336H/CASIC, Unicore UC6580 and u-blox 6/7/8/9/10 modules. + +## 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: ` comments in those files for the exact origin of each ported function. diff --git a/Drivers/gps-generic-module/bindings/tactility,gps-generic.yaml b/Drivers/gps-generic-module/bindings/tactility,gps-generic.yaml new file mode 100644 index 000000000..f7122434d --- /dev/null +++ b/Drivers/gps-generic-module/bindings/tactility,gps-generic.yaml @@ -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(). diff --git a/Drivers/gps-generic-module/devicetree.yaml b/Drivers/gps-generic-module/devicetree.yaml new file mode 100644 index 000000000..e3dee67d7 --- /dev/null +++ b/Drivers/gps-generic-module/devicetree.yaml @@ -0,0 +1,4 @@ +dependencies: + - TactilityKernel + - Modules/gps-module +bindings: bindings diff --git a/Drivers/gps-generic-module/include/gps_generic/bindings.h b/Drivers/gps-generic-module/include/gps_generic/bindings.h new file mode 100644 index 000000000..a64961270 --- /dev/null +++ b/Drivers/gps-generic-module/include/gps_generic/bindings.h @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once + +#include +#include + +DEFINE_DEVICETREE(gps_generic, struct GpsConfig) diff --git a/Drivers/gps-generic-module/include/gps_generic/gps_generic.h b/Drivers/gps-generic-module/include/gps_generic/gps_generic.h new file mode 100644 index 000000000..ecfdf5262 --- /dev/null +++ b/Drivers/gps-generic-module/include/gps_generic/gps_generic.h @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#include +#include + +/** + * @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 diff --git a/Drivers/gps-generic-module/include/gps_generic/gps_generic_module.h b/Drivers/gps-generic-module/include/gps_generic/gps_generic_module.h new file mode 100644 index 000000000..03d1c0417 --- /dev/null +++ b/Drivers/gps-generic-module/include/gps_generic/gps_generic_module.h @@ -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 diff --git a/Drivers/gps-generic-module/private/gps_generic/private/cas_messages.h b/Drivers/gps-generic-module/private/gps_generic/private/cas_messages.h new file mode 100644 index 000000000..011944af0 --- /dev/null +++ b/Drivers/gps-generic-module/private/gps_generic/private/cas_messages.h @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +#pragma once + +#include +#include + +// 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 +}; diff --git a/Drivers/gps-module/source/gps_response.h b/Drivers/gps-generic-module/private/gps_generic/private/gps_response.h similarity index 56% rename from Drivers/gps-module/source/gps_response.h rename to Drivers/gps-generic-module/private/gps_generic/private/gps_response.h index 13d0413a1..4f8fdabd9 100644 --- a/Drivers/gps-module/source/gps_response.h +++ b/Drivers/gps-generic-module/private/gps_generic/private/gps_response.h @@ -1,8 +1,8 @@ -// SPDX-License-Identifier: Apache-2.0 +// 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 tactility/drivers/gps.h) - callers only ever see GpsState/GpsModel. +// Not part of the public API (see gps/gps.h) - callers only ever see GpsState/GpsModel. enum class GpsResponse { None, NotAck, diff --git a/Drivers/gps-module/source/init.h b/Drivers/gps-generic-module/private/gps_generic/private/init.h similarity index 68% rename from Drivers/gps-module/source/init.h rename to Drivers/gps-generic-module/private/gps_generic/private/init.h index c51f0a93a..6c5cf89e8 100644 --- a/Drivers/gps-module/source/init.h +++ b/Drivers/gps-generic-module/private/gps_generic/private/init.h @@ -1,7 +1,7 @@ -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: GPL-3.0-or-later #pragma once -#include +#include struct Device; diff --git a/Drivers/gps-module/source/probe.h b/Drivers/gps-generic-module/private/gps_generic/private/probe.h similarity index 73% rename from Drivers/gps-module/source/probe.h rename to Drivers/gps-generic-module/private/gps_generic/private/probe.h index e72457215..5e2dc9c00 100644 --- a/Drivers/gps-module/source/probe.h +++ b/Drivers/gps-generic-module/private/gps_generic/private/probe.h @@ -1,7 +1,7 @@ -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: GPL-3.0-or-later #pragma once -#include +#include struct Device; diff --git a/Drivers/gps-module/source/ublox.h b/Drivers/gps-generic-module/private/gps_generic/private/ublox.h similarity index 86% rename from Drivers/gps-module/source/ublox.h rename to Drivers/gps-generic-module/private/gps_generic/private/ublox.h index 398bff527..d7465cc73 100644 --- a/Drivers/gps-module/source/ublox.h +++ b/Drivers/gps-generic-module/private/gps_generic/private/ublox.h @@ -1,10 +1,10 @@ -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: GPL-3.0-or-later #pragma once -#include +#include -#include #include +#include struct Device; diff --git a/Drivers/gps-module/source/ublox_messages.h b/Drivers/gps-generic-module/private/gps_generic/private/ublox_messages.h similarity index 99% rename from Drivers/gps-module/source/ublox_messages.h rename to Drivers/gps-generic-module/private/gps_generic/private/ublox_messages.h index 84bff1494..5fd71d1bf 100644 --- a/Drivers/gps-module/source/ublox_messages.h +++ b/Drivers/gps-generic-module/private/gps_generic/private/ublox_messages.h @@ -1,4 +1,4 @@ -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: GPL-3.0-or-later #pragma once #include diff --git a/Drivers/gps-module/source/gps.cpp b/Drivers/gps-generic-module/source/gps_generic.cpp similarity index 58% rename from Drivers/gps-module/source/gps.cpp rename to Drivers/gps-generic-module/source/gps_generic.cpp index 926043d4e..ddfa695b8 100644 --- a/Drivers/gps-module/source/gps.cpp +++ b/Drivers/gps-generic-module/source/gps_generic.cpp @@ -1,8 +1,9 @@ -// SPDX-License-Identifier: Apache-2.0 -#include +// SPDX-License-Identifier: GPL-3.0-or-later +#include +#include -#include "init.h" -#include "probe.h" +#include +#include #include #include @@ -10,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -18,12 +20,13 @@ #include -constexpr auto* TAG = "Gps"; +constexpr auto* TAG = "gps-generic"; + #define GET_CONFIG(device) (static_cast((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(10); +constexpr TickType_t GPS_THREAD_STOP_POLL_TICKS = pdMS_TO_TICKS(1000); struct GpsInternal { RecursiveMutex mutex; @@ -32,14 +35,59 @@ struct GpsInternal { GpsState state; // Mirrors GpsConfig::model, but overwritten with the autodetected model once probing succeeds. GpsModel model; - bool has_rmc; - minmea_sentence_rmc rmc; - TickType_t rmc_time; - bool has_gga; - minmea_sentence_gga gga; - TickType_t gga_time; + // 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; @@ -58,12 +106,12 @@ static bool is_interrupted(GpsInternal* internal) { static int32_t gps_thread_main(void* context) { auto* device = static_cast(context); auto* internal = static_cast(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 auto* config = GET_CONFIG(device); - - UartConfig uart_config = { + const UartConfig uart_config = { .baud_rate = config->baud_rate, .data_bits = UART_CONTROLLER_DATA_8_BITS, .parity = UART_CONTROLLER_PARITY_DISABLE, @@ -115,28 +163,20 @@ static int32_t gps_thread_main(void* context) { } if (bytes_read > 0U) { - switch (minmea_sentence_id((char*)buffer, false)) { + switch (minmea_sentence_id(reinterpret_cast(buffer), false)) { case MINMEA_SENTENCE_RMC: { - minmea_sentence_rmc rmc_frame; - if (minmea_parse_rmc(&rmc_frame, (char*)buffer)) { - recursive_mutex_lock(&internal->mutex); - internal->has_rmc = true; - internal->rmc = rmc_frame; - internal->rmc_time = get_ticks(); - recursive_mutex_unlock(&internal->mutex); + GpsEvent event { .type = GPS_EVENT_MESSAGE_RMC }; + if (minmea_parse_rmc(&event.data.rmc, reinterpret_cast(buffer))) { + notify_subscribers(internal, event); } else { LOG_E(TAG, "RMC parse error: %s", reinterpret_cast(buffer)); } break; } case MINMEA_SENTENCE_GGA: { - minmea_sentence_gga gga_frame; - if (minmea_parse_gga(&gga_frame, (char*)buffer)) { - recursive_mutex_lock(&internal->mutex); - internal->has_gga = true; - internal->gga = gga_frame; - internal->gga_time = get_ticks(); - recursive_mutex_unlock(&internal->mutex); + GpsEvent event { .type = GPS_EVENT_MESSAGE_GGA }; + if (minmea_parse_gga(&event.data.gga, reinterpret_cast(buffer))) { + notify_subscribers(internal, event); } else { LOG_E(TAG, "GGA parse error: %s", reinterpret_cast(buffer)); } @@ -152,7 +192,14 @@ static int32_t gps_thread_main(void* context) { LOG_W(TAG, "Failed to close UART %s", uart->name); } - set_state(internal, GpsState::GPS_STATE_OFF); + // 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; } @@ -166,8 +213,7 @@ static error_t start(Device* device) { recursive_mutex_construct(&internal->mutex); internal->model = config->model; - internal->state = GpsState::GPS_STATE_PENDING_ON; - + 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); @@ -194,11 +240,12 @@ static error_t stop(Device* device) { recursive_mutex_lock(&internal->mutex); internal->interrupt_requested = true; - internal->state = GpsState::GPS_STATE_PENDING_OFF; + 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_W(TAG, "GPS thread for %s did not stop in time", device->name); + LOG_E(TAG, "GPS thread for %s did not stop in time", device->name); + return ERROR_RESOURCE_BUSY; } thread_free(internal->thread); @@ -212,46 +259,49 @@ static error_t stop(Device* device) { // region GpsApi -static error_t gps_api_get_rmc(Device* device, minmea_sentence_rmc* out, TickType_t max_age) { +static error_t gps_api_event_subscribe(Device* device, GpsSubscription* sub) { auto* internal = static_cast(device_get_driver_data(device)); + sub->task = xTaskGetCurrentTaskHandle(); + sub->sequence = 0; + sub->consumed_sequence = 0; + recursive_mutex_lock(&internal->mutex); - error_t result; - if (!internal->has_rmc) { - result = ERROR_NOT_FOUND; - } else if (get_ticks() - internal->rmc_time > max_age) { - result = ERROR_TIMEOUT; - } else { - *out = internal->rmc; - result = ERROR_NONE; + 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(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_get_gga(Device* device, minmea_sentence_gga* out, TickType_t max_age) { - auto* internal = static_cast(device_get_driver_data(device)); +static error_t gps_api_event_await(Device*, GpsSubscription* sub, TickType_t timeout) { + uint32_t old_sequence = sub->sequence; - recursive_mutex_lock(&internal->mutex); - error_t result; - if (!internal->has_gga) { - result = ERROR_NOT_FOUND; - } else if (get_ticks() - internal->gga_time > max_age) { - result = ERROR_TIMEOUT; - } else { - *out = internal->gga; - result = ERROR_NONE; + while (sub->sequence == old_sequence) { + if (ulTaskNotifyTake(pdTRUE, timeout) == 0) { + return ERROR_TIMEOUT; + } } - recursive_mutex_unlock(&internal->mutex); - return result; -} -static GpsModel gps_api_get_model(Device* device) { - auto* internal = static_cast(device_get_driver_data(device)); - recursive_mutex_lock(&internal->mutex); - auto model = internal->model; - recursive_mutex_unlock(&internal->mutex); - return model; + sub->consumed_sequence = sub->sequence; + return ERROR_NONE; } static GpsState gps_api_get_state(Device* device) { @@ -262,66 +312,31 @@ static GpsState gps_api_get_state(Device* device) { 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); + strncpy(model_name, name_to_set, buffer_size); + return ERROR_NONE; +} + // endregion -const char* gps_model_to_string(enum 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_get_rmc(Device* device, minmea_sentence_rmc* out, TickType_t max_age) { - const auto* driver = device_get_driver(device); - return static_cast(driver->api)->get_rmc(device, out, max_age); -} - -error_t gps_get_gga(Device* device, minmea_sentence_gga* out, TickType_t max_age) { - const auto* driver = device_get_driver(device); - return static_cast(driver->api)->get_gga(device, out, max_age); -} - -enum GpsModel gps_get_model(Device* device) { - const auto* driver = device_get_driver(device); - return static_cast(driver->api)->get_model(device); -} - -enum GpsState gps_get_state(Device* device) { - const auto* driver = device_get_driver(device); - return static_cast(driver->api)->get_state(device); -} - -const DeviceType GPS_TYPE { - .name = "gps" -}; - -static const GpsApi gps_api = { - .get_rmc = gps_api_get_rmc, - .get_gga = gps_api_get_gga, - .get_model = gps_api_get_model, +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_module; +extern Module gps_generic_module; -Driver gps_driver = { - .name = "gps", - .compatible = (const char*[]) { "generic,gps", nullptr }, +Driver generic_gps_driver = { + .name = "gps-generic", + .compatible = (const char*[]) { "tactility,gps-generic", nullptr }, .start_device = start, .stop_device = stop, - .api = &gps_api, + .api = &generic_gps_api, .device_type = &GPS_TYPE, - .owner = &gps_module + .owner = &gps_generic_module }; diff --git a/Drivers/gps-module/source/init.cpp b/Drivers/gps-generic-module/source/init.cpp similarity index 95% rename from Drivers/gps-module/source/init.cpp rename to Drivers/gps-generic-module/source/init.cpp index 0a1f3b72c..655d4e863 100644 --- a/Drivers/gps-module/source/init.cpp +++ b/Drivers/gps-generic-module/source/init.cpp @@ -1,8 +1,8 @@ -// SPDX-License-Identifier: Apache-2.0 -#include "init.h" -#include "cas_messages.h" -#include "gps_response.h" -#include "ublox.h" +// SPDX-License-Identifier: GPL-3.0-or-later +#include +#include +#include +#include #include #include @@ -13,7 +13,7 @@ #include -constexpr auto* TAG = "Gps"; +constexpr auto* TAG = "gps"; bool init_mtk(Device* uart); bool init_mtk_l76b(Device* uart); @@ -77,7 +77,7 @@ static uint8_t make_cas_packet(uint8_t* buffer, uint8_t class_id, uint8_t msg_id 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(); - uint8_t buffer[CAS_ACK_NACK_MSG_SIZE] = {0}; + uint8_t buffer[CAS_MESSAGE_ACK_NACK_SIZE] = {0}; uint8_t buffer_pos = 0; TickType_t wait_ticks = pdMS_TO_TICKS(wait_millis); @@ -208,14 +208,14 @@ bool init_atgm336h(Device* uart) { uint8_t buffer[256]; // Set the intial configuration of the device - these _should_ work for most AT6558 devices - int msglen = make_cas_packet(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); if (get_ack_cas(uart, 0x06, 0x07, 250) != GpsResponse::Ok) { LOG_W(TAG, "ATGM336H: Could not set Config"); } // Set the update frequence to 1Hz - msglen = make_cas_packet(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); if (get_ack_cas(uart, 0x06, 0x04, 250) != GpsResponse::Ok) { LOG_W(TAG, "ATGM336H: Could not set Update Frequency"); diff --git a/Drivers/gps-generic-module/source/module.cpp b/Drivers/gps-generic-module/source/module.cpp new file mode 100644 index 000000000..138085080 --- /dev/null +++ b/Drivers/gps-generic-module/source/module.cpp @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#include +#include + +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 +}; + +} diff --git a/Drivers/gps-module/source/probe.cpp b/Drivers/gps-generic-module/source/probe.cpp similarity index 65% rename from Drivers/gps-module/source/probe.cpp rename to Drivers/gps-generic-module/source/probe.cpp index 3022bc5e0..68c08d150 100644 --- a/Drivers/gps-module/source/probe.cpp +++ b/Drivers/gps-generic-module/source/probe.cpp @@ -1,7 +1,7 @@ -// SPDX-License-Identifier: Apache-2.0 -#include "probe.h" -#include "gps_response.h" -#include "ublox.h" +// SPDX-License-Identifier: GPL-3.0-or-later +#include +#include +#include #include #include @@ -13,9 +13,6 @@ constexpr auto* TAG = "Gps"; -/** - * From: https://github.com/meshtastic/firmware/blob/3b0232de1b6282eacfbff6e50b68fca7e67b8511/src/meshUtils.cpp#L40 - */ static char* probe_strnstr(const char* s, const char* find, size_t slen) { char c; if ((c = *find++) != '\0') { @@ -36,9 +33,6 @@ static char* probe_strnstr(const char* s, const char* find, size_t slen) { return ((char*)s); } -/** - * From: https://github.com/meshtastic/firmware/blob/f81d3b045dd1b7e3ca7870af3da915ff4399ea98/src/gps/GPS.cpp - */ static GpsResponse get_ack(Device* uart, const char* message, uint32_t wait_millis) { uint8_t buffer[768] = {0}; uint8_t b; @@ -64,9 +58,6 @@ static GpsResponse get_ack(Device* uart, const char* message, uint32_t wait_mill return GpsResponse::None; } -/** - * From: https://github.com/meshtastic/firmware/blob/f81d3b045dd1b7e3ca7870af3da915ff4399ea98/src/gps/GPS.cpp - */ #define PROBE_SIMPLE(UART, CHIP, TOWRITE, RESPONSE, DRIVER, TIMEOUT, ...) \ do { \ LOG_I(TAG, "Probing for %s (%s)", CHIP, TOWRITE); \ @@ -78,18 +69,16 @@ static GpsResponse get_ack(Device* uart, const char* message, uint32_t wait_mill } \ } while (0) -/** - * From: https://github.com/meshtastic/firmware/blob/f81d3b045dd1b7e3ca7870af3da915ff4399ea98/src/gps/GPS.cpp - */ GpsModel gps_probe(Device* uart) { - // Close all NMEA sentences, valid for L76K, ATGM336H (and likely other AT6558 devices) - uart_controller_write_bytes(uart, (const uint8_t*)"$PCAS03,0,0,0,0,0,0,0,0,0,0,,,0,0*02\r\n", 40, 500); + // Close all NMEA sentences + // Valid for L76K, ATGM336H and likely other AT6558 devices + uart_controller_write_bytes(uart, reinterpret_cast("$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, (const uint8_t*)"$PUBX,40,GLL,0,0,0,0,0,0*5C\r\n", 29, 500); - uart_controller_write_bytes(uart, (const uint8_t*)"$PUBX,40,GSV,0,0,0,0,0,0*59\r\n", 29, 500); - uart_controller_write_bytes(uart, (const uint8_t*)"$PUBX,40,VTG,0,0,0,0,0,0*5E\r\n", 29, 500); + uart_controller_write_bytes(uart, reinterpret_cast("$PUBX,40,GLL,0,0,0,0,0,0*5C\r\n"), 29, 500); + uart_controller_write_bytes(uart, reinterpret_cast("$PUBX,40,GSV,0,0,0,0,0,0*59\r\n"), 29, 500); + uart_controller_write_bytes(uart, reinterpret_cast("$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 @@ -97,32 +86,35 @@ GpsModel gps_probe(Device* uart) { 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 */ + // 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 */ - uart_controller_write_bytes(uart, (const uint8_t*)"$PAIR062,2,0*3C\r\n", 17, 500); // GSA OFF to reduce volume - uart_controller_write_bytes(uart, (const uint8_t*)"$PAIR062,3,0*3D\r\n", 17, 500); // GSV OFF to reduce volume - uart_controller_write_bytes(uart, (const uint8_t*)"$PAIR513*3D\r\n", 13, 500); // save configuration + // Airoha (Mediatek) AG3335A/M/S, A3352Q, Quectel L89 2.0, SimCom SIM65M + // GSA OFF, reduce volume + uart_controller_write_bytes(uart, reinterpret_cast("$PAIR062,2,0*3C\r\n"), 17, 500); + // GSV OFF, reduce volume + uart_controller_write_bytes(uart, reinterpret_cast("$PAIR062,3,0*3D\r\n"), 17, 500); + // Save configuration + uart_controller_write_bytes(uart, reinterpret_cast("$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 platform (Waveshare Pico GPS) - uart_controller_write_bytes(uart, (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); + // Close all NMEA sentences + // Valid for L76B MTK + uart_controller_write_bytes(uart, reinterpret_cast("$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 != GpsModel::GPS_MODEL_UNKNOWN) { + if (ublox_result != GPS_MODEL_UNKNOWN) { return ublox_result; } else { LOG_W(TAG, "No GNSS Module"); - return GpsModel::GPS_MODEL_UNKNOWN; + return GPS_MODEL_UNKNOWN; } } diff --git a/Drivers/gps-module/source/ublox.cpp b/Drivers/gps-generic-module/source/ublox.cpp similarity index 98% rename from Drivers/gps-module/source/ublox.cpp rename to Drivers/gps-generic-module/source/ublox.cpp index afca86c77..8462cc897 100644 --- a/Drivers/gps-module/source/ublox.cpp +++ b/Drivers/gps-generic-module/source/ublox.cpp @@ -1,7 +1,9 @@ -// SPDX-License-Identifier: Apache-2.0 -#include "ublox.h" -#include "gps_response.h" -#include "ublox_messages.h" +// SPDX-License-Identifier: GPL-3.0-or-later +#include +#include +#include + +#include #include #include diff --git a/Drivers/gps-module/include/tactility/drivers/gps.h b/Drivers/gps-module/include/tactility/drivers/gps.h deleted file mode 100644 index e1950e778..000000000 --- a/Drivers/gps-module/include/tactility/drivers/gps.h +++ /dev/null @@ -1,112 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -#pragma once - -#ifdef __cplusplus -extern "C" { -#endif - -#include - -#include -#include -#include - -#include - -/** - * @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, 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, -}; - -/** - * @brief Configuration for a GPS_TYPE device. - * @warning Set device_set_parent() to the UART_CONTROLLER_TYPE device this receiver is wired to - * before starting - the driver reads/writes through its parent. - */ -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; -}; - -/** - * @brief API for GPS/GNSS receiver drivers. - */ -struct GpsApi { - /** - * @brief Gets the most recently parsed RMC (position/velocity/time) sentence. - * @param[in] device the GPS device - * @param[out] out the parsed sentence - * @param[in] max_age the maximum acceptable age of the cached sentence - * @retval ERROR_NONE when a sentence younger than max_age was copied into out - * @retval ERROR_NOT_FOUND when no RMC sentence has ever been parsed - * @retval ERROR_TIMEOUT when the cached sentence is older than max_age - */ - error_t (*get_rmc)(struct Device* device, struct minmea_sentence_rmc* out, TickType_t max_age); - - /** - * @brief Gets the most recently parsed GGA (fix data) sentence. - * @see GpsApi::get_rmc - */ - error_t (*get_gga)(struct Device* device, struct minmea_sentence_gga* out, TickType_t max_age); - - /** - * @brief Gets the model in use - the autodetected model when configured with GPS_MODEL_UNKNOWN. - * @param[in] device the GPS device - */ - enum GpsModel (*get_model)(struct Device* device); - - /** - * @brief Gets the current lifecycle state. - * @param[in] device the GPS device - */ - enum GpsState (*get_state)(struct Device* device); -}; - -/** @copydoc GpsApi::get_rmc */ -error_t gps_get_rmc(struct Device* device, struct minmea_sentence_rmc* out, TickType_t max_age); - -/** @copydoc GpsApi::get_gga */ -error_t gps_get_gga(struct Device* device, struct minmea_sentence_gga* out, TickType_t max_age); - -/** @copydoc GpsApi::get_model */ -enum GpsModel gps_get_model(struct Device* device); - -/** @copydoc GpsApi::get_state */ -enum GpsState gps_get_state(struct Device* device); - -extern const struct DeviceType GPS_TYPE; - -#ifdef __cplusplus -} -#endif diff --git a/Drivers/gps-module/include/tactility/gps_service.h b/Drivers/gps-module/include/tactility/gps_service.h deleted file mode 100644 index 1c23f5843..000000000 --- a/Drivers/gps-module/include/tactility/gps_service.h +++ /dev/null @@ -1,92 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -#pragma once - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include -#include - -#include -#include - -#include - -struct Module; - -#define GPS_SERVICE_ID "gps" - -/** - * @brief Aggregate receive state of the GPS service (across all configured receivers). - */ -enum GpsServiceState { - GPS_SERVICE_STATE_ON_PENDING, - GPS_SERVICE_STATE_ON, - GPS_SERVICE_STATE_OFF_PENDING, - GPS_SERVICE_STATE_OFF, -}; - -/** - * @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. - * @retval ERROR_RESOURCE if the configuration file could not be opened/written - */ -error_t gps_service_add_configuration(const struct GpsConfiguration* configuration); - -/** - * @brief Removes a persisted GPS configuration that matches by value. - * @retval ERROR_NOT_FOUND if no matching configuration was found - * @retval ERROR_RESOURCE if the configuration file could not be read/written - */ -error_t gps_service_remove_configuration(const struct GpsConfiguration* configuration); - -/** - * @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_service_for_each_configuration(void* context, void (*on_configuration)(const struct GpsConfiguration* configuration, size_t index, void* context)); - -/** - * @brief Iterates over the GPS_TYPE devices currently constructed by gps_service_start_receiving(). - */ -void gps_service_for_each_device(void* context, void (*on_device)(struct Device* device, void* context)); - -/** - * @brief Constructs and starts a GPS_TYPE device for every persisted configuration and begins receiving. - * @retval ERROR_INVALID_STATE if already receiving - * @retval ERROR_NOT_FOUND if there are no persisted configurations, or none of their UART devices could be found - */ -error_t gps_service_start_receiving(void); - -/** Stops and destroys every GPS_TYPE device constructed by gps_service_start_receiving(). */ -void gps_service_stop_receiving(void); - -enum GpsServiceState gps_service_get_state(void); - -/** @return true when a coordinate fix is available and is not older than 10 seconds */ -bool gps_service_has_coordinates(void); - -/** @copydoc gps_service_has_coordinates */ -bool gps_service_get_coordinates(struct minmea_sentence_rmc* out); - -/** @return true when GGA fix data is available and is not older than 10 seconds */ -bool gps_service_get_gga(struct minmea_sentence_gga* out); - -extern struct Module gps_module; - -#ifdef __cplusplus -} -#endif diff --git a/Drivers/gps-module/source/cas_messages.h b/Drivers/gps-module/source/cas_messages.h deleted file mode 100644 index d203ab15a..000000000 --- a/Drivers/gps-module/source/cas_messages.h +++ /dev/null @@ -1,68 +0,0 @@ -/** - * Source: https://raw.githubusercontent.com/meshtastic/firmware/3b0232de1b6282eacfbff6e50b68fca7e67b8511/src/gps/cas.h - */ -#pragma once - -#include - -// 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 -}; diff --git a/Drivers/gps-module/source/gps_service.cpp b/Drivers/gps-module/source/gps_service.cpp deleted file mode 100644 index a148bde58..000000000 --- a/Drivers/gps-module/source/gps_service.cpp +++ /dev/null @@ -1,398 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -#include -#include "gps_service_internal.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include -#include -#include -#include - -constexpr auto* TAG = "GpsService"; - -// A dynamically-constructed GPS_TYPE device, one per active GpsConfiguration. Device is the first -// member so `reinterpret_cast(device)` is never needed - callers just keep the -// Device* and, once done with it, `delete` via a GpsDeviceEntry* they already have. -struct GpsDeviceEntry { - Device device {}; - GpsConfig config {}; -}; - -struct GpsServiceData { - RecursiveMutex mutex {}; - std::vector devices; - GpsServiceState state = GPS_SERVICE_STATE_OFF; -}; - -static GpsServiceData* get_data() { - auto* instance = service_manager_find_instance(GPS_SERVICE_ID); - if (instance == nullptr) { - return nullptr; - } - return static_cast(service_instance_get_data(instance)); -} - -static void set_state(GpsServiceData* data, GpsServiceState state) { - recursive_mutex_lock(&data->mutex); - data->state = state; - recursive_mutex_unlock(&data->mutex); -} - -// 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_SERVICE_ID, "config.bin", out_path, out_path_size) == ERROR_NONE; -} - -void gps_service_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; - } - - 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*>(context)->push_back(*configuration); -} - -static void load_configurations(std::vector& out) { - gps_service_for_each_configuration(&out, collect_configuration); -} - -static error_t write_configurations(const std::vector& configurations) { - char directory[224]; - if (service_paths_get_user_data_directory(GPS_SERVICE_ID, directory, sizeof(directory)) != ERROR_NONE) { - return ERROR_RESOURCE; - } - ensure_directory_exists(directory); - - char path[256]; - if (!get_configuration_path(path, sizeof(path))) { - return ERROR_RESOURCE; - } - - 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); - return ok ? ERROR_NONE : ERROR_RESOURCE; -} - -static bool configurations_equal(const GpsConfiguration& a, const GpsConfiguration& b) { - return strcmp(a.uart_name, b.uart_name) == 0 && - a.baud_rate == b.baud_rate && - a.model == b.model; -} - -error_t gps_service_add_configuration(const GpsConfiguration* configuration) { - std::vector configurations; - load_configurations(configurations); - configurations.push_back(*configuration); - return write_configurations(configurations); -} - -error_t gps_service_remove_configuration(const GpsConfiguration* configuration) { - std::vector configurations; - load_configurations(configurations); - - size_t original_size = configurations.size(); - std::erase_if(configurations, [configuration](const GpsConfiguration& item) { - return configurations_equal(item, *configuration); - }); - - if (configurations.size() == original_size) { - return ERROR_NOT_FOUND; - } - - return write_configurations(configurations); -} - -// endregion - -// region Receiving - -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; - - if (device_construct(device) != ERROR_NONE) { - LOG_E(TAG, "Failed to construct %s", name); - 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; -} - -error_t gps_service_start_receiving() { - auto* data = get_data(); - if (data == nullptr) { - return ERROR_INVALID_STATE; - } - - recursive_mutex_lock(&data->mutex); - if (data->state != GpsServiceState::GPS_SERVICE_STATE_OFF) { - recursive_mutex_unlock(&data->mutex); - return ERROR_INVALID_STATE; - } - data->state = GpsServiceState::GPS_SERVICE_STATE_ON_PENDING; - recursive_mutex_unlock(&data->mutex); - - std::vector configurations; - load_configurations(configurations); - - if (configurations.empty()) { - LOG_E(TAG, "No GPS configurations"); - set_state(data, GpsServiceState::GPS_SERVICE_STATE_OFF); - return ERROR_NOT_FOUND; - } - - static uint32_t next_device_index = 0; - bool started_one_or_more = false; - - for (auto& configuration : configurations) { - 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); - continue; - } - - auto* entry = new(std::nothrow) GpsDeviceEntry(); - if (entry == nullptr) { - device_put(uart); - continue; - } - entry->config = GpsConfig { .baud_rate = configuration.baud_rate, .model = configuration.model }; - - char name[16]; - snprintf(name, sizeof(name), "gps%u", (unsigned)next_device_index++); - - bool started = construct_add_start(&entry->device, uart, name, &entry->config, "generic,gps"); - device_put(uart); - - if (started) { - recursive_mutex_lock(&data->mutex); - data->devices.push_back(entry); - recursive_mutex_unlock(&data->mutex); - started_one_or_more = true; - } else { - delete entry; - } - } - - if (!started_one_or_more) { - set_state(data, GPS_SERVICE_STATE_OFF); - return ERROR_RESOURCE; - } - - set_state(data, GPS_SERVICE_STATE_ON); - return ERROR_NONE; -} - -void gps_service_stop_receiving() { - auto* data = get_data(); - if (data == nullptr) { - return; - } - - recursive_mutex_lock(&data->mutex); - if (data->state != GPS_SERVICE_STATE_ON) { - recursive_mutex_unlock(&data->mutex); - return; - } - data->state = GPS_SERVICE_STATE_OFF_PENDING; - - for (auto* entry : data->devices) { - device_stop(&entry->device); - device_remove(&entry->device); - device_destruct(&entry->device); - delete entry; - } - data->devices.clear(); - - data->state = GPS_SERVICE_STATE_OFF; - recursive_mutex_unlock(&data->mutex); -} - -void gps_service_for_each_device(void* context, void (*on_device)(Device* device, void* context)) { - auto* data = get_data(); - if (data == nullptr) { - return; - } - - recursive_mutex_lock(&data->mutex); - for (auto* entry : data->devices) { - on_device(&entry->device, context); - } - recursive_mutex_unlock(&data->mutex); -} - -GpsServiceState gps_service_get_state() { - auto* data = get_data(); - if (data == nullptr) { - return GPS_SERVICE_STATE_OFF; - } - recursive_mutex_lock(&data->mutex); - auto state = data->state; - recursive_mutex_unlock(&data->mutex); - return state; -} - -bool gps_service_get_coordinates(minmea_sentence_rmc* out) { - auto* data = get_data(); - if (data == nullptr) { - return false; - } - - recursive_mutex_lock(&data->mutex); - bool found = false; - for (auto* entry : data->devices) { - if (gps_get_rmc(&entry->device, out, seconds_to_ticks(10)) == ERROR_NONE) { - found = true; - break; - } - } - recursive_mutex_unlock(&data->mutex); - return found; -} - -bool gps_service_has_coordinates() { - minmea_sentence_rmc rmc; - return gps_service_get_coordinates(&rmc); -} - -bool gps_service_get_gga(minmea_sentence_gga* out) { - auto* data = get_data(); - if (data == nullptr) { - return false; - } - - recursive_mutex_lock(&data->mutex); - bool found = false; - for (auto* entry : data->devices) { - if (gps_get_gga(&entry->device, out, seconds_to_ticks(10)) == ERROR_NONE) { - found = true; - break; - } - } - recursive_mutex_unlock(&data->mutex); - return found; -} - -// endregion - -// region ServiceManifest - -static void* create_service(const ServiceManifest*) { - auto* data = new(std::nothrow) GpsServiceData(); - if (data == nullptr) { - return nullptr; - } - recursive_mutex_construct(&data->mutex); - return data; -} - -static void destroy_service(const ServiceManifest*, void* data) { - auto* service_data = static_cast(data); - recursive_mutex_destruct(&service_data->mutex); - delete service_data; -} - -static void on_stop(ServiceInstance*, void* data) { - auto* service_data = static_cast(data); - if (service_data->state != GpsServiceState::GPS_SERVICE_STATE_OFF) { - gps_service_stop_receiving(); - } -} - -static const ServiceManifest gps_service_manifest = { - .id = GPS_SERVICE_ID, - .create_service = create_service, - .destroy_service = destroy_service, - .on_start = nullptr, - .on_stop = on_stop, -}; - -error_t gps_service_register() { - return service_manager_add(&gps_service_manifest, true); -} - -// endregion diff --git a/Drivers/gps-module/source/gps_service_internal.h b/Drivers/gps-module/source/gps_service_internal.h deleted file mode 100644 index b29ac3166..000000000 --- a/Drivers/gps-module/source/gps_service_internal.h +++ /dev/null @@ -1,8 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -#pragma once - -#include - -// Registers the GPS service manifest with the kernel service manager (auto-started). Called once -// from module.cpp's Module::start(). -error_t gps_service_register(); diff --git a/Drivers/gps-module/source/module.cpp b/Drivers/gps-module/source/module.cpp deleted file mode 100644 index c8d06b1c6..000000000 --- a/Drivers/gps-module/source/module.cpp +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -#include "gps_service_internal.h" - -#include -#include -#include -#include -#include - -constexpr auto* TAG = "GpsModule"; - -extern "C" { - -extern Driver gps_driver; - -static Driver* const gps_drivers[] = { - &gps_driver, - nullptr -}; - -static error_t start() { - error_t error = gps_service_register(); - if (error != ERROR_NONE) { - LOG_E(TAG, "Failed to register GPS service: %s", error_to_string(error)); - return error; - } - return ERROR_NONE; -} - -Module gps_module = { - .name = "gps", - .start = start, - .stop = nullptr, - .drivers = gps_drivers, - .symbols = nullptr, - .internal = nullptr -}; - -} diff --git a/Firmware/CMakeLists.txt b/Firmware/CMakeLists.txt index 457d65ec5..2b80054bd 100644 --- a/Firmware/CMakeLists.txt +++ b/Firmware/CMakeLists.txt @@ -98,6 +98,7 @@ else () lvgl-module crypt-module gps-module + gps-generic-module SDL2::SDL2-static SDL2-static ) diff --git a/Modules/crypt-module/LICENSE-Apache-2.0.md b/Modules/crypt-module/LICENSE-Apache-2.0.md new file mode 100644 index 000000000..f5f4b8b5e --- /dev/null +++ b/Modules/crypt-module/LICENSE-Apache-2.0.md @@ -0,0 +1,195 @@ +Apache License +============== + +_Version 2.0, January 2004_ +_<>_ + +### 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. + diff --git a/Drivers/gps-module/CMakeLists.txt b/Modules/gps-module/CMakeLists.txt similarity index 89% rename from Drivers/gps-module/CMakeLists.txt rename to Modules/gps-module/CMakeLists.txt index d7fc4f41a..1bd923a9a 100644 --- a/Drivers/gps-module/CMakeLists.txt +++ b/Modules/gps-module/CMakeLists.txt @@ -6,6 +6,7 @@ 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 ) diff --git a/Modules/gps-module/LICENSE-Apache-2.0.md b/Modules/gps-module/LICENSE-Apache-2.0.md new file mode 100644 index 000000000..f5f4b8b5e --- /dev/null +++ b/Modules/gps-module/LICENSE-Apache-2.0.md @@ -0,0 +1,195 @@ +Apache License +============== + +_Version 2.0, January 2004_ +_<>_ + +### 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. + diff --git a/Drivers/gps-module/devicetree.yaml b/Modules/gps-module/devicetree.yaml similarity index 100% rename from Drivers/gps-module/devicetree.yaml rename to Modules/gps-module/devicetree.yaml diff --git a/Modules/gps-module/include/gps/gps.h b/Modules/gps-module/include/gps/gps.h new file mode 100644 index 000000000..4fdd985ed --- /dev/null +++ b/Modules/gps-module/include/gps/gps.h @@ -0,0 +1,113 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include +#include + +#include + +/** + * @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 { + error_t (*event_subscribe)(struct Device* device, struct GpsSubscription* sub); + + error_t (*event_unsubscribe)(struct Device* device, struct GpsSubscription* sub); + + 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); + + 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_state */ +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 diff --git a/Modules/gps-module/include/gps/gps_module.h b/Modules/gps-module/include/gps/gps_module.h new file mode 100644 index 000000000..384348f07 --- /dev/null +++ b/Modules/gps-module/include/gps/gps_module.h @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +extern struct Module gps_module; + +#ifdef __cplusplus +} +#endif diff --git a/Modules/gps-module/include/gps/gps_settings.h b/Modules/gps-module/include/gps/gps_settings.h new file mode 100644 index 000000000..23c98f080 --- /dev/null +++ b/Modules/gps-module/include/gps/gps_settings.h @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +#include +#include + +/** + * @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 diff --git a/Modules/gps-module/private/gps/private/gps_ledger.h b/Modules/gps-module/private/gps/private/gps_ledger.h new file mode 100644 index 000000000..a0fbc757e --- /dev/null +++ b/Modules/gps-module/private/gps/private/gps_ledger.h @@ -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(); diff --git a/Modules/gps-module/source/gps.cpp b/Modules/gps-module/source/gps.cpp new file mode 100644 index 000000000..41ebd110d --- /dev/null +++ b/Modules/gps-module/source/gps.cpp @@ -0,0 +1,57 @@ +#include + +#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(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(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(driver->api)->event_await(device, sub, timeout); +} + +GpsState gps_get_state(Device* device) { + const auto* driver = device_get_driver(device); + return static_cast(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(driver->api)->get_model_name(device, model_name, buffer_size); +} + +const DeviceType GPS_TYPE { + .name = "gps" +}; + +#ifdef __cplusplus +} +#endif diff --git a/Modules/gps-module/source/gps_ledger.cpp b/Modules/gps-module/source/gps_ledger.cpp new file mode 100644 index 000000000..a89700ff4 --- /dev/null +++ b/Modules/gps-module/source/gps_ledger.cpp @@ -0,0 +1,175 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +constexpr auto* TAG = "gps_ledger"; + +/** + * @brief Configuration for a GPS_TYPE device. + * @warning Mirrors gps-generic-module's own (GPL) GpsConfig field-for-field - this module can't + * include that header (Apache/GPL boundary), so the layout has to be kept in sync by hand. uart is + * left NULL here: this path uses device_set_parent() to the UART_CONTROLLER_TYPE device instead, + * which the driver falls back to when config->uart is NULL. + */ +struct GpsConfig { + Device* uart = nullptr; + 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(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(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(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 collect_owned_devices() { + std::vector owned; + device_for_each_of_type(&GPS_TYPE, &owned, [](Device* device, void* context) { + if (is_ledger_owned(device)) { + static_cast*>(context)->push_back(device); + } + return true; + }); + return owned; +} + +void gps_ledger_sync() { + std::vector configurations; + gps_settings_for_each_configuration(&configurations, [](const GpsConfiguration* configuration, size_t, void* context) { + static_cast*>(context)->push_back(*configuration); + }); + + std::vector matched(configurations.size(), false); + std::vector 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); + } +} diff --git a/Modules/gps-module/source/gps_settings.cpp b/Modules/gps-module/source/gps_settings.cpp new file mode 100644 index 000000000..52eb5af4f --- /dev/null +++ b/Modules/gps-module/source/gps_settings.cpp @@ -0,0 +1,159 @@ +// SPDX-License-Identifier: Apache-2.0 +#include +#include + +#include +#include +#include + +#include + +#include +#include +#include + +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; +public: + explicit FileLockGuard(const char* path) { + file_get_mutex(path, &mutex); + file_lock(&mutex); + } + + ~FileLockGuard() { + file_unlock(&mutex); + } +}; + +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*>(context)->push_back(*configuration); +} + +static void load_configurations(std::vector& out) { + gps_settings_for_each_configuration(&out, collect_configuration); +} + +static error_t write_configurations(const std::vector& 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; + } + + gps_ledger_sync(); + + return ERROR_NONE; +} + +// endregion + +error_t gps_settings_add_configuration(const GpsConfiguration* configuration) { + std::vector 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 configurations; + load_configurations(configurations); + + if (index >= configurations.size()) { + return ERROR_NOT_FOUND; + } + + configurations.erase(configurations.begin() + static_cast(index)); + + error_t error = write_configurations(configurations); + if (error != ERROR_NONE) { + return error; + } + + return ERROR_NONE; +} diff --git a/Modules/gps-module/source/module.cpp b/Modules/gps-module/source/module.cpp new file mode 100644 index 000000000..da0a4c826 --- /dev/null +++ b/Modules/gps-module/source/module.cpp @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: Apache-2.0 +#include +#include + +#include +#include + +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 +}; + +} diff --git a/Modules/lvgl-module/include/tactility/lvgl_module.h b/Modules/lvgl-module/include/tactility/lvgl_module.h index 4fd5d9fda..a590a15df 100644 --- a/Modules/lvgl-module/include/tactility/lvgl_module.h +++ b/Modules/lvgl-module/include/tactility/lvgl_module.h @@ -72,7 +72,7 @@ void lvgl_module_configure(struct LvglModuleConfig config); * It is a recursive mutex. * @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. diff --git a/Modules/lvgl-module/source/arch/lvgl_esp32.c b/Modules/lvgl-module/source/arch/lvgl_esp32.c index 45140b84d..3251bcc18 100644 --- a/Modules/lvgl-module/source/arch/lvgl_esp32.c +++ b/Modules/lvgl-module/source/arch/lvgl_esp32.c @@ -13,19 +13,19 @@ extern void lvgl_devices_detach(); static bool initialized = false; -bool lvgl_lock(void) { - if (!initialized) return true; // We allow (fake) locking because it's safe to do so as LVGL is not running yet - return lvgl_port_lock(portMAX_DELAY); +void lvgl_lock(void) { + if (!initialized) { return; } + lvgl_port_lock(portMAX_DELAY); } 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 return lvgl_port_lock(timeoutTicks * portTICK_PERIOD_MS); } void lvgl_unlock(void) { - if (!initialized) return; + if (!initialized) { return; } lvgl_port_unlock(); } diff --git a/Tactility/CMakeLists.txt b/Tactility/CMakeLists.txt index efce7a6b2..b49699364 100644 --- a/Tactility/CMakeLists.txt +++ b/Tactility/CMakeLists.txt @@ -10,6 +10,7 @@ list(APPEND REQUIRES_LIST lvgl-module crypt-module gps-module + gps-generic-module lv_screenshot minitar ) diff --git a/Tactility/Include/Tactility/file/FileLock.h b/Tactility/Include/Tactility/file/FileLock.h index a7b615801..60c36f054 100644 --- a/Tactility/Include/Tactility/file/FileLock.h +++ b/Tactility/Include/Tactility/file/FileLock.h @@ -13,8 +13,9 @@ namespace tt::file { /** * @param[in] path the path to find a lock for + * @deprecated * @return a lock instance when a lock was found, otherwise nullptr */ -std::shared_ptr findLock(const std::string& path); +std::shared_ptr findLock(const std::string& path) __attribute__((deprecated("Use file_get_mutex() from TactilityKernel"))); } diff --git a/Tactility/Include/Tactility/lvgl/LvglSync.h b/Tactility/Include/Tactility/lvgl/LvglSync.h index c3c9841e4..f6e8db8ac 100644 --- a/Tactility/Include/Tactility/lvgl/LvglSync.h +++ b/Tactility/Include/Tactility/lvgl/LvglSync.h @@ -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 * @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 file_get_mutex() from TactilityKernel"))); /** @deprecated Use lvgl_unlock() from lvgl-module instead. */ -void unlock(); +void unlock() __attribute__((deprecated("Use file_get_mutex() from TactilityKernel"))); -std::shared_ptr getSyncLock(); +std::shared_ptr getSyncLock() __attribute__((deprecated("Use file_get_mutex() from TactilityKernel"))); } // namespace diff --git a/Tactility/Private/Tactility/hal/SdCard.h b/Tactility/Private/Tactility/hal/SdCard.h index d09379a44..73195f23a 100644 --- a/Tactility/Private/Tactility/hal/SdCard.h +++ b/Tactility/Private/Tactility/hal/SdCard.h @@ -10,10 +10,11 @@ namespace tt::hal::sdcard { /** * 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. + * @deprecated * @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 findSdCardLock(const std::string& path); +std::shared_ptr findSdCardLock(const std::string& path) __attribute__((deprecated("Use file_get_mutex() from TactilityKernel"))); void mountAll(); diff --git a/Tactility/Source/Tactility.cpp b/Tactility/Source/Tactility.cpp index 9f592305c..8d91d6f17 100644 --- a/Tactility/Source/Tactility.cpp +++ b/Tactility/Source/Tactility.cpp @@ -20,6 +20,9 @@ #include #include +#include +#include + #include #include #include @@ -29,7 +32,6 @@ #include #include #include -#include #include #include #include @@ -51,6 +53,8 @@ constexpr auto* TAG = "Tactility"; static DispatcherHandle_t mainDispatcherHandle = dispatcher_alloc(); +void initFileLvglLock(); + namespace { void mainDispatcherTrampoline(void* context) { @@ -370,16 +374,22 @@ void run(Module* dtsModules[], DtsDevice dtsDevices[]) { return; } + initFileLvglLock(); + // crypt-module check(module_construct_add_start(&crypt_module) == ERROR_NONE); // gps-module check(module_construct_add_start(&gps_module) == ERROR_NONE); + // gps-generic-module + check(module_construct_add_start(&gps_generic_module) == ERROR_NONE); + #ifdef ESP_PLATFORM initEsp(); #endif file::setFindLockFunction(file::findLock); + settings::initTimeZone(); // Remnants of the old HAL @@ -404,9 +414,8 @@ void run(Module* dtsModules[], DtsDevice dtsDevices[]) { .task_affinity = getCpuAffinityConfiguration().graphics #endif }); - check(module_construct(&lvgl_module) == ERROR_NONE); - check(module_add(&lvgl_module) == ERROR_NONE); - check(module_start(&lvgl_module) == ERROR_NONE); + check(module_construct_add_start(&lvgl_module) == ERROR_NONE); + check(module_construct_add_start(&gps_module) == ERROR_NONE); registerAndStartSecondaryServices(); diff --git a/Tactility/Source/app/addgps/AddGps.cpp b/Tactility/Source/app/addgps/AddGps.cpp index 7eb979ac1..fafe6f5d0 100644 --- a/Tactility/Source/app/addgps/AddGps.cpp +++ b/Tactility/Source/app/addgps/AddGps.cpp @@ -4,14 +4,15 @@ #include #include -#include #include -#include +#include +#include + +#include +#include #include #include -#include -#include namespace tt::app::addgps { @@ -30,18 +31,6 @@ class AddGpsApp final : public App { std::array baudRates = { 9600, 19200, 28800, 38400, 57600, 115200 }; const char* baudRatesDropdownValues = "9600\n19200\n28800\n38400\n57600\n115200"; - struct DuplicateCheckContext { - const char* uartName; - bool found; - }; - - static void onCheckDuplicateUart(const GpsConfiguration* configuration, size_t, void* context) { - auto* ctx = static_cast(context); - if (strcmp(configuration->uart_name, ctx->uartName) == 0) { - ctx->found = true; - } - } - static std::vector getModelNames() { std::vector result; for (int model = GpsModel::GPS_MODEL_UNKNOWN; model <= GpsModel::GPS_MODEL_UC6580; model++) { @@ -72,17 +61,8 @@ class AddGpsApp final : public App { } LOG_I(TAG, "Saving: uart=%s, model=%d, baud=%u", new_configuration.uart_name, (int)new_configuration.model, (unsigned)new_configuration.baud_rate); - - DuplicateCheckContext duplicate_check = { .uartName = new_configuration.uart_name, .found = false }; - gps_service_for_each_configuration(&duplicate_check, onCheckDuplicateUart); - if (duplicate_check.found) { - auto message = std::string("Bus \"") + new_configuration.uart_name + "\" is already in use in another configuration"; - app::alertdialog::start("Error", message.c_str()); - return; - } - - if (gps_service_add_configuration(&new_configuration) != ERROR_NONE) { - app::alertdialog::start("Error", "Failed to add configuration"); + if (gps_settings_add_configuration(&new_configuration) != ERROR_NONE) { + alertdialog::start("Error", "Failed to add configuration"); } else { stop(); } diff --git a/Tactility/Source/app/gpssettings/GpsSettings.cpp b/Tactility/Source/app/gpssettings/GpsSettings.cpp index 0d6170e21..db804004b 100644 --- a/Tactility/Source/app/gpssettings/GpsSettings.cpp +++ b/Tactility/Source/app/gpssettings/GpsSettings.cpp @@ -1,20 +1,28 @@ + + +#include "tactility/lvgl_module.h" + + #include + #include #include #include #include #include -#include -#include -#include -#include +#include #include +#include #include -#include #include +#include +#include + +#include +#include namespace tt::app::addgps { extern AppManifest manifest; @@ -26,28 +34,21 @@ extern const AppManifest manifest; class GpsSettingsApp final : public App { - static constexpr auto* TAG = "GpsSettings"; + struct DeviceRow { + Device* device; + lv_obj_t* button; + lv_obj_t* buttonLabel; + bool hasConfiguration = false; + size_t configurationIndex = 0; + }; std::unique_ptr timer; - lv_obj_t* statusWrapper = nullptr; - lv_obj_t* statusLabelWidget = nullptr; - lv_obj_t* statusLatitudeValue = nullptr; - lv_obj_t* statusLongitudeValue = nullptr; - lv_obj_t* statusAltitudeValue = nullptr; - lv_obj_t* statusSpeedValue = nullptr; - lv_obj_t* statusHeadingValue = nullptr; - lv_obj_t* statusSatellitesValue = nullptr; - lv_obj_t* switchWidget = nullptr; - lv_obj_t* spinnerWidget = nullptr; - lv_obj_t* infoContainerWidget = nullptr; - lv_obj_t* gpsConfigWrapper = nullptr; - lv_obj_t* addGpsWrapper = nullptr; - bool hasSetInfo = false; - - static void onGpsToggledCallback(lv_event_t* event) { - auto* app = (GpsSettingsApp*)lv_event_get_user_data(event); - app->onGpsToggled(event); - } + lv_obj_t* deviceListWrapper = nullptr; + std::vector deviceRows; + std::atomic isShown = false; + bool hasPendingDelete = false; + Device* pendingDeleteDevice = nullptr; + size_t pendingDeleteIndex = 0; static void onAddGpsCallback(lv_event_t* event) { auto* app = (GpsSettingsApp*)lv_event_get_user_data(event); @@ -58,283 +59,168 @@ class GpsSettingsApp final : public App { app::start(addgps::manifest.appId); } - void createInfoView(GpsModel model) { - auto* label = lv_label_create(infoContainerWidget); - if (model == GpsModel::GPS_MODEL_UNKNOWN) { - lv_label_set_text(label, "Model: auto-detect"); - } else { - lv_label_set_text_fmt(label, "Model: %s", gps_model_to_string(model)); - } + static void onDeviceButtonCallback(lv_event_t* event) { + auto* button = lv_event_get_target_obj(event); + auto* device = static_cast(lv_obj_get_user_data(button)); + + bool running = device_is_ready(device); + // device_start()/device_stop() are potentially blocking calls, so use a dispatcher to not block the UI + getMainDispatcher().dispatch([device, running] { + if (running) { + device_stop(device); + } else { + device_start(device); + } + }); } - static void onDeleteConfiguration(lv_event_t* event) { - auto* app = (GpsSettingsApp*)lv_event_get_user_data(event); + // Finds the persisted configuration backing `device` (matched by its parent UART's name) + // and returns its index into gps_settings_for_each_configuration()'s ordering - the handle + // gps_settings_remove_configuration_at() needs to delete exactly this entry, even if another + // entry happens to have identical field values. + // Devicetree-declared GPS_TYPE devices have no such configuration and never match. + static bool findConfigurationIndexForDevice(Device* device, size_t& outIndex) { + auto* parent = device_get_parent(device); + if (parent == nullptr) { + return false; + } - auto* button = lv_event_get_target_obj(event); - auto index_as_voidptr = lv_obj_get_user_data(button); // config index - int index; - // TODO: Find a better way to cast void* to int, or find a different way to pass the index - memcpy(&index, &index_as_voidptr, sizeof(int)); + struct Context { + const char* uartName; + size_t* outIndex; + bool found; + } context = { parent->name, &outIndex, false }; - std::vector configurations; - gps_service_for_each_configuration(&configurations, [](const GpsConfiguration* configuration, size_t, void* context) { - static_cast*>(context)->push_back(*configuration); + gps_settings_for_each_configuration(&context, [](const GpsConfiguration* configuration, size_t index, void* untyped_context) { + auto* ctx = static_cast(untyped_context); + if (!ctx->found && strcmp(configuration->uart_name, ctx->uartName) == 0) { + *ctx->outIndex = index; + ctx->found = true; + } }); - if (index < (int)configurations.size()) { - if (gps_service_remove_configuration(&configurations[index]) == ERROR_NONE) { - app->updateViews(); - } else { - alertdialog::start("Error", "Failed to remove configuration"); + return context.found; + } + + static void onDeleteButtonCallback(lv_event_t* event) { + auto* app = static_cast(lv_event_get_user_data(event)); + auto* button = lv_event_get_target_obj(event); + auto* device = static_cast(lv_obj_get_user_data(button)); + app->onDeleteDevice(device); + } + + void onDeleteDevice(Device* device) { + for (auto& row : deviceRows) { + if (row.device == device && row.hasConfiguration) { + pendingDeleteDevice = device; + pendingDeleteIndex = row.configurationIndex; + hasPendingDelete = true; + alertdialog::start("Confirmation", std::string("Do you want to delete ") + device->name + "?", std::vector { "Yes", "No" }); + return; } } } - void createGpsView(const GpsConfiguration& configuration, int index) { - auto* wrapper = lv_obj_create(gpsConfigWrapper); + void createDeviceRow(Device* device) { + auto* wrapper = lv_obj_create(deviceListWrapper); lv_obj_set_size(wrapper, LV_PCT(100), LV_SIZE_CONTENT); lv_obj_set_flex_flow(wrapper, LV_FLEX_FLOW_ROW); - lv_obj_set_style_margin_hor(wrapper, 0, 0); - lv_obj_set_style_margin_bottom(wrapper, 8, 0); + lv_obj_set_flex_align(wrapper, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); + lv_obj_set_style_border_width(wrapper, 0, 0); + lv_obj_set_style_pad_all(wrapper, 0, 0); - // Left wrapper - - auto* left_wrapper = lv_obj_create(wrapper); - lv_obj_set_style_border_width(left_wrapper, 0, 0); - lv_obj_set_style_pad_all(left_wrapper, 0, 0); - lv_obj_set_size(left_wrapper, LV_SIZE_CONTENT, LV_SIZE_CONTENT); - lv_obj_set_flex_grow(left_wrapper, 1); - lv_obj_set_flex_flow(left_wrapper, LV_FLEX_FLOW_COLUMN); - - auto* uart_label = lv_label_create(left_wrapper); - lv_label_set_text_fmt(uart_label, "UART: %s", configuration.uart_name); - - auto* baud_label = lv_label_create(left_wrapper); - lv_label_set_text_fmt(baud_label, "Baud: %lu", configuration.baud_rate); - - auto* model_label = lv_label_create(left_wrapper); - if (configuration.model == GpsModel::GPS_MODEL_UNKNOWN) { - lv_label_set_text(model_label, "Model: auto-detect"); + auto* name_label = lv_label_create(wrapper); + char model_name[64]; + if (gps_get_model_name(device, model_name, sizeof(model_name)) == ERROR_NONE) { + lv_label_set_text(name_label, model_name); } else { - lv_label_set_text_fmt(model_label, "Model: %s", gps_model_to_string(configuration.model)); + lv_label_set_text(name_label, device->name); } - // Right wrapper - auto* right_wrapper = lv_obj_create(wrapper); - lv_obj_set_style_border_width(right_wrapper, 0, 0); - lv_obj_set_style_pad_all(right_wrapper, 0, 0); - lv_obj_set_size(right_wrapper, LV_SIZE_CONTENT, LV_SIZE_CONTENT); - lv_obj_set_flex_flow(right_wrapper, LV_FLEX_FLOW_COLUMN); + auto* actions_wrapper = lv_obj_create(wrapper); + lv_obj_set_size(actions_wrapper, LV_SIZE_CONTENT, LV_SIZE_CONTENT); + lv_obj_set_flex_flow(actions_wrapper, LV_FLEX_FLOW_ROW); + lv_obj_set_style_border_width(actions_wrapper, 0, 0); + lv_obj_set_style_pad_all(actions_wrapper, 0, 0); + lv_obj_set_style_pad_column(actions_wrapper, 4, 0); - auto* delete_button = lv_button_create(right_wrapper); - lv_obj_add_event_cb(delete_button, onDeleteConfiguration, LV_EVENT_SHORT_CLICKED, this); - lv_obj_set_user_data(delete_button, reinterpret_cast(index)); - auto* delete_label = lv_label_create(delete_button); - lv_label_set_text_fmt(delete_label, LV_SYMBOL_TRASH); + auto* button = lv_button_create(actions_wrapper); + lv_obj_add_event_cb(button, onDeviceButtonCallback, LV_EVENT_SHORT_CLICKED, this); + lv_obj_set_user_data(button, device); + auto* button_label = lv_label_create(button); + lv_label_set_text(button_label, "Start"); + + DeviceRow row { .device = device, .button = button, .buttonLabel = button_label }; + + // Only devices backed by a persisted configuration (not devicetree-declared ones) can be deleted. + size_t configurationIndex; + if ((device->flags & DEVICE_FLAG_DYNAMIC) && findConfigurationIndexForDevice(device, configurationIndex)) { + auto* delete_button = lv_button_create(actions_wrapper); + lv_obj_add_event_cb(delete_button, onDeleteButtonCallback, LV_EVENT_SHORT_CLICKED, this); + lv_obj_set_user_data(delete_button, device); + auto* delete_label = lv_label_create(delete_button); + lv_label_set_text(delete_label, LVGL_ICON_SHARED_DELETE); + + row.hasConfiguration = true; + row.configurationIndex = configurationIndex; + } + + deviceRows.push_back(row); } - void updateViews() { + // Rebuilds the device list. Only needs to run when the set of devices could've changed + // (on show, and after returning from AddGpsApp) - button state itself is refreshed by the timer. + void rebuildDeviceList() { + lv_obj_clean(deviceListWrapper); + deviceRows.clear(); + + device_for_each_of_type(&GPS_TYPE, this, [](Device* device, void* context) { + static_cast(context)->createDeviceRow(device); + return true; + }); + } + + void updateDeviceStates() { auto lock = lvgl::getSyncLock()->asScopedLock(); if (lock.lock(100 / portTICK_PERIOD_MS)) { - auto state = gps_service_get_state(); + for (auto& row : deviceRows) { + const char* text = "Start"; + bool enabled = true; - // Update toolbar - switch (state) { - case GpsServiceState::GPS_SERVICE_STATE_ON_PENDING: - LOG_D(TAG, "OnPending"); - lv_obj_remove_flag(spinnerWidget, LV_OBJ_FLAG_HIDDEN); - lv_obj_add_state(switchWidget, LV_STATE_CHECKED); - lv_obj_add_state(switchWidget, LV_STATE_DISABLED); - lv_obj_remove_flag(statusWrapper, LV_OBJ_FLAG_HIDDEN); - lv_obj_add_flag(gpsConfigWrapper, LV_OBJ_FLAG_HIDDEN); - lv_obj_add_flag(addGpsWrapper, LV_OBJ_FLAG_HIDDEN); - break; - case GpsServiceState::GPS_SERVICE_STATE_ON: - LOG_D(TAG, "On"); - lv_obj_add_flag(spinnerWidget, LV_OBJ_FLAG_HIDDEN); - lv_obj_add_state(switchWidget, LV_STATE_CHECKED); - lv_obj_remove_state(switchWidget, LV_STATE_DISABLED); - lv_obj_remove_flag(statusWrapper, LV_OBJ_FLAG_HIDDEN); - lv_obj_add_flag(gpsConfigWrapper, LV_OBJ_FLAG_HIDDEN); - lv_obj_add_flag(addGpsWrapper, LV_OBJ_FLAG_HIDDEN); - break; - case GpsServiceState::GPS_SERVICE_STATE_OFF_PENDING: - LOG_D(TAG, "OffPending"); - lv_obj_remove_flag(spinnerWidget, LV_OBJ_FLAG_HIDDEN); - lv_obj_remove_state(switchWidget, LV_STATE_CHECKED); - lv_obj_add_state(switchWidget, LV_STATE_DISABLED); - lv_obj_add_flag(statusWrapper, LV_OBJ_FLAG_HIDDEN); - lv_obj_remove_flag(gpsConfigWrapper, LV_OBJ_FLAG_HIDDEN); - lv_obj_remove_flag(addGpsWrapper, LV_OBJ_FLAG_HIDDEN); - break; - case GpsServiceState::GPS_SERVICE_STATE_OFF: - LOG_D(TAG, "Off"); - lv_obj_add_flag(spinnerWidget, LV_OBJ_FLAG_HIDDEN); - lv_obj_remove_state(switchWidget, LV_STATE_CHECKED); - lv_obj_remove_state(switchWidget, LV_STATE_DISABLED); - lv_obj_add_flag(statusWrapper, LV_OBJ_FLAG_HIDDEN); - lv_obj_remove_flag(gpsConfigWrapper, LV_OBJ_FLAG_HIDDEN); - lv_obj_remove_flag(addGpsWrapper, LV_OBJ_FLAG_HIDDEN); - break; - } - - // Update status label and device info - if (state == GpsServiceState::GPS_SERVICE_STATE_ON) { - if (!hasSetInfo) { - gps_service_for_each_device(this, [](Device* device, void* context) { - static_cast(context)->createInfoView(gps_get_model(device)); - }); - hasSetInfo = true; + if (device_is_ready(row.device)) { + switch (gps_get_state(row.device)) { + case GPS_STATE_PENDING_ON: + text = "Starting..."; + enabled = false; + break; + case GPS_STATE_PENDING_OFF: + text = "Stopping..."; + enabled = false; + break; + default: + text = "Stop"; + enabled = true; + break; + } } - minmea_sentence_rmc rmc; - char buffer[64]; - if (gps_service_get_coordinates(&rmc)) { - lv_label_set_text(statusLabelWidget, "Lock acquired"); - lv_obj_set_style_text_color(statusLabelWidget, lv_color_hex(0x00ff00), 0); - - minmea_float latitude = { rmc.latitude.value, rmc.latitude.scale }; - minmea_float longitude = { rmc.longitude.value, rmc.longitude.scale }; - - double latCoord = minmea_tocoord(&latitude); - double lonCoord = minmea_tocoord(&longitude); - if (isnan(latCoord) || isnan(lonCoord)) { - lv_label_set_text(statusLatitudeValue, "--"); - lv_label_set_text(statusLongitudeValue, "--"); - } else { - const char* latDir = (latCoord >= 0) ? "N" : "S"; - const char* lonDir = (lonCoord >= 0) ? "E" : "W"; - - snprintf(buffer, sizeof(buffer), "%.6f %s", std::abs(latCoord), latDir); - lv_label_set_text(statusLatitudeValue, buffer); - - snprintf(buffer, sizeof(buffer), "%.6f %s", std::abs(lonCoord), lonDir); - lv_label_set_text(statusLongitudeValue, buffer); - } - - float speedKnots = minmea_tofloat(&rmc.speed); - if (!isnan(speedKnots)) { - float speedKmh = speedKnots * 1.852f; - snprintf(buffer, sizeof(buffer), "%.1f km/h", speedKmh); - lv_label_set_text(statusSpeedValue, buffer); - } else { - lv_label_set_text(statusSpeedValue, "--"); - } - - float heading = minmea_tofloat(&rmc.course); - if (!isnan(heading)) { - // Normalize heading to [0, 360) range - heading = fmodf(heading, 360.0f); - if (heading < 0) heading += 360.0f; - const char* dirs[] = {"N", "NE", "E", "SE", "S", "SW", "W", "NW"}; - // Calculate cardinal direction index (0-7) - int idx = (int)((heading + 22.5f) / 45.0f) % 8; - snprintf(buffer, sizeof(buffer), "%.0f° %s", heading, dirs[idx]); - lv_label_set_text(statusHeadingValue, buffer); - } else { - lv_label_set_text(statusHeadingValue, "--"); - } - + lv_label_set_text(row.buttonLabel, text); + if (enabled) { + lv_obj_remove_state(row.button, LV_STATE_DISABLED); } else { - lv_label_set_text(statusLabelWidget, "Acquiring lock..."); - lv_obj_set_style_text_color(statusLabelWidget, lv_color_hex(0xffaa00), 0); - lv_label_set_text(statusLatitudeValue, "--"); - lv_label_set_text(statusLongitudeValue, "--"); - lv_label_set_text(statusSpeedValue, "--"); - lv_label_set_text(statusHeadingValue, "--"); + lv_obj_add_state(row.button, LV_STATE_DISABLED); } - - minmea_sentence_gga gga; - if (gps_service_get_gga(&gga)) { - float altitude = minmea_tofloat(&gga.altitude); - if (!isnan(altitude)) { - snprintf(buffer, sizeof(buffer), "%.1f m", altitude); - lv_label_set_text(statusAltitudeValue, buffer); - } else { - lv_label_set_text(statusAltitudeValue, "--"); - } - - snprintf(buffer, sizeof(buffer), "%d", gga.satellites_tracked); - lv_label_set_text(statusSatellitesValue, buffer); - } else { - lv_label_set_text(statusAltitudeValue, "--"); - lv_label_set_text(statusSatellitesValue, "--"); - } - - lv_obj_remove_flag(statusLabelWidget, LV_OBJ_FLAG_HIDDEN); - } else { - if (hasSetInfo) { - lv_obj_clean(infoContainerWidget); - hasSetInfo = false; - } - - lv_obj_add_flag(statusLabelWidget, LV_OBJ_FLAG_HIDDEN); - } - - if (!lv_obj_has_flag(gpsConfigWrapper, LV_OBJ_FLAG_HIDDEN)) { - lv_obj_clean(gpsConfigWrapper); - std::vector configurations; - gps_service_for_each_configuration(&configurations, [](const GpsConfiguration* configuration, size_t, void* context) { - static_cast*>(context)->push_back(*configuration); - }); - int index = 0; - for (auto& configuration : configurations) { - createGpsView(configuration, index++); - } - } else { - lv_obj_clean(gpsConfigWrapper); } } } - void onGpsToggled(lv_event_t* event) { - bool wants_on = lv_obj_has_state(switchWidget, LV_STATE_CHECKED); - auto state = gps_service_get_state(); - bool is_on = (state == GpsServiceState::GPS_SERVICE_STATE_ON) || (state == GpsServiceState::GPS_SERVICE_STATE_ON_PENDING); - - if (wants_on != is_on) { - // start/stop are potentially blocking calls, so we use a dispatcher to not block the UI - if (wants_on) { - getMainDispatcher().dispatch([this] { - gps_service_start_receiving(); - }); - } else { - getMainDispatcher().dispatch([this] { - gps_service_stop_receiving(); - }); - } - } - } - - lv_obj_t* createInfoRow(lv_obj_t* parent, const char* labelText, lv_color_t color) { - lv_obj_t* row = lv_obj_create(parent); - lv_obj_set_size(row, LV_PCT(100), LV_SIZE_CONTENT); - lv_obj_set_flex_flow(row, LV_FLEX_FLOW_ROW); - lv_obj_set_flex_align(row, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_START); - - lv_obj_set_style_pad_all(row, 0, 0); - lv_obj_set_style_pad_right(row, 10, 0); - lv_obj_set_style_border_width(row, 0, 0); - lv_obj_set_style_bg_opa(row, LV_OPA_TRANSP, 0); - - lv_obj_t* label = lv_label_create(row); - lv_label_set_text(label, labelText); - lv_obj_set_style_text_color(label, lv_palette_lighten(LV_PALETTE_GREY, 5), 0); - - lv_obj_t* value = lv_label_create(row); - lv_label_set_text(value, "--"); - lv_obj_set_style_text_color(value, color, 0); - - return value; - } - public: GpsSettingsApp() { - // Runs continuously while the screen is shown - there's no push notification for GPS - // service state changes, so this is the only way this screen finds out about them. + // Runs while the screen is shown - there's no push notification for GPS device state + // changes, so this is the only way this screen finds out about them. timer = std::make_unique(Timer::Type::Periodic, kernel::secondsToTicks(1), [this] { - updateViews(); + updateDeviceStates(); }); } @@ -342,73 +228,73 @@ public: lv_obj_set_flex_flow(parent, LV_FLEX_FLOW_COLUMN); lv_obj_set_style_pad_row(parent, 0, LV_STATE_DEFAULT); + uint8_t margin = (lvgl_get_ui_density() == LVGL_UI_DENSITY_COMPACT) ? 2 : 8; + auto* toolbar = lvgl::toolbar_create(parent, app); + lvgl::toolbar_add_text_button_action(toolbar, LV_SYMBOL_PLUS, onAddGpsCallback, this); + lv_obj_set_style_margin_bottom(toolbar, margin, LV_STATE_DEFAULT); - spinnerWidget = lvgl::toolbar_add_spinner_action(toolbar); - lv_obj_add_flag(spinnerWidget, LV_OBJ_FLAG_HIDDEN); + deviceListWrapper = lv_obj_create(parent); + lv_obj_set_size(deviceListWrapper, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_flex_flow(deviceListWrapper, LV_FLEX_FLOW_COLUMN); + lv_obj_set_flex_grow(deviceListWrapper, 1); + lv_obj_set_style_border_width(deviceListWrapper, 0, 0); + lv_obj_set_style_pad_hor(deviceListWrapper, margin, 0); + lv_obj_set_style_pad_top(deviceListWrapper, 0, 0); + lv_obj_set_style_pad_bottom(deviceListWrapper, margin, 0); + lv_obj_set_style_pad_row(deviceListWrapper, margin, 0); - switchWidget = lvgl::toolbar_add_switch_action(toolbar); - lv_obj_add_event_cb(switchWidget, onGpsToggledCallback, LV_EVENT_VALUE_CHANGED, this); - - auto* main_wrapper = lv_obj_create(parent); - lv_obj_set_flex_flow(main_wrapper, LV_FLEX_FLOW_COLUMN); - lv_obj_set_width(main_wrapper, LV_PCT(100)); - lv_obj_set_flex_grow(main_wrapper, 1); - lv_obj_set_style_border_width(main_wrapper, 0, 0); - lv_obj_set_style_pad_all(main_wrapper, 0, 0); - - statusWrapper = lv_obj_create(main_wrapper); - lv_obj_set_width(statusWrapper, LV_PCT(100)); - lv_obj_set_height(statusWrapper, LV_SIZE_CONTENT); - lv_obj_set_flex_flow(statusWrapper, LV_FLEX_FLOW_COLUMN); - lv_obj_set_flex_align(statusWrapper, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); - lv_obj_set_style_pad_all(statusWrapper, 0, 0); - lv_obj_set_style_pad_row(statusWrapper, 8, 0); - lv_obj_set_style_border_width(statusWrapper, 0, 0); - - statusLabelWidget = lv_label_create(statusWrapper); - - infoContainerWidget = lv_obj_create(statusWrapper); - lv_obj_set_size(infoContainerWidget, LV_PCT(100), LV_SIZE_CONTENT); - lv_obj_set_flex_flow(infoContainerWidget, LV_FLEX_FLOW_COLUMN); - lv_obj_set_style_border_width(infoContainerWidget, 0, 0); - lv_obj_set_style_pad_row(infoContainerWidget, 5, 0); - lv_obj_set_style_pad_hor(infoContainerWidget, 10, 0); - hasSetInfo = false; - - statusLatitudeValue = createInfoRow(infoContainerWidget, "Latitude", lv_color_hex(0x00ff00)); - statusLongitudeValue = createInfoRow(infoContainerWidget, "Longitude", lv_color_hex(0x00ff00)); - statusAltitudeValue = createInfoRow(infoContainerWidget, "Altitude", lv_color_hex(0x00ffff)); - statusSpeedValue = createInfoRow(infoContainerWidget, "Speed", lv_color_hex(0xffff00)); - statusHeadingValue = createInfoRow(infoContainerWidget, "Heading", lv_color_hex(0xff88ff)); - statusSatellitesValue = createInfoRow(infoContainerWidget, "Satellites", lv_color_hex(0xffffff)); - - gpsConfigWrapper = lv_obj_create(main_wrapper); - lv_obj_set_size(gpsConfigWrapper, LV_PCT(100), LV_SIZE_CONTENT); - lv_obj_set_style_border_width(gpsConfigWrapper, 0, 0); - lv_obj_set_style_margin_all(gpsConfigWrapper, 0, 0); - lv_obj_set_style_pad_bottom(gpsConfigWrapper, 0, 0); - - addGpsWrapper = lv_obj_create(main_wrapper); - lv_obj_set_size(addGpsWrapper, LV_PCT(100), LV_SIZE_CONTENT); - lv_obj_set_style_border_width(addGpsWrapper, 0, 0); - lv_obj_set_style_pad_all(addGpsWrapper, 0, 0); - lv_obj_set_style_margin_top(addGpsWrapper, 0, 0); - lv_obj_set_style_margin_bottom(addGpsWrapper, 8, 0); - - auto* add_gps_button = lv_button_create(addGpsWrapper); - auto* add_gps_label = lv_label_create(add_gps_button); - lv_label_set_text(add_gps_label, "Add GPS"); - lv_obj_add_event_cb(add_gps_button, onAddGpsCallback, LV_EVENT_SHORT_CLICKED, this); - lv_obj_align(add_gps_button, LV_ALIGN_TOP_MID, 0, 0); + rebuildDeviceList(); timer->start(); - updateViews(); + updateDeviceStates(); + + // Only after deviceListWrapper is fully built: onResult() (Loader thread) checks + // this before touching it, since it can run before or after this onShow() call. + isShown = true; } void onHide(AppContext& app) override { + isShown = false; timer->stop(); } + + void onResult(AppContext&, LaunchId, Result result, std::unique_ptr bundle) override { + if (!hasPendingDelete) { + return; + } + hasPendingDelete = false; + + if (result != Result::Ok || bundle == nullptr || alertdialog::getResultIndex(*bundle) != 0) { // 0 = Yes + return; + } + + // This runs on the Loader thread, concurrently with the periodic timer callback + // (updateDeviceStates(), timer daemon thread) and possibly with onShow() (GUI + // thread). Take the same lock updateDeviceStates() uses and hold it across the + // free below, so the timer can never observe pendingDeleteDevice as a dangling + // pointer in deviceRows. + auto lock = lvgl::getSyncLock()->asScopedLock(); + lock.lock(); + + // Drop the stale row unconditionally (cheap vector op, no LVGL calls) - this is + // what keeps the timer safe regardless of whether onShow() has run yet this cycle. + std::erase_if(deviceRows, [this](const DeviceRow& row) { + return row.device == pendingDeleteDevice; + }); + + // gps_settings_remove_configuration_at() frees the underlying Device synchronously - + // do this only after the dangling pointer is already out of deviceRows. + gps_settings_remove_configuration_at(pendingDeleteIndex); + pendingDeleteDevice = nullptr; + + // Only safe to touch deviceListWrapper if onShow() already built it for this show + // cycle - it may not have run yet, in which case it'll rebuild fresh (post-deletion, + // deviceRows already correct) when it does. + if (isShown) { + rebuildDeviceList(); + } + } }; extern const AppManifest manifest = { diff --git a/Tactility/Source/file/FileLvglLock.cpp b/Tactility/Source/file/FileLvglLock.cpp new file mode 100644 index 000000000..c07cf9dc2 --- /dev/null +++ b/Tactility/Source/file/FileLvglLock.cpp @@ -0,0 +1,69 @@ +#include +#include +#include +#include +#include +#include + + +struct Device; +namespace tt { + +static const FileMutex lvgl_mutex = { + .lock = lvgl_lock, + .try_lock = lvgl_try_lock, + .unlock = lvgl_unlock, +}; + +/** + * Finds file systems with a device (e.g. sd card) that is owned by a SPI controller. + * If the SPI controller has a display on the bus, we create an LVGL lock for the file system path. + */ +void initFileLvglLock() { + file_system_for_each(nullptr, [](FileSystem* fs, void* context) { + char mount_path[64]; + if (file_system_get_path(fs, mount_path, sizeof(mount_path)) != ERROR_NONE) { + return true; + } + + // We only care about file system with a Device (owner) + auto* owner = file_system_get_owner(fs); + if (owner == nullptr) { + return true; + } + + // Ignore devices without a parent (root) + auto* parent = device_get_parent(owner); + if (parent == nullptr) { + return true; + } + + // If the FileSystem is on a SPI bus and there's more than 1 device, we assume the other one is the display. + auto* type = device_get_type(parent); + if (type != &SPI_CONTROLLER_TYPE || device_get_child_count(parent) <= 1) { + return true; + } + + struct Context { + const char* mountPath; + }; + Context ctx = { .mountPath = mount_path }; + + device_for_each_child(parent, &ctx, [](Device* child, void* context) { + Context* ctx = static_cast(context); + if (device_get_type(child) == &DISPLAY_TYPE) { + file_register_mutex( + ctx->mountPath, + &lvgl_mutex + ); + return false; + } + return true; + }); + + return true; + }); + +} + +} diff --git a/Tactility/Source/service/statusbar/Statusbar.cpp b/Tactility/Source/service/statusbar/Statusbar.cpp index 3039ac3fb..968c6006e 100644 --- a/Tactility/Source/service/statusbar/Statusbar.cpp +++ b/Tactility/Source/service/statusbar/Statusbar.cpp @@ -1,8 +1,5 @@ #include -#include -#include "tactility/module.h" - #include #include #include @@ -11,7 +8,6 @@ #include #include #include -#include #include #include #include @@ -23,11 +19,15 @@ #include #include +#include +#include + +#include #include #include -#include +#include namespace tt::service::statusbar { @@ -154,8 +154,7 @@ class StatusbarService final : public Service { } void updateGpsIcon() { - auto gps_state = gps_service_get_state(); - bool show_icon = (gps_state == GpsServiceState::GPS_SERVICE_STATE_ON_PENDING) || (gps_state == GpsServiceState::GPS_SERVICE_STATE_ON); + bool show_icon = device_has_active_by_type(&GPS_TYPE); if (gps_last_state != show_icon) { if (show_icon) { lvgl::statusbar_icon_set_image(gps_icon_id, LVGL_ICON_STATUSBAR_LOCATION_ON); diff --git a/TactilityKernel/include/tactility/device.h b/TactilityKernel/include/tactility/device.h index bc05dfa72..ee46d7313 100644 --- a/TactilityKernel/include/tactility/device.h +++ b/TactilityKernel/include/tactility/device.h @@ -24,6 +24,19 @@ struct DeviceType { const char* name; }; +typedef uint8_t device_flags_t; + +#ifndef BIT +#define BIT(nr) (1u << (nr)) +#endif + +#define DEVICE_FLAG_DTS BIT(0) /* Instantiated from a dts file */ +#define DEVICE_FLAG_DYNAMIC BIT(1) /* 1 means dynamically allocated */ + +#define DEVICE_FLAG_VIRTUAL BIT(2) /* No physical hardware */ +#define DEVICE_FLAG_REMOVABLE BIT(3) /* May disappear (USB, SDIO, etc.) */ +#define DEVICE_FLAG_HOTPLUG BIT(4) /* Supports hotplug */ + /** Represents a piece of hardware */ struct Device { /** Device address. Can represent an index, a memory address, or some kind of offset */ @@ -38,6 +51,8 @@ struct Device { /** The parent device that this device belongs to. Can be NULL, but only the root device should have a NULL parent. */ struct Device* parent; + device_flags_t flags; + /** * Internal state managed by the kernel. * Device implementers should initialize this to NULL. diff --git a/TactilityKernel/include/tactility/filesystem/file_lock.h b/TactilityKernel/include/tactility/filesystem/file_lock.h new file mode 100644 index 000000000..e976d74e8 --- /dev/null +++ b/TactilityKernel/include/tactility/filesystem/file_lock.h @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +struct FileMutex { + void (*lock)(); + bool (*try_lock)(TickType_t timeout); + void (*unlock)(); +}; + +void file_register_mutex(const char* path, const FileMutex* mutex); + +void file_get_mutex(const char* path, struct FileMutex* mutex); + +void file_lock(struct FileMutex* mutex); + +bool file_try_lock(struct FileMutex* mutex, TickType_t timeout); + +void file_unlock(struct FileMutex* mutex); + +#ifdef __cplusplus +} +#endif diff --git a/TactilityKernel/source/filesystem/file_lock.cpp b/TactilityKernel/source/filesystem/file_lock.cpp new file mode 100644 index 000000000..f7bb9e164 --- /dev/null +++ b/TactilityKernel/source/filesystem/file_lock.cpp @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +#include +#include +#include + +static const FileMutex no_mutex = { + .lock = nullptr, + .try_lock = nullptr, + .unlock = nullptr, +}; + +struct FileMutexEntry { + std::string path; + FileMutex mutex; +}; + +static std::vector mutex_entries; + +extern "C" { +void file_register_mutex(const char* path, const FileMutex* mutex) { + // Skip if entry for path exists + for (auto& entry : mutex_entries) { + if (entry.path == path) { + return; + } + } + + // Store a copy of the entry + mutex_entries.push_back({ + .path = path, + .mutex = *mutex + }); +} + +void file_get_mutex(const char* path, FileMutex* mutex) { + for (auto& entry : mutex_entries) { + if (entry.path.rfind(path) == 0) { + memcpy(mutex, &entry.mutex, sizeof(FileMutexEntry)); + return; + } + } + + memcpy(mutex, &no_mutex, sizeof(FileMutex)); +} + +void file_lock(FileMutex* mutex) { + if (mutex->lock) { + mutex->lock(); + } +} + +bool file_try_lock(FileMutex* mutex, TickType_t timeout) { + if (mutex->try_lock) { + return mutex->try_lock(timeout); + } + return true; +} + +void file_unlock(FileMutex* mutex) { + if (mutex->unlock) { + mutex->unlock(); + } +} + +} diff --git a/Tests/Tactility/CMakeLists.txt b/Tests/Tactility/CMakeLists.txt index a343f249b..2681a2bac 100644 --- a/Tests/Tactility/CMakeLists.txt +++ b/Tests/Tactility/CMakeLists.txt @@ -17,6 +17,7 @@ target_link_libraries(TactilityTests PRIVATE lvgl-module crypt-module gps-module + gps-generic-module lvgl SDL2::SDL2-static SDL2-static )