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

- Added generic GPS/GNSS support with device detection, configuration, and persistent settings.
- Improved device and module lifecycle management.
- Added flexible filesystem locking support for displays and storage.
- Improved display-idle and keyboard backlight handling.
- Updated architecture, driver, module, testing, and licensing documentation.
- Removed old HAL device and related code.
This commit is contained in:
Ken Van Hoeylandt
2026-07-25 17:20:17 +02:00
committed by GitHub
parent 29e80cfd65
commit 2a2558b29a
173 changed files with 3855 additions and 5445 deletions
+12
View File
@@ -0,0 +1,12 @@
cmake_minimum_required(VERSION 3.20)
include("${CMAKE_CURRENT_LIST_DIR}/../../Buildscripts/module.cmake")
file(GLOB_RECURSE SOURCE_FILES "source/*.c*")
tactility_add_module(gps-module
SRCS ${SOURCE_FILES}
PRIV_INCLUDE_DIRS private/
INCLUDE_DIRS include/
REQUIRES TactilityKernel minmea
)
+195
View File
@@ -0,0 +1,195 @@
Apache License
==============
_Version 2.0, January 2004_
_&lt;<http://www.apache.org/licenses/>&gt;_
### Terms and Conditions for use, reproduction, and distribution
#### 1. Definitions
“License” shall mean the terms and conditions for use, reproduction, and
distribution as defined by Sections 1 through 9 of this document.
“Licensor” shall mean the copyright owner or entity authorized by the copyright
owner that is granting the License.
“Legal Entity” shall mean the union of the acting entity and all other entities
that control, are controlled by, or are under common control with that entity.
For the purposes of this definition, “control” means **(i)** the power, direct or
indirect, to cause the direction or management of such entity, whether by
contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the
outstanding shares, or **(iii)** beneficial ownership of such entity.
“You” (or “Your”) shall mean an individual or Legal Entity exercising
permissions granted by this License.
“Source” form shall mean the preferred form for making modifications, including
but not limited to software source code, documentation source, and configuration
files.
“Object” form shall mean any form resulting from mechanical transformation or
translation of a Source form, including but not limited to compiled object code,
generated documentation, and conversions to other media types.
“Work” shall mean the work of authorship, whether in Source or Object form, made
available under the License, as indicated by a copyright notice that is included
in or attached to the work (an example is provided in the Appendix below).
“Derivative Works” shall mean any work, whether in Source or Object form, that
is based on (or derived from) the Work and for which the editorial revisions,
annotations, elaborations, or other modifications represent, as a whole, an
original work of authorship. For the purposes of this License, Derivative Works
shall not include works that remain separable from, or merely link (or bind by
name) to the interfaces of, the Work and Derivative Works thereof.
“Contribution” shall mean any work of authorship, including the original version
of the Work and any modifications or additions to that Work or Derivative Works
thereof, that is intentionally submitted to Licensor for inclusion in the Work
by the copyright owner or by an individual or Legal Entity authorized to submit
on behalf of the copyright owner. For the purposes of this definition,
“submitted” means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems, and
issue tracking systems that are managed by, or on behalf of, the Licensor for
the purpose of discussing and improving the Work, but excluding communication
that is conspicuously marked or otherwise designated in writing by the copyright
owner as “Not a Contribution.”
“Contributor” shall mean Licensor and any individual or Legal Entity on behalf
of whom a Contribution has been received by Licensor and subsequently
incorporated within the Work.
#### 2. Grant of Copyright License
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the Work and such
Derivative Works in Source or Object form.
#### 3. Grant of Patent License
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable (except as stated in this section) patent license to make, have
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
such license applies only to those patent claims licensable by such Contributor
that are necessarily infringed by their Contribution(s) alone or by combination
of their Contribution(s) with the Work to which such Contribution(s) was
submitted. If You institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
Contribution incorporated within the Work constitutes direct or contributory
patent infringement, then any patent licenses granted to You under this License
for that Work shall terminate as of the date such litigation is filed.
#### 4. Redistribution
You may reproduce and distribute copies of the Work or Derivative Works thereof
in any medium, with or without modifications, and in Source or Object form,
provided that You meet the following conditions:
* **(a)** You must give any other recipients of the Work or Derivative Works a copy of
this License; and
* **(b)** You must cause any modified files to carry prominent notices stating that You
changed the files; and
* **(c)** You must retain, in the Source form of any Derivative Works that You distribute,
all copyright, patent, trademark, and attribution notices from the Source form
of the Work, excluding those notices that do not pertain to any part of the
Derivative Works; and
* **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any
Derivative Works that You distribute must include a readable copy of the
attribution notices contained within such NOTICE file, excluding those notices
that do not pertain to any part of the Derivative Works, in at least one of the
following places: within a NOTICE text file distributed as part of the
Derivative Works; within the Source form or documentation, if provided along
with the Derivative Works; or, within a display generated by the Derivative
Works, if and wherever such third-party notices normally appear. The contents of
the NOTICE file are for informational purposes only and do not modify the
License. You may add Your own attribution notices within Derivative Works that
You distribute, alongside or as an addendum to the NOTICE text from the Work,
provided that such additional attribution notices cannot be construed as
modifying the License.
You may add Your own copyright statement to Your modifications and may provide
additional or different license terms and conditions for use, reproduction, or
distribution of Your modifications, or for any such Derivative Works as a whole,
provided Your use, reproduction, and distribution of the Work otherwise complies
with the conditions stated in this License.
#### 5. Submission of Contributions
Unless You explicitly state otherwise, any Contribution intentionally submitted
for inclusion in the Work by You to the Licensor shall be under the terms and
conditions of this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify the terms of
any separate license agreement you may have executed with Licensor regarding
such Contributions.
#### 6. Trademarks
This License does not grant permission to use the trade names, trademarks,
service marks, or product names of the Licensor, except as required for
reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE file.
#### 7. Disclaimer of Warranty
Unless required by applicable law or agreed to in writing, Licensor provides the
Work (and each Contributor provides its Contributions) on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
including, without limitation, any warranties or conditions of TITLE,
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
solely responsible for determining the appropriateness of using or
redistributing the Work and assume any risks associated with Your exercise of
permissions under this License.
#### 8. Limitation of Liability
In no event and under no legal theory, whether in tort (including negligence),
contract, or otherwise, unless required by applicable law (such as deliberate
and grossly negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special, incidental,
or consequential damages of any character arising as a result of this License or
out of the use or inability to use the Work (including but not limited to
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
any and all other commercial damages or losses), even if such Contributor has
been advised of the possibility of such damages.
#### 9. Accepting Warranty or Additional Liability
While redistributing the Work or Derivative Works thereof, You may choose to
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
other liability obligations and/or rights consistent with this License. However,
in accepting such obligations, You may act only on Your own behalf and on Your
sole responsibility, not on behalf of any other Contributor, and only if You
agree to indemnify, defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason of your
accepting any such warranty or additional liability.
_END OF TERMS AND CONDITIONS_
### APPENDIX: How to apply the Apache License to your work
To apply the Apache License to your work, attach the following boilerplate
notice, with the fields enclosed by brackets `[]` replaced with your own
identifying information. (Don't include the brackets!) The text should be
enclosed in the appropriate comment syntax for the file format. We also
recommend that a file or class name and description of purpose be included on
the same “printed page” as the copyright notice for easier identification within
third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+2
View File
@@ -0,0 +1,2 @@
dependencies:
- TactilityKernel
+137
View File
@@ -0,0 +1,137 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include <tactility/device.h>
#include <tactility/error.h>
#include <tactility/freertos/freertos.h>
#include <tactility/freertos/task.h>
#include <minmea.h>
/**
* @brief Supported GPS/GNSS receiver chipsets.
*/
enum GpsModel {
GPS_MODEL_UNKNOWN = 0,
GPS_MODEL_AG3335,
GPS_MODEL_AG3352,
// CASIC, might work with AT6558, Neoway N58 LTE Cat.1, Neoway G2 and Neoway G7A
GPS_MODEL_ATGM336H,
GPS_MODEL_LS20031,
GPS_MODEL_MTK,
GPS_MODEL_MTK_L76B,
GPS_MODEL_MTK_PA1616S,
GPS_MODEL_UBLOX6,
GPS_MODEL_UBLOX7,
GPS_MODEL_UBLOX8,
GPS_MODEL_UBLOX9,
GPS_MODEL_UBLOX10,
GPS_MODEL_UC6580,
};
/** @return a human-readable name for the model, e.g. "UBLOX8" or "Unknown" */
const char* gps_model_to_string(enum GpsModel model);
/**
* @brief Lifecycle state of a GPS_TYPE device.
*/
enum GpsState {
GPS_STATE_OFF,
GPS_STATE_PENDING_ON,
GPS_STATE_ON,
GPS_STATE_ERROR,
GPS_STATE_PENDING_OFF,
};
enum GpsEventType {
GPS_EVENT_UNSUBSCRIBED, // Last event, device wants to destroy itself and unsubscribed the subscriber.
GPS_EVENT_MESSAGE_RMC,
GPS_EVENT_MESSAGE_GGA,
};
struct GpsEvent {
enum GpsEventType type;
union {
struct minmea_sentence_rmc rmc;
struct minmea_sentence_gga gga;
} data;
};
struct GpsSubscription {
TaskHandle_t task;
struct GpsEvent event;
uint32_t sequence;
uint32_t consumed_sequence;
struct GpsSubscription* next;
};
/**
* @brief API for GPS/GNSS receiver drivers.
*/
struct GpsApi {
/**
* @brief Registers a subscriber for GPS events (e.g. RMC/GGA sentences).
* @param[in] device the GPS device
* @param[in,out] sub subscription to register; caller owns the storage and must keep it alive until unsubscribed
*/
error_t (*event_subscribe)(struct Device* device, struct GpsSubscription* sub);
/**
* @brief Removes a previously registered subscription.
* @param[in] device the GPS device
* @param[in] sub subscription to remove, as passed to event_subscribe
*/
error_t (*event_unsubscribe)(struct Device* device, struct GpsSubscription* sub);
/**
* @brief Blocks the calling task until a new event arrives for the subscription, or timeout elapses.
* @param[in] device the GPS device
* @param[in,out] sub subscription to wait on
* @param[in] timeout max ticks to wait
* @return ERROR_NONE if an event arrived, ERROR_TIMEOUT if the timeout elapsed
*/
error_t (*event_await)(struct Device* device, struct GpsSubscription* sub, TickType_t timeout);
/**
* @brief Gets the current lifecycle state.
* @param[in] device the GPS device
*/
enum GpsState (*get_state)(struct Device* device);
/**
* @brief Gets a human-readable model name for the device, e.g. "UBLOX8".
* @param[in] device the GPS device
* @param[out] model_name buffer to receive the NUL-terminated name
* @param[in] buffer_size size of model_name in bytes
* @return ERROR_NONE on success
*/
error_t (*get_model_name)(struct Device* device, char* model_name, size_t buffer_size);
};
/** @copydoc GpsApi::event_subscribe */
error_t gps_event_subscribe(struct Device* device, struct GpsSubscription* sub);
/** @copydoc GpsApi::event_unsubscribe */
error_t gps_event_unsubscribe(struct Device* device, struct GpsSubscription* sub);
/** @copydoc GpsApi::event_await */
error_t gps_event_await(struct Device* device, struct GpsSubscription* sub, TickType_t timeout);
/** @copydoc GpsApi::get_state */
enum GpsState gps_get_state(struct Device* device);
/** @copydoc GpsApi::get_model_name */
error_t gps_get_model_name(struct Device* device, char* model_name, size_t buffer_size);
extern const struct DeviceType GPS_TYPE;
#ifdef __cplusplus
}
#endif
@@ -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
@@ -0,0 +1,51 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include <stddef.h>
#include <stdint.h>
#include <gps/gps.h>
#include <tactility/error.h>
/**
* @brief A persisted GPS receiver configuration.
*/
struct GpsConfiguration {
/** UART controller device name, e.g. "uart0" - resolved via device_get_by_name(). */
char uart_name[32];
uint32_t baud_rate;
/** GPS_MODEL_UNKNOWN triggers an autoprobe. */
enum GpsModel model;
};
/**
* @brief Persists a new GPS configuration and triggers the ledger to materialize a (not started)
* GPS_TYPE device for it in the device tree. Use device_start()/device_stop() on the resulting
* device to control whether it's actually running.
* @retval ERROR_RESOURCE if the configuration file could not be opened/written
*/
error_t gps_settings_add_configuration(const struct GpsConfiguration* configuration);
/**
* @brief Removes the persisted GPS configuration at `index` (as seen via
* gps_settings_for_each_configuration()), and triggers the ledger to stop, destruct and remove
* its corresponding GPS_TYPE device from the device tree.
* @retval ERROR_NOT_FOUND if index is out of range
* @retval ERROR_RESOURCE if the configuration file could not be read/written
*/
error_t gps_settings_remove_configuration_at(size_t index);
/**
* @brief Iterates over all persisted GPS configurations.
* @param[in] context passed through to on_configuration, can be NULL
* @param[in] on_configuration called once per configuration, in file order, with its index
*/
void gps_settings_for_each_configuration(void* context, void (*on_configuration)(const struct GpsConfiguration* configuration, size_t index, void* context));
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,20 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
/**
* @brief Reconciles the device tree against the persisted GPS configurations (see
* gps/gps_settings.h): constructs+adds (but does not start) a GPS_TYPE device for every
* configuration that doesn't have one yet, and stops+destructs+removes any ledger-owned device
* whose configuration has disappeared.
*
* Only ever touches devices the ledger itself created (tagged DEVICE_FLAG_DYNAMIC) - devicetree-
* declared GPS_TYPE devices (tagged DEVICE_FLAG_DTS) are never constructed, started, stopped, or
* destructed by the ledger.
*/
void gps_ledger_sync();
/**
* @brief Stops+destructs+removes every ledger-owned device. Devicetree-declared GPS_TYPE devices
* are left untouched.
*/
void gps_ledger_clear();
+57
View File
@@ -0,0 +1,57 @@
#include <gps/gps.h>
#ifdef __cplusplus
extern "C" {
#endif
const char* gps_model_to_string(GpsModel model) {
switch (model) {
case GPS_MODEL_AG3335: return "AG3335";
case GPS_MODEL_AG3352: return "AG3352";
case GPS_MODEL_ATGM336H: return "ATGM336H";
case GPS_MODEL_LS20031: return "LS20031";
case GPS_MODEL_MTK: return "MTK";
case GPS_MODEL_MTK_L76B: return "MTK_L76B";
case GPS_MODEL_MTK_PA1616S: return "MTK_PA1616S";
case GPS_MODEL_UBLOX6: return "UBLOX6";
case GPS_MODEL_UBLOX7: return "UBLOX7";
case GPS_MODEL_UBLOX8: return "UBLOX8";
case GPS_MODEL_UBLOX9: return "UBLOX9";
case GPS_MODEL_UBLOX10: return "UBLOX10";
case GPS_MODEL_UC6580: return "UC6580";
default: return "Unknown";
}
}
error_t gps_event_subscribe(Device* device, GpsSubscription* sub) {
const auto* driver = device_get_driver(device);
return static_cast<const GpsApi*>(driver->api)->event_subscribe(device, sub);
}
error_t gps_event_unsubscribe(Device* device, GpsSubscription* sub) {
const auto* driver = device_get_driver(device);
return static_cast<const GpsApi*>(driver->api)->event_unsubscribe(device, sub);
}
error_t gps_event_await(Device* device, GpsSubscription* sub, TickType_t timeout) {
const auto* driver = device_get_driver(device);
return static_cast<const GpsApi*>(driver->api)->event_await(device, sub, timeout);
}
GpsState gps_get_state(Device* device) {
const auto* driver = device_get_driver(device);
return static_cast<const GpsApi*>(driver->api)->get_state(device);
}
error_t gps_get_model_name(Device* device, char* model_name, size_t buffer_size) {
const auto* driver = device_get_driver(device);
return static_cast<const GpsApi*>(driver->api)->get_model_name(device, model_name, buffer_size);
}
const DeviceType GPS_TYPE {
.name = "gps"
};
#ifdef __cplusplus
}
#endif
+167
View File
@@ -0,0 +1,167 @@
// SPDX-License-Identifier: Apache-2.0
#include <gps/private/gps_ledger.h>
#include <gps/gps.h>
#include <gps/gps_settings.h>
#include <tactility/device.h>
#include <tactility/driver.h>
#include <tactility/log.h>
#include <cstdio>
#include <cstring>
#include <new>
#include <vector>
constexpr auto* TAG = "gps_ledger";
struct GpsConfig {
uint32_t baud_rate;
enum GpsModel model;
};
// A GPS_TYPE device the ledger constructed for a persisted GpsConfiguration. Device is the first
// member so `reinterpret_cast<GpsLedgerEntry*>(device)` is safe when a Device* obtained from the
// device tree needs to be freed.
struct GpsLedgerEntry {
Device device {};
GpsConfig config {};
// device->name points into this buffer - must outlive the device (device->name only stores a
// pointer, it doesn't copy).
char name[16] {};
};
// Unique across every device the ledger creates, so device names ("gpsN") never collide.
static uint32_t next_device_index = 0;
static bool device_matches_configuration(Device* device, const GpsConfiguration& configuration) {
auto* parent = device_get_parent(device);
if (parent == nullptr || strcmp(parent->name, configuration.uart_name) != 0) {
return false;
}
const auto* config = static_cast<const GpsConfig*>(device->config);
return config->baud_rate == configuration.baud_rate && config->model == configuration.model;
}
// Constructs+adds (not started) a GPS_TYPE device wired to `configuration`'s named UART, tagged
// DEVICE_FLAG_DYNAMIC so the ledger recognizes it as its own on a later sync.
static bool create_device(const GpsConfiguration& configuration) {
Device* uart = nullptr;
if (device_get_by_name(configuration.uart_name, &uart) != ERROR_NONE) {
LOG_E(TAG, "Failed to find device %s", configuration.uart_name);
return false;
}
auto* entry = new(std::nothrow) GpsLedgerEntry();
if (entry == nullptr) {
device_put(uart);
return false;
}
entry->config = GpsConfig { .baud_rate = configuration.baud_rate, .model = configuration.model };
snprintf(entry->name, sizeof(entry->name), "gps%u", (unsigned)next_device_index++);
auto* device = &entry->device;
device->address = 0;
device->name = entry->name;
device->config = &entry->config;
device->parent = nullptr;
device->flags = DEVICE_FLAG_DYNAMIC;
device->internal = nullptr;
bool ok = false;
if (device_construct(device) == ERROR_NONE) {
device_set_parent(device, uart);
Driver* driver = driver_find_compatible("tactility,gps-generic");
if (driver != nullptr) {
device_set_driver(device, driver);
ok = device_add(device) == ERROR_NONE;
if (!ok) {
LOG_E(TAG, "Failed to add %s", device->name);
}
} else {
LOG_E(TAG, "No driver registered for tactility,gps-generic");
}
if (!ok) {
device_destruct(device);
}
} else {
LOG_E(TAG, "Failed to construct %s", device->name);
}
device_put(uart);
if (!ok) {
delete entry;
}
return ok;
}
// Stops (if needed), removes and destructs a ledger-owned device, and frees its entry.
static void destroy_device(Device* device) {
if (device_is_ready(device)) {
device_stop(device);
}
device_remove(device);
device_destruct(device);
delete reinterpret_cast<GpsLedgerEntry*>(device);
}
static bool is_ledger_owned(const Device* device) {
return !(device->flags & DEVICE_FLAG_DTS) && (device->flags & DEVICE_FLAG_DYNAMIC);
}
// Collects the ledger-owned GPS_TYPE devices. device_remove()/device_stop() must not run while
// device_for_each_of_type() holds the device ledger lock, so callers process the result afterwards.
static std::vector<Device*> collect_owned_devices() {
std::vector<Device*> owned;
device_for_each_of_type(&GPS_TYPE, &owned, [](Device* device, void* context) {
if (is_ledger_owned(device)) {
static_cast<std::vector<Device*>*>(context)->push_back(device);
}
return true;
});
return owned;
}
void gps_ledger_sync() {
std::vector<GpsConfiguration> configurations;
gps_settings_for_each_configuration(&configurations, [](const GpsConfiguration* configuration, size_t, void* context) {
static_cast<std::vector<GpsConfiguration>*>(context)->push_back(*configuration);
});
std::vector<bool> matched(configurations.size(), false);
std::vector<Device*> stale;
for (auto* device : collect_owned_devices()) {
bool found = false;
for (size_t i = 0; i < configurations.size(); i++) {
if (!matched[i] && device_matches_configuration(device, configurations[i])) {
matched[i] = true;
found = true;
break;
}
}
if (!found) {
stale.push_back(device);
}
}
// Configuration disappeared - stop, destruct and drop the device that was created for it.
for (auto* device : stale) {
destroy_device(device);
}
// New configuration - create a (not started) device for it.
for (size_t i = 0; i < configurations.size(); i++) {
if (!matched[i]) {
create_device(configurations[i]);
}
}
}
void gps_ledger_clear() {
for (auto* device : collect_owned_devices()) {
destroy_device(device);
}
}
+169
View File
@@ -0,0 +1,169 @@
// SPDX-License-Identifier: Apache-2.0
#include <gps/gps_settings.h>
#include <gps/private/gps_ledger.h>
#include <tactility/filesystem/file_mutex.h>
#include <tactility/log.h>
#include <tactility/service/service_paths.h>
#include <sys/stat.h>
#include <cstdio>
#include <cstring>
#include <vector>
constexpr auto* TAG = "gps_settings";
// Storage key for the persisted configuration file (services would use their own service ID for
// this; gps_settings has no service backing it, so it defines its own).
constexpr auto* GPS_SETTINGS_STORAGE_ID = "gps";
// region Configuration persistence
// Recursively creates every missing directory component of `path` (best-effort - mkdir() failures
// other than "already exists" are surfaced later, when the actual config file open fails).
static void ensure_directory_exists(const char* path) {
char buffer[224];
std::strncpy(buffer, path, sizeof(buffer) - 1);
buffer[sizeof(buffer) - 1] = '\0';
for (char* p = buffer + 1; *p != '\0'; p++) {
if (*p == '/') {
*p = '\0';
mkdir(buffer, 0777);
*p = '/';
}
}
mkdir(buffer, 0777);
}
static bool get_configuration_path(char* out_path, size_t out_path_size) {
return service_paths_get_user_data_path(GPS_SETTINGS_STORAGE_ID, "config.bin", out_path, out_path_size) == ERROR_NONE;
}
// Holds the lock (if any) that `path` needs for the lifetime of the guard - see file_find_lock().
class FileLockGuard {
FileMutex mutex;
bool locked;
public:
explicit FileLockGuard(const char* path) {
file_mutex_get(&mutex, path);
file_mutex_lock(&mutex);
locked = true;
}
~FileLockGuard() {
unlock();
}
void unlock() {
if (locked) {
file_mutex_unlock(&mutex);
locked = false;
}
}
};
void gps_settings_for_each_configuration(void* context, void (*on_configuration)(const GpsConfiguration* configuration, size_t index, void* context)) {
char path[224];
if (!get_configuration_path(path, sizeof(path))) {
return;
}
FileLockGuard lock(path);
FILE* file = fopen(path, "rb");
if (file == nullptr) {
return; // No configurations saved yet
}
GpsConfiguration configuration;
size_t index = 0;
while (fread(&configuration, sizeof(configuration), 1, file) == 1) {
on_configuration(&configuration, index, context);
index++;
}
fclose(file);
}
static void collect_configuration(const GpsConfiguration* configuration, size_t, void* context) {
static_cast<std::vector<GpsConfiguration>*>(context)->push_back(*configuration);
}
static void load_configurations(std::vector<GpsConfiguration>& out) {
gps_settings_for_each_configuration(&out, collect_configuration);
}
static error_t write_configurations(const std::vector<GpsConfiguration>& configurations) {
char directory[224];
if (service_paths_get_user_data_directory(GPS_SETTINGS_STORAGE_ID, directory, sizeof(directory)) != ERROR_NONE) {
return ERROR_RESOURCE;
}
char path[256];
if (!get_configuration_path(path, sizeof(path))) {
return ERROR_RESOURCE;
}
FileLockGuard lock(path);
ensure_directory_exists(directory);
FILE* file = fopen(path, "wb");
if (file == nullptr) {
LOG_E(TAG, "Failed to open %s for writing", path);
return ERROR_RESOURCE;
}
bool ok = true;
for (auto& configuration : configurations) {
if (fwrite(&configuration, sizeof(configuration), 1, file) != 1) {
ok = false;
break;
}
}
fclose(file);
if (!ok) {
return ERROR_RESOURCE;
}
lock.unlock();
gps_ledger_sync();
return ERROR_NONE;
}
// endregion
error_t gps_settings_add_configuration(const GpsConfiguration* configuration) {
std::vector<GpsConfiguration> configurations;
load_configurations(configurations);
configurations.push_back(*configuration);
error_t error = write_configurations(configurations);
if (error != ERROR_NONE) {
return error;
}
return ERROR_NONE;
}
error_t gps_settings_remove_configuration_at(size_t index) {
std::vector<GpsConfiguration> configurations;
load_configurations(configurations);
if (index >= configurations.size()) {
return ERROR_NOT_FOUND;
}
configurations.erase(configurations.begin() + static_cast<ptrdiff_t>(index));
error_t error = write_configurations(configurations);
if (error != ERROR_NONE) {
return error;
}
return ERROR_NONE;
}
+30
View File
@@ -0,0 +1,30 @@
// SPDX-License-Identifier: Apache-2.0
#include <gps/gps_module.h>
#include <gps/private/gps_ledger.h>
#include <tactility/error.h>
#include <tactility/module.h>
extern "C" {
static error_t start() {
// Materializes devices for configurations persisted in previous sessions.
gps_ledger_sync();
return ERROR_NONE;
}
static error_t stop() {
gps_ledger_clear();
return ERROR_NONE;
}
Module gps_module = {
.name = "gps",
.start = start,
.stop = stop,
.drivers = nullptr,
.symbols = nullptr,
.internal = nullptr
};
}