Merge TactilityHeadless into Tactility (#263)

There currently is no practical use to have TactilityHeadless as a subproject. I'm merging it with the Tactility project.
This commit is contained in:
Ken Van Hoeylandt
2025-03-30 10:54:36 +02:00
committed by GitHub
parent d0ca3b16f8
commit d72852a6e2
114 changed files with 30 additions and 105 deletions
+19 -5
View File
@@ -6,16 +6,29 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON)
if (DEFINED ENV{ESP_IDF_VERSION})
file(GLOB_RECURSE SOURCE_FILES Source/*.c*)
list(APPEND REQUIRES_LIST TactilityCore lvgl driver elf_loader lv_screenshot QRCode esp_lvgl_port minmea esp_wifi nvs_flash spiffs vfs fatfs lwip)
if ("${IDF_TARGET}" STREQUAL "esp32s3")
list(APPEND REQUIRES_LIST esp_tinyusb)
endif ()
idf_component_register(
SRCS ${SOURCE_FILES}
INCLUDE_DIRS "Include/"
PRIV_INCLUDE_DIRS "Private/"
REQUIRES TactilityHeadless lvgl driver elf_loader lv_screenshot QRCode esp_lvgl_port
REQUIRES ${REQUIRES_LIST}
)
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
target_compile_options(${COMPONENT_LIB} PUBLIC -Wno-unused-variable)
endif()
endif ()
if (NOT DEFINED TACTILITY_SKIP_SPIFFS)
# Read-only
fatfs_create_rawflash_image(system "${CMAKE_CURRENT_SOURCE_DIR}/../Data/system" FLASH_IN_PROJECT PRESERVE_TIME)
# Read-write
fatfs_create_spiflash_image(data "${CMAKE_CURRENT_SOURCE_DIR}/../Data/data" FLASH_IN_PROJECT PRESERVE_TIME)
endif ()
else()
file(GLOB_RECURSE SOURCES "Source/*.c*")
@@ -37,10 +50,11 @@ else()
add_definitions(-D_Nonnull=)
target_link_libraries(Tactility
PUBLIC TactilityHeadless
PUBLIC lvgl
PUBLIC TactilityCore
PUBLIC freertos_kernel
PUBLIC lvgl
PUBLIC lv_screenshot
PUBLIC minmea
)
endif()
+17
View File
@@ -0,0 +1,17 @@
#pragma once
#define TT_ASSET_FOLDER "A:/system/"
#define TT_ASSET(file) TT_ASSET_FOLDER file
// UI
#define TT_ASSETS_UI_SPINNER TT_ASSET("spinner.png")
// App icons
#define TT_ASSETS_APP_ICON_FALLBACK TT_ASSET("app_icon_fallback.png")
#define TT_ASSETS_APP_ICON_FILES TT_ASSET("app_icon_files.png")
#define TT_ASSETS_APP_ICON_DISPLAY_SETTINGS TT_ASSET("app_icon_display_settings.png")
#define TT_ASSETS_APP_ICON_POWER_SETTINGS TT_ASSET("app_icon_power_settings.png")
#define TT_ASSETS_APP_ICON_I2C_SETTINGS TT_ASSET("app_icon_i2c.png")
#define TT_ASSETS_APP_ICON_SETTINGS TT_ASSET("app_icon_settings.png")
#define TT_ASSETS_APP_ICON_SYSTEM_INFO TT_ASSET("app_icon_system_info.png")
#define TT_ASSETS_APP_ICON_TIME_DATE_SETTINGS TT_ASSET("app_icon_time_date_settings.png")
+21
View File
@@ -0,0 +1,21 @@
#pragma once
namespace tt {
#define SYSTEM_PARTITION_NAME "system"
#ifdef ESP_PLATFORM
#define MOUNT_POINT_SYSTEM "/system"
#else
#define MOUNT_POINT_SYSTEM "system"
#endif
#define DATA_PARTITION_NAME "data"
#ifdef ESP_PLATFORM
#define MOUNT_POINT_DATA "/data"
#else
#define MOUNT_POINT_DATA "data"
#endif
} // namespace
+34
View File
@@ -0,0 +1,34 @@
#pragma once
#include <cstdint>
#include <string>
namespace tt {
/**
* Settings that persist on NVS flash for ESP32.
* On simulator, the settings are only in-memory.
*/
class Preferences {
private:
const char* namespace_;
public:
explicit Preferences(const char* namespace_) {
this->namespace_ = namespace_;
}
bool hasBool(const std::string& key) const;
bool hasInt32(const std::string& key) const;
bool hasString(const std::string& key) const;
bool optBool(const std::string& key, bool& out) const;
bool optInt32(const std::string& key, int32_t& out) const;
bool optString(const std::string& key, std::string& out) const;
void putBool(const std::string& key, bool value);
void putInt32(const std::string& key, int32_t value);
void putString(const std::string& key, const std::string& value);
};
} // namespace
@@ -0,0 +1,26 @@
#pragma once
#include "Tactility/hal/Configuration.h"
#include <Tactility/TactilityCore.h>
#include <Tactility/Dispatcher.h>
namespace tt {
/** Initialize the hardware and started the internal services. */
void initHeadless(const hal::Configuration& config);
/** Provides access to the dispatcher that runs on the main task.
* @warning This dispatcher is used for WiFi and might block for some time during WiFi connection.
* @return the dispatcher
*/
Dispatcher& getMainDispatcher();
} // namespace
namespace tt::hal {
/** While technically this configuration is nullable, it's never null after initHeadless() is called. */
const Configuration* _Nullable getConfiguration();
} // namespace
@@ -0,0 +1,58 @@
#pragma once
#include "Tactility/hal/gps/GpsDevice.h"
#include "Tactility/hal/sdcard/SdCardDevice.h"
#include "Tactility/hal/spi/Spi.h"
#include "Tactility/hal/uart/Uart.h"
#include "i2c/I2c.h"
namespace tt::hal {
typedef bool (*InitBoot)();
namespace display { class DisplayDevice; }
namespace keyboard { class KeyboardDevice; }
namespace power { class PowerDevice; }
typedef std::shared_ptr<display::DisplayDevice> (*CreateDisplay)();
typedef std::shared_ptr<keyboard::KeyboardDevice> (*CreateKeyboard)();
typedef std::shared_ptr<power::PowerDevice> (*CreatePower)();
enum class LvglInit {
Default,
None
};
struct Configuration {
/**
* Called before I2C/SPI/etc is initialized.
* Used for powering on the peripherals manually.
*/
const InitBoot _Nullable initBoot = nullptr;
/** Init behaviour: default (esp_lvgl_port for ESP32, nothing for PC) or None (nothing on any platform). Only used in Tactility, not in TactilityHeadless. */
const LvglInit lvglInit = LvglInit::Default;
/** Display HAL functionality. */
const CreateDisplay _Nullable createDisplay = nullptr;
/** Keyboard HAL functionality. */
const CreateKeyboard _Nullable createKeyboard = nullptr;
/** An optional SD card interface. */
const std::shared_ptr<sdcard::SdCardDevice> _Nullable sdcard = nullptr;
/** An optional power interface for battery or other power delivery. */
const CreatePower _Nullable power = nullptr;
/** A list of I2C interface configurations */
const std::vector<i2c::Configuration> i2c = {};
/** A list of SPI interface configurations */
const std::vector<spi::Configuration> spi = {};
/** A list of UART interface configurations */
const std::vector<uart::Configuration> uart = {};
};
} // namespace
+110
View File
@@ -0,0 +1,110 @@
#pragma once
#include <functional>
#include <memory>
#include <ranges>
#include <string>
#include <vector>
#include <cassert>
namespace tt::hal {
/** Base class for HAL-related devices. */
class Device {
public:
enum class Type {
I2c,
Display,
Touch,
SdCard,
Keyboard,
Power,
Gps
};
typedef uint32_t Id;
private:
Id id;
public:
Device();
virtual ~Device() = default;
/** Unique identifier */
inline Id getId() const { return id; }
/** The type of device */
virtual Type getType() const = 0;
/** The part number or hardware name e.g. TdeckTouch, TdeckDisplay, BQ24295, etc. */
virtual std::string getName() const = 0;
/** A short description of what this device does.
* e.g. "USB charging controller with I2C interface."
*/
virtual std::string getDescription() const = 0;
};
/**
* Adds a device to the registry.
* @warning This will leak memory if you want to destroy a device and don't call deregisterDevice()!
*/
void registerDevice(const std::shared_ptr<Device>& device);
/** Remove a device from the registry. */
void deregisterDevice(const std::shared_ptr<Device>& device);
/** Find a single device with a custom filter */
std::shared_ptr<Device> _Nullable findDevice(const std::function<bool(const std::shared_ptr<Device>&)>& filterFunction);
/** Find devices with a custom filter */
std::vector<std::shared_ptr<Device>> findDevices(const std::function<bool(const std::shared_ptr<Device>&)>& filterFunction);
/** Find a device in the registry by its name. */
std::shared_ptr<Device> _Nullable findDevice(std::string name);
/** Find a device in the registry by its identifier. */
std::shared_ptr<Device> _Nullable findDevice(Device::Id id);
/** Find 0, 1 or more devices in the registry by type. */
std::vector<std::shared_ptr<Device>> findDevices(Device::Type type);
/** Get a copy of the entire device registry in its current state. */
std::vector<std::shared_ptr<Device>> getDevices();
/** Find devices of a certain type and cast them to the specified class */
template<class DeviceType>
std::vector<std::shared_ptr<DeviceType>> findDevices(Device::Type type) {
auto devices = findDevices(type);
if (devices.empty()) {
return {};
} else {
std::vector<std::shared_ptr<DeviceType>> result;
result.reserve(devices.size());
for (auto& device : devices) {
auto target_device = std::static_pointer_cast<DeviceType>(device);
assert(target_device != nullptr);
result.push_back(target_device);
}
return std::move(result);
}
}
/** Find the first device of the specified type and cast it to the specified class */
template<class DeviceType>
std::shared_ptr<DeviceType> findFirstDevice(Device::Type type) {
auto devices = findDevices(type);
if (devices.empty()) {
return {};
} else {
auto& first = devices[0];
return std::static_pointer_cast<DeviceType>(first);
}
}
}
+7
View File
@@ -0,0 +1,7 @@
#pragma once
#ifdef ESP_PLATFORM
#include <driver/gpio.h>
#else
typedef unsigned int gpio_num_t;
#endif
@@ -0,0 +1,40 @@
#pragma once
#include "../Device.h"
#include <lvgl.h>
namespace tt::hal::touch {
class TouchDevice;
}
namespace tt::hal::display {
class DisplayDevice : public Device {
public:
Type getType() const override { return Type::Display; }
virtual bool start() = 0;
virtual bool stop() = 0;
virtual void setPowerOn(bool turnOn) {}
virtual bool isPoweredOn() const { return true; }
virtual bool supportsPowerControl() const { return false; }
virtual std::shared_ptr<touch::TouchDevice> _Nullable createTouch() = 0;
/** Set a value in the range [0, 255] */
virtual void setBacklightDuty(uint8_t backlightDuty) { /* NO-OP */ }
virtual bool supportsBacklightDuty() const { return false; }
/** Set a value in the range [0, 255] */
virtual void setGammaCurve(uint8_t index) { /* NO-OP */ }
virtual uint8_t getGammaCurveCount() const { return 0; };
/** After start() returns true, this should return a valid pointer until stop() is called and returns true */
virtual lv_display_t* _Nullable getLvglDisplay() const = 0;
};
} // namespace tt::hal::display
@@ -0,0 +1,36 @@
#pragma once
#include <cstdint>
#include <vector>
#include <string>
namespace tt::hal::gps {
enum class GpsModel {
Unknown = 0,
AG3335,
AG3352,
ATGM336H, // Casic (might work with AT6558, Neoway N58 LTE Cat.1, Neoway G2, Neoway G7A)
LS20031,
MTK,
MTK_L76B,
MTK_PA1616S,
UBLOX6,
UBLOX7,
UBLOX8,
UBLOX9,
UBLOX10,
UC6580,
};
const char* toString(GpsModel model);
std::vector<std::string> getModels();
struct GpsConfiguration {
char uartName[32]; // e.g. "Internal" or "/dev/ttyUSB0"
uint32_t baudRate;
GpsModel model; // Choosing "Unknown" will result in a probe
};
}
@@ -0,0 +1,125 @@
#pragma once
#include "../Device.h"
#include "GpsConfiguration.h"
#include "Satellites.h"
#include <Tactility/Mutex.h>
#include <Tactility/Thread.h>
#include <minmea.h>
#include <utility>
namespace tt::hal::gps {
enum class GpsResponse {
None,
NotAck,
FrameErrors,
Ok,
};
class GpsDevice : public Device {
public:
typedef int GgaSubscriptionId;
typedef int RmcSubscriptionId;
enum class State {
PendingOn,
On,
Error,
PendingOff,
Off
};
private:
struct GgaSubscription {
GgaSubscriptionId id;
std::shared_ptr<std::function<void(Device::Id id, const minmea_sentence_gga&)>> onData;
};
struct RmcSubscription {
RmcSubscriptionId id;
std::shared_ptr<std::function<void(Device::Id id, const minmea_sentence_rmc&)>> onData;
};
const GpsConfiguration configuration;
Mutex mutex = Mutex(Mutex::Type::Recursive);
std::unique_ptr<Thread> _Nullable thread;
bool threadInterrupted = false;
std::vector<GgaSubscription> ggaSubscriptions;
std::vector<RmcSubscription> rmcSubscriptions;
GgaSubscriptionId lastSatelliteSubscriptionId = 0;
RmcSubscriptionId lastRmcSubscriptionId = 0;
GpsModel model = GpsModel::Unknown;
State state = State::Off;
static int32_t threadMainStatic(void* parameter);
int32_t threadMain();
bool isThreadInterrupted() const;
void setState(State newState);
public:
explicit GpsDevice(GpsConfiguration configuration) : configuration(std::move(configuration)) {}
~GpsDevice() override = default;
Type getType() const override { return Type::Gps; }
std::string getName() const override {
if (model != GpsModel::Unknown) {
return toString(model);
} else {
return "Unknown GPS";
}
}
std::string getDescription() const override { return ""; }
bool start();
bool stop();
GgaSubscriptionId subscribeGga(const std::function<void(Device::Id deviceId, const minmea_sentence_gga&)>& onData) {
auto lock = mutex.asScopedLock();
lock.lock();
ggaSubscriptions.push_back({
.id = ++lastSatelliteSubscriptionId,
.onData = std::make_shared<std::function<void(Device::Id, const minmea_sentence_gga&)>>(onData)
});
return lastSatelliteSubscriptionId;
}
void unsubscribeGga(GgaSubscriptionId subscriptionId) {
auto lock = mutex.asScopedLock();
lock.lock();
std::erase_if(ggaSubscriptions, [subscriptionId](auto& subscription) { return subscription.id == subscriptionId; });
}
RmcSubscriptionId subscribeRmc(const std::function<void(Device::Id deviceId, const minmea_sentence_rmc&)>& onData) {
auto lock = mutex.asScopedLock();
lock.lock();
rmcSubscriptions.push_back({
.id = ++lastRmcSubscriptionId,
.onData = std::make_shared<std::function<void(Device::Id, const minmea_sentence_rmc&)>>(onData)
});
return lastRmcSubscriptionId;
}
void unsubscribeRmc(GgaSubscriptionId subscriptionId) {
auto lock = mutex.asScopedLock();
lock.lock();
std::erase_if(rmcSubscriptions, [subscriptionId](auto& subscription) { return subscription.id == subscriptionId; });
}
GpsModel getModel() const;
State getState() const;
};
}
@@ -0,0 +1,59 @@
#pragma once
#include <Tactility/RtosCompat.h>
#include <Tactility/Mutex.h>
#include <minmea.h>
#include <ranges>
#include <memory>
namespace tt::hal::gps {
/** Thread-safe storage of recent satellites */
class SatelliteStorage {
public:
static constexpr size_t recordCount = 32;
private:
struct SatelliteRecord {
minmea_sat_info data {
.nr = 0,
.elevation = 0,
.azimuth = 0,
.snr = 0
};
TickType_t lastUpdated = 0;
bool inUse = false;
};
Mutex mutex = Mutex(Mutex::Type::Recursive);
std::array<SatelliteRecord, recordCount> records;
uint16_t recycleTimeSeconds;
uint16_t recentTimeSeconds;
SatelliteRecord* findRecord(int number);
SatelliteRecord* findUnusedRecord();
SatelliteRecord* findRecordToRecycle();
/** Tries to find an existing record, otherwise return a free one, otherwise return the oldest active one */
SatelliteRecord* findWithFallback(int number);
public:
explicit SatelliteStorage(
uint16_t recycleTimeSeconds = 120,
uint16_t recentTimeSeconds = 60
) : recycleTimeSeconds(recycleTimeSeconds), recentTimeSeconds(recentTimeSeconds) {}
void notify(const minmea_sat_info& info);
void getRecords(const std::function<void(const minmea_sat_info&)>& onRecord) const;
};
} // namespace tt::hal::gps
+94
View File
@@ -0,0 +1,94 @@
#pragma once
#include "./I2cCompat.h"
#include "Tactility/Lock.h"
#include <Tactility/RtosCompat.h>
#include <climits>
#include <string>
namespace tt::hal::i2c {
constexpr TickType_t defaultTimeout = 10 / portTICK_PERIOD_MS;
enum class InitMode {
ByTactility, // Tactility will initialize it in the correct bootup phase
ByExternal, // The device is already initialized and Tactility should assume it works
Disabled // Not initialized by default
};
struct Configuration {
std::string name;
/** The port to operate on */
i2c_port_t port;
/** Whether this bus should be initialized when device starts up */
InitMode initMode;
/**
* Whether this bus can be changed after booting.
* If the bus is internal and/or used for core features like touch screen, then it can be declared static.
*/
bool isMutable;
/** Configuration that must be valid when initAtBoot is set to true. */
i2c_config_t config;
};
enum class Status {
Started,
Stopped,
Unknown
};
/**
* Reconfigure a port with the provided settings.
* @warning This fails when the HAL Configuration is not mutable.
* @param[in] port the port to reconfigure
* @param[in] configuration the new configuration
* @return true on success
*/
bool configure(i2c_port_t port, const i2c_config_t& configuration);
/**
* Start the bus for the specified port.
* Devices might be started automatically at boot if their HAL configuration requires it.
*/
bool start(i2c_port_t port);
/** Stop the bus for the specified port. */
bool stop(i2c_port_t port);
/** @return true if the bus is started */
bool isStarted(i2c_port_t port);
/** Read bytes in master mode. */
bool masterRead(i2c_port_t port, uint8_t address, uint8_t* data, size_t dataSize, TickType_t timeout = defaultTimeout);
/** Read bytes from the specified register in master mode. */
bool masterReadRegister(i2c_port_t port, uint8_t address, uint8_t reg, uint8_t* data, size_t dataSize, TickType_t timeout = defaultTimeout);
/** Write bytes in master mode. */
bool masterWrite(i2c_port_t port, uint8_t address, const uint8_t* data, uint16_t dataSize, TickType_t timeout = defaultTimeout);
/** Write bytes to a register in master mode */
bool masterWriteRegister(i2c_port_t port, uint8_t address, uint8_t reg, const uint8_t* data, uint16_t dataSize, TickType_t timeout = defaultTimeout);
/**
* Write multiple values to multiple registers in master mode.
* The input is as follows: { register1, value1, register2, value2, ... }
* @return false if any of the write operations failed
*/
bool masterWriteRegisterArray(i2c_port_t port, uint8_t address, const uint8_t* data, uint16_t dataSize, TickType_t timeout = defaultTimeout);
/** Write bytes and then read the response bytes in master mode*/
bool masterWriteRead(i2c_port_t port, uint8_t address, const uint8_t* writeData, size_t writeDataSize, uint8_t* readData, size_t readDataSize, TickType_t timeout = defaultTimeout);
/** @return true when a device is detected at the specified address */
bool masterHasDeviceAtAddress(i2c_port_t port, uint8_t address, TickType_t timeout = defaultTimeout);
/**
* The lock for the specified bus.
* This can be used when calling native I2C functionality outside of Tactility.
*/
Lock& getLock(i2c_port_t port);
} // namespace
@@ -0,0 +1,38 @@
#pragma once
#ifdef ESP_PLATFORM
#include <hal/i2c_types.h>
#include <driver/i2c.h>
#else
#include <cstdint>
enum i2c_port_t {
I2C_NUM_0 = 0,
I2C_NUM_1,
LP_I2C_NUM_0,
I2C_NUM_MAX,
};
enum i2c_mode_t {
I2C_MODE_MASTER,
I2C_MODE_MAX,
};
struct i2c_config_t {
i2c_mode_t mode;
int sda_io_num;
int scl_io_num;
bool sda_pullup_en;
bool scl_pullup_en;
union {
struct {
uint32_t clk_speed;
} master;
};
uint32_t clk_flags;
};
#endif
@@ -0,0 +1,44 @@
#pragma once
#include "I2c.h"
#include "../Device.h"
namespace tt::hal::i2c {
/**
* Represents an I2C peripheral at a specific port and address.
* It helps to read and write registers.
*
* All read and write calls are thread-safe.
*/
class I2cDevice : public Device {
protected:
i2c_port_t port;
uint8_t address;
static constexpr TickType_t DEFAULT_TIMEOUT = 1000 / portTICK_PERIOD_MS;
bool readRegister8(uint8_t reg, uint8_t& result) const;
bool writeRegister8(uint8_t reg, uint8_t value) const;
bool readRegister12(uint8_t reg, float& out) const;
bool readRegister14(uint8_t reg, float& out) const;
bool readRegister16(uint8_t reg, uint16_t& out) const;
bool bitOn(uint8_t reg, uint8_t bitmask) const;
bool bitOff(uint8_t reg, uint8_t bitmask) const;
bool bitOnByIndex(uint8_t reg, uint8_t index) const { return bitOn(reg, 1 << index); }
bool bitOffByIndex(uint8_t reg, uint8_t index) const { return bitOff(reg, 1 << index); }
public:
explicit I2cDevice(i2c_port_t port, uint32_t address) : port(port), address(address) {}
Type getType() const override { return Type::I2c; }
i2c_port_t getPort() const { return port; }
uint8_t getAddress() const { return address; }
};
}
@@ -0,0 +1,24 @@
#pragma once
#include "../Device.h"
#include <lvgl.h>
namespace tt::hal::keyboard {
class Display;
class KeyboardDevice : public Device {
public:
Type getType() const override { return Type::Keyboard; }
virtual bool start(lv_display_t* display) = 0;
virtual bool stop() = 0;
virtual bool isAttached() const = 0;
virtual lv_indev_t* _Nullable getLvglIndev() = 0;
};
}
@@ -0,0 +1,44 @@
#pragma once
#include "../Device.h"
#include <cstdint>
namespace tt::hal::power {
class PowerDevice : public Device {
public:
PowerDevice() = default;
~PowerDevice() override = default;
Type getType() const override { return Type::Power; }
enum class MetricType {
IsCharging, // bool
Current, // int32_t, mAh - battery current: either during charging (positive value) or discharging (negative value)
BatteryVoltage, // uint32_t, mV
ChargeLevel, // uint8_t [0, 100]
};
union MetricData {
int32_t valueAsInt32 = 0;
uint32_t valueAsUint32;
uint8_t valueAsUint8;
float valueAsFloat;
bool valueAsBool;
};
virtual bool supportsMetric(MetricType type) const = 0;
/**
* @return false when metric is not supported or (temporarily) not available.
*/
virtual bool getMetric(MetricType type, MetricData& data) = 0;
virtual bool supportsChargeControl() const { return false; }
virtual bool isAllowedToCharge() const { return false; }
virtual void setAllowedToCharge(bool canCharge) { /* NO-OP*/ }
};
} // namespace tt
@@ -0,0 +1,66 @@
#pragma once
#include "../Device.h"
#include <Tactility/TactilityCore.h>
namespace tt::hal::sdcard {
class SdCardDevice : public Device {
public:
enum class State {
Mounted,
Unmounted,
Error,
Unknown
};
enum class MountBehaviour {
AtBoot, /** Only mount at boot */
Anytime /** Mount/dismount any time */
};
private:
MountBehaviour mountBehaviour;
public:
explicit SdCardDevice(MountBehaviour mountBehaviour) : mountBehaviour(mountBehaviour) {}
~SdCardDevice() override = default;
Type getType() const final { return Type::SdCard; };
virtual bool mount(const std::string& mountPath) = 0;
virtual bool unmount() = 0;
virtual State getState() const = 0;
/** Return empty string when not mounted or the mount path if mounted */
virtual std::string getMountPath() const = 0;
virtual Lock& getLock() const = 0;
virtual MountBehaviour getMountBehaviour() const { return mountBehaviour; }
bool isMounted() const { return getState() == State::Mounted; }
};
/** Return the SdCard device if the path is within the SdCard mounted path (path std::string::starts_with() check)*/
std::shared_ptr<SdCardDevice> _Nullable find(const std::string& path);
/**
* Acquires an SD card lock if the path is an SD card path.
* Always calls the function, but doesn't lock if the path is not an SD card path.
*/
template<typename ReturnType>
inline ReturnType withSdCardLock(const std::string& path, std::function<ReturnType()> fn) {
auto sdcard = find(path);
if (sdcard != nullptr) {
auto scoped_lockable = sdcard->getLock().asScopedLock();
scoped_lockable.lock(portMAX_DELAY);
}
return fn();
}
} // namespace tt::hal
@@ -0,0 +1,99 @@
#ifdef ESP_PLATFORM
#pragma once
#include "SdCardDevice.h"
#include <Tactility/hal/spi/Spi.h>
#include <sd_protocol_types.h>
#include <utility>
#include <vector>
#include <hal/spi_types.h>
#include <soc/gpio_num.h>
namespace tt::hal::sdcard {
/**
* SD card interface at the default SPI interface
*/
class SpiSdCardDevice final : public SdCardDevice {
public:
struct Config {
Config(
gpio_num_t spiPinCs,
gpio_num_t spiPinCd,
gpio_num_t spiPinWp,
gpio_num_t spiPinInt,
MountBehaviour mountBehaviourAtBoot,
/** When custom lock is nullptr, use the SPI default one */
std::shared_ptr<Lock> _Nullable customLock = nullptr,
std::vector<gpio_num_t> csPinWorkAround = std::vector<gpio_num_t>(),
spi_host_device_t spiHost = SPI2_HOST,
int spiFrequencyKhz = SDMMC_FREQ_DEFAULT
) : spiFrequencyKhz(spiFrequencyKhz),
spiPinCs(spiPinCs),
spiPinCd(spiPinCd),
spiPinWp(spiPinWp),
spiPinInt(spiPinInt),
mountBehaviourAtBoot(mountBehaviourAtBoot),
customLock(customLock ? std::move(customLock) : nullptr),
csPinWorkAround(std::move(csPinWorkAround)),
spiHost(spiHost)
{}
int spiFrequencyKhz;
gpio_num_t spiPinCs; // Clock
gpio_num_t spiPinCd; // Card detect
gpio_num_t spiPinWp; // Write-protect
gpio_num_t spiPinInt; // Interrupt
SdCardDevice::MountBehaviour mountBehaviourAtBoot;
std::shared_ptr<Lock> _Nullable customLock;
std::vector<gpio_num_t> csPinWorkAround;
spi_host_device_t spiHost;
bool formatOnMountFailed = false;
uint16_t maxOpenFiles = 4;
uint16_t allocUnitSize = 16 * 1024;
bool statusCheckEnabled = false;
};
private:
std::string mountPath;
sdmmc_card_t* card = nullptr;
std::shared_ptr<Config> config;
bool applyGpioWorkAround();
bool mountInternal(const std::string& mountPath);
public:
explicit SpiSdCardDevice(std::unique_ptr<Config> config) : SdCardDevice(config->mountBehaviourAtBoot),
config(std::move(config))
{}
std::string getName() const final { return "SD Card"; }
std::string getDescription() const final { return "SD card via SPI interface"; }
bool mount(const std::string& mountPath) final;
bool unmount() final;
std::string getMountPath() const final { return mountPath; }
Lock& getLock() const final {
if (config->customLock) {
return *config->customLock;
} else {
return *spi::getLock(config->spiHost);
}
}
State getState() const override;
sdmmc_card_t* _Nullable getCard() { return card; }
};
}
#endif
+48
View File
@@ -0,0 +1,48 @@
#pragma once
#include "SpiCompat.h"
#include <Tactility/Lock.h>
#include <Tactility/RtosCompat.h>
namespace tt::hal::spi {
constexpr TickType_t defaultTimeout = 10 / portTICK_PERIOD_MS;
enum class InitMode {
ByTactility, // Tactility will initialize it in the correct bootup phase
ByExternal, // The device is already initialized and Tactility should assume it works
Disabled // Not initialized by default
};
struct Configuration {
spi_host_device_t device;
spi_common_dma_t dma;
spi_bus_config_t config;
/** Whether this bus should be initialized when device starts up */
InitMode initMode;
/** Whether configuration can be changed. */
bool isMutable;
/** Optional custom lock */
std::shared_ptr<Lock> _Nullable lock;
};
enum class Status {
Started,
Stopped,
Unknown
};
/** Start communications */
bool start(spi_host_device_t device);
/** Stop communications */
bool stop(spi_host_device_t device);
/** @return true if communications were started successfully */
bool isStarted(spi_host_device_t device);
/** @return the lock that represents the specified device. Can be used with third party SPI implementations or native API calls (e.g. ESP-IDF). */
std::shared_ptr<Lock> getLock(spi_host_device_t device);
} // namespace tt::hal::spi
@@ -0,0 +1,19 @@
#pragma once
#include "../Gpio.h"
#ifdef ESP_PLATFORM
#include <driver/spi_common.h>
#else
#define SPI_HOST_MAX 3
typedef int spi_host_device_t;
struct spi_bus_config_t {
gpio_num_t miso_io_num;
gpio_num_t mosi_io_num;
gpio_num_t sclk_io_num;
};
struct spi_common_dma_t {};
#endif
@@ -0,0 +1,23 @@
#pragma once
#include "../Device.h"
#include <lvgl.h>
namespace tt::hal::touch {
class Display;
class TouchDevice : public Device {
public:
Type getType() const override { return Type::Touch; }
virtual bool start(lv_display_t* display) = 0;
virtual bool stop() = 0;
virtual lv_indev_t* _Nullable getLvglIndev() = 0;
};
}
@@ -0,0 +1,40 @@
#pragma once
namespace tt::hal::uart {
#ifdef ESP_PLATFORM
struct Configuration {
/** The unique name for this UART */
std::string name;
/** The port idenitifier (e.g. UART_NUM_0) */
uart_port_t port;
/** Receive GPIO pin */
gpio_num_t rxPin;
/** Transmit GPIO pin */
gpio_num_t txPin;
/** Read-To-Send GPIO pin */
gpio_num_t rtsPin;
/** Clear-To-Send Send GPIO pin */
gpio_num_t ctsPin;
/** Receive buffer size in bytes */
unsigned int rxBufferSize;
/** Transmit buffer size in bytes */
unsigned int txBufferSize;
/** Native configuration */
uart_config_t config;
};
#else
struct Configuration {
/** The unique name for this UART */
std::string name;
/** Initial baud rate in bits per second */
uint32_t baudRate;
};
#endif
}
+126
View File
@@ -0,0 +1,126 @@
#pragma once
#include <Tactility/RtosCompat.h>
#include "../Gpio.h"
#include "Tactility/Lock.h"
#include "UartCompat.h"
#include "Tactility/hal/uart/Configuration.h"
#include <memory>
#include <vector>
namespace tt::hal::uart {
constexpr TickType_t defaultTimeout = 10 / portTICK_PERIOD_MS;
enum class InitMode {
ByTactility, // Tactility will initialize it in the correct bootup phase
ByExternal, // The device is already initialized and Tactility should assume it works
Disabled // Not initialized by default
};
enum class Status {
Started,
Stopped,
Unknown
};
class Uart {
private:
uint32_t id;
public:
Uart();
virtual ~Uart();
inline uint32_t getId() const { return id; }
virtual bool start() = 0;
virtual bool isStarted() const = 0;
virtual bool stop() = 0;
/**
* Read up to a specified amount of bytes
* @param[out] buffer
* @param[in] bufferSize
* @param[in] timeout
* @return the amount of bytes that were read
*/
virtual size_t readBytes(std::byte* buffer, size_t bufferSize, TickType_t timeout = defaultTimeout) = 0;
size_t readBytes(std::uint8_t* buffer, size_t bufferSize, TickType_t timeout = defaultTimeout) {
return readBytes(reinterpret_cast<std::byte*>(buffer), bufferSize, timeout);
}
/** Read a single byte */
virtual bool readByte(std::byte* output, TickType_t timeout = defaultTimeout) = 0;
inline bool readByte(char* output, TickType_t timeout = defaultTimeout) {
return readByte(reinterpret_cast<std::byte*>(output), timeout);
}
inline bool readByte(uint8_t* output, TickType_t timeout = defaultTimeout) {
return readByte(reinterpret_cast<std::byte*>(output), timeout);
}
/**
* Read up to a specified amount of bytes
* @param[in] buffer
* @param[in] bufferSize
* @param[in] timeout
* @return the amount of bytes that were read
*/
virtual size_t writeBytes(const std::byte* buffer, size_t bufferSize, TickType_t timeout = defaultTimeout) = 0;
inline size_t writeBytes(const std::uint8_t* buffer, size_t bufferSize, TickType_t timeout = defaultTimeout) {
return writeBytes(reinterpret_cast<const std::byte*>(buffer), bufferSize, timeout);
}
/** @return the amount of bytes available for reading */
virtual size_t available(TickType_t timeout = defaultTimeout) = 0;
/** Set the baud rate for the specified port */
virtual bool setBaudRate(uint32_t baudRate, TickType_t timeout = defaultTimeout) = 0;
/** Get the baud rate for the specified port */
virtual uint32_t getBaudRate() = 0;
/** Flush input buffers */
virtual void flushInput() = 0;
/**
* Write a string (excluding null terminator character)
* @param[in] buffer
* @param[in] timeout
* @return the amount of bytes that were written
*/
bool writeString(const char* buffer, TickType_t timeout = defaultTimeout);
/**
* Read a buffer as a string until the specified character (the "untilChar" is included in the result)
* @warning if the input data doesn't return "untilByte" then the device goes out of memory
*/
std::string readStringUntil(char untilChar, TickType_t timeout = defaultTimeout);
/**
* Read a buffer as a byte array until the specified character (the "untilChar" is included in the result)
* @return the amount of bytes read from UART
*/
size_t readUntil(std::byte* buffer, size_t bufferSize, uint8_t untilByte, TickType_t timeout = defaultTimeout, bool addNullTerminator = true);
};
/**
* Opens a UART.
* @param[in] name the UART name as specified in the board configuration.
* @return the UART when it was successfully opened, or nullptr when it is in use.
*/
std::unique_ptr<Uart> open(std::string name);
std::vector<std::string> getNames();
} // namespace tt::hal::uart
@@ -0,0 +1,17 @@
#pragma once
#ifdef ESP_PLATFORM
#include <driver/uart.h>
#include <driver/gpio.h>
#include <hal/uart_types.h>
#else
#define UART_NUM_MAX 3
typedef int uart_port_t;
typedef struct {
} uart_config_t;
#endif
+21
View File
@@ -0,0 +1,21 @@
#pragma once
namespace tt::hal::usb {
enum class Mode {
Default, // Default state of USB stack
None, // State after TinyUSB was used and (partially) deinitialized
MassStorageSdmmc
};
bool startMassStorageWithSdmmc();
void stop();
Mode getMode();
bool isSupported();
bool canRebootIntoMassStorageSdmmc();
void rebootIntoMassStorageSdmmc();
bool isUsbBootMode();
void resetUsbBootMode();
}
@@ -0,0 +1,38 @@
#pragma once
#include <cstdint>
#include <functional>
namespace tt::kernel {
enum class SystemEvent {
BootInitHalBegin,
BootInitHalEnd,
BootInitI2cBegin,
BootInitI2cEnd,
BootInitSpiBegin,
BootInitSpiEnd,
BootInitUartBegin,
BootInitUartEnd,
BootInitLvglBegin,
BootInitLvglEnd,
BootSplash,
/** Gained IP address */
NetworkConnected,
NetworkDisconnected,
/** An important system time-related event, such as NTP update or time-zone change */
Time,
};
/** Value 0 mean "no subscription" */
typedef uint32_t SystemEventSubscription;
typedef std::function<void(SystemEvent)> OnSystemEvent;
void systemEventPublish(SystemEvent event);
SystemEventSubscription systemEventAddListener(SystemEvent event, OnSystemEvent handler);
void systemEventRemoveListener(SystemEventSubscription subscription);
}
@@ -0,0 +1,24 @@
#pragma once
#include <memory>
namespace tt::service {
// Forward declaration
class ServiceContext;
class Service {
public:
Service() = default;
virtual ~Service() = default;
virtual void onStart(ServiceContext& serviceContext) {}
virtual void onStop(ServiceContext& serviceContext) {}
};
template<typename T>
std::shared_ptr<Service> create() { return std::shared_ptr<T>(new T); }
}
@@ -0,0 +1,93 @@
#pragma once
#include "ServiceManifest.h"
#include <Tactility/Mutex.h>
#include <memory>
namespace tt::service {
class Paths;
/**
* The public representation of a service instance.
* @warning Do not store references or pointers to these! You can retrieve them via the Loader service.
*/
class ServiceContext {
protected:
virtual ~ServiceContext() = default;
public:
/** @return a reference ot the service's manifest */
virtual const service::ServiceManifest& getManifest() const = 0;
/** Retrieve the paths that are relevant to this service */
virtual std::unique_ptr<Paths> getPaths() const = 0;
};
class Paths {
public:
Paths() = default;
virtual ~Paths() = default;
/**
* Returns the directory path for the data location for a service.
* The data directory is intended to survive OS upgrades.
* The path will not end with a "/".
*/
virtual std::string getDataDirectory() const = 0;
/**
* @see getDataDirectory(), but with LVGL prefix.
*/
virtual std::string getDataDirectoryLvgl() const = 0;
/**
* Returns the full path for an entry inside the data location for a service.
* The data directory is intended to survive OS upgrades.
* Configuration data should be stored here.
* @param[in] childPath the path without a "/" prefix
*/
virtual std::string getDataPath(const std::string& childPath) const = 0;
/**
* @see getDataPath(), but with LVGL prefix.
*/
virtual std::string getDataPathLvgl(const std::string& childPath) const = 0;
/**
* Returns the directory path for the system location for a service.
* The system directory is not intended to survive OS upgrades.
* You should not store configuration data here.
* The path will not end with a "/".
* This is mainly used for core services.
*/
virtual std::string getSystemDirectory() const = 0;
/**
* @see getSystemDirectory(), but with LVGL prefix.
*/
virtual std::string getSystemDirectoryLvgl() const = 0;
/**
* Returns the full path for an entry inside the system location for an app.
* The data directory is not intended to survive OS upgrades.
* You should not store configuration data here.
* This is mainly used for core apps (system/boot/settings type).
* @param[in] childPath the path without a "/" prefix
*/
virtual std::string getSystemPath(const std::string& childPath) const = 0;
/**
* @see getSystemPath(), but with LVGL prefix.
*/
virtual std::string getSystemPathLvgl(const std::string& childPath) const = 0;
};
} // namespace
@@ -0,0 +1,23 @@
#pragma once
#include "Tactility/service/Service.h"
#include <string>
namespace tt::service {
// Forward declarations
class ServiceContext;
typedef std::shared_ptr<Service>(*CreateService)();
/** A ledger that describes the main parts of a service. */
struct ServiceManifest {
/** The identifier by which the app is launched by the system and other apps. */
std::string id {};
/** Create the instance of the app */
CreateService createService = nullptr;
};
} // namespace
@@ -0,0 +1,59 @@
#pragma once
#include "ServiceManifest.h"
#include "Service.h"
#include <memory>
namespace tt::service {
/** Register a service.
* @param[in] the service manifest
*/
void addService(std::shared_ptr<const ServiceManifest> manifest, bool autoStart = true);
/** Register a service.
* @param[in] the service manifest
*/
void addService(const ServiceManifest& manifest, bool autoStart = true);
/** Start a service.
* @param[in] the service id as defined in its manifest
* @return true on success
*/
bool startService(const std::string& id);
/** Stop a service.
* @param[in] the service id as defined in its manifest
* @return true on success or false when service wasn't running.
*/
bool stopService(const std::string& id);
/** Find a service manifest by its id.
* @param[in] id the id as defined in the manifest
* @return the matching manifest or nullptr when it wasn't found
*/
std::shared_ptr<const ServiceManifest> _Nullable findManifestId(const std::string& id);
/** Find a ServiceContext by its manifest id.
* @param[in] id the id as defined in the manifest
* @return the service context or nullptr when it wasn't found
*/
std::shared_ptr<ServiceContext> _Nullable findServiceContextById(const std::string& id);
/** Find a Service by its manifest id.
* @param[in] id the id as defined in the manifest
* @return the service context or nullptr when it wasn't found
*/
std::shared_ptr<Service> _Nullable findServiceById(const std::string& id);
/** Find a Service by its manifest id.
* @param[in] id the id as defined in the manifest
* @return the service context or nullptr when it wasn't found
*/
template <typename T>
std::shared_ptr<T> _Nullable findServiceById(const std::string& id) {
return std::static_pointer_cast<T>(findServiceById(id));
}
} // namespace
@@ -0,0 +1,54 @@
#pragma once
#ifdef ESP_PLATFORM
#include <cstdint>
#include <cstring>
#include <esp_now.h>
#include <functional>
namespace tt::service::espnow {
typedef int ReceiverSubscription;
constexpr ReceiverSubscription NO_SUBSCRIPTION = -1;
enum class Mode {
Station,
AccessPoint
};
struct EspNowConfig {
uint8_t masterKey[ESP_NOW_KEY_LEN];
uint8_t address[ESP_NOW_ETH_ALEN];
Mode mode;
uint8_t channel;
bool longRange;
bool encrypt;
EspNowConfig(
uint8_t masterKey[16],
Mode mode,
uint8_t channel,
bool longRange,
bool encrypt
) : mode(mode), channel(channel), longRange(longRange), encrypt(encrypt) {
memcpy((void*)this->masterKey, (void*)masterKey, 16);
}
};
void enable(const EspNowConfig& config);
void disable();
bool isEnabled();
bool addPeer(const esp_now_peer_info_t& peer);
bool send(const uint8_t* address, const uint8_t* buffer, size_t bufferLength);
ReceiverSubscription subscribeReceiver(std::function<void(const esp_now_recv_info_t* receiveInfo, const uint8_t* data, int length)> onReceive);
void unsubscribeReceiver(ReceiverSubscription subscription);
}
#endif // ESP_PLATFORM
@@ -0,0 +1,69 @@
#pragma once
#include "Tactility/Mutex.h"
#include "Tactility/PubSub.h"
#include "Tactility/hal/gps/GpsDevice.h"
#include "Tactility/service/Service.h"
#include "Tactility/service/ServiceContext.h"
#include "Tactility/service/gps/GpsState.h"
namespace tt::service::gps {
class GpsService final : public Service {
private:
struct GpsDeviceRecord {
std::shared_ptr<hal::gps::GpsDevice> device = nullptr;
hal::gps::GpsDevice::GgaSubscriptionId satelliteSubscriptionId = -1;
hal::gps::GpsDevice::RmcSubscriptionId rmcSubscriptionId = -1;
};
minmea_sentence_rmc rmcRecord;
TickType_t rmcTime = 0;
Mutex mutex = Mutex(Mutex::Type::Recursive);
Mutex stateMutex;
std::vector<GpsDeviceRecord> deviceRecords;
std::shared_ptr<PubSub> statePubSub = std::make_shared<PubSub>();
std::unique_ptr<Paths> paths;
State state = State::Off;
bool startGpsDevice(GpsDeviceRecord& deviceRecord);
static bool stopGpsDevice(GpsDeviceRecord& deviceRecord);
GpsDeviceRecord* _Nullable findGpsRecord(const std::shared_ptr<hal::gps::GpsDevice>& record);
void onGgaSentence(hal::Device::Id deviceId, const minmea_sentence_gga& gga);
void onRmcSentence(hal::Device::Id deviceId, const minmea_sentence_rmc& rmc);
void setState(State newState);
void addGpsDevice(const std::shared_ptr<hal::gps::GpsDevice>& device);
void removeGpsDevice(const std::shared_ptr<hal::gps::GpsDevice>& device);
bool getConfigurationFilePath(std::string& output) const;
public:
void onStart(tt::service::ServiceContext &serviceContext) final;
void onStop(tt::service::ServiceContext &serviceContext) final;
bool addGpsConfiguration(hal::gps::GpsConfiguration configuration);
bool removeGpsConfiguration(hal::gps::GpsConfiguration configuration);
bool getGpsConfigurations(std::vector<hal::gps::GpsConfiguration>& configurations) const;
bool startReceiving();
void stopReceiving();
State getState() const;
bool hasCoordinates() const;
bool getCoordinates(minmea_sentence_rmc& rmc) const;
/** @return GPS service pubsub that broadcasts State* objects */
std::shared_ptr<PubSub> getStatePubsub() const { return statePubSub; }
};
std::shared_ptr<GpsService> findGpsService();
} // tt::service::gps
@@ -0,0 +1,12 @@
#pragma once
namespace tt::service::gps {
enum class State {
OnPending,
On,
OffPending,
Off
};
}
@@ -0,0 +1,10 @@
#pragma once
#include <minmea.h>
namespace tt::hal::gps {
/** @return true when the input float is valid (contains non-zero values) */
inline bool isValid(const minmea_float& inFloat) { return inFloat.value != 0 && inFloat.scale != 0; }
}
@@ -0,0 +1,133 @@
#pragma once
#include "./WifiGlobals.h"
#include "./WifiSettings.h"
#include <Tactility/PubSub.h>
#include <cstdio>
#include <string>
#include <vector>
#ifdef ESP_PLATFORM
#include "esp_wifi.h"
#include "WifiSettings.h"
#else
#include <cstdint>
// From esp_wifi_types.h in ESP-IDF 5.2
typedef enum {
WIFI_AUTH_OPEN = 0, /**< authenticate mode : open */
WIFI_AUTH_WEP, /**< authenticate mode : WEP */
WIFI_AUTH_WPA_PSK, /**< authenticate mode : WPA_PSK */
WIFI_AUTH_WPA2_PSK, /**< authenticate mode : WPA2_PSK */
WIFI_AUTH_WPA_WPA2_PSK, /**< authenticate mode : WPA_WPA2_PSK */
WIFI_AUTH_ENTERPRISE, /**< authenticate mode : WiFi EAP security */
WIFI_AUTH_WPA2_ENTERPRISE = WIFI_AUTH_ENTERPRISE, /**< authenticate mode : WiFi EAP security */
WIFI_AUTH_WPA3_PSK, /**< authenticate mode : WPA3_PSK */
WIFI_AUTH_WPA2_WPA3_PSK, /**< authenticate mode : WPA2_WPA3_PSK */
WIFI_AUTH_WAPI_PSK, /**< authenticate mode : WAPI_PSK */
WIFI_AUTH_OWE, /**< authenticate mode : OWE */
WIFI_AUTH_WPA3_ENT_192, /**< authenticate mode : WPA3_ENT_SUITE_B_192_BIT */
WIFI_AUTH_WPA3_EXT_PSK, /**< authenticate mode : WPA3_PSK_EXT_KEY */
WIFI_AUTH_WPA3_EXT_PSK_MIXED_MODE, /**< authenticate mode: WPA3_PSK + WPA3_PSK_EXT_KEY */
WIFI_AUTH_MAX
} wifi_auth_mode_t;
#endif
namespace tt::service::wifi {
enum class EventType {
/** Radio was turned on */
RadioStateOn,
/** Radio is turning on. */
RadioStateOnPending,
/** Radio is turned off */
RadioStateOff,
/** Radio is turning off */
RadioStateOffPending,
/** Started scanning for access points */
ScanStarted,
/** Finished scanning for access points */ // TODO: 1 second validity
ScanFinished,
Disconnected,
ConnectionPending,
ConnectionSuccess,
ConnectionFailed
};
enum class RadioState {
OnPending,
On,
ConnectionPending,
ConnectionActive,
OffPending,
Off,
};
struct Event {
EventType type;
};
struct ApRecord {
std::string ssid;
int8_t rssi;
int32_t channel;
wifi_auth_mode_t auth_mode;
};
/**
* @brief Get wifi pubsub that broadcasts Event objects
* @return PubSub
*/
std::shared_ptr<PubSub> getPubsub();
/** @return Get the current radio state */
RadioState getRadioState();
/** For logging purposes */
const char* radioStateToString(RadioState state);
/**
* @brief Request scanning update. Returns immediately. Results are through pubsub.
*/
void scan();
/** @return true if wifi is actively scanning */
bool isScanning();
/** @return true the ssid name or empty string */
std::string getConnectionTarget();
/** @return the access points from the last scan (if any). It only contains public APs. */
std::vector<ApRecord> getScanResults();
/**
* @brief Overrides the default scan result size of 16.
* @param[in] records the record limit for the scan result (84 bytes per record!)
*/
void setScanRecords(uint16_t records);
/**
* @brief Enable/disable the radio. Ignores input if desired state matches current state.
* @param[in] enabled
*/
void setEnabled(bool enabled);
/**
* @brief Connect to a network. Disconnects any existing connection.
* Returns immediately but runs in the background. Results are through pubsub.
* @param[in] ap
* @param[in] remember whether to save the ap data to the settings upon successful connection
*/
void connect(const settings::WifiApSettings* ap, bool remember);
/** @brief Disconnect from the access point. Doesn't have any effect when not connected. */
void disconnect();
/** @return true if the connection isn't unencrypted. */
bool isConnectionSecure();
/** @return the RSSI value (negative number) or return 1 when not connected. */
int getRssi();
} // namespace
@@ -0,0 +1,8 @@
#pragma once
#define TT_WIFI_AUTO_CONNECT true // Default setting for new Wi-Fi entries
#define TT_WIFI_SCAN_RECORD_LIMIT 16 // default, can be overridden
#define TT_WIFI_SSID_LIMIT 32 // 32 characters/octets, according to IEEE 802.11-2020 spec
#define TT_WIFI_CREDENTIALS_PASSWORD_LIMIT 64 // 64 characters/octets, according to IEEE 802.11-2020 spec
@@ -0,0 +1,33 @@
#pragma once
#include "WifiGlobals.h"
#include <cstdint>
namespace tt::service::wifi::settings {
/**
* This struct is stored as-is into NVS flash.
*
* The SSID and secret are increased by 1 byte to facilitate string null termination.
* This makes it easier to use the char array as a string in various places.
*/
struct WifiApSettings {
char ssid[TT_WIFI_SSID_LIMIT + 1] = { 0 };
char password[TT_WIFI_CREDENTIALS_PASSWORD_LIMIT + 1] = { 0 };
int32_t channel = 0;
bool auto_connect = true;
};
bool contains(const char* ssid);
bool load(const char* ssid, WifiApSettings* settings);
bool save(const WifiApSettings* settings);
bool remove(const char* ssid);
void setEnableOnBoot(bool enable);
bool shouldEnableOnBoot();
} // namespace
+32
View File
@@ -0,0 +1,32 @@
#pragma once
#include <string>
namespace tt::time {
/**
* Set the timezone
* @param[in] name human-readable name
* @param[in] code the technical code (from timezones.csv)
*/
void setTimeZone(const std::string& name, const std::string& code);
/**
* Get the name of the timezone
*/
std::string getTimeZoneName();
/**
* Get the code of the timezone (see timezones.csv)
*/
std::string getTimeZoneCode();
/** @return true when clocks should be shown as a 24 hours one instead of 12 hours */
bool isTimeFormat24Hour();
/** Set whether clocks should be shown as a 24 hours instead of 12 hours
* @param[in] show24Hour
*/
void setTimeFormat24Hour(bool show24Hour);
}
+11
View File
@@ -0,0 +1,11 @@
#pragma once
#ifdef ESP_PLATFORM
namespace tt {
void initEsp();
} // namespace
#endif // ESP_PLATFORM
@@ -0,0 +1,13 @@
#pragma once
#ifdef ESP_PLATFORM
#include "esp_err.h"
namespace tt {
esp_err_t initPartitionsEsp();
} // namespace
#endif // ESP_PLATFORM
+9
View File
@@ -0,0 +1,9 @@
#pragma once
#include "Tactility/hal/Configuration.h"
namespace tt::hal {
void init(const Configuration& configuration);
} // namespace
+68
View File
@@ -0,0 +1,68 @@
/**
* Source: https://raw.githubusercontent.com/meshtastic/firmware/3b0232de1b6282eacfbff6e50b68fca7e67b8511/src/gps/cas.h
*/
#pragma once
#include <cstdint>
// CASIC binary message definitions
// Reference: https://www.icofchina.com/d/file/xiazai/2020-09-22/20f1b42b3a11ac52089caf3603b43fb5.pdf
// ATGM33H-5N: https://www.icofchina.com/pro/mokuai/2016-08-01/4.html
// (https://www.icofchina.com/d/file/xiazai/2016-12-05/b5c57074f4b1fcc62ba8c7868548d18a.pdf)
// NEMA (Class ID - 0x4e) message IDs
#define CAS_NEMA_GGA 0x00
#define CAS_NEMA_GLL 0x01
#define CAS_NEMA_GSA 0x02
#define CAS_NEMA_GSV 0x03
#define CAS_NEMA_RMC 0x04
#define CAS_NEMA_VTG 0x05
#define CAS_NEMA_GST 0x07
#define CAS_NEMA_ZDA 0x08
#define CAS_NEMA_DHV 0x0D
// Size of a CAS-ACK-(N)ACK message (14 bytes)
#define CAS_ACK_NACK_MSG_SIZE 0x0E
// CFG-RST (0x06, 0x02)
// Factory reset
constexpr uint8_t _message_CAS_CFG_RST_FACTORY[] = {
0xFF, 0x03, // Fields to clear
0x01, // Reset Mode: Controlled Software reset
0x03 // Startup Mode: Factory
};
// CFG_RATE (0x06, 0x01)
// 1HZ update rate, this should always be the case after
// factory reset but update it regardless
constexpr uint8_t _message_CAS_CFG_RATE_1HZ[] = {
0xE8, 0x03, // Update Rate: 0x03E8 = 1000ms
0x00, 0x00 // Reserved
};
// CFG-NAVX (0x06, 0x07)
// Initial ATGM33H-5N configuration, Updates for Dynamic Mode, Fix Mode, and SV system
// Qwirk: The ATGM33H-5N-31 should only support GPS+BDS, however it will happily enable
// and use GPS+BDS+GLONASS iff the correct CFG_NAVX command is used.
constexpr uint8_t _message_CAS_CFG_NAVX_CONF[] = {
0x03, 0x01, 0x00, 0x00, // Update Mask: Dynamic Mode, Fix Mode, Nav Settings
0x03, // Dynamic Mode: Automotive
0x03, // Fix Mode: Auto 2D/3D
0x00, // Min SV
0x00, // Max SVs
0x00, // Min CNO
0x00, // Reserved1
0x00, // Init 3D fix
0x00, // Min Elevation
0x00, // Dr Limit
0x07, // Nav System: 2^0 = GPS, 2^1 = BDS 2^2 = GLONASS: 2^3
// 3=GPS+BDS, 7=GPS+BDS+GLONASS
0x00, 0x00, // Rollover Week
0x00, 0x00, 0x00, 0x00, // Fix Altitude
0x00, 0x00, 0x00, 0x00, // Fix Height Error
0x00, 0x00, 0x00, 0x00, // PDOP Maximum
0x00, 0x00, 0x00, 0x00, // TDOP Maximum
0x00, 0x00, 0x00, 0x00, // Position Accuracy Max
0x00, 0x00, 0x00, 0x00, // Time Accuracy Max
0x00, 0x00, 0x00, 0x00 // Static Hold Threshold
};
@@ -0,0 +1,14 @@
#pragma once
#include "Tactility/hal/gps/GpsDevice.h"
namespace tt::hal::uart { class Uart; }
namespace tt::hal::gps {
/**
* Init sequence on UART for a specific GPS model.
*/
bool init(uart::Uart& uart, GpsModel type);
}
@@ -0,0 +1,10 @@
#pragma once
#include "Tactility/hal/gps/GpsDevice.h"
#include "Tactility/hal/uart/Uart.h"
namespace tt::hal::gps {
GpsModel probe(uart::Uart& iart);
}
@@ -0,0 +1,27 @@
#pragma once
#include "Tactility/hal/gps/GpsDevice.h"
#include "Tactility/hal/uart/Uart.h"
#include <cstdint>
#include <cstddef>
namespace tt::hal::gps::ublox {
void checksum(uint8_t* message, size_t length);
// From https://github.com/meshtastic/firmware/blob/7648391f91f2b84e367ae2b38220b30936fb45b1/src/gps/GPS.cpp#L128
uint8_t makePacket(uint8_t classId, uint8_t messageId, const uint8_t* payload, uint8_t payloadSize, uint8_t* bufferOut);
template<size_t DataSize>
inline void sendPacket(uart_port_t port, uint8_t type, uint8_t id, uint8_t data[DataSize], const char* errorMessage, TickType_t timeout) {
static uint8_t buffer[250] = {0};
size_t length = makePacket(type, id, data, DataSize, buffer);
// hal::uart::writeBytes(port, buffer, length);
}
GpsModel probe(uart::Uart& uart);
bool init(uart::Uart& uart, GpsModel model);
} // namespace tt::service::gps
@@ -0,0 +1,469 @@
#pragma once
#include <cstdint>
namespace tt::hal::gps::ublox {
// Power Management
constexpr uint8_t _message_PMREQ[] = {
0x00, 0x00, 0x00, 0x00, // 4 bytes duration of request task (milliseconds)
0x02, 0x00, 0x00, 0x00 // Bitfield, set backup = 1
};
// Used for sleep mode
// See https://github.com/meshtastic/firmware/blob/af8b64e84ee60175d7a0e43c6c3458e3a3558708/src/gps/GPS.cpp#L939
constexpr uint8_t _message_PMREQ_10[] = {
0x00, // version (0 for this version)
0x00, 0x00, 0x00, // Reserved 1
0x00, 0x00, 0x00, 0x00, // 4 bytes duration of request task (milliseconds)
0x06, 0x00, 0x00, 0x00, // Bitfield, set backup =1 and force =1
0x08, 0x00, 0x00, 0x00 // wakeupSources Wake on uartrx
};
constexpr uint8_t _message_CFG_RXM_PSM[] = {
0x08, // Reserved
0x01 // Power save mode
};
// only for Neo-6
constexpr uint8_t _message_CFG_RXM_ECO[] = {
0x08, // Reserved
0x04 // eco mode
};
constexpr uint8_t _message_CFG_PM2[] = {
0x01, // version
0x00, // Reserved 1, set to 0x06 by u-Center
0x00, // Reserved 2
0x00, // Reserved 1
0x00, 0x11, 0x03, 0x00, // flags-> cyclic mode, wait for normal fix ok, do not wake to update RTC, doNotEnterOff,
// LimitPeakCurrent
0xE8, 0x03, 0x00, 0x00, // update period 1000 ms
0x10, 0x27, 0x00, 0x00, // search period 10s
0x00, 0x00, 0x00, 0x00, // Grid offset 0
0x01, 0x00, // onTime 1 second
0x00, 0x00, // min search time 0
0x00, 0x00, // 0x2C, 0x01, // reserved 4
0x00, 0x00, // 0x00, 0x00, // reserved 5
0x00, 0x00, 0x00, 0x00, // 0x4F, 0xC1, 0x03, 0x00, // reserved 6
0x00, 0x00, 0x00, 0x00, // 0x87, 0x02, 0x00, 0x00, // reserved 7
0x00, // 0xFF, // reserved 8
0x00, // 0x00, // reserved 9
0x00, 0x00, // 0x00, 0x00, // reserved 10
0x00, 0x00, 0x00, 0x00 // 0x64, 0x40, 0x01, 0x00 // reserved 11
};
// Constallation setup, none required for Neo-6
// For Neo-7 GPS & SBAS
constexpr uint8_t _message_GNSS_7[] = {
0x00, // msgVer (0 for this version)
0x00, // numTrkChHw (max number of hardware channels, read only, so it's always 0)
0xff, // numTrkChUse (max number of channels to use, 0xff = max available)
0x02, // numConfigBlocks (number of GNSS systems), most modules support maximum 3 GNSS systems
// GNSS config format: gnssId, resTrkCh, maxTrkCh, reserved1, flags
0x00, 0x08, 0x10, 0x00, 0x01, 0x00, 0x00, 0x01, // GPS
0x01, 0x01, 0x03, 0x00, 0x01, 0x00, 0x00, 0x01 // SBAS
};
// It's not critical if the module doesn't acknowledge this configuration.
// The module should operate adequately with its factory or previously saved settings.
// It appears that there is a firmware bug in some GPS modules: When an attempt is made
// to overwrite a saved state with identical values, no ACK/NAK is received, contrary to
// what is specified in the Ublox documentation.
// There is also a possibility that the module may be GPS-only.
// For M8 GPS, GLONASS, Galileo, SBAS, QZSS
constexpr uint8_t _message_GNSS_8[] = {
0x00, // msgVer (0 for this version)
0x00, // numTrkChHw (max number of hardware channels, read only, so it's always 0)
0xff, // numTrkChUse (max number of channels to use, 0xff = max available)
0x05, // numConfigBlocks (number of GNSS systems)
// GNSS config format: gnssId, resTrkCh, maxTrkCh, reserved1, flags
0x00, 0x08, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01, // GPS
0x01, 0x01, 0x03, 0x00, 0x01, 0x00, 0x01, 0x01, // SBAS
0x02, 0x04, 0x08, 0x00, 0x01, 0x00, 0x01, 0x01, // Galileo
0x05, 0x00, 0x03, 0x00, 0x01, 0x00, 0x01, 0x01, // QZSS
0x06, 0x08, 0x0E, 0x00, 0x01, 0x00, 0x01, 0x01 // GLONASS
};
/*
// For M8 GPS, GLONASS, BeiDou, SBAS, QZSS
constexpr uint8_t _message_GNSS_8_B[] = {
0x00, // msgVer (0 for this version)
0x00, // numTrkChHw (max number of hardware channels, read only, so it's always 0)
0xff, // numTrkChUse (max number of channels to use, 0xff = max available) read only for protocol >23
0x05, // numConfigBlocks (number of GNSS systems)
// GNSS config format: gnssId, resTrkCh, maxTrkCh, reserved1, flags
0x00, 0x08, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01, // GPS
0x01, 0x01, 0x03, 0x00, 0x01, 0x00, 0x01, 0x01, // SBAS
0x03, 0x08, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01, // BeiDou
0x05, 0x00, 0x03, 0x00, 0x01, 0x00, 0x01, 0x01, // QZSS
0x06, 0x08, 0x0E, 0x00, 0x01, 0x00, 0x01, 0x01 // GLONASS
};
*/
// For M8 we want to enable NMEA version 4.10 messages to allow for Galileo and or BeiDou
constexpr uint8_t _message_NMEA[] {
0x00, // filter flags
0x41, // NMEA Version
0x00, // Max number of SVs to report per TaklerId
0x02, // flags
0x00, 0x00, 0x00, 0x00, // gnssToFilter
0x00, // svNumbering
0x00, // mainTalkerId
0x00, // gsvTalkerId
0x01, // Message version
0x00, 0x00, // bdsTalkerId 2 chars 0=default
0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // Reserved
};
// Enable jamming/interference monitor
// For Neo-6, Max-7 and Neo-7
constexpr uint8_t _message_JAM_6_7[] = {
0xf3, 0xac, 0x62, 0xad, // config1 bbThreshold = 3, cwThreshold = 15, enable = 1, reserved bits 0x16B156
0x1e, 0x03, 0x00, 0x00 // config2 antennaSetting Unknown = 0, reserved 3, = 0x00,0x00, reserved 2 = 0x31E
};
// For M8
constexpr uint8_t _message_JAM_8[] = {
0xf3, 0xac, 0x62, 0xad, // config1 bbThreshold = 3, cwThreshold = 15, enable1 = 1, reserved bits 0x16B156
0x1e, 0x43, 0x00, 0x00 // config2 antennaSetting Unknown = 0, enable2 = 1, generalBits = 0x31E
};
// Configure navigation engine expert settings:
// there are many variations of what were Reserved fields for the Neo-6 in later versions
// ToDo: check UBX-MON-VER for module type and protocol version
// For the Neo-6
constexpr uint8_t _message_NAVX5[] = {
0x00, 0x00, // msgVer (0 for this version)
0x4c, 0x66, // mask1
0x00, 0x00, 0x00, 0x00, // Reserved 0
0x00, // Reserved 1
0x00, // Reserved 2
0x03, // minSVs (Minimum number of satellites for navigation) = 3
0x10, // maxSVs (Maximum number of satellites for navigation) = 16
0x06, // minCNO (Minimum satellite signal level for navigation) = 6 dBHz
0x00, // Reserved 5
0x00, // iniFix3D (Initial fix must be 3D) (0 = false 1 = true)
0x00, // Reserved 6
0x00, // Reserved 7
0x00, // Reserved 8
0x00, 0x00, // wknRollover 0 = firmware default
0x00, 0x00, 0x00, 0x00, // Reserved 9
0x00, // Reserved 10
0x00, // Reserved 11
0x00, // usePPP (Precice Point Positioning) (0 = false, 1 = true)
0x01, // useAOP (AssistNow Autonomous configuration) = 1 (enabled)
0x00, // Reserved 12
0x00, // Reserved 13
0x00, 0x00, // aopOrbMaxErr = 0 to reset to firmware default
0x00, // Reserved 14
0x00, // Reserved 15
0x00, 0x00, // Reserved 3
0x00, 0x00, 0x00, 0x00 // Reserved 4
};
// For the M8
constexpr uint8_t _message_NAVX5_8[] = {
0x02, 0x00, // msgVer (2 for this version)
0x4c, 0x66, // mask1
0x00, 0x00, 0x00, 0x00, // mask2
0x00, 0x00, // Reserved 1
0x03, // minSVs (Minimum number of satellites for navigation) = 3
0x10, // maxSVs (Maximum number of satellites for navigation) = 16
0x06, // minCNO (Minimum satellite signal level for navigation) = 6 dBHz
0x00, // Reserved 2
0x00, // iniFix3D (Initial fix must be 3D) (0 = false 1 = true)
0x00, 0x00, // Reserved 3
0x00, // ackAiding
0x00, 0x00, // wknRollover 0 = firmware default
0x00, // sigAttenCompMode
0x00, // Reserved 4
0x00, 0x00, // Reserved 5
0x00, 0x00, // Reserved 6
0x00, // usePPP (Precice Point Positioning) (0 = false, 1 = true)
0x01, // aopCfg (AssistNow Autonomous configuration) = 1 (enabled)
0x00, 0x00, // Reserved 7
0x00, 0x00, // aopOrbMaxErr = 0 to reset to firmware default
0x00, 0x00, 0x00, 0x00, // Reserved 8
0x00, 0x00, 0x00, // Reserved 9
0x00 // useAdr
};
// Set GPS update rate to 1Hz
// Lowering the update rate helps to save power.
// Additionally, for some new modules like the M9/M10, an update rate lower than 5Hz
// is recommended to avoid a known issue with satellites disappearing.
// The module defaults for M8, M9, M10 are the same as we use here so no update is necessary
constexpr uint8_t _message_1HZ[] = {
0xE8, 0x03, // Measurement Rate (1000ms for 1Hz)
0x01, 0x00, // Navigation rate, always 1 in GPS mode
0x01, 0x00 // Time reference
};
// Disable GLL. GLL - Geographic position (latitude and longitude), which provides the current geographical
// coordinates.
constexpr uint8_t _message_GLL[] = {
0xF0, 0x01, // NMEA ID for GLL
0x00, // Rate for DDC
0x00, // Rate for UART1
0x00, // Rate for UART2
0x00, // Rate for USB
0x00, // Rate for SPI
0x00 // Reserved
};
// Disable GSA. GSA - GPS DOP and active satellites, used for detailing the satellites used in the positioning and
// the DOP (Dilution of Precision)
constexpr uint8_t _message_GSA[] = {
0xF0, 0x02, // NMEA ID for GSA
0x00, // Rate for DDC
0x00, // Rate for UART1
0x00, // Rate for UART2
0x00, // Rate for USB usefull for native linux
0x00, // Rate for SPI
0x00 // Reserved
};
// Disable GSV. GSV - Satellites in view, details the number and location of satellites in view.
constexpr uint8_t _message_GSV[] = {
0xF0, 0x03, // NMEA ID for GSV
0x00, // Rate for DDC
0x00, // Rate for UART1
0x00, // Rate for UART2
0x00, // Rate for USB
0x00, // Rate for SPI
0x00 // Reserved
};
// Disable VTG. VTG - Track made good and ground speed, which provides course and speed information relative to
// the ground.
constexpr uint8_t _message_VTG[] = {
0xF0, 0x05, // NMEA ID for VTG
0x00, // Rate for DDC
0x00, // Rate for UART1
0x00, // Rate for UART2
0x00, // Rate for USB
0x00, // Rate for SPI
0x00 // Reserved
};
// Enable RMC. RMC - Recommended Minimum data, the essential gps pvt (position, velocity, time) data.
constexpr uint8_t _message_RMC[] = {
0xF0, 0x04, // NMEA ID for RMC
0x00, // Rate for DDC
0x01, // Rate for UART1
0x00, // Rate for UART2
0x01, // Rate for USB usefull for native linux
0x00, // Rate for SPI
0x00 // Reserved
};
// Enable GGA. GGA - Global Positioning System Fix Data, which provides 3D location and accuracy data.
constexpr uint8_t _message_GGA[] = {
0xF0, 0x00, // NMEA ID for GGA
0x00, // Rate for DDC
0x01, // Rate for UART1
0x00, // Rate for UART2
0x01, // Rate for USB, usefull for native linux
0x00, // Rate for SPI
0x00 // Reserved
};
// Disable UBX-AID-ALPSRV as it may confuse TinyGPS. The Neo-6 seems to send this message
// whether the AID Autonomous is enabled or not
constexpr uint8_t _message_AID[] = {
0x0B, 0x32, // NMEA ID for UBX-AID-ALPSRV
0x00, // Rate for DDC
0x00, // Rate for UART1
0x00, // Rate for UART2
0x00, // Rate for USB
0x00, // Rate for SPI
0x00 // Reserved
};
// Turn off TEXT INFO Messages for all but M10 series
// B5 62 06 02 0A 00 01 00 00 00 03 03 00 03 03 00 1F 20
constexpr uint8_t _message_DISABLE_TXT_INFO[] = {
0x01, // Protocol ID for NMEA
0x00, 0x00, 0x00, // Reserved
0x03, // I2C
0x03, // I/O Port 1
0x00, // I/O Port 2
0x03, // USB
0x03, // SPI
0x00 // Reserved
};
// The Power Management configuration allows the GPS module to operate in different power modes for optimized
// power consumption. The modes supported are: 0x00 = Full power: The module operates at full power with no power
// saving. 0x01 = Balanced: The module dynamically adjusts the tracking behavior to balance power consumption.
// 0x02 = Interval: The module operates in a periodic mode, cycling between tracking and power saving states.
// 0x03 = Aggressive with 1 Hz: The module operates in a power saving mode with a 1 Hz update rate.
// 0x04 = Aggressive with 2 Hz: The module operates in a power saving mode with a 2 Hz update rate.
// 0x05 = Aggressive with 4 Hz: The module operates in a power saving mode with a 4 Hz update rate.
// The 'period' field specifies the position update and search period. It is only valid when the powerSetupValue
// is set to Interval; otherwise, it must be set to '0'. The 'onTime' field specifies the duration of the ON phase
// and must be smaller than the period. It is only valid when the powerSetupValue is set to Interval; otherwise,
// it must be set to '0'.
// This command applies to M8 products
constexpr uint8_t _message_PMS[] = {
0x00, // Version (0)
0x03, // Power setup value 3 = Agresssive 1Hz
0x00, 0x00, // period: not applicable, set to 0
0x00, 0x00, // onTime: not applicable, set to 0
0x00, 0x00 // reserved, generated by u-center
};
constexpr uint8_t _message_SAVE[] = {
0x00, 0x00, 0x00, 0x00, // clearMask: no sections cleared
0xFF, 0xFF, 0x00, 0x00, // saveMask: save all sections
0x00, 0x00, 0x00, 0x00, // loadMask: no sections loaded
0x17 // deviceMask: BBR, Flash, EEPROM, and SPI Flash
};
constexpr uint8_t _message_SAVE_10[] = {
0x00, 0x00, 0x00, 0x00, // clearMask: no sections cleared
0xFF, 0xFF, 0x00, 0x00, // saveMask: save all sections
0x00, 0x00, 0x00, 0x00, // loadMask: no sections loaded
0x01 // deviceMask: only save to BBR
};
// As the M10 has no flash, the best we can do to preserve the config is to set it in RAM and BBR.
// BBR will survive a restart, and power off for a while, but modules with small backup
// batteries or super caps will not retain the config for a long power off time.
// for all configurations using sleep / low power modes, V_BCKP needs to be hooked to permanent power for fast aquisition after
// sleep
// VALSET Commands for M10
// Please refer to the M10 Protocol Specification:
// https://content.u-blox.com/sites/default/files/u-blox-M10-SPG-5.10_InterfaceDescription_UBX-21035062.pdf
// Where the VALSET/VALGET/VALDEL commands are described in detail.
// and:
// https://content.u-blox.com/sites/default/files/u-blox-M10-ROM-5.10_ReleaseNotes_UBX-22001426.pdf
// for interesting insights.
//
// Integration manual:
// https://content.u-blox.com/sites/default/files/documents/SAM-M10Q_IntegrationManual_UBX-22020019.pdf
// has details on low-power modes
/*
OPERATEMODE E1 2 (0 | 1 | 2)
POSUPDATEPERIOD U4 5
ACQPERIOD U4 10
GRIDOFFSET U4 0
ONTIME U2 1
MINACQTIME U1 0
MAXACQTIME U1 0
DONOTENTEROFF L 1
WAITTIMEFIX L 1
UPDATEEPH L 1
EXTINTWAKE L 0 no ext ints
EXTINTBACKUP L 0 no ext ints
EXTINTINACTIVE L 0 no ext ints
EXTINTACTIVITY U4 0 no ext ints
LIMITPEAKCURRENT L 1
// Ram layer config message:
// b5 62 06 8a 26 00 00 01 00 00 01 00 d0 20 02 02 00 d0 40 05 00 00 00 05 00 d0 30 01 00 08 00 d0 10 01 09 00 d0 10 01 10 00 d0
// 10 01 8b de
// BBR layer config message:
// b5 62 06 8a 26 00 00 02 00 00 01 00 d0 20 02 02 00 d0 40 05 00 00 00 05 00 d0 30 01 00 08 00 d0 10 01 09 00 d0 10 01 10 00 d0
// 10 01 8c 03
*/
constexpr uint8_t _message_VALSET_PM_RAM[] = {0x00, 0x01, 0x00, 0x00, 0x01, 0x00, 0xd0, 0x20, 0x02, 0x02, 0x00, 0xd0, 0x40, 0x05, 0x00, 0x00, 0x00, 0x05, 0x00, 0xd0, 0x30, 0x01, 0x00, 0x08, 0x00, 0xd0, 0x10, 0x01, 0x09, 0x00, 0xd0, 0x10, 0x01, 0x10, 0x00, 0xd0, 0x10, 0x01};
constexpr uint8_t _message_VALSET_PM_BBR[] = {0x00, 0x02, 0x00, 0x00, 0x01, 0x00, 0xd0, 0x20, 0x02, 0x02, 0x00, 0xd0, 0x40, 0x05, 0x00, 0x00, 0x00, 0x05, 0x00, 0xd0, 0x30, 0x01, 0x00, 0x08, 0x00, 0xd0, 0x10, 0x01, 0x09, 0x00, 0xd0, 0x10, 0x01, 0x10, 0x00, 0xd0, 0x10, 0x01};
/*
CFG-ITFM replaced by 5 valset messages which can be combined into one for RAM and one for BBR
20410001 bbthreshold U1 3
20410002 cwthreshold U1 15
1041000d enable L 0 -> 1
20410010 ant E1 0
10410013 enable aux L 0 -> 1
b5 62 06 8a 0e 00 00 01 00 00 0d 00 41 10 01 13 00 41 10 01 63 c6
*/
constexpr uint8_t _message_VALSET_ITFM_RAM[] = {0x00, 0x01, 0x00, 0x00, 0x0d, 0x00, 0x41, 0x10, 0x01, 0x13, 0x00, 0x41, 0x10, 0x01};
constexpr uint8_t _message_VALSET_ITFM_BBR[] = {0x00, 0x02, 0x00, 0x00, 0x0d, 0x00, 0x41, 0x10, 0x01, 0x13, 0x00, 0x41, 0x10, 0x01};
// Turn off all NMEA messages:
// Ram layer config message:
// b5 62 06 8a 22 00 00 01 00 00 c0 00 91 20 00 ca 00 91 20 00 c5 00 91 20 00 ac 00 91 20 00 b1 00 91 20 00 bb 00 91 20 00 40 8f
// Disable GLL, GSV, VTG messages in BBR layer
// BBR layer config message:
// b5 62 06 8a 13 00 00 02 00 00 ca 00 91 20 00 c5 00 91 20 00 b1 00 91 20 00 f8 4e
constexpr uint8_t _message_VALSET_DISABLE_NMEA_RAM[] = {
/*0x00, 0x01, 0x00, 0x00, 0xca, 0x00, 0x91, 0x20, 0x00, 0xc5, 0x00, 0x91, 0x20, 0x00, 0xb1, 0x00, 0x91, 0x20, 0x00 */
0x00, 0x01, 0x00, 0x00, 0xc0, 0x00, 0x91, 0x20, 0x00, 0xca, 0x00, 0x91, 0x20, 0x00, 0xc5, 0x00, 0x91,
0x20, 0x00, 0xac, 0x00, 0x91, 0x20, 0x00, 0xb1, 0x00, 0x91, 0x20, 0x00, 0xbb, 0x00, 0x91, 0x20, 0x00
};
constexpr uint8_t _message_VALSET_DISABLE_NMEA_BBR[] = {0x00, 0x02, 0x00, 0x00, 0xca, 0x00, 0x91, 0x20, 0x00, 0xc5, 0x00, 0x91, 0x20, 0x00, 0xb1, 0x00, 0x91, 0x20, 0x00};
// Turn off text info messages:
// Ram layer config message:
// b5 62 06 8a 09 00 00 01 00 00 07 00 92 20 06 59 50
// BBR layer config message:
// b5 62 06 8a 09 00 00 02 00 00 07 00 92 20 06 5a 58
// Turn NMEA GGA, RMC messages on:
// Layer config messages:
// RAM:
// b5 62 06 8a 0e 00 00 01 00 00 bb 00 91 20 01 ac 00 91 20 01 6a 8f
// BBR:
// b5 62 06 8a 0e 00 00 02 00 00 bb 00 91 20 01 ac 00 91 20 01 6b 9c
// FLASH:
// b5 62 06 8a 0e 00 00 04 00 00 bb 00 91 20 01 ac 00 91 20 01 6d b6
// Doing this for the FLASH layer isn't really required since we save the config to flash later
constexpr uint8_t _message_VALSET_DISABLE_TXT_INFO_RAM[] = {0x00, 0x01, 0x00, 0x00, 0x07, 0x00, 0x92, 0x20, 0x03};
constexpr uint8_t _message_VALSET_DISABLE_TXT_INFO_BBR[] = {0x00, 0x02, 0x00, 0x00, 0x07, 0x00, 0x92, 0x20, 0x03};
constexpr uint8_t _message_VALSET_ENABLE_NMEA_RAM[] = {0x00, 0x01, 0x00, 0x00, 0xbb, 0x00, 0x91, 0x20, 0x01, 0xac, 0x00, 0x91, 0x20, 0x01};
constexpr uint8_t _message_VALSET_ENABLE_NMEA_BBR[] = {0x00, 0x02, 0x00, 0x00, 0xbb, 0x00, 0x91, 0x20, 0x01, 0xac, 0x00, 0x91, 0x20, 0x01};
constexpr uint8_t _message_VALSET_DISABLE_SBAS_RAM[] = {0x00, 0x01, 0x00, 0x00, 0x20, 0x00, 0x31, 0x10, 0x00, 0x05, 0x00, 0x31, 0x10, 0x00};
constexpr uint8_t _message_VALSET_DISABLE_SBAS_BBR[] = {0x00, 0x02, 0x00, 0x00, 0x20, 0x00, 0x31, 0x10, 0x00, 0x05, 0x00, 0x31, 0x10, 0x00};
/*
Operational issues with the M10:
PowerSave doesn't work with SBAS, seems like you can have SBAS enabled, but it will never lock
onto the SBAS sats.
PowerSave doesn't work with BDS B1C, u-blox says use B1l instead.
BDS B1l cannot be enabled with BDS B1C or GLONASS L1OF, so GLONASS will work with B1C, but not B1l
So no powersave with GLONASS and BDS B1l enabled.
So disable GLONASS and use BDS B1l, which is part of the default M10 config.
GNSS configuration:
Default GNSS configuration is: GPS, Galileo, BDS B1l, with QZSS and SBAS enabled.
The PMREQ puts the receiver to sleep and wakeup re-acquires really fast and seems to not need
the PM config. Lets try without it.
PMREQ sort of works with SBAS, but the awake time is too short to re-acquire any SBAS sats.
The defination of "Got Fix" doesn't seem to include SBAS. Much more too this...
Even if it was, it can take minutes (up to 12.5),
even under good sat visibility conditions to re-acquire the SBAS data.
Another effect fo the quick transition to sleep is that no other sats will be acquired so the
sat count will tend to remain at what the initial fix was.
*/
// GNSS disable SBAS as recommended by u-blox if using GNSS defaults and power save mode
/*
Ram layer config message:
b5 62 06 8a 0e 00 00 01 00 00 20 00 31 10 00 05 00 31 10 00 46 87
BBR layer config message:
b5 62 06 8a 0e 00 00 02 00 00 20 00 31 10 00 05 00 31 10 00 47 94
*/
}
@@ -0,0 +1,15 @@
#pragma once
#include "Tactility/hal/i2c/I2c.h"
#include <vector>
namespace tt::hal::i2c {
/**
* Called by main HAL init to ready the internal state of the I2C HAL.
* @param[in] configurations HAL configuration for a board
* @return true on success
*/
bool init(const std::vector<i2c::Configuration>& configurations);
}
@@ -0,0 +1,17 @@
#pragma once
#include "Tactility/hal/spi/Spi.h"
#include <vector>
#include <memory>
namespace tt::hal::spi {
/**
* Called by main HAL init to ready the internal state of the SPI HAL.
* @param[in] configurations HAL configuration for a board
* @return true on success
*/
bool init(const std::vector<spi::Configuration>& configurations);
}
@@ -0,0 +1,38 @@
#pragma once
#ifdef ESP_PLATFORM
#include "Tactility/Mutex.h"
#include "Tactility/hal/uart/Uart.h"
#include "Tactility/hal/uart/Configuration.h"
namespace tt::hal::uart {
class UartEsp final : public Uart {
private:
Mutex mutex;
const Configuration& configuration;
bool started = false;
public:
explicit UartEsp(const Configuration& configuration) : configuration(configuration) {}
bool start() final;
bool isStarted() const final;
bool stop() final;
size_t readBytes(std::byte* buffer, size_t bufferSize, TickType_t timeout) final;
bool readByte(std::byte* output, TickType_t timeout) final;
size_t writeBytes(const std::byte* buffer, size_t bufferSize, TickType_t timeout) final;
size_t available(TickType_t timeout) final;
bool setBaudRate(uint32_t baudRate, TickType_t timeout) final;
uint32_t getBaudRate() final;
void flushInput() final;
};
std::unique_ptr<Uart> create(const Configuration& configuration);
} // namespace tt::hal::uart
#endif
@@ -0,0 +1,9 @@
#pragma once
#include "Tactility/hal/uart/Uart.h"
namespace tt::hal::uart {
bool init(const std::vector<uart::Configuration>& configurations);
}
@@ -0,0 +1,47 @@
#pragma once
#ifndef ESP_PLATFORM
#include "Tactility/Mutex.h"
#include "Tactility/hal/uart/Configuration.h"
#include "Tactility/hal/uart/Uart.h"
#include <termios.h>
namespace tt::hal::uart {
class UartPosix final : public Uart {
private:
struct AutoCloseFileDeleter {
void operator()(FILE* file) {
fclose(file);
}
};
Mutex mutex;
const Configuration& configuration;
std::unique_ptr<FILE, AutoCloseFileDeleter> device;
bool awaitAvailable(TickType_t timeout);
public:
explicit UartPosix(const Configuration& configuration) : configuration(configuration) {}
bool start() final;
bool isStarted() const final;
bool stop() final;
size_t readBytes(std::byte* buffer, size_t bufferSize, TickType_t timeout) final;
bool readByte(std::byte* output, TickType_t timeout) final;
size_t writeBytes(const std::byte* buffer, size_t bufferSize, TickType_t timeout) final;
size_t available(TickType_t timeout) final;
bool setBaudRate(uint32_t baudRate, TickType_t timeout) final;
uint32_t getBaudRate() final;
void flushInput() final;
};
std::unique_ptr<Uart> create(const Configuration& configuration);
} // namespace tt::hal::uart
#endif
@@ -0,0 +1,5 @@
#pragma once
bool tusbIsSupported();
bool tusbStartMassStorageWithSdmmc();
void tusbStop();
@@ -0,0 +1,7 @@
#pragma once
namespace tt::network::ntp {
void init();
}
@@ -0,0 +1,30 @@
#pragma once
#include "Tactility/service/ServiceContext.h"
#include "Tactility/service/Service.h"
namespace tt::service {
class ServiceInstance : public ServiceContext {
private:
Mutex mutex = Mutex(Mutex::Type::Normal);
std::shared_ptr<const ServiceManifest> manifest;
std::shared_ptr<Service> service;
public:
explicit ServiceInstance(std::shared_ptr<const service::ServiceManifest> manifest);
~ServiceInstance() override = default;
/** @return a reference ot the service's manifest */
const service::ServiceManifest& getManifest() const override;
/** Retrieve the paths that are relevant to this service */
std::unique_ptr<Paths> getPaths() const override;
std::shared_ptr<Service> getService() const { return service; }
};
}
@@ -0,0 +1,28 @@
#pragma once
#include "Tactility/service/ServiceInstance.h"
namespace tt::service {
class ServiceInstancePaths final : public Paths {
private:
std::shared_ptr<const ServiceManifest> manifest;
public:
explicit ServiceInstancePaths(std::shared_ptr<const ServiceManifest> manifest) : manifest(std::move(manifest)) {}
~ServiceInstancePaths() final = default;
std::string getDataDirectory() const final;
std::string getDataDirectoryLvgl() const final;
std::string getDataPath(const std::string& childPath) const final;
std::string getDataPathLvgl(const std::string& childPath) const final;
std::string getSystemDirectory() const final;
std::string getSystemDirectoryLvgl() const final;
std::string getSystemPath(const std::string& childPath) const final;
std::string getSystemPathLvgl(const std::string& childPath) const final;
};
}
@@ -0,0 +1,75 @@
#pragma once
#ifdef ESP_PLATFORM
#include "Tactility/MessageQueue.h"
#include "Tactility/service/Service.h"
#include "Tactility/service/espnow/EspNow.h"
#include <Tactility/Mutex.h>
#include <functional>
namespace tt::service::espnow {
class EspNowService final : public Service {
private:
struct ReceiverSubscriptionData {
ReceiverSubscription id;
std::function<void(const esp_now_recv_info_t* receiveInfo, const uint8_t* data, int length)> onReceive;
};
struct SendCallback {
uint8_t macAddress[ESP_NOW_ETH_ALEN];
bool success;
};
Mutex mutex = Mutex(Mutex::Type::Recursive);
std::vector<ReceiverSubscriptionData> subscriptions;
ReceiverSubscription lastSubscriptionId = 0;
bool enabled = false;
// Dispatcher calls this and forwards to non-static function
static void enableFromDispatcher(std::shared_ptr<void> context);
void enableFromDispatcher(const EspNowConfig& config);
static void disableFromDispatcher(std::shared_ptr<void> context);
void disableFromDispatcher();
static void receiveCallback(const esp_now_recv_info_t* receiveInfo, const uint8_t* data, int length);
void onReceive(const esp_now_recv_info_t* receiveInfo, const uint8_t* data, int length);
public:
// region Overrides
void onStart(ServiceContext& service) override;
void onStop(ServiceContext& service) override;
// endregion Overrides
// region Internal API
void enable(const EspNowConfig& config);
void disable();
bool isEnabled() const;
bool addPeer(const esp_now_peer_info_t& peer);
bool send(const uint8_t* address, const uint8_t* buffer, size_t bufferLength);
ReceiverSubscription subscribeReceiver(std::function<void(const esp_now_recv_info_t* receiveInfo, const uint8_t* data, int length)> onReceive);
void unsubscribeReceiver(ReceiverSubscription subscription);
// region Internal API
};
std::shared_ptr<EspNowService> findService();
}
#endif // ESP_PLATFORM
@@ -0,0 +1,11 @@
#pragma once
#include "Tactility/service/espnow/EspNow.h"
namespace tt::service::espnow {
bool initWifi(const EspNowConfig& config);
bool deinitWifi();
}
@@ -0,0 +1,7 @@
#pragma once
namespace tt::time {
void init();
}
+55
View File
@@ -0,0 +1,55 @@
#ifdef ESP_PLATFORM
#include "Tactility/PartitionsEsp.h"
#include <Tactility/Log.h>
#include <esp_vfs_fat.h>
#include <nvs_flash.h>
namespace tt {
static const char* TAG = "partitions";
static esp_err_t initNvsFlashSafely() {
esp_err_t result = nvs_flash_init();
if (result == ESP_ERR_NVS_NO_FREE_PAGES || result == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
result = nvs_flash_init();
}
return result;
}
static wl_handle_t data_wl_handle = WL_INVALID_HANDLE;
esp_err_t initPartitionsEsp() {
ESP_ERROR_CHECK(initNvsFlashSafely());
const esp_vfs_fat_mount_config_t mount_config = {
.format_if_mount_failed = false,
.max_files = 4,
.allocation_unit_size = CONFIG_WL_SECTOR_SIZE,
.disk_status_check_enable = false,
.use_one_fat = true,
};
auto system_result = esp_vfs_fat_spiflash_mount_ro("/system", "system", &mount_config);
if (system_result != ESP_OK) {
TT_LOG_E(TAG, "Failed to mount /system (%s)", esp_err_to_name(system_result));
} else {
TT_LOG_I(TAG, "Mounted /system");
}
auto data_result = esp_vfs_fat_spiflash_mount_rw_wl("/data", "data", &mount_config, &data_wl_handle);
if (data_result != ESP_OK) {
TT_LOG_E(TAG, "Failed to mount /data (%s)", esp_err_to_name(data_result));
} else {
TT_LOG_I(TAG, "Mounted /data");
}
return system_result == ESP_OK && data_result == ESP_OK;
}
} // namespace
#endif // ESP_PLATFORM
+107
View File
@@ -0,0 +1,107 @@
#ifdef ESP_PLATFORM
#include "nvs_flash.h"
#include "Tactility/Preferences.h"
#include <Tactility/TactilityCore.h>
#define TAG "preferences"
namespace tt {
bool Preferences::optBool(const std::string& key, bool& out) const {
nvs_handle_t handle;
if (nvs_open(namespace_, NVS_READWRITE, &handle) != ESP_OK) {
TT_LOG_E(TAG, "Failed to open namespace %s", namespace_);
return false;
} else {
uint8_t out_number;
bool success = nvs_get_u8(handle, key.c_str(), &out_number) == ESP_OK;
nvs_close(handle);
if (success) {
out = (bool)out_number;
}
return success;
}
}
bool Preferences::optInt32(const std::string& key, int32_t& out) const {
nvs_handle_t handle;
if (nvs_open(namespace_, NVS_READWRITE, &handle) != ESP_OK) {
TT_LOG_E(TAG, "Failed to open namespace %s", namespace_);
return false;
} else {
bool success = nvs_get_i32(handle, key.c_str(), &out) == ESP_OK;
nvs_close(handle);
return success;
}
}
bool Preferences::optString(const std::string& key, std::string& out) const {
nvs_handle_t handle;
if (nvs_open(namespace_, NVS_READWRITE, &handle) != ESP_OK) {
TT_LOG_E(TAG, "Failed to open namespace %s", namespace_);
return false;
} else {
size_t out_size = 256;
char* out_data = static_cast<char*>(malloc(out_size));
bool success = nvs_get_str(handle, key.c_str(), out_data, &out_size) == ESP_OK;
nvs_close(handle);
out = out_data;
free(out_data);
return success;
}
}
bool Preferences::hasBool(const std::string& key) const {
bool temp;
return optBool(key, temp);
}
bool Preferences::hasInt32(const std::string& key) const {
int32_t temp;
return optInt32(key, temp);
}
bool Preferences::hasString(const std::string& key) const {
std::string temp;
return optString(key, temp);
}
void Preferences::putBool(const std::string& key, bool value) {
nvs_handle_t handle;
if (nvs_open(namespace_, NVS_READWRITE, &handle) == ESP_OK) {
if (nvs_set_u8(handle, key.c_str(), (uint8_t)value) != ESP_OK) {
TT_LOG_E(TAG, "Failed to write %s:%s", namespace_, key.c_str());
}
nvs_close(handle);
} else {
TT_LOG_E(TAG, "Failed to open namespace %s", namespace_);
}
}
void Preferences::putInt32(const std::string& key, int32_t value) {
nvs_handle_t handle;
if (nvs_open(namespace_, NVS_READWRITE, &handle) == ESP_OK) {
if (nvs_set_i32(handle, key.c_str(), value) != ESP_OK) {
TT_LOG_E(TAG, "Failed to write %s:%s", namespace_, key.c_str());
}
nvs_close(handle);
} else {
TT_LOG_E(TAG, "Failed to open namespace %s", namespace_);
}
}
void Preferences::putString(const std::string& key, const std::string& text) {
nvs_handle_t handle;
if (nvs_open(namespace_, NVS_READWRITE, &handle) == ESP_OK) {
nvs_set_str(handle, key.c_str(), text.c_str());
nvs_close(handle);
} else {
TT_LOG_E(TAG, "Failed to open namespace %s", namespace_);
}
}
} // namespace
#endif
+70
View File
@@ -0,0 +1,70 @@
#ifndef ESP_PLATFOM
#include "Tactility/Preferences.h"
#include <Tactility/Bundle.h>
namespace tt {
static Bundle preferences;
/**
* Creates a string that is effectively "namespace:key" so we can create a single map (bundle)
* to store all the key/value pairs.
*
* @param[in] namespace
* @param[in] key
* @param[out] out
*/
std::string get_bundle_key(const std::string& namespace_, const std::string& key) {
return namespace_ + ':' + key;
}
bool Preferences::hasBool(const std::string& key) const {
std::string bundle_key = get_bundle_key(namespace_, key);
return preferences.hasBool(bundle_key);
}
bool Preferences::hasInt32(const std::string& key) const {
std::string bundle_key = get_bundle_key(namespace_, key);
return preferences.hasInt32(bundle_key);
}
bool Preferences::hasString(const std::string& key) const {
std::string bundle_key = get_bundle_key(namespace_, key);
return preferences.hasString(bundle_key);
}
bool Preferences::optBool(const std::string& key, bool& out) const {
std::string bundle_key = get_bundle_key(namespace_, key);
return preferences.optBool(bundle_key, out);
}
bool Preferences::optInt32(const std::string& key, int32_t& out) const {
std::string bundle_key = get_bundle_key(namespace_, key);
return preferences.optInt32(bundle_key, out);
}
bool Preferences::optString(const std::string& key, std::string& out) const {
std::string bundle_key = get_bundle_key(namespace_, key);
return preferences.optString(bundle_key, out);
}
void Preferences::putBool(const std::string& key, bool value) {
std::string bundle_key = get_bundle_key(namespace_, key);
return preferences.putBool(bundle_key, value);
}
void Preferences::putInt32(const std::string& key, int32_t value) {
std::string bundle_key = get_bundle_key(namespace_, key);
return preferences.putInt32(bundle_key, value);
}
void Preferences::putString(const std::string& key, const std::string& value) {
std::string bundle_key = get_bundle_key(namespace_, key);
return preferences.putString(bundle_key, value);
}
#endif
} // namespace
+65
View File
@@ -0,0 +1,65 @@
#include "Tactility/TactilityHeadless.h"
#include "Tactility/hal/Configuration.h"
#include "Tactility/hal/Hal_i.h"
#include "Tactility/network/NtpPrivate.h"
#include "Tactility/service/ServiceManifest.h"
#include "Tactility/service/ServiceRegistry.h"
#include <Tactility/Dispatcher.h>
#include <Tactility/time/TimePrivate.h>
#ifdef ESP_PLATFORM
#include "Tactility/InitEsp.h"
#endif
namespace tt {
#define TAG "tactility"
namespace service::gps { extern const ServiceManifest manifest; }
namespace service::wifi { extern const ServiceManifest manifest; }
namespace service::sdcard { extern const ServiceManifest manifest; }
#ifdef ESP_PLATFORM
namespace service::espnow { extern const ServiceManifest manifest; }
#endif
static Dispatcher mainDispatcher;
static const hal::Configuration* hardwareConfig = nullptr;
static void registerAndStartSystemServices() {
TT_LOG_I(TAG, "Registering and starting system services");
addService(service::gps::manifest);
addService(service::sdcard::manifest);
addService(service::wifi::manifest);
#ifdef ESP_PLATFORM
addService(service::espnow::manifest);
#endif
}
void initHeadless(const hal::Configuration& config) {
TT_LOG_I(TAG, "Tactility v%s on %s (%s)", TT_VERSION, CONFIG_TT_BOARD_NAME, CONFIG_TT_BOARD_ID);
#ifdef ESP_PLATFORM
initEsp();
#endif
hardwareConfig = &config;
time::init();
hal::init(config);
network::ntp::init();
registerAndStartSystemServices();
}
Dispatcher& getMainDispatcher() {
return mainDispatcher;
}
namespace hal {
const Configuration* getConfiguration() {
return hardwareConfig;
}
} // namespace hal
} // namespace tt
+39
View File
@@ -0,0 +1,39 @@
#ifdef ESP_PLATFORM
#include "Tactility/PartitionsEsp.h"
#include "Tactility/TactilityCore.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "nvs_flash.h"
namespace tt {
#define TAG "tactility"
// Initialize NVS
static void initNvs() {
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
TT_LOG_I(TAG, "nvs erasing");
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK(ret);
TT_LOG_I(TAG, "nvs initialized");
}
static void initNetwork() {
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
}
void initEsp() {
initNvs();
initPartitionsEsp();
initNetwork();
}
} // namespace
#endif
+95
View File
@@ -0,0 +1,95 @@
#include "Tactility/hal/Device.h"
#include <Tactility/Mutex.h>
namespace tt::hal {
std::vector<std::shared_ptr<Device>> devices;
Mutex mutex = Mutex(Mutex::Type::Recursive);
static Device::Id nextId = 0;
#define TAG "devices"
Device::Device() : id(nextId++) {}
template <std::ranges::range RangeType>
auto toVector(RangeType&& range) {
auto view = range | std::views::common;
return std::vector(view.begin(), view.end());
}
void registerDevice(const std::shared_ptr<Device>& device) {
auto scoped_mutex = mutex.asScopedLock();
scoped_mutex.lock();
if (findDevice(device->getId()) == nullptr) {
devices.push_back(device);
TT_LOG_I(TAG, "Registered %s with id %lu", device->getName().c_str(), device->getId());
} else {
TT_LOG_W(TAG, "Device %s with id %lu was already registered", device->getName().c_str(), device->getId());
}
}
void deregisterDevice(const std::shared_ptr<Device>& device) {
auto scoped_mutex = mutex.asScopedLock();
scoped_mutex.lock();
auto id_to_remove = device->getId();
auto remove_iterator = std::remove_if(devices.begin(), devices.end(), [id_to_remove](const auto& device) {
return device->getId() == id_to_remove;
});
if (remove_iterator != devices.end()) {
TT_LOG_I(TAG, "Deregistering %s with id %lu", device->getName().c_str(), device->getId());
devices.erase(remove_iterator);
} else {
TT_LOG_W(TAG, "Deregistering %s with id %lu failed: not found", device->getName().c_str(), device->getId());
}
}
std::vector<std::shared_ptr<Device>> findDevices(const std::function<bool(const std::shared_ptr<Device>&)>& filterFunction) {
auto scoped_mutex = mutex.asScopedLock();
scoped_mutex.lock();
auto devices_view = devices | std::views::filter([&filterFunction](auto& device) {
return filterFunction(device);
});
return toVector(devices_view);
}
std::shared_ptr<Device> _Nullable findDevice(const std::function<bool(const std::shared_ptr<Device>&)>& filterFunction) {
auto scoped_mutex = mutex.asScopedLock();
scoped_mutex.lock();
auto result_set = devices | std::views::filter([&filterFunction](auto& device) {
return filterFunction(device);
});
if (!result_set.empty()) {
return result_set.front();
} else {
return nullptr;
}
}
std::shared_ptr<Device> _Nullable findDevice(std::string name) {
return findDevice([&name](auto& device){
return device->getName() == name;
});
}
std::shared_ptr<Device> _Nullable findDevice(Device::Id id) {
return findDevice([id](auto& device){
return device->getId() == id;
});
}
std::vector<std::shared_ptr<Device>> findDevices(Device::Type type) {
return findDevices([type](auto& device) {
return device->getType() == type;
});
}
std::vector<std::shared_ptr<Device>> getDevices() {
return devices;
}
}
+53
View File
@@ -0,0 +1,53 @@
#include "Tactility/hal/Configuration.h"
#include "Tactility/hal/Device.h"
#include "Tactility/hal/gps/GpsInit.h"
#include "Tactility/hal/i2c/I2cInit.h"
#include "Tactility/hal/power/PowerDevice.h"
#include "Tactility/hal/spi/SpiInit.h"
#include "Tactility/hal/uart/UartInit.h"
#include <Tactility/kernel/SystemEvents.h>
#define TAG "hal"
#define TT_SDCARD_MOUNT_POINT "/sdcard"
namespace tt::hal {
void init(const Configuration& configuration) {
kernel::systemEventPublish(kernel::SystemEvent::BootInitHalBegin);
kernel::systemEventPublish(kernel::SystemEvent::BootInitI2cBegin);
tt_check(i2c::init(configuration.i2c), "I2C init failed");
kernel::systemEventPublish(kernel::SystemEvent::BootInitI2cEnd);
kernel::systemEventPublish(kernel::SystemEvent::BootInitSpiBegin);
tt_check(spi::init(configuration.spi), "SPI init failed");
kernel::systemEventPublish(kernel::SystemEvent::BootInitSpiEnd);
kernel::systemEventPublish(kernel::SystemEvent::BootInitUartBegin);
tt_check(uart::init(configuration.uart), "UART init failed");
kernel::systemEventPublish(kernel::SystemEvent::BootInitUartEnd);
if (configuration.initBoot != nullptr) {
TT_LOG_I(TAG, "Init power");
tt_check(configuration.initBoot(), "Init power failed");
}
if (configuration.sdcard != nullptr) {
TT_LOG_I(TAG, "Mounting sdcard");
if (!configuration.sdcard->mount(TT_SDCARD_MOUNT_POINT)) {
TT_LOG_W(TAG, "SD card mount failed (init can continue)");
}
hal::registerDevice(configuration.sdcard);
}
if (configuration.power != nullptr) {
std::shared_ptr<tt::hal::power::PowerDevice> power = configuration.power();
hal::registerDevice(power);
}
kernel::systemEventPublish(kernel::SystemEvent::BootInitHalEnd);
}
} // namespace
@@ -0,0 +1,51 @@
#include "Tactility/hal/gps/GpsConfiguration.h"
#include "Tactility/service/gps/GpsService.h"
#include <Tactility/TactilityCore.h>
#include <Tactility/file/ObjectFile.h>
namespace tt::hal::gps {
const char* toString(GpsModel model) {
using enum GpsModel;
switch (model) {
case AG3335:
return TT_STRINGIFY(AG3335);
case AG3352:
return TT_STRINGIFY(AG3352);
case ATGM336H:
return TT_STRINGIFY(ATGM336H);
case LS20031:
return TT_STRINGIFY(LS20031);
case MTK:
return TT_STRINGIFY(MTK);
case MTK_L76B:
return TT_STRINGIFY(MTK_L76B);
case MTK_PA1616S:
return TT_STRINGIFY(MTK_PA1616S);
case UBLOX6:
return TT_STRINGIFY(UBLOX6);
case UBLOX7:
return TT_STRINGIFY(UBLOX7);
case UBLOX8:
return TT_STRINGIFY(UBLOX8);
case UBLOX9:
return TT_STRINGIFY(UBLOX9);
case UBLOX10:
return TT_STRINGIFY(UBLOX10);
case UC6580:
return TT_STRINGIFY(UC6580);
default:
return TT_STRINGIFY(Unknown);
}
}
std::vector<std::string> getModels() {
std::vector<std::string> result;
for (GpsModel model = GpsModel::Unknown; model <= GpsModel::UC6580; ++(int&)model) {
result.push_back(toString(model));
}
return result;
}
}
+189
View File
@@ -0,0 +1,189 @@
#include "Tactility/hal/gps/GpsDevice.h"
#include "Tactility/hal/gps/GpsInit.h"
#include "Tactility/hal/gps/Probe.h"
#include "Tactility/hal/uart/Uart.h"
#include <cstring>
#include <minmea.h>
namespace tt::hal::gps {
constexpr uint32_t GPS_UART_BUFFER_SIZE = 256;
constexpr const char* TAG = "GpsDevice";
int32_t GpsDevice::threadMainStatic(void* parameter) {
auto* gps_device = (GpsDevice*)parameter;
return gps_device->threadMain();
}
int32_t GpsDevice::threadMain() {
uint8_t buffer[GPS_UART_BUFFER_SIZE];
auto uart = uart::open(configuration.uartName);
if (uart == nullptr) {
TT_LOG_E(TAG, "Failed to open UART %s", configuration.uartName);
return -1;
}
if (!uart->start()) {
TT_LOG_E(TAG, "Failed to start UART %s", configuration.uartName);
return -1;
}
if (!uart->setBaudRate((int)configuration.baudRate)) {
TT_LOG_E(TAG, "Failed to set baud rate to %lu for UART %s", configuration.baudRate, configuration.uartName);
return -1;
}
GpsModel model = configuration.model;
if (model == GpsModel::Unknown) {
model = probe(*uart);
if (model == GpsModel::Unknown) {
TT_LOG_E(TAG, "Probe failed");
setState(State::Error);
return -1;
}
}
mutex.lock();
this->model = model;
mutex.unlock();
if (!init(*uart, model)) {
TT_LOG_E(TAG, "Init failed");
setState(State::Error);
return -1;
}
setState(State::On);
// Reference: https://gpsd.gitlab.io/gpsd/NMEA.html
while (!isThreadInterrupted()) {
size_t bytes_read = uart->readUntil(reinterpret_cast<std::byte*>(buffer), GPS_UART_BUFFER_SIZE, '\n', 100 / portTICK_PERIOD_MS);
// Thread might've been interrupted in the meanwhile
if (isThreadInterrupted()) {
break;
}
if (bytes_read > 0U) {
TT_LOG_I(TAG, "[%ul] %s", bytes_read, buffer);
switch (minmea_sentence_id((char*)buffer, false)) {
case MINMEA_SENTENCE_RMC:
minmea_sentence_rmc rmc_frame;
if (minmea_parse_rmc(&rmc_frame, (char*)buffer)) {
mutex.lock();
for (auto& subscription : rmcSubscriptions) {
(*subscription.onData)(getId(), rmc_frame);
}
mutex.unlock();
TT_LOG_D(TAG, "RMC %f lat, %f lon, %f m/s", minmea_tocoord(&rmc_frame.latitude), minmea_tocoord(&rmc_frame.longitude), minmea_tofloat(&rmc_frame.speed));
} else {
TT_LOG_W(TAG, "RMC parse error: %s", buffer);
}
break;
case MINMEA_SENTENCE_GGA:
minmea_sentence_gga gga_frame;
if (minmea_parse_gga(&gga_frame, (char*)buffer)) {
mutex.lock();
for (auto& subscription : ggaSubscriptions) {
(*subscription.onData)(getId(), gga_frame);
}
mutex.unlock();
TT_LOG_D(TAG, "GGA %f lat, %f lon", minmea_tocoord(&gga_frame.latitude), minmea_tocoord(&gga_frame.longitude));
} else {
TT_LOG_W(TAG, "GGA parse error: %s", buffer);
}
break;
default:
break;
}
}
}
if (uart->isStarted() && !uart->stop()) {
TT_LOG_W(TAG, "Failed to stop UART %s", configuration.uartName);
}
return 0;
}
bool GpsDevice::start() {
auto lock = mutex.asScopedLock();
lock.lock();
if (thread != nullptr && thread->getState() != Thread::State::Stopped) {
TT_LOG_W(TAG, "Already started");
return true;
}
threadInterrupted = false;
TT_LOG_I(TAG, "Starting thread");
setState(State::PendingOn);
thread = std::make_unique<Thread>(
"gps",
4096,
threadMainStatic,
this
);
thread->setPriority(tt::Thread::Priority::High);
thread->start();
TT_LOG_I(TAG, "Starting finished");
return true;
}
bool GpsDevice::stop() {
auto lock = mutex.asScopedLock();
lock.lock();
setState(State::PendingOff);
if (thread != nullptr) {
threadInterrupted = true;
// Detach thread, it will auto-delete when leaving the current scope
auto old_thread = std::move(thread);
if (old_thread->getState() != Thread::State::Stopped) {
// Unlock so thread can lock
lock.unlock();
// Wait for thread to finish
old_thread->join();
// Re-lock to continue logic below
lock.lock();
}
}
setState(State::Off);
return true;
}
bool GpsDevice::isThreadInterrupted() const {
auto lock = mutex.asScopedLock();
lock.lock();
return threadInterrupted;
}
GpsModel GpsDevice::getModel() const {
auto lock = mutex.asScopedLock();
lock.lock();
return model; // Make copy because of thread safety
}
GpsDevice::State GpsDevice::getState() const {
auto lock = mutex.asScopedLock();
lock.lock();
return state; // Make copy because of thread safety
}
void GpsDevice::setState(State newState) {
auto lock = mutex.asScopedLock();
lock.lock();
state = newState;
}
} // namespace tt::hal::gps
+288
View File
@@ -0,0 +1,288 @@
#include "Tactility/hal/gps/Cas.h"
#include "Tactility/hal/gps/GpsDevice.h"
#include "Tactility/hal/gps/Ublox.h"
#include <cstring>
#define TAG "gps"
namespace tt::hal::gps {
bool initMtk(uart::Uart& uart);
bool initMtkL76b(uart::Uart& uart);
bool initMtkPa1616s(uart::Uart& uart);
bool initAtgm336h(uart::Uart& uart);
bool initUc6580(uart::Uart& uart);
bool initAg33xx(uart::Uart& uart);
// region CAS
// Calculate the checksum for a CAS packet
static void CASChecksum(uint8_t *message, size_t length)
{
uint32_t cksum = ((uint32_t)message[5] << 24); // Message ID
cksum += ((uint32_t)message[4]) << 16; // Class
cksum += message[2]; // Payload Len
// Iterate over the payload as a series of uint32_t's and
// accumulate the cksum
for (size_t i = 0; i < (length - 10) / 4; i++) {
uint32_t pl = 0;
memcpy(&pl, (message + 6) + (i * sizeof(uint32_t)), sizeof(uint32_t)); // avoid pointer dereference
cksum += pl;
}
// Place the checksum values in the message
message[length - 4] = (cksum & 0xFF);
message[length - 3] = (cksum & (0xFF << 8)) >> 8;
message[length - 2] = (cksum & (0xFF << 16)) >> 16;
message[length - 1] = (cksum & (0xFF << 24)) >> 24;
}
// Function to create a CAS packet for editing in memory
static uint8_t makeCASPacket(uint8_t* buffer, uint8_t class_id, uint8_t msg_id, uint8_t payload_size, const uint8_t *msg)
{
// General CAS structure
// | H1 | H2 | payload_len | cls | msg | Payload ... | Checksum |
// Size: | 1 | 1 | 2 | 1 | 1 | payload_len | 4 |
// Pos: | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 ... | 6 + payload_len ... |
// |------|------|-------------|------|------|------|--------------|---------------------------|
// | 0xBA | 0xCE | 0xXX | 0xXX | 0xXX | 0xXX | 0xXX | 0xXX ... | 0xXX | 0xXX | 0xXX | 0xXX |
// Construct the CAS packet
buffer[0] = 0xBA; // header 1 (0xBA)
buffer[1] = 0xCE; // header 2 (0xCE)
buffer[2] = payload_size; // length 1
buffer[3] = 0; // length 2
buffer[4] = class_id; // class
buffer[5] = msg_id; // id
buffer[6 + payload_size] = 0x00; // Checksum
buffer[7 + payload_size] = 0x00;
buffer[8 + payload_size] = 0x00;
buffer[9 + payload_size] = 0x00;
for (int i = 0; i < payload_size; i++) {
buffer[6 + i] = msg[i];
}
CASChecksum(buffer, (payload_size + 10));
return (payload_size + 10);
}
GpsResponse getACKCas(uart::Uart& uart, uint8_t class_id, uint8_t msg_id, uint32_t waitMillis)
{
uint32_t startTime = kernel::getMillis();
uint8_t buffer[CAS_ACK_NACK_MSG_SIZE] = {0};
uint8_t bufferPos = 0;
// CAS-ACK-(N)ACK structure
// | H1 | H2 | Payload Len | cls | msg | Payload | Checksum (4) |
// | | | | | | Cls | Msg | Reserved | |
// |------|------|-------------|------|------|------|------|-------------|---------------------------|
// ACK-NACK| 0xBA | 0xCE | 0x04 | 0x00 | 0x05 | 0x00 | 0xXX | 0xXX | 0x00 | 0x00 | 0xXX | 0xXX | 0xXX | 0xXX |
// ACK-ACK | 0xBA | 0xCE | 0x04 | 0x00 | 0x05 | 0x01 | 0xXX | 0xXX | 0x00 | 0x00 | 0xXX | 0xXX | 0xXX | 0xXX |
while (kernel::getTicks() - startTime < waitMillis) {
if (uart.available()) {
uart.readByte(&buffer[bufferPos++]);
// keep looking at the first two bytes of buffer until
// we have found the CAS frame header (0xBA, 0xCE), if not
// keep reading bytes until we find a frame header or we run
// out of time.
if ((bufferPos == 2) && !(buffer[0] == 0xBA && buffer[1] == 0xCE)) {
buffer[0] = buffer[1];
buffer[1] = 0;
bufferPos = 1;
}
}
// we have read all the bytes required for the Ack/Nack (14-bytes)
// and we must have found a frame to get this far
if (bufferPos == sizeof(buffer) - 1) {
uint8_t msg_cls = buffer[4]; // message class should be 0x05
uint8_t msg_msg_id = buffer[5]; // message id should be 0x00 or 0x01
uint8_t payload_cls = buffer[6]; // payload class id
uint8_t payload_msg = buffer[7]; // payload message id
// Check for an ACK-ACK for the specified class and message id
if ((msg_cls == 0x05) && (msg_msg_id == 0x01) && payload_cls == class_id && payload_msg == msg_id) {
#ifdef GPS_DEBUG
LOG_INFO("Got ACK for class %02X message %02X in %dms", class_id, msg_id, millis() - startTime);
#endif
return GpsResponse::Ok;
}
// Check for an ACK-NACK for the specified class and message id
if ((msg_cls == 0x05) && (msg_msg_id == 0x00) && payload_cls == class_id && payload_msg == msg_id) {
#ifdef GPS_DEBUG
LOG_WARN("Got NACK for class %02X message %02X in %dms", class_id, msg_id, millis() - startTime);
#endif
return GpsResponse::NotAck;
}
// This isn't the frame we are looking for, clear the buffer
// and try again until we run out of time.
memset(buffer, 0x0, sizeof(buffer));
bufferPos = 0;
}
}
return GpsResponse::None;
}
// endregion
bool init(uart::Uart& uart, GpsModel type) {
switch (type) {
case GpsModel::Unknown:
tt_crash();
case GpsModel::AG3335:
case GpsModel::AG3352:
return initAg33xx(uart);
case GpsModel::ATGM336H:
return initAtgm336h(uart);
case GpsModel::LS20031:
return true;
case GpsModel::MTK:
return initMtk(uart);
case GpsModel::MTK_L76B:
return initMtkL76b(uart);
case GpsModel::MTK_PA1616S:
return initMtkPa1616s(uart);
case GpsModel::UBLOX6:
case GpsModel::UBLOX7:
case GpsModel::UBLOX8:
case GpsModel::UBLOX9:
case GpsModel::UBLOX10:
return ublox::init(uart, type);
case GpsModel::UC6580:
return initUc6580(uart);
}
TT_LOG_I(TAG, "Init not implemented %d", static_cast<int>(type));
return false;
}
bool initAg33xx(uart::Uart& uart) {
uart.writeString("$PAIR066,1,0,1,0,0,1*3B\r\n"); // Enable GPS+GALILEO+NAVIC
// Configure NMEA (sentences will output once per fix)
uart.writeString("$PAIR062,0,1*3F\r\n"); // GGA ON
uart.writeString("$PAIR062,1,0*3F\r\n"); // GLL OFF
uart.writeString("$PAIR062,2,0*3C\r\n"); // GSA OFF
uart.writeString("$PAIR062,3,0*3D\r\n"); // GSV OFF
uart.writeString("$PAIR062,4,1*3B\r\n"); // RMC ON
uart.writeString("$PAIR062,5,0*3B\r\n"); // VTG OFF
uart.writeString("$PAIR062,6,0*38\r\n"); // ZDA ON
kernel::delayMillis(250);
uart.writeString("$PAIR513*3D\r\n"); // save configuration
return true;
}
bool initUc6580(uart::Uart& uart) {
// The Unicore UC6580 can use a lot of sat systems, enable it to
// use GPS L1 & L5 + BDS B1I & B2a + GLONASS L1 + GALILEO E1 & E5a + SBAS + QZSS
// This will reset the receiver, so wait a bit afterwards
// The paranoid will wait for the OK*04 confirmation response after each command.
uart.writeString("$CFGSYS,h35155\r\n");
kernel::delayMillis(750);
// Must be done after the CFGSYS command
// Turn off GSV messages, we don't really care about which and where the sats are, maybe someday.
uart.writeString("$CFGMSG,0,3,0\r\n");
kernel::delayMillis(250);
// Turn off GSA messages, TinyGPS++ doesn't use this message.
uart.writeString("$CFGMSG,0,2,0\r\n");
kernel::delayMillis(250);
// Turn off NOTICE __TXT messages, these may provide Unicore some info but we don't care.
uart.writeString("$CFGMSG,6,0,0\r\n");
kernel::delayMillis(250);
uart.writeString("$CFGMSG,6,1,0\r\n");
kernel::delayMillis(250);
return true;
}
bool initAtgm336h(uart::Uart& uart) {
uint8_t buffer[256];
// Set the intial configuration of the device - these _should_ work for most AT6558 devices
int msglen = makeCASPacket(buffer, 0x06, 0x07, sizeof(_message_CAS_CFG_NAVX_CONF), _message_CAS_CFG_NAVX_CONF);
uart.writeBytes(buffer, msglen);
if (getACKCas(uart, 0x06, 0x07, 250) != GpsResponse::Ok) {
TT_LOG_W(TAG, "ATGM336H: Could not set Config");
}
// Set the update frequence to 1Hz
msglen = makeCASPacket(buffer, 0x06, 0x04, sizeof(_message_CAS_CFG_RATE_1HZ), _message_CAS_CFG_RATE_1HZ);
uart.writeBytes(buffer, msglen);
if (getACKCas(uart, 0x06, 0x04, 250) != GpsResponse::Ok) {
TT_LOG_W(TAG, "ATGM336H: Could not set Update Frequency");
}
// Set the NEMA output messages
// Ask for only RMC and GGA
uint8_t fields[] = {CAS_NEMA_RMC, CAS_NEMA_GGA};
for (unsigned int i = 0; i < sizeof(fields); i++) {
// Construct a CAS-CFG-MSG packet
uint8_t cas_cfg_msg_packet[] = {0x4e, fields[i], 0x01, 0x00};
msglen = makeCASPacket(buffer, 0x06, 0x01, sizeof(cas_cfg_msg_packet), cas_cfg_msg_packet);
uart.writeBytes(buffer, msglen);
if (getACKCas(uart, 0x06, 0x01, 250) != GpsResponse::Ok) {
TT_LOG_W(TAG, "ATGM336H: Could not enable NMEA MSG: %d", fields[i]);
}
}
return true;
}
bool initMtkPa1616s(uart::Uart& uart) {
// PA1616S is used in some GPS breakout boards from Adafruit
// PA1616S does not have GLONASS capability. PA1616D does, but is not implemented here.
uart.writeString("$PMTK353,1,0,0,0,0*2A\r\n");
// Above command will reset the GPS and takes longer before it will accept new commands
kernel::delayMillis(1000);
// Only ask for RMC and GGA (GNRMC and GNGGA)
uart.writeString("$PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*28\r\n");
kernel::delayMillis(250);
// Enable SBAS / WAAS
uart.writeString("$PMTK301,2*2E\r\n");
kernel::delayMillis(250);
return true;
}
bool initMtkL76b(uart::Uart& uart) {
// Waveshare Pico-GPS hat uses the L76B with 9600 baud
// Initialize the L76B Chip, use GPS + GLONASS
// See note in L76_Series_GNSS_Protocol_Specification, chapter 3.29
uart.writeString("$PMTK353,1,1,0,0,0*2B\r\n");
// Above command will reset the GPS and takes longer before it will accept new commands
kernel::delayMillis(1000);
// only ask for RMC and GGA (GNRMC and GNGGA)
// See note in L76_Series_GNSS_Protocol_Specification, chapter 2.1
uart.writeString("$PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*28\r\n");
kernel::delayMillis(250);
// Enable SBAS
uart.writeString("$PMTK301,2*2E\r\n");
kernel::delayMillis(250);
// Enable PPS for 2D/3D fix only
uart.writeString("$PMTK285,3,100*3F\r\n");
kernel::delayMillis(250);
// Switch to Fitness Mode, for running and walking purpose with low speed (<5 m/s)
uart.writeString("$PMTK886,1*29\r\n");
kernel::delayMillis(250);
return true;
}
bool initMtk(uart::Uart& uart) {
// Initialize the L76K Chip, use GPS + GLONASS + BEIDOU
uart.writeString("$PCAS04,7*1E\r\n");
kernel::delayMillis(250);
// only ask for RMC and GGA
uart.writeString("$PCAS03,1,0,0,0,1,0,0,0,0,0,,,0,0*02\r\n");
kernel::delayMillis(250);
// Switch to Vehicle Mode, since SoftRF enables Aviation < 2g
uart.writeString("$PCAS11,3*1E\r\n");
kernel::delayMillis(250);
return true;
}
} // namespace tt::hal::gps
+140
View File
@@ -0,0 +1,140 @@
#include "Tactility/hal/gps/GpsDevice.h"
#include "Tactility/hal/gps/Ublox.h"
#include <Tactility/Log.h>
#include <Tactility/hal/uart/Uart.h>
#include <Tactility/kernel/Kernel.h>
#include <cstring>
#define TAG "gps"
#define GPS_UART_BUFFER_SIZE 256
using namespace tt;
using namespace tt::hal;
namespace tt::hal::gps {
/**
* From: https://github.com/meshtastic/firmware/blob/3b0232de1b6282eacfbff6e50b68fca7e67b8511/src/meshUtils.cpp#L40
*/
char* strnstr(const char* s, const char* find, size_t slen) {
char c;
if ((c = *find++) != '\0') {
char sc;
size_t len;
len = strlen(find);
do {
do {
if (slen-- < 1 || (sc = *s++) == '\0')
return (nullptr);
} while (sc != c);
if (len > slen)
return (nullptr);
} while (strncmp(s, find, len) != 0);
s--;
}
return ((char*)s);
}
/**
* From: https://github.com/meshtastic/firmware/blob/f81d3b045dd1b7e3ca7870af3da915ff4399ea98/src/gps/GPS.cpp
*/
GpsResponse getAck(uart::Uart& uart, const char* message, uint32_t waitMillis) {
uint8_t buffer[768] = {0};
uint8_t b;
int bytesRead = 0;
uint32_t startTimeout = kernel::getMillis() + waitMillis;
#ifdef GPS_DEBUG
std::string debugmsg = "";
#endif
while (kernel::getMillis() < startTimeout) {
if (uart.available()) {
uart.readByte(&b);
#ifdef GPS_DEBUG
debugmsg += vformat("%c", (b >= 32 && b <= 126) ? b : '.');
#endif
buffer[bytesRead] = b;
bytesRead++;
if ((bytesRead == 767) || (b == '\r')) {
if (strnstr((char*)buffer, message, bytesRead) != nullptr) {
#ifdef GPS_DEBUG
LOG_DEBUG("Found: %s", message); // Log the found message
#endif
return GpsResponse::Ok;
} else {
bytesRead = 0;
#ifdef GPS_DEBUG
LOG_DEBUG(debugmsg.c_str());
#endif
}
}
}
}
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 { \
TT_LOG_I(TAG, "Probing for %s (%s)", CHIP, TOWRITE); \
UART.flushInput(); \
UART.writeString(TOWRITE "\r\n", TIMEOUT); \
if (getAck(UART, RESPONSE, TIMEOUT) == GpsResponse::Ok) { \
TT_LOG_I(TAG, "Probe detected %s %s", CHIP, #DRIVER); \
return DRIVER; \
} \
} while (0)
/**
* From: https://github.com/meshtastic/firmware/blob/f81d3b045dd1b7e3ca7870af3da915ff4399ea98/src/gps/GPS.cpp
*/
GpsModel probe(uart::Uart& uart) {
// Close all NMEA sentences, valid for L76K, ATGM336H (and likely other AT6558 devices)
uart.writeString("$PCAS03,0,0,0,0,0,0,0,0,0,0,,,0,0*02\r\n");
kernel::delayMillis(20);
// Close NMEA sequences on Ublox
uart.writeString("$PUBX,40,GLL,0,0,0,0,0,0*5C\r\n");
uart.writeString("$PUBX,40,GSV,0,0,0,0,0,0*59\r\n");
uart.writeString("$PUBX,40,VTG,0,0,0,0,0,0*5E\r\n");
kernel::delayMillis(20);
// Unicore UFirebirdII Series: UC6580, UM620, UM621, UM670A, UM680A, or UM681A
PROBE_SIMPLE(uart, "UC6580", "$PDTINFO", "UC6580", GpsModel::UC6580, 500);
PROBE_SIMPLE(uart, "UM600", "$PDTINFO", "UM600", GpsModel::UC6580, 500);
PROBE_SIMPLE(uart, "ATGM336H", "$PCAS06,1*1A", "$GPTXT,01,01,02,HW=ATGM336H", GpsModel::ATGM336H, 500);
/* ATGM332D series (-11(GPS), -21(BDS), -31(GPS+BDS), -51(GPS+GLONASS), -71-0(GPS+BDS+GLONASS))
based on AT6558 */
PROBE_SIMPLE(uart, "ATGM332D", "$PCAS06,1*1A", "$GPTXT,01,01,02,HW=ATGM332D", GpsModel::ATGM336H, 500);
/* Airoha (Mediatek) AG3335A/M/S, A3352Q, Quectel L89 2.0, SimCom SIM65M */
uart.writeString("$PAIR062,2,0*3C\r\n"); // GSA OFF to reduce volume
uart.writeString("$PAIR062,3,0*3D\r\n"); // GSV OFF to reduce volume
uart.writeString("$PAIR513*3D\r\n"); // save configuration
PROBE_SIMPLE(uart, "AG3335", "$PAIR021*39", "$PAIR021,AG3335", GpsModel::AG3335, 500);
PROBE_SIMPLE(uart, "AG3352", "$PAIR021*39", "$PAIR021,AG3352", GpsModel::AG3352, 500);
PROBE_SIMPLE(uart, "LC86", "$PQTMVERNO*58", "$PQTMVERNO,LC86", GpsModel::AG3352, 500);
PROBE_SIMPLE(uart, "L76K", "$PCAS06,0*1B", "$GPTXT,01,01,02,SW=", GpsModel::MTK, 500);
// Close all NMEA sentences, valid for L76B MTK platform (Waveshare Pico GPS)
uart.writeString("$PMTK514,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*2E\r\n");
kernel::delayMillis(20);
PROBE_SIMPLE(uart, "L76B", "$PMTK605*31", "Quectel-L76B", GpsModel::MTK_L76B, 500);
PROBE_SIMPLE(uart, "PA1616S", "$PMTK605*31", "1616S", GpsModel::MTK_PA1616S, 500);
auto ublox_result = ublox::probe(uart);
if (ublox_result != GpsModel::Unknown) {
return ublox_result;
} else {
TT_LOG_W(TAG, "No GNSS Module (baudrate %lu)", uart.getBaudRate());
return GpsModel::Unknown;
}
}
} // namespace tt::hal::gps
+114
View File
@@ -0,0 +1,114 @@
#include "Tactility/hal/gps/Satellites.h"
#include <algorithm>
#define TAG "satellites"
namespace tt::hal::gps {
constexpr inline bool hasTimeElapsed(TickType_t now, TickType_t timeInThePast, TickType_t expireTimeInTicks) {
return (TickType_t)(now - timeInThePast) >= expireTimeInTicks;
}
SatelliteStorage::SatelliteRecord* SatelliteStorage::findRecord(int number) {
auto result = records | std::views::filter([number](auto& record) {
return record.inUse && record.data.nr == number;
});
if (!result.empty()) {
return &result.front();
} else {
return nullptr;
}
}
SatelliteStorage::SatelliteRecord* SatelliteStorage::findUnusedRecord() {
auto lock = mutex.asScopedLock();
lock.lock();
auto result = records | std::views::filter([](auto& record) {
return !record.inUse;
});
if (!result.empty()) {
auto* record = &result.front();
record->inUse = true;
TT_LOG_D(TAG, "Found unused record");
return record;
} else {
return nullptr;
}
}
SatelliteStorage::SatelliteRecord* SatelliteStorage::findRecordToRecycle() {
auto lock = mutex.asScopedLock();
lock.lock();
int candidate_index = -1;
auto candidate_age = portMAX_DELAY;
TickType_t expire_duration = kernel::secondsToTicks(recycleTimeSeconds);
TickType_t now = kernel::getTicks();
for (int i = 0; i < records.size(); ++i) {
// First try to find a record that is "old enough"
if (hasTimeElapsed(now, records[i].lastUpdated, expire_duration)) {
TT_LOG_D(TAG, "! [%d] %lu < %lu", i, records[i].lastUpdated, expire_duration);
candidate_index = i;
break;
}
// Otherwise keep finding the oldest record
if (records[i].inUse && records[i].lastUpdated < candidate_age) {
candidate_index = i;
candidate_age = records[i].lastUpdated;
TT_LOG_D(TAG, "? [%d] %lu < %lu", i, records[i].lastUpdated, candidate_age);
}
}
assert(candidate_index != -1);
TT_LOG_D(TAG, "Recycled record %d", candidate_index);
return &records[candidate_index];
}
SatelliteStorage::SatelliteRecord* SatelliteStorage::findWithFallback(int number) {
auto lock = mutex.asScopedLock();
lock.lock();
if (auto* found_record = findRecord(number)) {
return found_record;
} else if (auto* unused_record = findUnusedRecord()) {
return unused_record;
} else {
return findRecordToRecycle();
}
}
void SatelliteStorage::notify(const minmea_sat_info& data) {
auto lock = mutex.asScopedLock();
lock.lock();
auto* record = findWithFallback(data.nr);
if (record != nullptr) {
record->inUse = true;
record->lastUpdated = kernel::getTicks();
record->data = data;
TT_LOG_D(TAG, "Updated satellite %d: elevation %d, azimuth %d, snr %d", record->data.nr, record->data.elevation, record->data.elevation, record->data.snr);
}
}
void SatelliteStorage::getRecords(const std::function<void(const minmea_sat_info&)>& onRecord) const {
auto lock = mutex.asScopedLock();
lock.lock();
TickType_t expire_duration = kernel::secondsToTicks(recentTimeSeconds);
TickType_t now = kernel::getTicks();
for (auto& record: records) {
if (record.inUse && !hasTimeElapsed(now, record.lastUpdated, expire_duration)) {
onRecord(record.data);
}
}
}
} // namespace tt::hal::gps
+480
View File
@@ -0,0 +1,480 @@
#include "Tactility/hal/gps/Ublox.h"
#include "Tactility/hal/gps/UbloxMessages.h"
#include "Tactility/hal/uart/Uart.h"
#include <cstring>
#define TAG "ublox"
namespace tt::hal::gps::ublox {
bool initUblox6(uart::Uart& uart);
bool initUblox789(uart::Uart& uart, GpsModel model);
bool initUblox10(uart::Uart& uart);
#define SEND_UBX_PACKET(UART, BUFFER, TYPE, ID, DATA, ERRMSG, TIMEOUT) \
do { \
auto msglen = makePacket(TYPE, ID, DATA, sizeof(DATA), BUFFER); \
UART.writeBytes(BUFFER, sizeof(BUFFER)); \
if (getAck(UART, TYPE, ID, TIMEOUT) != GpsResponse::Ok) { \
TT_LOG_I(TAG, "Sending packet failed: %s", #ERRMSG); \
} \
} while (0)
void checksum(uint8_t* message, size_t length) {
uint8_t CK_A = 0, CK_B = 0;
// Calculate the checksum, starting from the CLASS field (which is message[2])
for (size_t i = 2; i < length - 2; i++) {
CK_A = (CK_A + message[i]) & 0xFF;
CK_B = (CK_B + CK_A) & 0xFF;
}
// Place the calculated checksum values in the message
message[length - 2] = CK_A;
message[length - 1] = CK_B;
}
uint8_t makePacket(uint8_t classId, uint8_t messageId, const uint8_t* payload, uint8_t payloadSize, uint8_t* bufferOut) {
// Construct the UBX packet
bufferOut[0] = 0xB5U; // header
bufferOut[1] = 0x62U; // header
bufferOut[2] = classId; // class
bufferOut[3] = messageId; // id
bufferOut[4] = payloadSize; // length
bufferOut[5] = 0x00U;
bufferOut[6 + payloadSize] = 0x00U; // CK_A
bufferOut[7 + payloadSize] = 0x00U; // CK_B
for (int i = 0; i < payloadSize; i++) {
bufferOut[6 + i] = payload[i];
}
checksum(bufferOut, (payloadSize + 8U));
return (payloadSize + 8U);
}
GpsResponse getAck(uart::Uart& uart, uint8_t class_id, uint8_t msg_id, uint32_t waitMillis) {
uint8_t b;
uint8_t ack = 0;
const uint8_t ackP[2] = {class_id, msg_id};
uint8_t buf[10] = {0xB5, 0x62, 0x05, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00};
uint32_t startTime = kernel::getMillis();
const char frame_errors[] = "More than 100 frame errors";
int sCounter = 0;
#ifdef GPS_DEBUG
std::string debugmsg = "";
#endif
for (int j = 2; j < 6; j++) {
buf[8] += buf[j];
buf[9] += buf[8];
}
for (int j = 0; j < 2; j++) {
buf[6 + j] = ackP[j];
buf[8] += buf[6 + j];
buf[9] += buf[8];
}
while (kernel::getTicks() - startTime < waitMillis) {
if (ack > 9) {
#ifdef GPS_DEBUG
TT_LOG_I(TAG, "Got ACK for class %02X message %02X in %lums", class_id, msg_id, kernel::getMillis() - startTime);
#endif
return GpsResponse::Ok; // ACK received
}
if (uart.available()) {
uart.readByte(&b);
if (b == frame_errors[sCounter]) {
sCounter++;
if (sCounter == 26) {
#ifdef GPS_DEBUG
TT_LOG_I(TAG, "%s", debugmsg.c_str());
#endif
return GpsResponse::FrameErrors;
}
} else {
sCounter = 0;
}
#ifdef GPS_DEBUG
debugmsg += std::format("%02X", b);
#endif
if (b == buf[ack]) {
ack++;
} else {
if (ack == 3 && b == 0x00) { // UBX-ACK-NAK message
#ifdef GPS_DEBUG
TT_LOG_I(TAG, "%s", debugmsg.c_str());
#endif
TT_LOG_W(TAG, "Got NAK for class %02X message %02X", class_id, msg_id);
return GpsResponse::NotAck; // NAK received
}
ack = 0; // Reset the acknowledgement counter
}
}
}
#ifdef GPS_DEBUG
TT_LOG_I(TAG, "%s", debugmsg.c_str());
TT_LOG_W(TAG, "No response for class %02X message %02X", class_id, msg_id);
#endif
return GpsResponse::None; // No response received within timeout
}
static int getAck(uart::Uart& uart, uint8_t* buffer, uint16_t size, uint8_t requestedClass, uint8_t requestedId, TickType_t timeout) {
uint16_t ubxFrameCounter = 0;
uint32_t startTime = kernel::getTicks();
uint16_t needRead = 0;
while (kernel::getTicks() - startTime < timeout) {
while (uart.available()) {
uint8_t c;
uart.readByte(&c);
switch (ubxFrameCounter) {
case 0:
if (c == 0xB5) {
ubxFrameCounter++;
}
break;
case 1:
if (c == 0x62) {
ubxFrameCounter++;
} else {
ubxFrameCounter = 0;
}
break;
case 2:
if (c == requestedClass) {
ubxFrameCounter++;
} else {
ubxFrameCounter = 0;
}
break;
case 3:
if (c == requestedId) {
ubxFrameCounter++;
} else {
ubxFrameCounter = 0;
}
break;
case 4:
needRead = c;
ubxFrameCounter++;
break;
case 5: {
// Payload length msb
needRead |= (c << 8);
ubxFrameCounter++;
// Check for buffer overflow
if (needRead >= size) {
ubxFrameCounter = 0;
break;
}
auto read_bytes = uart.readBytes(buffer, needRead, 250 / portTICK_PERIOD_MS);
if (read_bytes != needRead) {
ubxFrameCounter = 0;
} else {
// return payload length
#ifdef GPS_DEBUG
TT_LOG_I(TAG, "Got ACK for class %02X message %02X in %lums", requestedClass, requestedId, kernel::getMillis() - startTime);
#endif
return needRead;
}
break;
}
default:
break;
}
}
}
return 0;
}
#define DETECTED_MESSAGE "%s detected, using %s Module"
static struct uBloxGnssModelInfo {
char swVersion[30];
char hwVersion[10];
uint8_t extensionNo;
char extension[10][30];
uint8_t protocol_version;
} ublox_info;
GpsModel probe(uart::Uart& uart) {
TT_LOG_I(TAG, "Probing for U-blox");
uint8_t cfg_rate[] = {0xB5, 0x62, 0x06, 0x08, 0x00, 0x00, 0x00, 0x00};
checksum(cfg_rate, sizeof(cfg_rate));
uart.flushInput();
uart.writeBytes(cfg_rate, sizeof(cfg_rate));
// Check that the returned response class and message ID are correct
GpsResponse response = getAck(uart, 0x06, 0x08, 750);
if (response == GpsResponse::None) {
TT_LOG_W(TAG, "No GNSS Module (baudrate %lu)", uart.getBaudRate());
return GpsModel::Unknown;
} else if (response == GpsResponse::FrameErrors) {
TT_LOG_W(TAG, "UBlox Frame Errors (baudrate %lu)", uart.getBaudRate());
}
uint8_t buffer[256];
memset(buffer, 0, sizeof(buffer));
uint8_t _message_MONVER[8] = {
0xB5, 0x62, // Sync message for UBX protocol
0x0A, 0x04, // Message class and ID (UBX-MON-VER)
0x00, 0x00, // Length of payload (we're asking for an answer, so no payload)
0x00, 0x00 // Checksum
};
// Get Ublox gnss module hardware and software info
checksum(_message_MONVER, sizeof(_message_MONVER));
uart.flushInput();
uart.writeBytes(_message_MONVER, sizeof(_message_MONVER));
uint16_t ack_response_len = getAck(uart, buffer, sizeof(buffer), 0x0A, 0x04, 1200);
if (ack_response_len) {
uint16_t position = 0;
for (char& i: ublox_info.swVersion) {
i = buffer[position];
position++;
}
for (char& i: ublox_info.hwVersion) {
i = buffer[position];
position++;
}
while (ack_response_len >= position + 30) {
for (int i = 0; i < 30; i++) {
ublox_info.extension[ublox_info.extensionNo][i] = buffer[position];
position++;
}
ublox_info.extensionNo++;
if (ublox_info.extensionNo > 9)
break;
}
TT_LOG_I(TAG, "Module Info : ");
TT_LOG_I(TAG, "Soft version: %s", ublox_info.swVersion);
TT_LOG_I(TAG, "Hard version: %s", ublox_info.hwVersion);
TT_LOG_I(TAG, "Extensions:%d", ublox_info.extensionNo);
for (int i = 0; i < ublox_info.extensionNo; i++) {
TT_LOG_I(TAG, " %s", ublox_info.extension[i]);
}
memset(buffer, 0, sizeof(buffer));
// tips: extensionNo field is 0 on some 6M GNSS modules
for (int i = 0; i < ublox_info.extensionNo; ++i) {
if (!strncmp(ublox_info.extension[i], "MOD=", 4)) {
strncpy((char*)buffer, &(ublox_info.extension[i][4]), sizeof(buffer));
} else if (!strncmp(ublox_info.extension[i], "PROTVER", 7)) {
char* ptr = nullptr;
memset(buffer, 0, sizeof(buffer));
strncpy((char*)buffer, &(ublox_info.extension[i][8]), sizeof(buffer));
TT_LOG_I(TAG, "Protocol Version:%s", (char*)buffer);
if (strlen((char*)buffer)) {
ublox_info.protocol_version = strtoul((char*)buffer, &ptr, 10);
TT_LOG_I(TAG, "ProtVer=%d", ublox_info.protocol_version);
} else {
ublox_info.protocol_version = 0;
}
}
}
if (strncmp(ublox_info.hwVersion, "00040007", 8) == 0) {
TT_LOG_I(TAG, DETECTED_MESSAGE, "U-blox 6", "6");
return GpsModel::UBLOX6;
} else if (strncmp(ublox_info.hwVersion, "00070000", 8) == 0) {
TT_LOG_I(TAG, DETECTED_MESSAGE, "U-blox 7", "7");
return GpsModel::UBLOX7;
} else if (strncmp(ublox_info.hwVersion, "00080000", 8) == 0) {
TT_LOG_I(TAG, DETECTED_MESSAGE, "U-blox 8", "8");
return GpsModel::UBLOX8;
} else if (strncmp(ublox_info.hwVersion, "00190000", 8) == 0) {
TT_LOG_I(TAG, DETECTED_MESSAGE, "U-blox 9", "9");
return GpsModel::UBLOX9;
} else if (strncmp(ublox_info.hwVersion, "000A0000", 8) == 0) {
TT_LOG_I(TAG, DETECTED_MESSAGE, "U-blox 10", "10");
return GpsModel::UBLOX10;
}
}
return GpsModel::Unknown;
}
bool init(uart::Uart& uart, GpsModel model) {
TT_LOG_I(TAG, "U-blox init");
switch (model) {
case GpsModel::UBLOX6:
return initUblox6(uart);
case GpsModel::UBLOX7:
case GpsModel::UBLOX8:
case GpsModel::UBLOX9:
return initUblox789(uart, model);
case GpsModel::UBLOX10:
return initUblox10(uart);
default:
TT_LOG_E(TAG, "Unknown or unsupported U-blox model");
return false;
}
}
bool initUblox10(uart::Uart& uart) {
uint8_t buffer[256];
kernel::delayMillis(1000);
uart.flushInput();
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_DISABLE_NMEA_RAM, "disable NMEA messages in M10 RAM", 300);
kernel::delayMillis(750);
uart.flushInput();
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_DISABLE_NMEA_BBR, "disable NMEA messages in M10 BBR", 300);
kernel::delayMillis(750);
uart.flushInput();
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_DISABLE_TXT_INFO_RAM, "disable Info messages for M10 GPS RAM", 300);
kernel::delayMillis(750);
uart.flushInput();
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_DISABLE_TXT_INFO_BBR, "disable Info messages for M10 GPS BBR", 300);
kernel::delayMillis(750);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_PM_RAM, "enable powersave for M10 GPS RAM", 300);
kernel::delayMillis(750);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_PM_BBR, "enable powersave for M10 GPS BBR", 300);
kernel::delayMillis(750);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_ITFM_RAM, "enable jam detection M10 GPS RAM", 300);
kernel::delayMillis(750);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_ITFM_BBR, "enable jam detection M10 GPS BBR", 300);
kernel::delayMillis(750);
// Here is where the init commands should go to do further M10 initialization.
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_DISABLE_SBAS_RAM, "disable SBAS M10 GPS RAM", 300);
kernel::delayMillis(750); // will cause a receiver restart so wait a bit
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_DISABLE_SBAS_BBR, "disable SBAS M10 GPS BBR", 300);
kernel::delayMillis(750); // will cause a receiver restart so wait a bit
// Done with initialization
// Enable wanted NMEA messages in BBR layer so they will survive a periodic sleep
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_ENABLE_NMEA_BBR, "enable messages for M10 GPS BBR", 300);
kernel::delayMillis(750);
// Enable wanted NMEA messages in RAM layer
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_ENABLE_NMEA_RAM, "enable messages for M10 GPS RAM", 500);
kernel::delayMillis(750);
// As the M10 has no flash, the best we can do to preserve the config is to set it in RAM and BBR.
// BBR will survive a restart, and power off for a while, but modules with small backup
// batteries or super caps will not retain the config for a long power off time.
auto packet_size = makePacket(0x06, 0x09, _message_SAVE_10, sizeof(_message_SAVE_10), buffer);
uart.writeBytes(buffer, packet_size);
if (getAck(uart, 0x06, 0x09, 2000) != GpsResponse::Ok) {
TT_LOG_W(TAG, "Unable to save GNSS module config");
} else {
TT_LOG_I(TAG, "GNSS module configuration saved!");
}
return true;
}
bool initUblox789(uart::Uart& uart, GpsModel model) {
uint8_t buffer[256];
if (model == GpsModel::UBLOX7) {
TT_LOG_D(TAG, "Set GPS+SBAS");
auto msglen = makePacket(0x06, 0x3e, _message_GNSS_7, sizeof(_message_GNSS_7), buffer);
uart.writeBytes(buffer, msglen);
} else { // 8,9
auto msglen = makePacket(0x06, 0x3e, _message_GNSS_8, sizeof(_message_GNSS_8), buffer);
uart.writeBytes(buffer, msglen);
}
if (getAck(uart, 0x06, 0x3e, 800) == GpsResponse::NotAck) {
// It's not critical if the module doesn't acknowledge this configuration.
TT_LOG_D(TAG, "reconfigure GNSS - defaults maintained. Is this module GPS-only?");
} else {
if (model == GpsModel::UBLOX7) {
TT_LOG_I(TAG, "GPS+SBAS configured");
} else { // 8,9
TT_LOG_I(TAG, "GPS+SBAS+GLONASS+Galileo configured");
}
// Documentation say, we need wait at least 0.5s after reconfiguration of GNSS module, before sending next
// commands for the M8 it tends to be more. 1 sec should be enough
kernel::delayMillis(1000);
}
uart.flushInput();
SEND_UBX_PACKET(uart, buffer, 0x06, 0x02, _message_DISABLE_TXT_INFO, "disable text info messages", 500);
if (model == GpsModel::UBLOX8) { // 8
uart.flushInput();
SEND_UBX_PACKET(uart, buffer, 0x06, 0x39, _message_JAM_8, "enable interference resistance", 500);
uart.flushInput();
SEND_UBX_PACKET(uart, buffer, 0x06, 0x23, _message_NAVX5_8, "configure NAVX5_8 settings", 500);
} else { // 6,7,9
SEND_UBX_PACKET(uart, buffer, 0x06, 0x39, _message_JAM_6_7, "enable interference resistance", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x23, _message_NAVX5, "configure NAVX5 settings", 500);
}
// Turn off unwanted NMEA messages, set update rate
SEND_UBX_PACKET(uart, buffer, 0x06, 0x08, _message_1HZ, "set GPS update rate", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x01, _message_GLL, "disable NMEA GLL", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x01, _message_GSA, "enable NMEA GSA", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x01, _message_GSV, "disable NMEA GSV", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x01, _message_VTG, "disable NMEA VTG", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x01, _message_RMC, "enable NMEA RMC", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x01, _message_GGA, "enable NMEA GGA", 500);
if (ublox_info.protocol_version >= 18) {
uart.flushInput();
SEND_UBX_PACKET(uart, buffer, 0x06, 0x86, _message_PMS, "enable powersave for GPS", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x3B, _message_CFG_PM2, "enable powersave details for GPS", 500);
// For M8 we want to enable NMEA version 4.10 so we can see the additional satellites.
if (model == GpsModel::UBLOX8) {
uart.flushInput();
SEND_UBX_PACKET(uart, buffer, 0x06, 0x17, _message_NMEA, "enable NMEA 4.10", 500);
}
} else {
SEND_UBX_PACKET(uart, buffer, 0x06, 0x11, _message_CFG_RXM_PSM, "enable powersave mode for GPS", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x3B, _message_CFG_PM2, "enable powersave details for GPS", 500);
}
auto packet_size = makePacket(0x06, 0x09, _message_SAVE, sizeof(_message_SAVE), buffer);
uart.writeBytes(buffer, packet_size);
if (getAck(uart, 0x06, 0x09, 2000) != GpsResponse::Ok) {
TT_LOG_W(TAG, "Unable to save GNSS module config");
} else {
TT_LOG_I(TAG, "GNSS module configuration saved!");
}
return true;
}
bool initUblox6(uart::Uart& uart) {
uint8_t buffer[256];
uart.flushInput();
SEND_UBX_PACKET(uart, buffer, 0x06, 0x02, _message_DISABLE_TXT_INFO, "disable text info messages", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x39, _message_JAM_6_7, "enable interference resistance", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x23, _message_NAVX5, "configure NAVX5 settings", 500);
// Turn off unwanted NMEA messages, set update rate
SEND_UBX_PACKET(uart, buffer, 0x06, 0x08, _message_1HZ, "set GPS update rate", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x01, _message_GLL, "disable NMEA GLL", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x01, _message_GSA, "enable NMEA GSA", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x01, _message_GSV, "disable NMEA GSV", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x01, _message_VTG, "disable NMEA VTG", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x01, _message_RMC, "enable NMEA RMC", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x01, _message_GGA, "enable NMEA GGA", 500);
uart.flushInput();
SEND_UBX_PACKET(uart, buffer, 0x06, 0x11, _message_CFG_RXM_ECO, "enable powersave ECO mode for Neo-6", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x3B, _message_CFG_PM2, "enable powersave details for GPS", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x01, _message_AID, "disable UBX-AID", 500);
auto packet_size = makePacket(0x06, 0x09, _message_SAVE, sizeof(_message_SAVE), buffer);
uart.writeBytes(buffer, packet_size);
if (getAck(uart, 0x06, 0x09, 2000) != GpsResponse::Ok) {
TT_LOG_W(TAG, "Unable to save GNSS module config");
} else {
TT_LOG_I(TAG, "GNSS module config saved!");
}
return true;
}
} // namespace tt::hal::gps::ublox
+287
View File
@@ -0,0 +1,287 @@
#include "Tactility/hal/i2c/I2c.h"
#include <Tactility/Log.h>
#include <Tactility/Mutex.h>
#ifdef ESP_PLATFORM
#include <esp_check.h>
#endif // ESP_PLATFORM
#define TAG "i2c"
namespace tt::hal::i2c {
struct Data {
Mutex mutex;
bool isConfigured = false;
bool isStarted = false;
Configuration configuration;
};
static const uint8_t ACK_CHECK_EN = 1;
static Data dataArray[I2C_NUM_MAX];
bool init(const std::vector<i2c::Configuration>& configurations) {
TT_LOG_I(TAG, "Init");
for (const auto& configuration: configurations) {
#ifdef ESP_PLATFORM
if (configuration.config.mode != I2C_MODE_MASTER) {
TT_LOG_E(TAG, "Currently only master mode is supported");
return false;
}
#endif // ESP_PLATFORM
Data& data = dataArray[configuration.port];
data.configuration = configuration;
data.isConfigured = true;
}
for (const auto& config: configurations) {
if (config.initMode == InitMode::ByTactility) {
if (!start(config.port)) {
return false;
}
} else if (config.initMode == InitMode::ByExternal) {
dataArray[config.port].isStarted = true;
}
}
return true;
}
bool configure(i2c_port_t port, const i2c_config_t& configuration) {
auto lock = getLock(port).asScopedLock();
lock.lock();
Data& data = dataArray[port];
if (data.isStarted) {
TT_LOG_E(TAG, "(%d) Cannot reconfigure while interface is started", port);
return false;
} else if (!data.configuration.isMutable) {
TT_LOG_E(TAG, "(%d) Mutation not allowed because configuration is immutable", port);
return false;
} else {
data.configuration.config = configuration;
return true;
}
}
bool start(i2c_port_t port) {
auto lock = getLock(port).asScopedLock();
lock.lock();
Data& data = dataArray[port];
Configuration& config = data.configuration;
if (data.isStarted) {
TT_LOG_E(TAG, "(%d) Starting: Already started", port);
return false;
}
if (!data.isConfigured) {
TT_LOG_E(TAG, "(%d) Starting: Not configured", port);
return false;
}
#ifdef ESP_PLATFORM
esp_err_t result = i2c_param_config(port, &config.config);
if (result != ESP_OK) {
TT_LOG_E(TAG, "(%d) Starting: Failed to configure: %s", port, esp_err_to_name(result));
return false;
}
result = i2c_driver_install(port, config.config.mode, 0, 0, 0);
if (result != ESP_OK) {
TT_LOG_E(TAG, "(%d) Starting: Failed to install driver: %s", port, esp_err_to_name(result));
return false;
}
#endif // ESP_PLATFORM
data.isStarted = true;
TT_LOG_I(TAG, "(%d) Started", port);
return true;
}
bool stop(i2c_port_t port) {
auto lock = getLock(port).asScopedLock();
lock.lock();
Data& data = dataArray[port];
Configuration& config = data.configuration;
if (!config.isMutable) {
TT_LOG_E(TAG, "(%d) Stopping: Not allowed for immutable configuration", port);
return false;
}
if (!data.isStarted) {
TT_LOG_E(TAG, "(%d) Stopping: Not started", port);
return false;
}
#ifdef ESP_PLATFORM
esp_err_t result = i2c_driver_delete(port);
if (result != ESP_OK) {
TT_LOG_E(TAG, "(%d) Stopping: Failed to delete driver: %s", port, esp_err_to_name(result));
return false;
}
#endif // ESP_PLATFORM
data.isStarted = false;
TT_LOG_I(TAG, "(%d) Stopped", port);
return true;
}
bool isStarted(i2c_port_t port) {
auto lock = getLock(port).asScopedLock();
lock.lock();
return dataArray[port].isStarted;
}
bool masterRead(i2c_port_t port, uint8_t address, uint8_t* data, size_t dataSize, TickType_t timeout) {
auto lock = getLock(port).asScopedLock();
if (!lock.lock(timeout)) {
TT_LOG_E(TAG, "(%d) Mutex timeout", port);
return false;
}
#ifdef ESP_PLATFORM
auto result = i2c_master_read_from_device(port, address, data, dataSize, timeout);
ESP_ERROR_CHECK_WITHOUT_ABORT(result);
return result == ESP_OK;
#else
return false;
#endif // ESP_PLATFORM
}
bool masterReadRegister(i2c_port_t port, uint8_t address, uint8_t reg, uint8_t* data, size_t dataSize, TickType_t timeout) {
auto lock = getLock(port).asScopedLock();
if (!lock.lock(timeout)) {
TT_LOG_E(TAG, "(%d) Mutex timeout", port);
return false;
}
#ifdef ESP_PLATFORM
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
// Set address pointer
i2c_master_start(cmd);
i2c_master_write_byte(cmd, (address << 1) | I2C_MASTER_WRITE, ACK_CHECK_EN);
i2c_master_write(cmd, &reg, 1, ACK_CHECK_EN);
// Read length of response from current pointer
i2c_master_start(cmd);
i2c_master_write_byte(cmd, (address << 1) | I2C_MASTER_READ, ACK_CHECK_EN);
if (dataSize > 1) {
i2c_master_read(cmd, data, dataSize - 1, I2C_MASTER_ACK);
}
i2c_master_read_byte(cmd, data + dataSize - 1, I2C_MASTER_NACK);
i2c_master_stop(cmd);
// TODO: We're passing an inaccurate timeout value as we already lost time with locking
esp_err_t result = i2c_master_cmd_begin(port, cmd, timeout);
i2c_cmd_link_delete(cmd);
ESP_ERROR_CHECK_WITHOUT_ABORT(result);
return result == ESP_OK;
#else
return false;
#endif // ESP_PLATFORM
}
bool masterWrite(i2c_port_t port, uint8_t address, const uint8_t* data, uint16_t dataSize, TickType_t timeout) {
auto lock = getLock(port).asScopedLock();
if (!lock.lock(timeout)) {
TT_LOG_E(TAG, "(%d) Mutex timeout", port);
return false;
}
#ifdef ESP_PLATFORM
auto result = i2c_master_write_to_device(port, address, data, dataSize, timeout);
ESP_ERROR_CHECK_WITHOUT_ABORT(result);
return result == ESP_OK;
#else
return false;
#endif // ESP_PLATFORM
}
bool masterWriteRegister(i2c_port_t port, uint8_t address, uint8_t reg, const uint8_t* data, uint16_t dataSize, TickType_t timeout) {
tt_check(reg != 0);
auto lock = getLock(port).asScopedLock();
if (!lock.lock(timeout)) {
TT_LOG_E(TAG, "(%d) Mutex timeout", port);
return false;
}
#ifdef ESP_PLATFORM
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
i2c_master_start(cmd);
i2c_master_write_byte(cmd, (address << 1) | I2C_MASTER_WRITE, ACK_CHECK_EN);
i2c_master_write_byte(cmd, reg, ACK_CHECK_EN);
i2c_master_write(cmd, (uint8_t*) data, dataSize, ACK_CHECK_EN);
i2c_master_stop(cmd);
// TODO: We're passing an inaccurate timeout value as we already lost time with locking
esp_err_t result = i2c_master_cmd_begin(port, cmd, timeout);
i2c_cmd_link_delete(cmd);
ESP_ERROR_CHECK_WITHOUT_ABORT(result);
return result == ESP_OK;
#else
return false;
#endif // ESP_PLATFORM
}
bool masterWriteRegisterArray(i2c_port_t port, uint8_t address, const uint8_t* data, uint16_t dataSize, TickType_t timeout) {
#ifdef ESP_PLATFORM
assert(dataSize % 2 == 0);
bool result = true;
for (int i = 0; i < dataSize; i += 2) {
// TODO: We're passing an inaccurate timeout value as we already lost time with locking and previous writes in this loop
if (!masterWriteRegister(port, address, data[i], &data[i + 1], 1, timeout)) {
result = false;
}
}
return result;
#else
return false;
#endif // ESP_PLATFORM
}
bool masterWriteRead(i2c_port_t port, uint8_t address, const uint8_t* writeData, size_t writeDataSize, uint8_t* readData, size_t readDataSize, TickType_t timeout) {
auto lock = getLock(port).asScopedLock();
if (!lock.lock(timeout)) {
TT_LOG_E(TAG, "(%d) Mutex timeout", port);
return false;
}
#ifdef ESP_PLATFORM
esp_err_t result = i2c_master_write_read_device(port, address, writeData, writeDataSize, readData, readDataSize, timeout);
ESP_ERROR_CHECK_WITHOUT_ABORT(result);
return result == ESP_OK;
#else
return false;
#endif // ESP_PLATFORM
}
bool masterHasDeviceAtAddress(i2c_port_t port, uint8_t address, TickType_t timeout) {
auto lock = getLock(port).asScopedLock();
if (!lock.lock(timeout)) {
TT_LOG_E(TAG, "(%d) Mutex timeout", port);
return false;
}
#ifdef ESP_PLATFORM
uint8_t message[2] = { 0, 0 };
// TODO: We're passing an inaccurate timeout value as we already lost time with locking
return i2c_master_write_to_device(port, address, message, 2, timeout) == ESP_OK;
#else
return false;
#endif // ESP_PLATFORM
}
Lock& getLock(i2c_port_t port) {
return dataArray[port].mutex;
}
} // namespace
+65
View File
@@ -0,0 +1,65 @@
#include "Tactility/hal/i2c/I2cDevice.h"
#include <cstdint>
namespace tt::hal::i2c {
bool I2cDevice::readRegister12(uint8_t reg, float& out) const {
std::uint8_t data[2] = {0};
if (tt::hal::i2c::masterReadRegister(port, address, reg, data, 2, DEFAULT_TIMEOUT)) {
out = (data[0] & 0x0F) << 8 | data[1];
return true;
} else {
return false;
}
}
bool I2cDevice::readRegister14(uint8_t reg, float& out) const {
std::uint8_t data[2] = {0};
if (tt::hal::i2c::masterReadRegister(port, address, reg, data, 2, DEFAULT_TIMEOUT)) {
out = (data[0] & 0x3F) << 8 | data[1];
return true;
} else {
return false;
}
}
bool I2cDevice::readRegister16(uint8_t reg, uint16_t& out) const {
std::uint8_t data[2] = {0};
if (tt::hal::i2c::masterReadRegister(port, address, reg, data, 2, DEFAULT_TIMEOUT)) {
out = data[0] << 8 | data[1];
return true;
} else {
return false;
}
}
bool I2cDevice::readRegister8(uint8_t reg, uint8_t& result) const {
return tt::hal::i2c::masterWriteRead(port, address, &reg, 1, &result, 1, DEFAULT_TIMEOUT);
}
bool I2cDevice::writeRegister8(uint8_t reg, uint8_t value) const {
return tt::hal::i2c::masterWriteRegister(port, address, reg, &value, 1, DEFAULT_TIMEOUT);
}
bool I2cDevice::bitOn(uint8_t reg, uint8_t bitmask) const {
uint8_t state;
if (readRegister8(reg, state)) {
state |= bitmask;
return writeRegister8(reg, state);
} else {
return false;
}
}
bool I2cDevice::bitOff(uint8_t reg, uint8_t bitmask) const {
uint8_t state;
if (readRegister8(reg, state)) {
state &= ~bitmask;
return writeRegister8(reg, state);
} else {
return false;
}
}
} // namespace
+17
View File
@@ -0,0 +1,17 @@
#include "Tactility/hal/Device.h"
#include "Tactility/hal/sdcard/SdCardDevice.h"
namespace tt::hal::sdcard {
std::shared_ptr<SdCardDevice> _Nullable find(const std::string& path) {
auto sdcards = findDevices<SdCardDevice>(Device::Type::SdCard);
for (auto& sdcard : sdcards) {
if (sdcard->isMounted() && path.starts_with(sdcard->getMountPath())) {
return sdcard;
}
}
return nullptr;
}
}
@@ -0,0 +1,155 @@
#ifdef ESP_PLATFORM
#include "Tactility/hal/sdcard/SpiSdCardDevice.h"
#include <Tactility/Log.h>
#include <driver/gpio.h>
#include <esp_vfs_fat.h>
#include <sdmmc_cmd.h>
#define TAG "spi_sdcard"
namespace tt::hal::sdcard {
/**
* Before we can initialize the sdcard's SPI communications, we have to set all
* other SPI pins on the board high.
* See https://github.com/espressif/esp-idf/issues/1597
* See https://github.com/Xinyuan-LilyGO/T-Deck/blob/master/examples/UnitTest/UnitTest.ino
* @return success result
*/
bool SpiSdCardDevice::applyGpioWorkAround() {
TT_LOG_D(TAG, "init");
uint64_t pin_bit_mask = BIT64(config->spiPinCs);
for (auto const& pin: config->csPinWorkAround) {
pin_bit_mask |= BIT64(pin);
}
gpio_config_t sd_gpio_config = {
.pin_bit_mask = pin_bit_mask,
.mode = GPIO_MODE_OUTPUT,
.pull_up_en = GPIO_PULLUP_DISABLE,
.pull_down_en = GPIO_PULLDOWN_DISABLE,
.intr_type = GPIO_INTR_DISABLE,
};
if (gpio_config(&sd_gpio_config) != ESP_OK) {
TT_LOG_E(TAG, "GPIO init failed");
return false;
}
for (auto const& pin: config->csPinWorkAround) {
if (gpio_set_level(pin, 1) != ESP_OK) {
TT_LOG_E(TAG, "Failed to set board CS pin high");
return false;
}
}
return true;
}
bool SpiSdCardDevice::mountInternal(const std::string& newMountPath) {
TT_LOG_I(TAG, "Mounting %s", newMountPath.c_str());
esp_vfs_fat_sdmmc_mount_config_t mount_config = {
.format_if_mount_failed = config->formatOnMountFailed,
.max_files = config->maxOpenFiles,
.allocation_unit_size = config->allocUnitSize,
.disk_status_check_enable = config->statusCheckEnabled,
.use_one_fat = false
};
// Init without card detect (CD) and write protect (WD)
sdspi_device_config_t slot_config = SDSPI_DEVICE_CONFIG_DEFAULT();
slot_config.host_id = config->spiHost;
slot_config.gpio_cs = config->spiPinCs;
slot_config.gpio_cd = config->spiPinCd;
slot_config.gpio_wp = config->spiPinWp;
slot_config.gpio_int = config->spiPinInt;
sdmmc_host_t host = SDSPI_HOST_DEFAULT();
// The following value is from T-Deck repo's UnitTest.ino project:
// https://github.com/Xinyuan-LilyGO/T-Deck/blob/master/examples/UnitTest/UnitTest.ino
// Observation: Using this automatically sets the bus to 20MHz
host.max_freq_khz = config->spiFrequencyKhz;
host.slot = config->spiHost;
esp_err_t result = esp_vfs_fat_sdspi_mount(newMountPath.c_str(), &host, &slot_config, &mount_config, &card);
if (result != ESP_OK) {
if (result == ESP_FAIL) {
TT_LOG_E(TAG, "Mounting failed. Ensure the card is formatted with FAT.");
} else {
TT_LOG_E(TAG, "Mounting failed (%s)", esp_err_to_name(result));
}
return false;
}
mountPath = newMountPath;
return true;
}
bool SpiSdCardDevice::mount(const std::string& newMountPath) {
if (!applyGpioWorkAround()) {
TT_LOG_E(TAG, "Failed to set SPI CS pins high. This is a pre-requisite for mounting.");
return false;
}
if (mountInternal(newMountPath)) {
sdmmc_card_print_info(stdout, card);
return true;
} else {
TT_LOG_E(TAG, "Mount failed for %s", newMountPath.c_str());
return false;
}
}
bool SpiSdCardDevice::unmount() {
if (card == nullptr) {
TT_LOG_E(TAG, "Can't unmount: not mounted");
return false;
}
if (esp_vfs_fat_sdcard_unmount(mountPath.c_str(), card) == ESP_OK) {
mountPath = "";
card = nullptr;
return true;
} else {
TT_LOG_E(TAG, "Unmount failed for %s", mountPath.c_str());
return false;
}
}
// TODO: Refactor to "bool getStatus(Status* status)" method so that it can fail when the lvgl lock fails
SdCardDevice::State SpiSdCardDevice::getState() const {
if (card == nullptr) {
return State::Unmounted;
}
/**
* The SD card and the screen are on the same SPI bus.
* Writing and reading to the bus from 2 devices at the same time causes crashes.
* This work-around ensures that this check is only happening when LVGL isn't rendering.
*/
auto lock = getLock().asScopedLock();
bool locked = lock.lock(50); // TODO: Refactor to a more reliable locking mechanism
if (!locked) {
TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL");
return State::Unknown;
}
bool result = sdmmc_get_status(card) == ESP_OK;
if (result) {
return State::Mounted;
} else {
return State::Error;
}
}
}
#endif
+146
View File
@@ -0,0 +1,146 @@
#include "Tactility/hal/spi/Spi.h"
#include <Tactility/Mutex.h>
#define TAG "spi"
namespace tt::hal::spi {
struct Data {
std::shared_ptr<Lock> lock;
bool isConfigured = false;
bool isStarted = false;
Configuration configuration;
};
static Data dataArray[SPI_HOST_MAX];
bool init(const std::vector<spi::Configuration>& configurations) {
TT_LOG_I(TAG, "Init");
for (const auto& configuration: configurations) {
Data& data = dataArray[configuration.device];
data.configuration = configuration;
data.isConfigured = true;
if (configuration.lock != nullptr) {
data.lock = configuration.lock;
} else {
data.lock = std::make_shared<Mutex>();
}
}
for (const auto& config: configurations) {
if (config.initMode == InitMode::ByTactility) {
if (!start(config.device)) {
return false;
}
} else if (config.initMode == InitMode::ByExternal) {
dataArray[config.device].isStarted = true;
}
}
return true;
}
bool configure(spi_host_device_t device, const spi_bus_config_t& configuration) {
auto lock = getLock(device)->asScopedLock();
lock.lock();
Data& data = dataArray[device];
if (data.isStarted) {
TT_LOG_E(TAG, "(%d) Cannot reconfigure while interface is started", device);
return false;
} else if (!data.configuration.isMutable) {
TT_LOG_E(TAG, "(%d) Mutation not allowed by original configuration", device);
return false;
} else {
data.configuration.config = configuration;
return true;
}
}
bool start(spi_host_device_t device) {
auto lock = getLock(device)->asScopedLock();
lock.lock();
Data& data = dataArray[device];
if (data.isStarted) {
TT_LOG_E(TAG, "(%d) Starting: Already started", device);
return false;
}
if (!data.isConfigured) {
TT_LOG_E(TAG, "(%d) Starting: Not configured", device);
return false;
}
#ifdef ESP_PLATFORM
Configuration& config = data.configuration;
auto result = spi_bus_initialize(device, &data.configuration.config, data.configuration.dma);
if (result != ESP_OK) {
TT_LOG_E(TAG, "(%d) Starting: Failed to initialize: %s", device, esp_err_to_name(result));
return false;
} else {
data.isStarted = true;
}
#else
data.isStarted = true;
#endif
TT_LOG_I(TAG, "(%d) Started", device);
return true;
}
bool stop(spi_host_device_t device) {
auto lock = getLock(device)->asScopedLock();
lock.lock();
Data& data = dataArray[device];
Configuration& config = data.configuration;
if (!config.isMutable) {
TT_LOG_E(TAG, "(%d) Stopping: Not allowed, immutable", device);
return false;
}
if (!data.isStarted) {
TT_LOG_E(TAG, "(%d) Stopping: Not started", device);
return false;
}
#ifdef ESP_PLATFORM
auto result = spi_bus_free(device);
if (result != ESP_OK) {
TT_LOG_E(TAG, "(%d) Stopping: Failed to free device: %s", device, esp_err_to_name(result));
return false;
} else {
data.isStarted = false;
}
#else
data.isStarted = false;
#endif
TT_LOG_I(TAG, "(%d) Stopped", device);
return true;
}
bool isStarted(spi_host_device_t device) {
auto lock = getLock(device)->asScopedLock();
lock.lock();
return dataArray[device].isStarted;
}
std::shared_ptr<Lock> getLock(spi_host_device_t device) {
return dataArray[device].lock;
}
}
+174
View File
@@ -0,0 +1,174 @@
#include "Tactility/hal/uart/Uart.h"
#include <Tactility/Log.h>
#include <Tactility/Mutex.h>
#include <ranges>
#include <cstring>
#ifdef ESP_PLATFORM
#include "Tactility/TactilityHeadless.h"
#include "Tactility/hal/uart/UartEsp.h"
#include <esp_check.h>
#else
#include "Tactility/hal/uart/UartPosix.h"
#include <dirent.h>
#endif
#define TAG "uart"
namespace tt::hal::uart {
constexpr uint32_t uartIdNotInUse = 0;
struct UartEntry {
uint32_t usageId = uartIdNotInUse;
Configuration configuration;
};
static std::vector<UartEntry> uartEntries = {};
static uint32_t lastUartId = uartIdNotInUse;
bool init(const std::vector<uart::Configuration>& configurations) {
TT_LOG_I(TAG, "Init");
for (const auto& configuration: configurations) {
uartEntries.push_back({
.usageId = uartIdNotInUse,
.configuration = configuration
});
}
return true;
}
bool Uart::writeString(const char* buffer, TickType_t timeout) {
auto size = strlen(buffer);
writeBytes((std::byte*)buffer, size, timeout);
return true;
}
size_t Uart::readUntil(std::byte* buffer, size_t bufferSize, uint8_t untilByte, TickType_t timeout, bool addNullTerminator) {
TickType_t start_time = kernel::getTicks();
auto* buffer_write_ptr = reinterpret_cast<uint8_t*>(buffer);
uint8_t* buffer_limit = buffer_write_ptr + bufferSize - 1; // Keep 1 extra char as mull terminator
TickType_t timeout_left = timeout;
while (readByte(reinterpret_cast<std::byte*>(buffer_write_ptr), timeout_left) && buffer_write_ptr < buffer_limit) {
#ifdef DEBUG_READ_UNTIL
// If first successful read and we're not receiving an empty response
if (buffer_write_ptr == buffer && *buffer_write_ptr != 0x00U && *buffer_write_ptr != untilByte) {
printf(">>");
}
#endif
if (*buffer_write_ptr == untilByte) {
// TODO: Fix when untilByte is null terminator char already
if (addNullTerminator) {
buffer_write_ptr++;
*buffer_write_ptr = 0x00U;
}
break;
}
#ifdef DEBUG_READ_UNTIL
printf("%c", *buffer_write_ptr);
#endif
buffer_write_ptr++;
TickType_t now = kernel::getTicks();
if (now > (start_time + timeout)) {
#ifdef DEBUG_READ_UNTIL
TT_LOG_W(TAG, "readUntil() timeout");
#endif
break;
} else {
timeout_left = timeout - (now - start_time);
}
}
#ifdef DEBUG_READ_UNTIL
// If we read data and it's not an empty response
if (buffer_write_ptr != buffer && *buffer != 0x00U && *buffer != untilByte) {
printf("\n");
}
#endif
if (addNullTerminator && (buffer_write_ptr > reinterpret_cast<uint8_t*>(buffer))) {
return reinterpret_cast<size_t>(buffer_write_ptr) - reinterpret_cast<size_t>(buffer) - 1UL;
} else {
return reinterpret_cast<size_t>(buffer_write_ptr) - reinterpret_cast<size_t>(buffer);
}
}
std::unique_ptr<Uart> open(std::string name) {
TT_LOG_I(TAG, "Open %s", name.c_str());
auto result = std::views::filter(uartEntries, [&name](auto& entry) {
return entry.configuration.name == name;
});
if (result.empty()) {
TT_LOG_E(TAG, "UART not found: %s", name.c_str());
return nullptr;
}
auto& entry = *result.begin();
if (entry.usageId != uartIdNotInUse) {
TT_LOG_E(TAG, "UART in use: %s", name.c_str());
return nullptr;
}
auto uart = create(entry.configuration);
assert(uart != nullptr);
entry.usageId = uart->getId();
TT_LOG_I(TAG, "Opened %lu", entry.usageId);
return uart;
}
void close(uint32_t uartId) {
TT_LOG_I(TAG, "Close %lu", uartId);
auto result = std::views::filter(uartEntries, [&uartId](auto& entry) {
return entry.usageId == uartId;
});
if (!result.empty()) {
auto& entry = *result.begin();
entry.usageId = uartIdNotInUse;
} else {
TT_LOG_W(TAG, "Auto-closing UART, but can't find it");
}
}
std::vector<std::string> getNames() {
std::vector<std::string> names;
#ifdef ESP_PLATFORM
for (auto& config : getConfiguration()->uart) {
names.push_back(config.name);
}
#else
DIR* dir = opendir("/dev");
if (dir == nullptr) {
TT_LOG_E(TAG, "Failed to read /dev");
return names;
}
struct dirent* current_entry;
while ((current_entry = readdir(dir)) != nullptr) {
auto name = std::string(current_entry->d_name);
if (name.starts_with("tty")) {
auto path = std::string("/dev/") + name;
names.push_back(path);
}
}
closedir(dir);
#endif
return names;
}
Uart::Uart() : id(++lastUartId) {}
Uart::~Uart() {
close(getId());
}
} // namespace tt::hal::uart
+156
View File
@@ -0,0 +1,156 @@
#ifdef ESP_PLATFORM
#include "Tactility/hal/uart/UartEsp.h"
#include <Tactility/Log.h>
#include <Tactility/Mutex.h>
#include <sstream>
#include <esp_check.h>
#define TAG "uart"
namespace tt::hal::uart {
bool UartEsp::start() {
TT_LOG_I(TAG, "[%s] Starting", configuration.name.c_str());
auto lock = mutex.asScopedLock();
lock.lock();
if (started) {
TT_LOG_E(TAG, "[%s] Starting: Already started", configuration.name.c_str());
return false;
}
int intr_alloc_flags;
#if CONFIG_UART_ISR_IN_IRAM
intr_alloc_flags = ESP_INTR_FLAG_IRAM;
#else
intr_alloc_flags = 0;
#endif
esp_err_t result = uart_param_config(configuration.port, &configuration.config);
if (result != ESP_OK) {
TT_LOG_E(TAG, "[%s] Starting: Failed to configure: %s", configuration.name.c_str(), esp_err_to_name(result));
return false;
}
if (uart_is_driver_installed(configuration.port)) {
TT_LOG_W(TAG, "[%s] Driver was still installed. You probably forgot to stop, or another system uses/used the driver.", configuration.name.c_str());
uart_driver_delete(configuration.port);
}
result = uart_set_pin(configuration.port, configuration.txPin, configuration.rxPin, configuration.rtsPin, configuration.ctsPin);
if (result != ESP_OK) {
TT_LOG_E(TAG, "[%s] Starting: Failed set pins: %s", configuration.name.c_str(), esp_err_to_name(result));
return false;
}
result = uart_driver_install(configuration.port, (int)configuration.rxBufferSize, (int)configuration.txBufferSize, 0, nullptr, intr_alloc_flags);
if (result != ESP_OK) {
TT_LOG_E(TAG, "[%s] Starting: Failed to install driver: %s", configuration.name.c_str(), esp_err_to_name(result));
return false;
}
started = true;
TT_LOG_I(TAG, "[%s] Started", configuration.name.c_str());
return true;
}
bool UartEsp::stop() {
TT_LOG_I(TAG, "[%s] Stopping", configuration.name.c_str());
auto lock = mutex.asScopedLock();
lock.lock();
if (!started) {
TT_LOG_E(TAG, "[%s] Stopping: Not started", configuration.name.c_str());
return false;
}
esp_err_t result = uart_driver_delete(configuration.port);
if (result != ESP_OK) {
TT_LOG_E(TAG, "[%s] Stopping: Failed to delete driver: %s", configuration.name.c_str(), esp_err_to_name(result));
return false;
}
started = false;
TT_LOG_I(TAG, "[%s] Stopped", configuration.name.c_str());
return true;
}
bool UartEsp::isStarted() const {
auto lock = mutex.asScopedLock();
lock.lock();
return started;
}
size_t UartEsp::readBytes(std::byte* buffer, size_t bufferSize, TickType_t timeout) {
auto lock = mutex.asScopedLock();
if (!lock.lock(timeout)) {
return false;
}
auto start_time = kernel::getTicks();
auto lock_time = kernel::getTicks() - start_time;
auto remaining_timeout = std::max(timeout - lock_time, 0UL);
auto result = uart_read_bytes(configuration.port, buffer, bufferSize, remaining_timeout);
return result;
}
bool UartEsp::readByte(std::byte* output, TickType_t timeout) {
return readBytes(output, 1, timeout) == 1;
}
size_t UartEsp::writeBytes(const std::byte* buffer, size_t bufferSize, TickType_t timeout) {
auto lock = mutex.asScopedLock();
if (!lock.lock(timeout)) {
return false;
}
return uart_write_bytes(configuration.port, buffer, bufferSize);
}
size_t UartEsp::available(TickType_t timeout) {
auto lock = mutex.asScopedLock();
if (!lock.lock(timeout)) {
return false;
}
size_t size = 0;
uart_get_buffered_data_len(configuration.port, &size);
return size;
}
void UartEsp::flushInput() {
uart_flush_input(configuration.port);
}
uint32_t UartEsp::getBaudRate() {
uint32_t baud_rate = 0;
auto result = uart_get_baudrate(configuration.port, &baud_rate);
ESP_ERROR_CHECK_WITHOUT_ABORT(result);
return baud_rate;
}
bool UartEsp::setBaudRate(uint32_t baudRate, TickType_t timeout) {
auto lock = mutex.asScopedLock();
if (!lock.lock(timeout)) {
return false;
}
auto result = uart_set_baudrate(configuration.port, baudRate);
ESP_ERROR_CHECK_WITHOUT_ABORT(result);
return result == ESP_OK;
}
std::unique_ptr<Uart> create(const Configuration& configuration) {
return std::make_unique<UartEsp>(configuration);
}
} // namespace tt::hal::uart
#endif
+191
View File
@@ -0,0 +1,191 @@
#ifndef ESP_PLATFORM
#include "Tactility/hal/uart/UartPosix.h"
#include "Tactility/hal/uart/Uart.h"
#include <Tactility/Log.h>
#include <cstring>
#include <sstream>
#include <sys/ioctl.h>
#include <unistd.h>
#define TAG "uart"
namespace tt::hal::uart {
bool UartPosix::start() {
auto lock = mutex.asScopedLock();
lock.lock();
if (device != nullptr) {
TT_LOG_E(TAG, "[%s] Starting: Already started", configuration.name.c_str());
return false;
}
auto file = fopen(configuration.name.c_str(), "w");
if (file == nullptr) {
TT_LOG_E(TAG, "[%s] Open device failed", configuration.name.c_str());
return false;
}
auto new_device = std::unique_ptr<FILE, AutoCloseFileDeleter>(file);
struct termios tty;
if (tcgetattr(fileno(file), &tty) < 0) {
printf("[%s] tcgetattr failed: %s\n", configuration.name.c_str(), strerror(errno));
return false;
}
if (cfsetospeed(&tty, (speed_t)configuration.baudRate) == -1) {
TT_LOG_E(TAG, "[%s] Setting output speed failed", configuration.name.c_str());
}
if (cfsetispeed(&tty, (speed_t)configuration.baudRate) == -1) {
TT_LOG_E(TAG, "[%s] Setting input speed failed", configuration.name.c_str());
}
tty.c_cflag |= (CLOCAL | CREAD); /* ignore modem controls */
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8; /* 8-bit characters */
tty.c_cflag &= ~PARENB; /* no parity bit */
tty.c_cflag &= ~CSTOPB; /* only need 1 stop bit */
tty.c_cflag &= ~CRTSCTS; /* no hardware flowcontrol */
tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
tty.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
tty.c_oflag &= ~OPOST;
/* fetch bytes as they become available */
tty.c_cc[VMIN] = 1;
tty.c_cc[VTIME] = 1;
if (tcsetattr(fileno(file), TCSANOW, &tty) != 0) {
printf("[%s] tcsetattr failed: %s\n", configuration.name.c_str(), strerror(errno));
return false;
}
device = std::move(new_device);
TT_LOG_I(TAG, "[%s] Started", configuration.name.c_str());
return true;
}
bool UartPosix::stop() {
auto lock = mutex.asScopedLock();
lock.lock();
if (device == nullptr) {
TT_LOG_E(TAG, "[%s] Stopping: Not started", configuration.name.c_str());
return false;
}
device = nullptr;
TT_LOG_I(TAG, "[%s] Stopped", configuration.name.c_str());
return true;
}
bool UartPosix::isStarted() const {
auto lock = mutex.asScopedLock();
lock.lock();
return device != nullptr;
}
size_t UartPosix::readBytes(std::byte* buffer, size_t bufferSize, TickType_t timeout) {
auto lock = mutex.asScopedLock();
if (!lock.lock(timeout)) {
return false;
}
if (awaitAvailable(timeout)) {
return read(fileno(device.get()), buffer, bufferSize);
} else {
return 0;
}
}
bool UartPosix::readByte(std::byte* output, TickType_t timeout) {
if (awaitAvailable(timeout)) {
return read(fileno(device.get()), output, 1) == 1;
} else {
return false;
}
}
size_t UartPosix::writeBytes(const std::byte* buffer, size_t bufferSize, TickType_t timeout) {
if (!mutex.lock(timeout)) {
return false;
}
return write(fileno(device.get()), buffer, bufferSize);
}
size_t UartPosix::available(TickType_t timeout) {
auto lock = mutex.asScopedLock();
if (!lock.lock(timeout)) {
return false;
}
uint32_t bytes_available = 0;
ioctl(fileno(device.get()), FIONREAD, bytes_available);
return bytes_available;
}
void UartPosix::flushInput() {
// TODO
}
uint32_t UartPosix::getBaudRate() {
struct termios tty;
if (tcgetattr(fileno(device.get()), &tty) < 0) {
printf("[%s] tcgetattr failed: %s\n", configuration.name.c_str(), strerror(errno));
return false;
} else {
return (uint32_t)cfgetispeed(&tty);
}
}
bool UartPosix::setBaudRate(uint32_t baudRate, TickType_t timeout) {
auto lock = mutex.asScopedLock();
if (!lock.lock(timeout)) {
return false;
}
struct termios tty;
if (tcgetattr(fileno(device.get()), &tty) < 0) {
printf("[%s] tcgetattr failed: %s\n", configuration.name.c_str(), strerror(errno));
return false;
}
if (cfsetospeed(&tty, (speed_t)configuration.baudRate) == -1) {
TT_LOG_E(TAG, "[%s] Failed to set output speed", configuration.name.c_str());
return false;
}
if (cfsetispeed(&tty, (speed_t)configuration.baudRate) == -1) {
TT_LOG_E(TAG, "[%s] Failed to set input speed", configuration.name.c_str());
return false;
}
return true;
}
bool UartPosix::awaitAvailable(TickType_t timeout) {
auto start_time = kernel::getTicks();
do {
if (available(timeout) > 0) {
return true;
}
kernel::delayTicks(timeout / 10);
} while ((kernel::getTicks() - start()) < timeout);
return false;
}
std::unique_ptr<Uart> create(const Configuration& configuration) {
return std::make_unique<UartPosix>(configuration);
}
} // namespace tt::hal::uart
#endif
+108
View File
@@ -0,0 +1,108 @@
#ifdef ESP_PLATFORM
#include "Tactility/hal/usb/Usb.h"
#include "Tactility/TactilityHeadless.h"
#include "Tactility/hal/sdcard/SpiSdCardDevice.h"
#include "Tactility/hal/usb/UsbTusb.h"
#include <Tactility/Log.h>
namespace tt::hal::usb {
#define TAG "usb"
#define BOOT_FLAG 42
struct BootMode {
uint32_t flag = 0;
};
static Mode currentMode = Mode::Default;
static RTC_NOINIT_ATTR BootMode bootMode;
sdmmc_card_t* _Nullable getCard() {
auto sdcard = getConfiguration()->sdcard;
if (sdcard == nullptr) {
TT_LOG_W(TAG, "No SD card configuration found");
return nullptr;
}
if (!sdcard->isMounted()) {
TT_LOG_W(TAG, "SD card not mounted");
return nullptr;
}
auto spi_sdcard = std::static_pointer_cast<sdcard::SpiSdCardDevice>(sdcard);
if (spi_sdcard == nullptr) {
TT_LOG_W(TAG, "SD card interface is not supported (must be SpiSdCard)");
return nullptr;
}
auto* card = spi_sdcard->getCard();
if (card == nullptr) {
TT_LOG_W(TAG, "SD card has no card object available");
return nullptr;
}
return card;
}
static bool canStartNewMode() {
return isSupported() && (currentMode == Mode::Default || currentMode == Mode::None);
}
bool isSupported() {
return tusbIsSupported();
}
bool startMassStorageWithSdmmc() {
if (!canStartNewMode()) {
TT_LOG_E(TAG, "Can't start");
return false;
}
if (tusbStartMassStorageWithSdmmc()) {
currentMode = Mode::MassStorageSdmmc;
return true;
} else {
TT_LOG_E(TAG, "Failed to init mass storage");
return false;
}
}
void stop() {
if (canStartNewMode()) {
return;
}
tusbStop();
currentMode = Mode::None;
}
Mode getMode() {
return currentMode;
}
bool canRebootIntoMassStorageSdmmc() {
return tusbIsSupported() && getCard() != nullptr;
}
void rebootIntoMassStorageSdmmc() {
if (tusbIsSupported()) {
bootMode.flag = BOOT_FLAG;
esp_restart();
}
}
bool isUsbBootMode() {
return bootMode.flag == BOOT_FLAG;
}
void resetUsbBootMode() {
bootMode.flag = 0;
}
}
#endif
+21
View File
@@ -0,0 +1,21 @@
#ifndef ESP_PLATFORM
#include "Tactility/hal/usb/Usb.h"
#define TAG "usb"
namespace tt::hal::usb {
bool startMassStorageWithSdmmc() { return false; }
void stop() {}
Mode getMode() { return Mode::Default; }
bool isSupported() { return false; }
bool canRebootIntoMassStorageSdmmc() { return false; }
void rebootIntoMassStorageSdmmc() {}
bool isUsbBootMode() { return false; }
void resetUsbBootMode() {}
}
#endif
+173
View File
@@ -0,0 +1,173 @@
#ifdef ESP_PLATFORM
#include "Tactility/hal/usb/UsbTusb.h"
#include <sdkconfig.h>
#if CONFIG_TINYUSB_MSC_ENABLED == 1
#include <Tactility/Log.h>
#include <tinyusb.h>
#include <tusb_msc_storage.h>
#define TAG "usb"
#define EPNUM_MSC 1
#define TUSB_DESC_TOTAL_LEN (TUD_CONFIG_DESC_LEN + TUD_MSC_DESC_LEN)
namespace tt::hal::usb {
extern sdmmc_card_t* _Nullable getCard();
}
enum {
ITF_NUM_MSC = 0,
ITF_NUM_TOTAL
};
enum {
EDPT_CTRL_OUT = 0x00,
EDPT_CTRL_IN = 0x80,
EDPT_MSC_OUT = 0x01,
EDPT_MSC_IN = 0x81,
};
static bool driverInstalled = false;
static tusb_desc_device_t descriptor_config = {
.bLength = sizeof(descriptor_config),
.bDescriptorType = TUSB_DESC_DEVICE,
.bcdUSB = 0x0200,
.bDeviceClass = TUSB_CLASS_MISC,
.bDeviceSubClass = MISC_SUBCLASS_COMMON,
.bDeviceProtocol = MISC_PROTOCOL_IAD,
.bMaxPacketSize0 = CFG_TUD_ENDPOINT0_SIZE,
.idVendor = 0x303A, // TODO: Espressif VID. Do we need to change this?
.idProduct = 0x4002,
.bcdDevice = 0x100,
.iManufacturer = 0x01,
.iProduct = 0x02,
.iSerialNumber = 0x03,
.bNumConfigurations = 0x01
};
static char const* string_desc_arr[] = {
(const char[]) { 0x09, 0x04 }, // 0: is supported language is English (0x0409)
"Espressif", // 1: Manufacturer
"Tactility Device", // 2: Product
"42", // 3: Serials
"Tactility Mass Storage", // 4. MSC
};
static uint8_t const msc_fs_configuration_desc[] = {
// Config number, interface count, string index, total length, attribute, power in mA
TUD_CONFIG_DESCRIPTOR(1, ITF_NUM_TOTAL, 0, TUSB_DESC_TOTAL_LEN, TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP, 100),
// Interface number, string index, EP Out & EP In address, EP size
TUD_MSC_DESCRIPTOR(ITF_NUM_MSC, 0, EDPT_MSC_OUT, EDPT_MSC_IN, 64),
};
#if (TUD_OPT_HIGH_SPEED)
static const tusb_desc_device_qualifier_t device_qualifier = {
.bLength = sizeof(tusb_desc_device_qualifier_t),
.bDescriptorType = TUSB_DESC_DEVICE_QUALIFIER,
.bcdUSB = 0x0200,
.bDeviceClass = TUSB_CLASS_MISC,
.bDeviceSubClass = MISC_SUBCLASS_COMMON,
.bDeviceProtocol = MISC_PROTOCOL_IAD,
.bMaxPacketSize0 = CFG_TUD_ENDPOINT0_SIZE,
.bNumConfigurations = 0x01,
.bReserved = 0
};
static uint8_t const msc_hs_configuration_desc[] = {
// Config number, interface count, string index, total length, attribute, power in mA
TUD_CONFIG_DESCRIPTOR(1, ITF_NUM_TOTAL, 0, TUSB_DESC_TOTAL_LEN, TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP, 100),
// Interface number, string index, EP Out & EP In address, EP size
TUD_MSC_DESCRIPTOR(ITF_NUM_MSC, 0, EDPT_MSC_OUT, EDPT_MSC_IN, 512),
};
#endif // TUD_OPT_HIGH_SPEED
static void storage_mount_changed_cb(tinyusb_msc_event_t* event) {
if (event->mount_changed_data.is_mounted) {
TT_LOG_I(TAG, "Mounted");
} else {
TT_LOG_I(TAG, "Unmounted");
}
}
static bool ensureDriverInstalled() {
if (driverInstalled) {
return true;
}
const tinyusb_config_t tusb_cfg = {
.device_descriptor = &descriptor_config,
.string_descriptor = string_desc_arr,
.string_descriptor_count = sizeof(string_desc_arr) / sizeof(string_desc_arr[0]),
.external_phy = false,
#if (TUD_OPT_HIGH_SPEED)
.fs_configuration_descriptor = msc_fs_configuration_desc,
.hs_configuration_descriptor = msc_hs_configuration_desc,
.qualifier_descriptor = &device_qualifier,
#else
.configuration_descriptor = msc_fs_configuration_desc,
#endif // TUD_OPT_HIGH_SPEED
.self_powered = false,
.vbus_monitor_io = 0
};
if (tinyusb_driver_install(&tusb_cfg) != ESP_OK) {
TT_LOG_E(TAG, "Failed to install TinyUSB driver");
return false;
}
driverInstalled = true;
return true;
}
bool tusbIsSupported() { return true; }
bool tusbStartMassStorageWithSdmmc() {
ensureDriverInstalled();
auto* card = tt::hal::usb::getCard();
if (card == nullptr) {
TT_LOG_E(TAG, "SD card not mounted");
return false;
}
const tinyusb_msc_sdmmc_config_t config_sdmmc = {
.card = card,
.callback_mount_changed = storage_mount_changed_cb,
.callback_premount_changed = nullptr,
.mount_config = {
.format_if_mount_failed = false,
.max_files = 5,
.allocation_unit_size = 0,
.disk_status_check_enable = false,
.use_one_fat = false
}
};
auto result = tinyusb_msc_storage_init_sdmmc(&config_sdmmc);
if (result != ESP_OK) {
TT_LOG_E(TAG, "TinyUSB init failed: %s", esp_err_to_name(result));
}
return result == ESP_OK;
}
void tusbStop() {
tinyusb_msc_storage_deinit();
}
#else
bool tusbIsSupported() { return false; }
bool tusbStartMassStorageWithSdmmc() { return false; }
void tusbStop() {}
#endif // TinyUSB enabled
#endif // ESP_PLATFORM
+98
View File
@@ -0,0 +1,98 @@
#include "Tactility/kernel/SystemEvents.h"
#include <Tactility/Mutex.h>
#include <Tactility/CoreExtraDefines.h>
#include <list>
#define TAG "system_event"
namespace tt::kernel {
struct SubscriptionData {
SystemEventSubscription id;
SystemEvent event;
OnSystemEvent handler;
};
static Mutex mutex;
static SystemEventSubscription subscriptionCounter = 0;
static std::list<SubscriptionData> subscriptions;
static const char* getEventName(SystemEvent event) {
switch (event) {
using enum SystemEvent;
case BootInitHalBegin:
return TT_STRINGIFY(BootInitHalBegin);
case BootInitHalEnd:
return TT_STRINGIFY(BootInitHalEnd);
case BootInitI2cBegin:
return TT_STRINGIFY(BootInitI2cBegin);
case BootInitI2cEnd:
return TT_STRINGIFY(BootInitI2cEnd);
case BootInitSpiBegin:
return TT_STRINGIFY(BootInitSpiBegin);
case BootInitSpiEnd:
return TT_STRINGIFY(BootInitSpiEnd);
case BootInitUartBegin:
return TT_STRINGIFY(BootInitUartBegin);
case BootInitUartEnd:
return TT_STRINGIFY(BootInitUartEnd);
case BootInitLvglBegin:
return TT_STRINGIFY(BootInitLvglBegin);
case BootInitLvglEnd:
return TT_STRINGIFY(BootInitLvglEnd);
case BootSplash:
return TT_STRINGIFY(BootSplash);
case NetworkConnected:
return TT_STRINGIFY(NetworkConnected);
case NetworkDisconnected:
return TT_STRINGIFY(NetworkDisconnected);
case Time:
return TT_STRINGIFY(Time);
}
tt_crash(); // Missing case above
}
void systemEventPublish(SystemEvent event) {
TT_LOG_I(TAG, "%s", getEventName(event));
if (mutex.lock(portMAX_DELAY)) {
for (auto& subscription : subscriptions) {
if (subscription.event == event) {
subscription.handler(event);
}
}
mutex.unlock();
}
}
SystemEventSubscription systemEventAddListener(SystemEvent event, std::function<void(SystemEvent)> handler) {
if (mutex.lock(portMAX_DELAY)) {
auto id = ++subscriptionCounter;
subscriptions.push_back({
.id = id,
.event = event,
.handler = handler
});
mutex.unlock();
return id;
} else {
tt_crash();
}
}
void systemEventRemoveListener(SystemEventSubscription subscription) {
if (mutex.lock(portMAX_DELAY)) {
std::erase_if(subscriptions, [subscription](auto& item) {
return (item.id == subscription);
});
mutex.unlock();
}
}
}
+34
View File
@@ -0,0 +1,34 @@
#include "Tactility/network/NtpPrivate.h"
#ifdef ESP_PLATFORM
#include <Tactility/kernel/SystemEvents.h>
#include <Tactility/TactilityCore.h>
#include <esp_netif_sntp.h>
#include <esp_sntp.h>
#endif
#define TAG "ntp"
namespace tt::network::ntp {
#ifdef ESP_PLATFORM
static void onTimeSynced(struct timeval* tv) {
TT_LOG_I(TAG, "Time synced (%llu)", tv->tv_sec);
kernel::systemEventPublish(kernel::SystemEvent::Time);
}
void init() {
esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG("pool.ntp.org");
config.sync_cb = onTimeSynced;
esp_netif_sntp_init(&config);
}
#else
void init() {
}
#endif
}
@@ -0,0 +1,17 @@
#include "Tactility/service/ServiceInstance.h"
#include "Tactility/service/ServiceInstancePaths.h"
namespace tt::service {
ServiceInstance::ServiceInstance(std::shared_ptr<const service::ServiceManifest> manifest) :
manifest(manifest),
service(manifest->createService())
{}
const service::ServiceManifest& ServiceInstance::getManifest() const { return *manifest; }
std::unique_ptr<Paths> ServiceInstance::getPaths() const {
return std::make_unique<ServiceInstancePaths>(manifest);
}
}
@@ -0,0 +1,50 @@
#include "Tactility/service/ServiceInstancePaths.h"
#include "Tactility/Partitions.h"
#define LVGL_PATH_PREFIX std::string("A:/")
#ifdef ESP_PLATFORM
#define PARTITION_PREFIX std::string("/")
#else
#define PARTITION_PREFIX std::string("")
#endif
namespace tt::service {
std::string ServiceInstancePaths::getDataDirectory() const {
return PARTITION_PREFIX + DATA_PARTITION_NAME + "/service/" + manifest->id;
}
std::string ServiceInstancePaths::getDataDirectoryLvgl() const {
return LVGL_PATH_PREFIX + DATA_PARTITION_NAME + "/service/" + manifest->id;
}
std::string ServiceInstancePaths::getDataPath(const std::string& childPath) const {
assert(!childPath.starts_with('/'));
return PARTITION_PREFIX + DATA_PARTITION_NAME + "/service/" + manifest->id + '/' + childPath;
}
std::string ServiceInstancePaths::getDataPathLvgl(const std::string& childPath) const {
assert(!childPath.starts_with('/'));
return LVGL_PATH_PREFIX + DATA_PARTITION_NAME + "/service/" + manifest->id + '/' + childPath;
}
std::string ServiceInstancePaths::getSystemDirectory() const {
return PARTITION_PREFIX + SYSTEM_PARTITION_NAME + "/service/" + manifest->id;
}
std::string ServiceInstancePaths::getSystemDirectoryLvgl() const {
return LVGL_PATH_PREFIX + SYSTEM_PARTITION_NAME + "/service/" + manifest->id;
}
std::string ServiceInstancePaths::getSystemPath(const std::string& childPath) const {
assert(!childPath.starts_with('/'));
return PARTITION_PREFIX + SYSTEM_PARTITION_NAME + "/service/" + manifest->id + '/' + childPath;
}
std::string ServiceInstancePaths::getSystemPathLvgl(const std::string& childPath) const {
return LVGL_PATH_PREFIX + SYSTEM_PARTITION_NAME + "/service/" + manifest->id + '/' + childPath;
}
}
@@ -0,0 +1,118 @@
#include "Tactility/service/ServiceRegistry.h"
#include "Tactility/service/ServiceInstance.h"
#include "Tactility/service/ServiceManifest.h"
#include <Tactility/Mutex.h>
#include <string>
#include <unordered_map>
namespace tt::service {
#define TAG "service_registry"
typedef std::unordered_map<std::string, std::shared_ptr<const ServiceManifest>> ManifestMap;
typedef std::unordered_map<std::string, std::shared_ptr<ServiceInstance>> ServiceInstanceMap;
static ManifestMap service_manifest_map;
static ServiceInstanceMap service_instance_map;
static Mutex manifest_mutex(Mutex::Type::Normal);
static Mutex instance_mutex(Mutex::Type::Normal);
void addService(std::shared_ptr<const ServiceManifest> manifest, bool autoStart) {
// We'll move the manifest pointer, but we'll need to id later
std::string id = manifest->id;
TT_LOG_I(TAG, "Adding %s", id.c_str());
manifest_mutex.lock();
if (service_manifest_map[id] == nullptr) {
service_manifest_map[id] = std::move(manifest);
} else {
TT_LOG_E(TAG, "Service id in use: %s", id.c_str());
}
manifest_mutex.unlock();
if (autoStart) {
startService(id);
}
}
void addService(const ServiceManifest& manifest, bool autoStart) {
addService(std::make_shared<const ServiceManifest>(manifest), autoStart);
}
std::shared_ptr<const ServiceManifest> _Nullable findManifestId(const std::string& id) {
manifest_mutex.lock();
auto iterator = service_manifest_map.find(id);
auto manifest = iterator != service_manifest_map.end() ? iterator->second : nullptr;
manifest_mutex.unlock();
return manifest;
}
static std::shared_ptr<ServiceInstance> _Nullable findServiceInstanceById(const std::string& id) {
manifest_mutex.lock();
auto iterator = service_instance_map.find(id);
auto service = iterator != service_instance_map.end() ? iterator->second : nullptr;
manifest_mutex.unlock();
return service;
}
// TODO: Return proper error/status instead of BOOL?
bool startService(const std::string& id) {
TT_LOG_I(TAG, "Starting %s", id.c_str());
auto manifest = findManifestId(id);
if (manifest == nullptr) {
TT_LOG_E(TAG, "manifest not found for service %s", id.c_str());
return false;
}
auto service_instance = std::make_shared<ServiceInstance>(manifest);
// Register first, so that a service can retrieve itself during onStart()
instance_mutex.lock();
service_instance_map[manifest->id] = service_instance;
instance_mutex.unlock();
service_instance->getService()->onStart(*service_instance);
TT_LOG_I(TAG, "Started %s", id.c_str());
return true;
}
std::shared_ptr<ServiceContext> _Nullable findServiceContextById(const std::string& id) {
return findServiceInstanceById(id);
}
std::shared_ptr<Service> _Nullable findServiceById(const std::string& id) {
auto instance = findServiceInstanceById(id);
return instance != nullptr ? instance->getService() : nullptr;
}
bool stopService(const std::string& id) {
TT_LOG_I(TAG, "Stopping %s", id.c_str());
auto service_instance = findServiceInstanceById(id);
if (service_instance == nullptr) {
TT_LOG_W(TAG, "service not running: %s", id.c_str());
return false;
}
service_instance->getService()->onStop(*service_instance);
instance_mutex.lock();
service_instance_map.erase(id);
instance_mutex.unlock();
if (service_instance.use_count() > 1) {
TT_LOG_W(TAG, "Possible memory leak: service %s still has %ld references", service_instance->getManifest().id.c_str(), service_instance.use_count() - 1);
}
TT_LOG_I(TAG, "Stopped %s", id.c_str());
return true;
}
} // namespace
@@ -0,0 +1,80 @@
#ifdef ESP_PLATFORM
#include "Tactility/service/espnow/EspNow.h"
#include "Tactility/service/espnow/EspNowService.h"
#include <Tactility/Log.h>
namespace tt::service::espnow {
constexpr const char* TAG = "EspNow";
void enable(const EspNowConfig& config) {
auto service = findService();
if (service != nullptr) {
service->enable(config);
} else {
TT_LOG_E(TAG, "Service not found");
}
}
void disable() {
auto service = findService();
if (service != nullptr) {
service->disable();
} else {
TT_LOG_E(TAG, "Service not found");
}
}
bool isEnabled() {
auto service = findService();
if (service != nullptr) {
return service->isEnabled();
} else {
return false;
}
}
bool addPeer(const esp_now_peer_info_t& peer) {
auto service = findService();
if (service != nullptr) {
return service->addPeer(peer);
} else {
TT_LOG_E(TAG, "Service not found");
return false;
}
}
bool send(const uint8_t* address, const uint8_t* buffer, size_t bufferLength) {
auto service = findService();
if (service != nullptr) {
return service->send(address, buffer, bufferLength);
} else {
TT_LOG_E(TAG, "Service not found");
return false;
}
}
ReceiverSubscription subscribeReceiver(std::function<void(const esp_now_recv_info_t* receiveInfo, const uint8_t* data, int length)> onReceive) {
auto service = findService();
if (service != nullptr) {
return service->subscribeReceiver(onReceive);
} else {
TT_LOG_E(TAG, "Service not found");
return -1;
}
}
void unsubscribeReceiver(ReceiverSubscription subscription) {
auto service = findService();
if (service != nullptr) {
service->unsubscribeReceiver(subscription);
} else {
TT_LOG_E(TAG, "Service not found");
}
}
}
#endif // ESP_PLATFORM
@@ -0,0 +1,222 @@
#ifdef ESP_PLATFORM
#include "Tactility/service/espnow/EspNowService.h"
#include "Tactility/TactilityHeadless.h"
#include "Tactility/service/ServiceManifest.h"
#include "Tactility/service/ServiceRegistry.h"
#include "Tactility/service/espnow/EspNowWifi.h"
#include <cstring>
#include <esp_now.h>
#include <esp_random.h>
namespace tt::service::espnow {
extern const ServiceManifest manifest;
constexpr const char* TAG = "EspNowService";
constexpr TickType_t MAX_DELAY = 1000U / portTICK_PERIOD_MS;
static uint8_t BROADCAST_MAC[ESP_NOW_ETH_ALEN];
constexpr bool isBroadcastAddress(uint8_t address[ESP_NOW_ETH_ALEN]) { return memcmp(address, BROADCAST_MAC, ESP_NOW_ETH_ALEN) == 0; }
void EspNowService::onStart(ServiceContext& service) {
auto lock = mutex.asScopedLock();
lock.lock();
memset(BROADCAST_MAC, 0xFF, sizeof(BROADCAST_MAC));
}
void EspNowService::onStop(ServiceContext& service) {
auto lock = mutex.asScopedLock();
lock.lock();
if (isEnabled()) {
disable();
}
}
// region Enable
void EspNowService::enable(const EspNowConfig& config) {
auto enable_context = std::make_shared<EspNowConfig>(config);
getMainDispatcher().dispatch(enableFromDispatcher, enable_context);
}
void EspNowService::enableFromDispatcher(std::shared_ptr<void> context) {
auto service = findService();
if (service == nullptr) {
TT_LOG_E(TAG, "Service not running");
return;
}
auto config = std::static_pointer_cast<EspNowConfig>(context);
service->enableFromDispatcher(*config);
}
void EspNowService::enableFromDispatcher(const EspNowConfig& config) {
auto lock = mutex.asScopedLock();
lock.lock();
if (enabled) {
return;
}
if (!initWifi(config)) {
TT_LOG_E(TAG, "initWifi() failed");
return;
}
if (esp_now_init() != ESP_OK) {
TT_LOG_E(TAG, "esp_now_init() failed");
return;
}
if (esp_now_register_recv_cb(receiveCallback) != ESP_OK) {
TT_LOG_E(TAG, "esp_now_register_recv_cb() failed");
return;
}
//#if CONFIG_ESPNOW_ENABLE_POWER_SAVE
// ESP_ERROR_CHECK( esp_now_set_wake_window(CONFIG_ESPNOW_WAKE_WINDOW) );
// ESP_ERROR_CHECK( esp_wifi_connectionless_module_set_wake_interval(CONFIG_ESPNOW_WAKE_INTERVAL) );
//#endif
if (esp_now_set_pmk(config.masterKey) != ESP_OK) {
TT_LOG_E(TAG, "esp_now_set_pmk() failed");
return;
}
// Add default unencrypted broadcast peer
esp_now_peer_info_t broadcast_peer;
memset(&broadcast_peer, 0, sizeof(esp_now_peer_info_t));
memcpy(broadcast_peer.peer_addr, BROADCAST_MAC, sizeof(BROADCAST_MAC));
service::espnow::addPeer(broadcast_peer);
enabled = true;
}
// endregion Enable
// region Disable
void EspNowService::disable() {
getMainDispatcher().dispatch(disableFromDispatcher, nullptr);
}
void EspNowService::disableFromDispatcher(TT_UNUSED std::shared_ptr<void> context) {
auto service = findService();
if (service == nullptr) {
TT_LOG_E(TAG, "Service not running");
return;
}
service->disableFromDispatcher();
}
void EspNowService::disableFromDispatcher() {
auto lock = mutex.asScopedLock();
lock.lock();
if (!enabled) {
return;
}
if (esp_now_deinit() != ESP_OK) {
TT_LOG_E(TAG, "esp_now_deinit() failed");
}
if (!deinitWifi()) {
TT_LOG_E(TAG, "deinitWifi() failed");
}
enabled = false;
}
// region Disable
// region Callbacks
void EspNowService::receiveCallback(const esp_now_recv_info_t* receiveInfo, const uint8_t* data, int length) {
auto service = findService();
if (service == nullptr) {
TT_LOG_E(TAG, "Service not running");
return;
}
service->onReceive(receiveInfo, data, length);
}
void EspNowService::onReceive(const esp_now_recv_info_t* receiveInfo, const uint8_t* data, int length) {
auto lock = mutex.asScopedLock();
lock.lock();
TT_LOG_D(TAG, "Received %d bytes", length);
for (const auto& item: subscriptions) {
item.onReceive(receiveInfo, data, length);
}
}
// endregion Callbacks
bool EspNowService::isEnabled() const {
auto lock = mutex.asScopedLock();
lock.lock();
return enabled;
}
bool EspNowService::addPeer(const esp_now_peer_info_t& peer) {
if (esp_now_add_peer(&peer) != ESP_OK) {
TT_LOG_E(TAG, "Failed to add peer");
return false;
} else {
TT_LOG_I(TAG, "Peer added");
return true;
}
}
bool EspNowService::send(const uint8_t* address, const uint8_t* buffer, size_t bufferLength) {
auto lock = mutex.asScopedLock();
lock.lock();
if (!isEnabled()) {
return false;
} else {
return esp_now_send(address, buffer, bufferLength) == ESP_OK;
}
}
ReceiverSubscription EspNowService::subscribeReceiver(std::function<void(const esp_now_recv_info_t* receiveInfo, const uint8_t* data, int length)> onReceive) {
auto lock = mutex.asScopedLock();
lock.lock();
auto id = lastSubscriptionId++;
subscriptions.push_back(ReceiverSubscriptionData {
.id = id,
.onReceive = onReceive
});
return id;
}
void EspNowService::unsubscribeReceiver(tt::service::espnow::ReceiverSubscription subscriptionId) {
auto lock = mutex.asScopedLock();
lock.lock();
std::erase_if(subscriptions, [subscriptionId](auto& subscription) { return subscription.id == subscriptionId; });
}
std::shared_ptr<EspNowService> findService() {
return std::static_pointer_cast<EspNowService>(
service::findServiceById(manifest.id)
);
}
extern const ServiceManifest manifest = {
.id = "EspNow",
.createService = create<EspNowService>
};
}
#endif // ESP_PLATFORM
@@ -0,0 +1,106 @@
#ifdef ESP_PLATFORM
#include "Tactility/service/espnow/EspNow.h"
#include "Tactility/service/wifi/Wifi.h"
#include <Tactility/Log.h>
#include <esp_now.h>
#include <esp_wifi.h>
namespace tt::service::espnow {
constexpr const char* TAG = "EspNowService";
static bool disableWifiService() {
auto wifi_state = wifi::getRadioState();
if (wifi_state != wifi::RadioState::Off && wifi_state != wifi::RadioState::OffPending) {
wifi::setEnabled(false);
}
if (wifi::getRadioState() == wifi::RadioState::Off) {
return true;
} else {
TickType_t timeout_time = kernel::getTicks() + kernel::millisToTicks(2000);
while (kernel::getTicks() < timeout_time && wifi::getRadioState() != wifi::RadioState::Off) {
kernel::delayTicks(50);
}
return wifi::getRadioState() == wifi::RadioState::Off;
}
}
bool initWifi(const EspNowConfig& config) {
if (!disableWifiService()) {
TT_LOG_E(TAG, "Failed to disable wifi");
return false;
}
wifi_mode_t mode;
if (config.mode == Mode::Station) {
mode = wifi_mode_t::WIFI_MODE_STA;
} else {
mode = wifi_mode_t::WIFI_MODE_AP;
}
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
if (esp_wifi_init(&cfg) != ESP_OK) {
TT_LOG_E(TAG, "esp_wifi_init() failed");
return false;
}
if (esp_wifi_set_storage(WIFI_STORAGE_RAM) != ESP_OK) {
TT_LOG_E(TAG, "esp_wifi_set_storage() failed");
return false;
}
if (esp_wifi_set_mode(mode) != ESP_OK) {
TT_LOG_E(TAG, "esp_wifi_set_mode() failed");
return false;
}
if (esp_wifi_start() != ESP_OK) {
TT_LOG_E(TAG, "esp_wifi_start() failed");
return false;
}
if (esp_wifi_set_channel(config.channel, WIFI_SECOND_CHAN_NONE) != ESP_OK) {
TT_LOG_E(TAG, "esp_wifi_set_channel() failed");
return false;
}
if (config.longRange) {
wifi_interface_t wifi_interface;
if (config.mode == Mode::Station) {
wifi_interface = WIFI_IF_STA;
} else {
wifi_interface = WIFI_IF_AP;
}
if (esp_wifi_set_protocol(wifi_interface, WIFI_PROTOCOL_11B | WIFI_PROTOCOL_11G | WIFI_PROTOCOL_11N | WIFI_PROTOCOL_LR) != ESP_OK) {
TT_LOG_W(TAG, "esp_wifi_set_protocol() for long range failed");
}
}
return true;
}
bool deinitWifi() {
if (esp_wifi_stop() != ESP_OK) {
TT_LOG_E(TAG, "Failed to stop radio");
return false;
}
if (esp_wifi_set_mode(WIFI_MODE_NULL) != ESP_OK) {
TT_LOG_E(TAG, "Failed to unset mode");
}
if (esp_wifi_deinit() != ESP_OK) {
TT_LOG_E(TAG, "Failed to deinit");
}
return true;
}
} // namespace tt::service::espnow
#endif // ESP_PLATFORM
@@ -0,0 +1,108 @@
#include "Tactility/service/gps/GpsService.h"
#include <Tactility/file/ObjectFile.h>
#include <cstring>
using tt::hal::gps::GpsDevice;
namespace tt::service::gps {
constexpr const char* TAG = "GpsService";
bool GpsService::getConfigurationFilePath(std::string& output) const {
if (paths == nullptr) {
TT_LOG_E(TAG, "Can't add configuration: service not started");
return false;
}
if (!file::findOrCreateDirectory(paths->getDataDirectory(), 0777)) {
TT_LOG_E(TAG, "Failed to find or create path %s", paths->getDataDirectory().c_str());
return false;
}
output = paths->getDataPath("config.bin");
return true;
}
bool GpsService::getGpsConfigurations(std::vector<hal::gps::GpsConfiguration>& configurations) const {
std::string path;
if (!getConfigurationFilePath(path)) {
return false;
}
auto reader = file::ObjectFileReader(path, sizeof(hal::gps::GpsConfiguration));
if (!reader.open()) {
TT_LOG_E(TAG, "Failed to open configuration file");
return false;
}
hal::gps::GpsConfiguration configuration;
while (reader.hasNext()) {
if (!reader.readNext(&configuration)) {
TT_LOG_E(TAG, "Failed to read configuration");
reader.close();
return false;
} else {
configurations.push_back(configuration);
}
}
return true;
}
bool GpsService::addGpsConfiguration(hal::gps::GpsConfiguration configuration) {
std::string path;
if (!getConfigurationFilePath(path)) {
return false;
}
auto appender = file::ObjectFileWriter(path, sizeof(hal::gps::GpsConfiguration), 1, true);
if (!appender.open()) {
TT_LOG_E(TAG, "Failed to open/create configuration file");
return false;
}
if (!appender.write(&configuration)) {
TT_LOG_E(TAG, "Failed to add configuration");
appender.close();
return false;
}
appender.close();
return true;
}
bool GpsService::removeGpsConfiguration(hal::gps::GpsConfiguration configuration) {
std::string path;
if (!getConfigurationFilePath(path)) {
return false;
}
std::vector<hal::gps::GpsConfiguration> configurations;
if (!getGpsConfigurations(configurations)) {
TT_LOG_E(TAG, "Failed to get gps configurations");
return false;
}
auto count = std::erase_if(configurations, [&configuration](auto& item) {
return strcmp(item.uartName, configuration.uartName) == 0 &&
item.baudRate == configuration.baudRate &&
item.model == configuration.model;
});
auto writer = file::ObjectFileWriter(path, sizeof(hal::gps::GpsConfiguration), 1, false);
if (!writer.open()) {
TT_LOG_E(TAG, "Failed to open configuration file");
return false;
}
for (auto& configuration : configurations) {
writer.write(&configuration);
}
writer.close();
return count > 0;
}
} // namespace tt::service::gps
+240
View File
@@ -0,0 +1,240 @@
#include "Tactility/service/gps/GpsService.h"
#include "Tactility/service/ServiceManifest.h"
#include "Tactility/service/ServiceRegistry.h"
#include <Tactility/Log.h>
#include <Tactility/file/File.h>
using tt::hal::gps::GpsDevice;
namespace tt::service::gps {
constexpr const char* TAG = "GpsService";
extern const ServiceManifest manifest;
constexpr inline bool hasTimeElapsed(TickType_t now, TickType_t timeInThePast, TickType_t expireTimeInTicks) {
return (TickType_t)(now - timeInThePast) >= expireTimeInTicks;
}
GpsService::GpsDeviceRecord* _Nullable GpsService::findGpsRecord(const std::shared_ptr<GpsDevice>& device) {
auto lock = mutex.asScopedLock();
lock.lock();
auto result = std::views::filter(deviceRecords, [&device](auto& record) {
return record.device.get() == device.get();
});
if (!result.empty()) {
return &result.front();
} else {
return nullptr;
}
}
void GpsService::addGpsDevice(const std::shared_ptr<GpsDevice>& device) {
auto lock = mutex.asScopedLock();
lock.lock();
GpsDeviceRecord record = {.device = device};
if (getState() == State::On) { // Ignore during OnPending due to risk of data corruptiohn
startGpsDevice(record);
}
deviceRecords.push_back(record);
}
void GpsService::removeGpsDevice(const std::shared_ptr<GpsDevice>& device) {
auto lock = mutex.asScopedLock();
lock.lock();
GpsDeviceRecord* record = findGpsRecord(device);
if (getState() == State::On) { // Ignore during OnPending due to risk of data corruptiohn
stopGpsDevice(*record);
}
std::erase_if(deviceRecords, [&device](auto& reference) {
return reference.device.get() == device.get();
});
}
void GpsService::onStart(tt::service::ServiceContext& serviceContext) {
auto lock = mutex.asScopedLock();
lock.lock();
paths = serviceContext.getPaths();
}
void GpsService::onStop(tt::service::ServiceContext& serviceContext) {
if (getState() == State::On) {
stopReceiving();
}
}
bool GpsService::startGpsDevice(GpsDeviceRecord& record) {
TT_LOG_I(TAG, "[device %lu] starting", record.device->getId());
auto lock = mutex.asScopedLock();
lock.lock();
auto device = record.device;
if (!device->start()) {
TT_LOG_E(TAG, "[device %lu] starting failed", record.device->getId());
return false;
}
record.satelliteSubscriptionId = device->subscribeGga([this](hal::Device::Id deviceId, auto& record) {
mutex.lock();
onGgaSentence(deviceId, record);
mutex.unlock();
});
record.rmcSubscriptionId = device->subscribeRmc([this](hal::Device::Id deviceId, auto& record) {
mutex.lock();
if (record.longitude.value != 0 && record.longitude.scale != 0) {
rmcRecord = record;
rmcTime = kernel::getTicks();
}
onRmcSentence(deviceId, record);
mutex.unlock();
});
return true;
}
bool GpsService::stopGpsDevice(GpsDeviceRecord& record) {
TT_LOG_I(TAG, "[device %lu] stopping", record.device->getId());
auto device = record.device;
device->unsubscribeGga(record.satelliteSubscriptionId);
device->unsubscribeRmc(record.rmcSubscriptionId);
record.satelliteSubscriptionId = -1;
record.rmcSubscriptionId = -1;
if (!device->stop()) {
TT_LOG_E(TAG, "[device %lu] stopping failed", record.device->getId());
return false;
}
return true;
}
bool GpsService::startReceiving() {
TT_LOG_I(TAG, "Start receiving");
if (getState() != State::Off) {
TT_LOG_E(TAG, "Already receiving");
return false;
}
setState(State::OnPending);
auto lock = mutex.asScopedLock();
lock.lock();
deviceRecords.clear();
std::vector<hal::gps::GpsConfiguration> configurations;
if (!getGpsConfigurations(configurations)) {
TT_LOG_E(TAG, "Failed to get GPS configurations");
setState(State::Off);
return false;
}
if (configurations.empty()) {
TT_LOG_E(TAG, "No GPS configurations");
setState(State::Off);
return false;
}
for (const auto& configuration: configurations) {
auto device = std::make_shared<GpsDevice>(configuration);
addGpsDevice(device);
}
bool started_one_or_more = false;
for (auto& record: deviceRecords) {
started_one_or_more |= startGpsDevice(record);
}
rmcTime = 0;
if (started_one_or_more) {
setState(State::On);
return true;
} else {
setState(State::Off);
return false;
}
}
void GpsService::stopReceiving() {
TT_LOG_I(TAG, "Stop receiving");
setState(State::OffPending);
auto lock = mutex.asScopedLock();
lock.lock();
for (auto& record: deviceRecords) {
stopGpsDevice(record);
}
rmcTime = 0;
setState(State::Off);
}
void GpsService::onGgaSentence(hal::Device::Id deviceId, const minmea_sentence_gga& gga) {
TT_LOG_D(TAG, "[device %lu] LAT %f LON %f, satellites: %d", deviceId, minmea_tocoord(&gga.latitude), minmea_tocoord(&gga.longitude), gga.satellites_tracked);
}
void GpsService::onRmcSentence(hal::Device::Id deviceId, const minmea_sentence_rmc& rmc) {
TT_LOG_D(TAG, "[device %lu] LAT %f LON %f, speed: %.2f", deviceId, minmea_tocoord(&rmc.latitude), minmea_tocoord(&rmc.longitude), minmea_tofloat(&rmc.speed));
}
State GpsService::getState() const {
auto lock = stateMutex.asScopedLock();
lock.lock();
return state;
}
void GpsService::setState(State newState) {
auto lock = stateMutex.asScopedLock();
lock.lock();
state = newState;
lock.unlock();
statePubSub->publish(&state);
}
bool GpsService::hasCoordinates() const {
auto lock = mutex.asScopedLock();
lock.lock();
return getState() == State::On && rmcTime != 0 && !hasTimeElapsed(kernel::getTicks(), rmcTime, kernel::secondsToTicks(10));
}
bool GpsService::getCoordinates(minmea_sentence_rmc& rmc) const {
if (hasCoordinates()) {
rmc = rmcRecord;
return true;
} else {
return false;
}
}
std::shared_ptr<GpsService> findGpsService() {
auto service = findServiceById(manifest.id);
assert(service != nullptr);
return std::static_pointer_cast<GpsService>(service);
}
extern const ServiceManifest manifest = {
.id = "Gps",
.createService = create<GpsService>
};
} // namespace tt::service::gps
@@ -0,0 +1,84 @@
#include "Tactility/service/ServiceContext.h"
#include "Tactility/TactilityHeadless.h"
#include "Tactility/service/ServiceRegistry.h"
#include <Tactility/Mutex.h>
#include <Tactility/Timer.h>
#define TAG "sdcard_service"
namespace tt::service::sdcard {
extern const ServiceManifest manifest;
class SdCardService final : public Service {
private:
Mutex mutex;
std::unique_ptr<Timer> updateTimer;
hal::sdcard::SdCardDevice::State lastState = hal::sdcard::SdCardDevice::State::Unmounted;
bool lock(TickType_t timeout) const {
return mutex.lock(timeout);
}
void unlock() const {
mutex.unlock();
}
void update() {
auto sdcard = tt::hal::getConfiguration()->sdcard;
assert(sdcard);
if (lock(50)) {
auto new_state = sdcard->getState();
if (new_state == hal::sdcard::SdCardDevice::State::Error) {
TT_LOG_W(TAG, "Sdcard error - unmounting. Did you eject the card in an unsafe manner?");
sdcard->unmount();
}
if (new_state != lastState) {
lastState = new_state;
}
unlock();
} else {
TT_LOG_W(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED);
}
}
static void onUpdate(std::shared_ptr<void> context) {
auto service = std::static_pointer_cast<SdCardService>(context);
service->update();
}
public:
void onStart(ServiceContext& serviceContext) final {
if (hal::getConfiguration()->sdcard != nullptr) {
auto service = findServiceById(manifest.id);
updateTimer = std::make_unique<Timer>(Timer::Type::Periodic, onUpdate, service);
// We want to try and scan more often in case of startup or scan lock failure
updateTimer->start(1000);
} else {
TT_LOG_I(TAG, "Timer not started: no SD card config");
}
}
void onStop(ServiceContext& serviceContext) final {
if (updateTimer != nullptr) {
// Stop thread
updateTimer->stop();
updateTimer = nullptr;
}
}
};
extern const ServiceManifest manifest = {
.id = "sdcard",
.createService = create<SdCardService>
};
} // namespace
+24
View File
@@ -0,0 +1,24 @@
#include "Tactility/service/wifi/Wifi.h"
namespace tt::service::wifi {
const char* radioStateToString(RadioState state) {
switch (state) {
using enum RadioState;
case OnPending:
return TT_STRINGIFY(OnPending);
case On:
return TT_STRINGIFY(On);
case ConnectionPending:
return TT_STRINGIFY(ConnectionPending);
case ConnectionActive:
return TT_STRINGIFY(ConnectionActive);
case OffPending:
return TT_STRINGIFY(OnPending);
case Off:
return TT_STRINGIFY(Off);
}
tt_crash("not implemented");
}
}
+918
View File
@@ -0,0 +1,918 @@
#ifdef ESP_PLATFORM
#include "Tactility/service/wifi/Wifi.h"
#include "Tactility/TactilityHeadless.h"
#include "Tactility/service/ServiceContext.h"
#include "Tactility/service/wifi/WifiSettings.h"
#include <Tactility/Timer.h>
#include <freertos/FreeRTOS.h>
#include <atomic>
#include <cstring>
#include <sys/cdefs.h>
namespace tt::service::wifi {
#define TAG "wifi_service"
#define WIFI_CONNECTED_BIT BIT0
#define WIFI_FAIL_BIT BIT1
#define AUTO_SCAN_INTERVAL 10000 // ms
// Forward declarations
class Wifi;
static void scan_list_free_safely(std::shared_ptr<Wifi> wifi);
// Methods for main thread dispatcher
static void dispatchAutoConnect(std::shared_ptr<void> context);
static void dispatchEnable(std::shared_ptr<void> context);
static void dispatchDisable(std::shared_ptr<void> context);
static void dispatchScan(std::shared_ptr<void> context);
static void dispatchConnect(std::shared_ptr<void> context);
static void dispatchDisconnectButKeepActive(std::shared_ptr<void> context);
class Wifi {
private:
std::atomic<RadioState> radio_state = RadioState::Off;
bool scan_active = false;
bool secure_connection = false;
public:
/** @brief Locking mechanism for modifying the Wifi instance */
Mutex radioMutex = Mutex(Mutex::Type::Recursive);
Mutex dataMutex = Mutex(Mutex::Type::Recursive);
std::unique_ptr<Timer> autoConnectTimer;
/** @brief The public event bus */
std::shared_ptr<PubSub> pubsub = std::make_shared<PubSub>();
// TODO: Deal with messages that come in while an action is ongoing
// for example: when scanning and you turn off the radio, the scan should probably stop or turning off
// the radio should disable the on/off button in the app as it is pending.
/** @brief The network interface when wifi is started */
esp_netif_t* _Nullable netif = nullptr;
/** @brief Scanning results */
wifi_ap_record_t* _Nullable scan_list = nullptr;
/** @brief The current item count in scan_list (-1 when scan_list is NULL) */
uint16_t scan_list_count = 0;
/** @brief Maximum amount of records to scan (value > 0) */
uint16_t scan_list_limit = TT_WIFI_SCAN_RECORD_LIMIT;
/** @brief when we last requested a scan. Loops around every 50 days. */
TickType_t last_scan_time = portMAX_DELAY;
esp_event_handler_instance_t event_handler_any_id = nullptr;
esp_event_handler_instance_t event_handler_got_ip = nullptr;
EventFlag connection_wait_flags;
settings::WifiApSettings connection_target = {
.ssid = { 0 },
.password = { 0 },
.auto_connect = false
};
bool pause_auto_connect = false; // Pause when manually disconnecting until manually connecting again
bool connection_target_remember = false; // Whether to store the connection_target on successful connection or not
RadioState getRadioState() const {
auto lock = dataMutex.asScopedLock();
lock.lock();
// TODO: Handle lock failure
return radio_state;
}
void setRadioState(RadioState newState) {
auto lock = dataMutex.asScopedLock();
lock.lock();
// TODO: Handle lock failure
radio_state = newState;
}
bool isScanning() const {
auto lock = dataMutex.asScopedLock();
lock.lock();
// TODO: Handle lock failure
return scan_active;
}
void setScanning(bool newState) {
auto lock = dataMutex.asScopedLock();
lock.lock();
// TODO: Handle lock failure
scan_active = newState;
}
bool isScanActive() const {
auto lock = dataMutex.asScopedLock();
lock.lock();
return scan_active;
}
void setScanActive(bool newState) {
auto lock = dataMutex.asScopedLock();
lock.lock();
scan_active = newState;
}
bool isSecureConnection() const {
auto lock = dataMutex.asScopedLock();
lock.lock();
return secure_connection;
}
void setSecureConnection(bool newState) {
auto lock = dataMutex.asScopedLock();
lock.lock();
secure_connection = newState;
}
};
static std::shared_ptr<Wifi> wifi_singleton;
// region Public functions
std::shared_ptr<PubSub> getPubsub() {
auto wifi = wifi_singleton;
if (wifi == nullptr) {
tt_crash("Service not running");
}
return wifi->pubsub;
}
RadioState getRadioState() {
auto wifi = wifi_singleton;
if (wifi != nullptr) {
return wifi->getRadioState();
} else {
return RadioState::Off;
}
}
std::string getConnectionTarget() {
auto wifi = wifi_singleton;
if (wifi == nullptr) {
return "";
}
RadioState state = wifi->getRadioState();
if (
state != RadioState::ConnectionPending &&
state != RadioState::ConnectionActive
) {
return "";
}
return wifi->connection_target.ssid;
}
void scan() {
TT_LOG_I(TAG, "scan()");
auto wifi = wifi_singleton;
if (wifi == nullptr) {
return;
}
getMainDispatcher().dispatch(dispatchScan, wifi);
}
bool isScanning() {
auto wifi = wifi_singleton;
if (wifi == nullptr) {
return false;
} else {
return wifi->isScanActive();
}
}
void connect(const settings::WifiApSettings* ap, bool remember) {
TT_LOG_I(TAG, "connect(%s, %d)", ap->ssid, remember);
auto wifi = wifi_singleton;
if (wifi == nullptr) {
return;
}
auto lock = wifi->dataMutex.asScopedLock();
if (!lock.lock(10 / portTICK_PERIOD_MS)) {
return;
}
// Manual connect (e.g. via app) should stop auto-connecting until the connection is established
wifi->pause_auto_connect = true;
memcpy(&wifi->connection_target, ap, sizeof(settings::WifiApSettings));
wifi->connection_target_remember = remember;
if (wifi->getRadioState() == RadioState::Off) {
getMainDispatcher().dispatch(dispatchEnable, wifi);
}
getMainDispatcher().dispatch(dispatchConnect, wifi);
}
void disconnect() {
TT_LOG_I(TAG, "disconnect()");
auto wifi = wifi_singleton;
if (wifi == nullptr) {
return;
}
auto lock = wifi->dataMutex.asScopedLock();
if (!lock.lock(10 / portTICK_PERIOD_MS)) {
return;
}
wifi->connection_target = (settings::WifiApSettings) {
.ssid = { 0 },
.password = { 0 },
.auto_connect = false
};
// Manual disconnect (e.g. via app) should stop auto-connecting until a new connection is established
wifi->pause_auto_connect = true;
getMainDispatcher().dispatch(dispatchDisconnectButKeepActive, wifi);
}
void setScanRecords(uint16_t records) {
TT_LOG_I(TAG, "setScanRecords(%d)", records);
auto wifi = wifi_singleton;
if (wifi == nullptr) {
return;
}
auto lock = wifi->dataMutex.asScopedLock();
if (!lock.lock(10 / portTICK_PERIOD_MS)) {
return;
}
if (records != wifi->scan_list_limit) {
scan_list_free_safely(wifi);
wifi->scan_list_limit = records;
}
}
std::vector<ApRecord> getScanResults() {
TT_LOG_I(TAG, "getScanResults()");
auto wifi = wifi_singleton;
std::vector<ApRecord> records;
if (wifi == nullptr) {
return records;
}
auto lock = wifi->dataMutex.asScopedLock();
if (!lock.lock(10 / portTICK_PERIOD_MS)) {
return records;
}
if (wifi->scan_list_count > 0) {
uint16_t i = 0;
for (; i < wifi->scan_list_count; ++i) {
records.push_back((ApRecord) {
.ssid = (const char*)wifi->scan_list[i].ssid,
.rssi = wifi->scan_list[i].rssi,
.channel = wifi->scan_list[i].primary,
.auth_mode = wifi->scan_list[i].authmode
});
}
}
return records;
}
void setEnabled(bool enabled) {
TT_LOG_I(TAG, "setEnabled(%d)", enabled);
auto wifi = wifi_singleton;
if (wifi == nullptr) {
return;
}
auto lock = wifi->dataMutex.asScopedLock();
if (!lock.lock(10 / portTICK_PERIOD_MS)) {
return;
}
if (enabled) {
getMainDispatcher().dispatch(dispatchEnable, wifi);
} else {
getMainDispatcher().dispatch(dispatchDisable, wifi);
}
wifi->pause_auto_connect = false;
wifi->last_scan_time = 0;
}
bool isConnectionSecure() {
auto wifi = wifi_singleton;
if (wifi == nullptr) {
return false;
}
auto lock = wifi->dataMutex.asScopedLock();
if (!lock.lock(10 / portTICK_PERIOD_MS)) {
return false;
}
return wifi->isSecureConnection();
}
int getRssi() {
assert(wifi_singleton);
static int rssi = 0;
if (esp_wifi_sta_get_rssi(&rssi) == ESP_OK) {
return rssi;
} else {
return 1;
}
}
// endregion Public functions
static void scan_list_alloc(std::shared_ptr<Wifi> wifi) {
auto lock = wifi->dataMutex.asScopedLock();
if (lock.lock()) {
assert(wifi->scan_list == nullptr);
wifi->scan_list = static_cast<wifi_ap_record_t*>(malloc(sizeof(wifi_ap_record_t) * wifi->scan_list_limit));
wifi->scan_list_count = 0;
}
}
static void scan_list_alloc_safely(std::shared_ptr<Wifi> wifi) {
auto lock = wifi->dataMutex.asScopedLock();
if (lock.lock()) {
if (wifi->scan_list == nullptr) {
scan_list_alloc(wifi);
}
}
}
static void scan_list_free(std::shared_ptr<Wifi> wifi) {
auto lock = wifi->dataMutex.asScopedLock();
if (lock.lock()) {
assert(wifi->scan_list != nullptr);
free(wifi->scan_list);
wifi->scan_list = nullptr;
wifi->scan_list_count = 0;
}
}
static void scan_list_free_safely(std::shared_ptr<Wifi> wifi) {
auto lock = wifi->dataMutex.asScopedLock();
if (lock.lock()) {
if (wifi->scan_list != nullptr) {
scan_list_free(wifi);
}
}
}
static void publish_event_simple(std::shared_ptr<Wifi> wifi, EventType type) {
auto lock = wifi->dataMutex.asScopedLock();
if (lock.lock()) {
Event turning_on_event = {.type = type};
wifi->pubsub->publish(&turning_on_event);
}
}
static bool copy_scan_list(std::shared_ptr<Wifi> wifi) {
auto state = wifi->getRadioState();
bool can_fetch_results = (state == RadioState::On || state == RadioState::ConnectionActive) &&
wifi->isScanActive();
if (!can_fetch_results) {
TT_LOG_I(TAG, "Skip scan result fetching");
return false;
}
auto lock = wifi->dataMutex.asScopedLock();
if (!lock.lock()) {
return false;
}
// Create scan list if it does not exist
scan_list_alloc_safely(wifi);
wifi->scan_list_count = 0;
uint16_t record_count = wifi->scan_list_limit;
esp_err_t scan_result = esp_wifi_scan_get_ap_records(&record_count, wifi->scan_list);
if (scan_result == ESP_OK) {
uint16_t safe_record_count = std::min(wifi->scan_list_limit, record_count);
wifi->scan_list_count = safe_record_count;
TT_LOG_I(TAG, "Scanned %u APs. Showing %u:", record_count, safe_record_count);
for (uint16_t i = 0; i < safe_record_count; i++) {
wifi_ap_record_t* record = &wifi->scan_list[i];
TT_LOG_I(TAG, " - SSID %s (RSSI %d, channel %d)", record->ssid, record->rssi, record->primary);
}
return true;
} else {
TT_LOG_I(TAG, "Failed to get scanned records: %s", esp_err_to_name(scan_result));
return false;
}
}
static bool find_auto_connect_ap(std::shared_ptr<void> context, settings::WifiApSettings& settings) {
auto wifi = std::static_pointer_cast<Wifi>(context);
auto lock = wifi->dataMutex.asScopedLock();
if (lock.lock(10 / portTICK_PERIOD_MS)) {
TT_LOG_I(TAG, "auto_connect()");
for (int i = 0; i < wifi->scan_list_count; ++i) {
auto ssid = reinterpret_cast<const char*>(wifi->scan_list[i].ssid);
if (settings::contains(ssid)) {
static_assert(sizeof(wifi->scan_list[i].ssid) == (TT_WIFI_SSID_LIMIT + 1), "SSID size mismatch");
if (settings::load(ssid, &settings)) {
if (settings.auto_connect) {
return true;
}
} else {
TT_LOG_E(TAG, "Failed to load credentials for ssid %s", ssid);
}
break;
}
}
}
return false;
}
static void dispatchAutoConnect(std::shared_ptr<void> context) {
TT_LOG_I(TAG, "dispatchAutoConnect()");
auto wifi = std::static_pointer_cast<Wifi>(context);
settings::WifiApSettings settings;
if (find_auto_connect_ap(context, settings)) {
TT_LOG_I(TAG, "Auto-connecting to %s", settings.ssid);
connect(&settings, false);
}
}
static void eventHandler(TT_UNUSED void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) {
auto wifi = wifi_singleton;
if (wifi == nullptr) {
TT_LOG_E(TAG, "eventHandler: no wifi instance");
return;
}
if (event_base == WIFI_EVENT) {
TT_LOG_I(TAG, "eventHandler: WIFI_EVENT (%ld)", event_id);
} else if (event_base == IP_EVENT) {
TT_LOG_I(TAG, "eventHandler: IP_EVENT (%ld)", event_id);
}
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
TT_LOG_I(TAG, "eventHandler: sta start");
if (wifi->getRadioState() == RadioState::ConnectionPending) {
esp_wifi_connect();
}
} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
TT_LOG_I(TAG, "eventHandler: disconnected");
if (wifi->getRadioState() == RadioState::ConnectionPending) {
wifi->connection_wait_flags.set(WIFI_FAIL_BIT);
}
wifi->setRadioState(RadioState::On);
publish_event_simple(wifi, EventType::Disconnected);
} else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
auto* event = static_cast<ip_event_got_ip_t*>(event_data);
TT_LOG_I(TAG, "eventHandler: got ip:" IPSTR, IP2STR(&event->ip_info.ip));
if (wifi->getRadioState() == RadioState::ConnectionPending) {
wifi->connection_wait_flags.set(WIFI_CONNECTED_BIT);
// We resume auto-connecting only when there was an explicit request by the user for the connection
// TODO: Make thread-safe
wifi->pause_auto_connect = false; // Resume auto-connection
}
} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_SCAN_DONE) {
auto* event = static_cast<wifi_event_sta_scan_done_t*>(event_data);
TT_LOG_I(TAG, "eventHandler: wifi scanning done (scan id %u)", event->scan_id);
bool copied_list = copy_scan_list(wifi);
auto state = wifi->getRadioState();
if (
state != RadioState::Off &&
state != RadioState::OffPending
) {
wifi->setScanActive(false);
esp_wifi_scan_stop();
}
publish_event_simple(wifi_singleton, EventType::ScanFinished);
TT_LOG_I(TAG, "eventHandler: Finished scan");
if (copied_list && wifi_singleton->getRadioState() == RadioState::On && !wifi->pause_auto_connect) {
getMainDispatcher().dispatch(dispatchAutoConnect, wifi);
}
}
}
static void dispatchEnable(std::shared_ptr<void> context) {
TT_LOG_I(TAG, "dispatchEnable()");
auto wifi = std::static_pointer_cast<Wifi>(context);
RadioState state = wifi->getRadioState();
if (
state == RadioState::On ||
state == RadioState::OnPending ||
state == RadioState::OffPending
) {
TT_LOG_W(TAG, "Can't enable from current state");
return;
}
auto lock = wifi->radioMutex.asScopedLock();
if (lock.lock(50 / portTICK_PERIOD_MS)) {
TT_LOG_I(TAG, "Enabling");
wifi->setRadioState(RadioState::OnPending);
publish_event_simple(wifi, EventType::RadioStateOnPending);
if (wifi->netif != nullptr) {
esp_netif_destroy(wifi->netif);
}
wifi->netif = esp_netif_create_default_wifi_sta();
// Warning: this is the memory-intensive operation
// It uses over 117kB of RAM with default settings for S3 on IDF v5.1.2
wifi_init_config_t config = WIFI_INIT_CONFIG_DEFAULT();
esp_err_t init_result = esp_wifi_init(&config);
if (init_result != ESP_OK) {
TT_LOG_E(TAG, "Wifi init failed");
if (init_result == ESP_ERR_NO_MEM) {
TT_LOG_E(TAG, "Insufficient memory");
}
wifi->setRadioState(RadioState::Off);
publish_event_simple(wifi, EventType::RadioStateOff);
return;
}
esp_wifi_set_storage(WIFI_STORAGE_RAM);
// TODO: don't crash on check failure
ESP_ERROR_CHECK(esp_event_handler_instance_register(
WIFI_EVENT,
ESP_EVENT_ANY_ID,
&eventHandler,
nullptr,
&wifi->event_handler_any_id
));
// TODO: don't crash on check failure
ESP_ERROR_CHECK(esp_event_handler_instance_register(
IP_EVENT,
IP_EVENT_STA_GOT_IP,
&eventHandler,
nullptr,
&wifi->event_handler_got_ip
));
if (esp_wifi_set_mode(WIFI_MODE_STA) != ESP_OK) {
TT_LOG_E(TAG, "Wifi mode setting failed");
wifi->setRadioState(RadioState::Off);
esp_wifi_deinit();
publish_event_simple(wifi, EventType::RadioStateOff);
return;
}
esp_err_t start_result = esp_wifi_start();
if (start_result != ESP_OK) {
TT_LOG_E(TAG, "Wifi start failed");
if (start_result == ESP_ERR_NO_MEM) {
TT_LOG_E(TAG, "Insufficient memory");
}
wifi->setRadioState(RadioState::Off);
esp_wifi_set_mode(WIFI_MODE_NULL);
esp_wifi_deinit();
publish_event_simple(wifi, EventType::RadioStateOff);
return;
}
wifi->setRadioState(RadioState::On);
publish_event_simple(wifi, EventType::RadioStateOn);
TT_LOG_I(TAG, "Enabled");
} else {
TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED);
}
}
static void dispatchDisable(std::shared_ptr<void> context) {
TT_LOG_I(TAG, "dispatchDisable()");
auto wifi = std::static_pointer_cast<Wifi>(context);
auto lock = wifi->radioMutex.asScopedLock();
if (!lock.lock(50 / portTICK_PERIOD_MS)) {
TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "disable()");
return;
}
RadioState state = wifi->getRadioState();
if (
state == RadioState::Off ||
state == RadioState::OffPending ||
state == RadioState::OnPending
) {
TT_LOG_W(TAG, "Can't disable from current state");
return;
}
TT_LOG_I(TAG, "Disabling");
wifi->setRadioState(RadioState::OffPending);
publish_event_simple(wifi, EventType::RadioStateOffPending);
// Free up scan list memory
scan_list_free_safely(wifi_singleton);
if (esp_wifi_stop() != ESP_OK) {
TT_LOG_E(TAG, "Failed to stop radio");
wifi->setRadioState(RadioState::On);
publish_event_simple(wifi, EventType::RadioStateOn);
return;
}
if (esp_wifi_set_mode(WIFI_MODE_NULL) != ESP_OK) {
TT_LOG_E(TAG, "Failed to unset mode");
}
if (esp_event_handler_instance_unregister(
WIFI_EVENT,
ESP_EVENT_ANY_ID,
wifi->event_handler_any_id
) != ESP_OK) {
TT_LOG_E(TAG, "Failed to unregister id event handler");
}
if (esp_event_handler_instance_unregister(
IP_EVENT,
IP_EVENT_STA_GOT_IP,
wifi->event_handler_got_ip
) != ESP_OK) {
TT_LOG_E(TAG, "Failed to unregister ip event handler");
}
if (esp_wifi_deinit() != ESP_OK) {
TT_LOG_E(TAG, "Failed to deinit");
}
assert(wifi->netif != nullptr);
esp_netif_destroy(wifi->netif);
wifi->netif = nullptr;
wifi->setScanActive(false);
wifi->setRadioState(RadioState::Off);
publish_event_simple(wifi, EventType::RadioStateOff);
TT_LOG_I(TAG, "Disabled");
}
static void dispatchScan(std::shared_ptr<void> context) {
TT_LOG_I(TAG, "dispatchScan()");
auto wifi = std::static_pointer_cast<Wifi>(context);
auto lock = wifi->radioMutex.asScopedLock();
if (!lock.lock(10 / portTICK_PERIOD_MS)) {
TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED);
return;
}
RadioState state = wifi->getRadioState();
if (state != RadioState::On && state != RadioState::ConnectionActive && state != RadioState::ConnectionPending) {
TT_LOG_W(TAG, "Scan unavailable: wifi not enabled");
return;
}
if (wifi->isScanActive()) {
TT_LOG_W(TAG, "Scan already pending");
return;
}
// TODO: Thread safety
wifi->last_scan_time = tt::kernel::getTicks();
if (esp_wifi_scan_start(nullptr, false) != ESP_OK) {
TT_LOG_I(TAG, "Can't start scan");
return;
}
TT_LOG_I(TAG, "Starting scan");
wifi->setScanActive(true);
publish_event_simple(wifi, EventType::ScanStarted);
}
static void dispatchConnect(std::shared_ptr<void> context) {
TT_LOG_I(TAG, "dispatchConnect()");
auto wifi = std::static_pointer_cast<Wifi>(context);
auto lock = wifi->radioMutex.asScopedLock();
if (!lock.lock(50 / portTICK_PERIOD_MS)) {
TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "dispatchConnect()");
return;
}
TT_LOG_I(TAG, "Connecting to %s", wifi->connection_target.ssid);
// Stop radio first, if needed
RadioState radio_state = wifi->getRadioState();
if (
radio_state == RadioState::On ||
radio_state == RadioState::ConnectionActive ||
radio_state == RadioState::ConnectionPending
) {
TT_LOG_I(TAG, "Connecting: Stopping radio first");
esp_err_t stop_result = esp_wifi_stop();
wifi->setScanActive(false);
if (stop_result != ESP_OK) {
TT_LOG_E(TAG, "Connecting: Failed to disconnect (%s)", esp_err_to_name(stop_result));
return;
}
}
wifi->setScanActive(false);
wifi->setRadioState(RadioState::ConnectionPending);
publish_event_simple(wifi, EventType::ConnectionPending);
wifi_config_t config;
memset(&config, 0, sizeof(wifi_config_t));
config.sta.channel = wifi_singleton->connection_target.channel;
config.sta.scan_method = WIFI_FAST_SCAN;
config.sta.sort_method = WIFI_CONNECT_AP_BY_SIGNAL;
config.sta.threshold.rssi = -127;
config.sta.pmf_cfg.capable = true;
static_assert(sizeof(config.sta.ssid) == (sizeof(wifi_singleton->connection_target.ssid)-1), "SSID size mismatch");
memcpy(config.sta.ssid, wifi_singleton->connection_target.ssid, sizeof(config.sta.ssid));
if (wifi_singleton->connection_target.password[0] != 0x00) {
memcpy(config.sta.password, wifi_singleton->connection_target.password, sizeof(config.sta.password));
config.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK;
}
TT_LOG_I(TAG, "esp_wifi_set_config()");
esp_err_t set_config_result = esp_wifi_set_config(WIFI_IF_STA, &config);
if (set_config_result != ESP_OK) {
wifi->setRadioState(RadioState::On);
TT_LOG_E(TAG, "Failed to set wifi config (%s)", esp_err_to_name(set_config_result));
publish_event_simple(wifi, EventType::ConnectionFailed);
return;
}
TT_LOG_I(TAG, "esp_wifi_start()");
esp_err_t wifi_start_result = esp_wifi_start();
if (wifi_start_result != ESP_OK) {
wifi->setRadioState(RadioState::On);
TT_LOG_E(TAG, "Failed to start wifi to begin connecting (%s)", esp_err_to_name(wifi_start_result));
publish_event_simple(wifi, EventType::ConnectionFailed);
return;
}
/* Waiting until either the connection is established (WIFI_CONNECTED_BIT)
* or connection failed for the maximum number of re-tries (WIFI_FAIL_BIT).
* The bits are set by wifi_event_handler() */
uint32_t bits = wifi_singleton->connection_wait_flags.wait(WIFI_FAIL_BIT | WIFI_CONNECTED_BIT);
TT_LOG_I(TAG, "Waiting for EventFlag by event_handler()");
if (bits & WIFI_CONNECTED_BIT) {
wifi->setSecureConnection(config.sta.password[0] != 0x00U);
wifi->setRadioState(RadioState::ConnectionActive);
publish_event_simple(wifi, EventType::ConnectionSuccess);
TT_LOG_I(TAG, "Connected to %s", wifi->connection_target.ssid);
if (wifi->connection_target_remember) {
if (!settings::save(&wifi->connection_target)) {
TT_LOG_E(TAG, "Failed to store credentials");
} else {
TT_LOG_I(TAG, "Stored credentials");
}
}
} else if (bits & WIFI_FAIL_BIT) {
wifi->setRadioState(RadioState::On);
publish_event_simple(wifi, EventType::ConnectionFailed);
TT_LOG_I(TAG, "Failed to connect to %s", wifi->connection_target.ssid);
} else {
wifi->setRadioState(RadioState::On);
publish_event_simple(wifi, EventType::ConnectionFailed);
TT_LOG_E(TAG, "UNEXPECTED EVENT");
}
wifi_singleton->connection_wait_flags.clear(WIFI_FAIL_BIT | WIFI_CONNECTED_BIT);
}
static void dispatchDisconnectButKeepActive(std::shared_ptr<void> context) {
TT_LOG_I(TAG, "dispatchDisconnectButKeepActive()");
auto wifi = std::static_pointer_cast<Wifi>(context);
auto lock = wifi->radioMutex.asScopedLock();
if (!lock.lock(50 / portTICK_PERIOD_MS)) {
TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED);
return;
}
esp_err_t stop_result = esp_wifi_stop();
if (stop_result != ESP_OK) {
TT_LOG_E(TAG, "Failed to disconnect (%s)", esp_err_to_name(stop_result));
return;
}
wifi_config_t config;
memset(&config, 0, sizeof(wifi_config_t));
config.sta.channel = wifi_singleton->connection_target.channel;
config.sta.scan_method = WIFI_ALL_CHANNEL_SCAN;
config.sta.sort_method = WIFI_CONNECT_AP_BY_SIGNAL;
config.sta.threshold.rssi = -127;
config.sta.pmf_cfg.capable = true;
esp_err_t set_config_result = esp_wifi_set_config(WIFI_IF_STA, &config);
if (set_config_result != ESP_OK) {
// TODO: disable radio, because radio state is in limbo between off and on
wifi->setRadioState(RadioState::Off);
TT_LOG_E(TAG, "failed to set wifi config (%s)", esp_err_to_name(set_config_result));
publish_event_simple(wifi, EventType::RadioStateOff);
return;
}
esp_err_t wifi_start_result = esp_wifi_start();
if (wifi_start_result != ESP_OK) {
// TODO: disable radio, because radio state is in limbo between off and on
wifi->setRadioState(RadioState::Off);
TT_LOG_E(TAG, "failed to start wifi to begin connecting (%s)", esp_err_to_name(wifi_start_result));
publish_event_simple(wifi, EventType::RadioStateOff);
return;
}
wifi->setRadioState(RadioState::On);
publish_event_simple(wifi, EventType::Disconnected);
TT_LOG_I(TAG, "Disconnected");
}
static bool shouldScanForAutoConnect(std::shared_ptr<Wifi> wifi) {
auto lock = wifi->dataMutex.asScopedLock();
if (!lock.lock(100)) {
return false;
}
bool is_radio_in_scannable_state = wifi->getRadioState() == RadioState::On &&
!wifi->isScanActive() &&
!wifi->pause_auto_connect;
if (!is_radio_in_scannable_state) {
return false;
}
TickType_t current_time = tt::kernel::getTicks();
bool scan_time_has_looped = (current_time < wifi->last_scan_time);
bool no_recent_scan = (current_time - wifi->last_scan_time) > (AUTO_SCAN_INTERVAL / portTICK_PERIOD_MS);
return scan_time_has_looped || no_recent_scan;
}
void onAutoConnectTimer(std::shared_ptr<void> context) {
auto wifi = std::static_pointer_cast<Wifi>(wifi_singleton);
// Automatic scanning is done so we can automatically connect to access points
bool should_auto_scan = shouldScanForAutoConnect(wifi);
if (should_auto_scan) {
getMainDispatcher().dispatch(dispatchScan, wifi);
}
}
class WifiService final : public Service {
public:
void onStart(ServiceContext& service) override {
assert(wifi_singleton == nullptr);
wifi_singleton = std::make_shared<Wifi>();
wifi_singleton->autoConnectTimer = std::make_unique<Timer>(Timer::Type::Periodic, onAutoConnectTimer, wifi_singleton);
// We want to try and scan more often in case of startup or scan lock failure
wifi_singleton->autoConnectTimer->start(std::min(2000, AUTO_SCAN_INTERVAL));
if (settings::shouldEnableOnBoot()) {
TT_LOG_I(TAG, "Auto-enabling due to setting");
getMainDispatcher().dispatch(dispatchEnable, wifi_singleton);
}
}
void onStop(ServiceContext& service) override {
auto wifi = wifi_singleton;
assert(wifi != nullptr);
RadioState state = wifi->getRadioState();
if (state != RadioState::Off) {
dispatchDisable(wifi);
}
wifi->autoConnectTimer->stop();
wifi->autoConnectTimer = nullptr; // Must release as it holds a reference to this Wifi instance
// Acquire all mutexes
wifi->dataMutex.lock();
wifi->radioMutex.lock();
// Detach
wifi_singleton = nullptr;
// Release mutexes
wifi->dataMutex.unlock();
wifi->radioMutex.unlock();
// Release (hopefully) last Wifi instance by scope
}
};
extern const ServiceManifest manifest = {
.id = "Wifi",
.createService = create<WifiService>
};
} // namespace
#endif // ESP_PLATFORM
+163
View File
@@ -0,0 +1,163 @@
#include "Tactility/service/wifi/Wifi.h"
#ifndef ESP_PLATFORM
#include "Tactility/service/ServiceContext.h"
#include <Tactility/Check.h>
#include <Tactility/Log.h>
#include <Tactility/Mutex.h>
#include <Tactility/PubSub.h>
namespace tt::service::wifi {
#define TAG "wifi"
#define WIFI_CONNECTED_BIT BIT0
#define WIFI_FAIL_BIT BIT1
struct Wifi {
Wifi() = default;
~Wifi() = default;
/** @brief Locking mechanism for modifying the Wifi instance */
Mutex mutex = Mutex(Mutex::Type::Recursive);
/** @brief The public event bus */
std::shared_ptr<PubSub> pubsub = std::make_shared<PubSub>();
/** @brief The internal message queue */
bool scan_active = false;
bool secure_connection = false;
RadioState radio_state = RadioState::ConnectionActive;
};
static Wifi* wifi = nullptr;
// region Static
static void publish_event_simple(Wifi* wifi, EventType type) {
Event turning_on_event = { .type = type };
wifi->pubsub->publish(&turning_on_event);
}
// endregion Static
// region Public functions
std::shared_ptr<PubSub> getPubsub() {
assert(wifi);
return wifi->pubsub;
}
RadioState getRadioState() {
return wifi->radio_state;
}
std::string getConnectionTarget() {
return "Home Wifi";
}
void scan() {
assert(wifi);
wifi->scan_active = false; // TODO: enable and then later disable automatically
}
bool isScanning() {
assert(wifi);
return wifi->scan_active;
}
void connect(const settings::WifiApSettings* ap, bool remember) {
assert(wifi);
// TODO: implement
}
void disconnect() {
assert(wifi);
}
void setScanRecords(uint16_t records) {
assert(wifi);
// TODO: implement
}
std::vector<ApRecord> getScanResults() {
tt_check(wifi);
std::vector<ApRecord> records;
records.push_back((ApRecord) {
.ssid = "Home Wifi",
.rssi = -30,
.auth_mode = WIFI_AUTH_WPA2_PSK
});
records.push_back((ApRecord) {
.ssid = "No place like 127.0.0.1",
.rssi = -67,
.auth_mode = WIFI_AUTH_WPA2_PSK
});
records.push_back((ApRecord) {
.ssid = "Pretty fly for a Wi-Fi",
.rssi = -70,
.auth_mode = WIFI_AUTH_WPA2_PSK
});
records.push_back((ApRecord) {
.ssid = "An AP with a really, really long name",
.rssi = -80,
.auth_mode = WIFI_AUTH_WPA2_PSK
});
records.push_back((ApRecord) {
.ssid = "Bad Reception",
.rssi = -90,
.auth_mode = WIFI_AUTH_OPEN
});
return records;
}
void setEnabled(bool enabled) {
assert(wifi != nullptr);
if (enabled) {
wifi->radio_state = RadioState::On;
wifi->secure_connection = true;
} else {
wifi->radio_state = RadioState::Off;
}
}
bool isConnectionSecure() {
return wifi->secure_connection;
}
int getRssi() {
if (wifi->radio_state == RadioState::ConnectionActive) {
return -30;
} else {
return 0;
}
}
// endregion Public functions
class WifiService final : public Service {
public:
void onStart(TT_UNUSED ServiceContext& service) final {
tt_check(wifi == nullptr);
wifi = new Wifi();
}
void onStop(TT_UNUSED ServiceContext& service) final {
tt_check(wifi != nullptr);
delete wifi;
wifi = nullptr;
}
};
extern const ServiceManifest manifest = {
.id = "Wifi",
.createService = create<WifiService>
};
} // namespace
#endif // ESP_PLATFORM
@@ -0,0 +1,18 @@
#include "Tactility/Preferences.h"
#define WIFI_PREFERENCES_NAMESPACE "wifi"
#define WIFI_PREFERENCES_KEY_ENABLE_ON_BOOT "enable_on_boot"
namespace tt::service::wifi::settings {
void setEnableOnBoot(bool enable) {
Preferences(WIFI_PREFERENCES_NAMESPACE).putBool(WIFI_PREFERENCES_KEY_ENABLE_ON_BOOT, enable);
}
bool shouldEnableOnBoot() {
bool enable = false;
Preferences(WIFI_PREFERENCES_NAMESPACE).optBool(WIFI_PREFERENCES_KEY_ENABLE_ON_BOOT, enable);
return enable;
}
} // namespace
@@ -0,0 +1,148 @@
#ifdef ESP_PLATFORM
#include "Tactility/service/wifi/WifiGlobals.h"
#include "Tactility/service/wifi/WifiSettings.h"
#include <Tactility/Log.h>
#include <Tactility/crypt/Hash.h>
#include <Tactility/crypt/Crypt.h>
#include <nvs_flash.h>
#include <cstring>
#define TAG "wifi_settings"
#define TT_NVS_NAMESPACE "wifi_settings" // limited by NVS_KEY_NAME_MAX_SIZE
// region Wi-Fi Credentials - static
static esp_err_t credentials_nvs_open(nvs_handle_t* handle, nvs_open_mode_t mode) {
return nvs_open(TT_NVS_NAMESPACE, NVS_READWRITE, handle);
}
static void credentials_nvs_close(nvs_handle_t handle) {
nvs_close(handle);
}
// endregion Wi-Fi Credentials - static
// region Wi-Fi Credentials - public
namespace tt::service::wifi::settings {
bool contains(const char* ssid) {
nvs_handle_t handle;
esp_err_t result = credentials_nvs_open(&handle, NVS_READONLY);
if (result != ESP_OK) {
TT_LOG_E(TAG, "Failed to open NVS handle: %s", esp_err_to_name(result));
return false;
}
bool key_exists = nvs_find_key(handle, ssid, NULL) == ESP_OK;
credentials_nvs_close(handle);
return key_exists;
}
bool load(const char* ssid, WifiApSettings* settings) {
nvs_handle_t handle;
esp_err_t result = credentials_nvs_open(&handle, NVS_READONLY);
if (result != ESP_OK) {
TT_LOG_E(TAG, "Failed to open NVS handle: %s", esp_err_to_name(result));
return false;
}
WifiApSettings encrypted_settings;
size_t length = sizeof(WifiApSettings);
result = nvs_get_blob(handle, ssid, &encrypted_settings, &length);
uint8_t iv[16];
crypt::getIv(ssid, strlen(ssid), iv);
int decrypt_result = crypt::decrypt(
iv,
(uint8_t*)encrypted_settings.password,
(uint8_t*)settings->password,
TT_WIFI_CREDENTIALS_PASSWORD_LIMIT
);
// Manually ensure null termination, because encryption must be a multiple of 16 bytes
encrypted_settings.password[TT_WIFI_CREDENTIALS_PASSWORD_LIMIT] = 0;
if (decrypt_result != 0) {
result = ESP_FAIL;
TT_LOG_E(TAG, "Failed to decrypt credentials for \"%s\": %d", ssid, decrypt_result);
}
if (result != ESP_OK && result != ESP_ERR_NVS_NOT_FOUND) {
TT_LOG_E(TAG, "Failed to get credentials for \"%s\": %s", ssid, esp_err_to_name(result));
}
credentials_nvs_close(handle);
settings->auto_connect = encrypted_settings.auto_connect;
strcpy((char*)settings->ssid, encrypted_settings.ssid);
return result == ESP_OK;
}
bool save(const WifiApSettings* settings) {
nvs_handle_t handle;
esp_err_t result = credentials_nvs_open(&handle, NVS_READWRITE);
if (result != ESP_OK) {
TT_LOG_E(TAG, "Failed to open NVS handle: %s", esp_err_to_name(result));
return false;
}
WifiApSettings encrypted_settings = {
.ssid = { 0 },
.password = { 0 },
.auto_connect = settings->auto_connect,
};
strcpy((char*)encrypted_settings.ssid, settings->ssid);
// We only decrypt multiples of 16, so we have to ensure the last byte is set to 0
encrypted_settings.password[TT_WIFI_CREDENTIALS_PASSWORD_LIMIT] = 0;
uint8_t iv[16];
crypt::getIv(settings->ssid, strlen(settings->ssid), iv);
int encrypt_result = crypt::encrypt(
iv,
(uint8_t*)settings->password,
(uint8_t*)encrypted_settings.password,
TT_WIFI_CREDENTIALS_PASSWORD_LIMIT
);
if (encrypt_result != 0) {
result = ESP_FAIL;
TT_LOG_E(TAG, "Failed to encrypt credentials \"%s\": %d", settings->ssid, encrypt_result);
}
if (result == ESP_OK) {
result = nvs_set_blob(handle, settings->ssid, &encrypted_settings, sizeof(WifiApSettings));
if (result != ESP_OK) {
TT_LOG_E(TAG, "Failed to get credentials for \"%s\": %s", settings->ssid, esp_err_to_name(result));
}
}
credentials_nvs_close(handle);
return result == ESP_OK;
}
bool remove(const char* ssid) {
nvs_handle_t handle;
esp_err_t result = credentials_nvs_open(&handle, NVS_READWRITE);
if (result != ESP_OK) {
TT_LOG_E(TAG, "Failed to open NVS handle to store \"%s\": %s", ssid, esp_err_to_name(result));
return false;
}
result = nvs_erase_key(handle, ssid);
if (result != ESP_OK) {
TT_LOG_E(TAG, "Failed to erase credentials for \"%s\": %s", ssid, esp_err_to_name(result));
}
credentials_nvs_close(handle);
return result == ESP_OK;
}
// end region Wi-Fi Credentials - public
} // nemespace
#endif // ESP_PLATFORM
@@ -0,0 +1,27 @@
#ifndef ESP_PLATFORM
#include "Tactility/service/wifi/WifiSettings.h"
namespace tt::service::wifi::settings {
#define TAG "wifi_settings_mock"
bool contains(const char* ssid) {
return false;
}
bool load(const char* ssid, WifiApSettings* settings) {
return false;
}
bool save(const WifiApSettings* settings) {
return true;
}
bool remove(const char* ssid) {
return true;
}
} // namespace
#endif // ESP_PLATFORM

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