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:
committed by
GitHub
parent
d0ca3b16f8
commit
d72852a6e2
@@ -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
|
||||
@@ -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
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user