Cleanup rpc interfaces

This commit is contained in:
2025-10-22 23:07:41 -04:00
parent 63a2f86343
commit 703020452f
28 changed files with 224 additions and 97 deletions

View File

@@ -0,0 +1,231 @@
#include <iostream>
#include <memory>
#include "esp_log.h"
#include "sys/param.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "lwip/err.h"
#include "lwip/sockets.h"
#include "lwip/sys.h"
#include "lwip/netdb.h"
#include "wireless/TCPServer.h"
#include "bits/shared_ptr_base.h"
#include "constants/app_comms.h"
#include "constants/tcp.h"
#define TAG "TCPServer"
// todo: - add message routing to correct client
// - authenticate (don't just return true from the auth function)
// - tx from board
TCPServer::TCPServer(const int port, const std::shared_ptr<PtrQueue<std::vector<uint8_t>>>& rx_queue) {
this->m_port = port;
this->m_mutex = xSemaphoreCreateMutex();
this->m_clients = std::unordered_set<int>();
this->m_task = nullptr;
this->m_rx_task = nullptr;
this->m_rx_queue = rx_queue;
this->m_server_sock = 0;
xTaskCreate(tcp_server_task, "tcp_accept_server", 3072, this, 5, &this->m_task);
xTaskCreate(socket_monitor_thread, "tcp_rx", 4096, this, 5, &this->m_rx_task);
}
TCPServer::~TCPServer() {
vTaskDelete(this->m_task);
vTaskDelete(this->m_rx_task);
vSemaphoreDelete(this->m_mutex);
}
[[noreturn]] void TCPServer::tcp_server_task(void *args) {
constexpr int keepAlive = 1;
constexpr int keepIdle = KEEPALIVE_IDLE;
constexpr int keepInterval = KEEPALIVE_INTERVAL;
constexpr int keepCount = KEEPALIVE_COUNT;
const auto that = static_cast<TCPServer*>(args);
while (true) {
ESP_LOGI(TAG, "Attempting to start TCP Server on port %d", that->m_port);
that->m_server_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
if (that->m_server_sock < 0) {
ESP_LOGE(TAG, "Unable to create TCP socket: errno %d\n", errno);
vTaskDelay(SLEEP_AFTER_FAIL_MS / portTICK_PERIOD_MS);
continue;
}
constexpr int opt = 1;
setsockopt(that->m_server_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
ESP_LOGI(TAG, "Socket created\n");
sockaddr_in server_addr = {
.sin_family = AF_INET,
.sin_port = htons(that->m_port),
.sin_addr = {
.s_addr = htonl(INADDR_ANY),
},
};
int err = bind(that->m_server_sock, reinterpret_cast<struct sockaddr *>(&server_addr), sizeof(server_addr));
if (0 != err) {
ESP_LOGE(TAG, "Socket unable to bind: errno %d\n", errno);
close(that->m_server_sock);
that->m_server_sock = -1;
vTaskDelay(SLEEP_AFTER_FAIL_MS / portTICK_PERIOD_MS);
continue;
}
ESP_LOGI(TAG, "Socket bound to port %d\n", that->m_port);
err = listen(that->m_server_sock, TCP_DEFAULT_LISTEN_BACKLOG);
if (0 != err) {
ESP_LOGE(TAG, "Error occurred during TCP listen: errno %d\n", errno);
close(that->m_server_sock);
that->m_server_sock = -1;
vTaskDelay(SLEEP_AFTER_FAIL_MS / portTICK_PERIOD_MS);
continue;
}
while (is_network_connected()) {
sockaddr_in client_addr{};
socklen_t addr_len = sizeof(client_addr);
int client_sock = accept(that->m_server_sock, reinterpret_cast<struct sockaddr *>(&client_addr), &addr_len);
if (client_sock < 0) {
ESP_LOGE(TAG, "Unable to accept TCP connection: errno %d\n", errno);
continue;
}
err = that->authenticate_client(client_sock);
if (0 != err) {
ESP_LOGE(TAG, "Client failed authentication\n");
}
setsockopt(client_sock, SOL_SOCKET, SO_KEEPALIVE, &keepAlive, sizeof(int));
setsockopt(client_sock, IPPROTO_TCP, TCP_KEEPIDLE, &keepIdle, sizeof(int));
setsockopt(client_sock, IPPROTO_TCP, TCP_KEEPINTVL, &keepInterval, sizeof(int));
setsockopt(client_sock, IPPROTO_TCP, TCP_KEEPCNT, &keepCount, sizeof(int));
xSemaphoreTake(that->m_mutex, portMAX_DELAY);
that->m_clients.emplace(client_sock);
xSemaphoreGive(that->m_mutex);
}
close(that->m_server_sock);
vTaskDelay(SLEEP_AFTER_FAIL_MS / portTICK_PERIOD_MS);
}
}
[[noreturn]] void TCPServer::socket_monitor_thread(void *args) {
const auto that = static_cast<TCPServer *>(args);
while (true) {
vTaskDelay(0); // Avoid starving other threads
fd_set readfds;
FD_ZERO(&readfds);
int max_fd = -1;
xSemaphoreTake(that->m_mutex, portMAX_DELAY);
for (const auto sock : that->m_clients) {
FD_SET(sock, &readfds);
if (sock > max_fd) max_fd = sock;
}
xSemaphoreGive(that->m_mutex);
// todo: Select seems to be timing out the watchdog, even though we have a 50ms timeout.
// Potentially select is not respecting our timeout?
timeval timeout = {0, 50000}; // 50 ms timeout
int ret = select(max_fd + 1, &readfds, nullptr, nullptr, &timeout);
vTaskDelay(0); // Avoid starving other threads
if (ret > 0) {
xSemaphoreTake(that->m_mutex, portMAX_DELAY);
std::vector<int> to_remove;
for (int sock : that->m_clients) {
vTaskDelay(0); // Avoid starving other threads
if (FD_ISSET(sock, &readfds)) {
// Handle socket
auto buffer = std::make_unique<std::vector<uint8_t>>();
buffer->resize(MAX_RX_BUFFER_SIZE);
uint32_t msg_size = 0;
recv(sock, &msg_size, 4, MSG_WAITALL);
if (msg_size < 1 || msg_size > 512) {
continue;
}
ESP_LOGD(TAG, "Message size: %ld\n", msg_size);
if (int len = recv(sock, buffer->data(), msg_size, MSG_WAITALL); len < 0) {
ESP_LOGE(TAG, "Error occurred during receiving: errno %d\n", errno);
to_remove.emplace_back(sock);
} else if (0 == len) {
ESP_LOGI(TAG, "TCP Connection closed\n");
close(sock);
to_remove.emplace_back(sock);
} else {
ESP_LOGD(TAG, "TCP Server Received %d bytes\n", len);
buffer->resize(len);
that->m_rx_queue->enqueue(std::move(buffer));
}
}
}
for (const auto r : to_remove) {
that->m_clients.erase(r);
}
xSemaphoreGive(that->m_mutex);
}
}
}
bool TCPServer::is_network_connected() {
esp_netif_ip_info_t ip_info;
esp_netif_t *netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF");
if (netif != nullptr && esp_netif_get_ip_info(netif, &ip_info) == ESP_OK) {
return true;
}
if (0 != ip_info.ip.addr) {
return true;
}
netif = esp_netif_get_handle_from_ifkey("WIFI_AP_DEF");
if (netif != nullptr && esp_netif_get_ip_info(netif, &ip_info) == ESP_OK) {
return true;
}
if (0 != ip_info.ip.addr) {
return true;
}
return false;
}
bool TCPServer::authenticate_client(int sock) {
// todo: authentication (key?)
return 0;
}
int TCPServer::send_msg(char *buffer, const uint32_t length) const {
if (!is_network_connected()) {
return -1;
}
for (const auto client_sock : m_clients) {
send(client_sock, &length, 4, 0);
send(client_sock, buffer, length, 0);
}
return 0;
}

View File

@@ -0,0 +1,239 @@
#include <cstring>
#include "wireless/WifiManager.h"
#include "ConfigManager.h"
#include "constants/wifi.h"
#define TAG "WifiManager"
#define SOFTAP_SCAN_FREQUENCY_MS 30000
#define NUM_CONNECT_ATTEMPTS 5
WifiManager::~WifiManager() {
this->handle_disconnect();
vTaskDelete(this->m_task);
vSemaphoreDelete(this->m_mutex);
}
int WifiManager::connect() {
this->update_state(wifi_state::connect);
vTaskResume(this->m_task);
return 0;
}
int WifiManager::disconnect() {
this->update_state(wifi_state::disconnect);
vTaskResume(this->m_task);
return 0;
}
[[noreturn]] void WifiManager::manage() {
while (true) {
xSemaphoreTake(this->m_mutex, portMAX_DELAY);
this->m_attempts++;
const auto state = this->m_state;
xSemaphoreGive(this->m_mutex);
// Wifi state machine
switch (state) {
case wifi_state::connect:
ESP_LOGI(TAG, "Attempting to connect to wifi in station mode");
init_connection();
update_state(wifi_state::connecting);
break;
case wifi_state::connecting:
ESP_LOGI(TAG, "connecting...");
handle_connecting();
break;
case wifi_state::broadcast:
ESP_LOGI(TAG, "Attempting to broadcast in softap mode");
init_softap();
update_state(wifi_state::broadcasting);
break;
case wifi_state::broadcasting:
ESP_LOGI(TAG, "Broadcasting in softap mode");
vTaskDelay(SOFTAP_SCAN_FREQUENCY_MS / portTICK_PERIOD_MS); // only scan every 30 seconds, as we may disconnect users
handle_broadcasting(); // scans for known networks
break;
case wifi_state::disconnect:
ESP_LOGI(TAG, "Shutting down wifi");
handle_disconnect();
update_state(wifi_state::disconnected);
break;
case wifi_state::disconnected:
ESP_LOGI(TAG, "Disconnected from wifi, starting back up");
update_state(wifi_state::connect);
break;
default:
vTaskSuspend(nullptr);
break;
}
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}
[[noreturn]] void WifiManager::s_manage(WifiManager *that) {
that->manage();
}
int WifiManager::init_connection() {
if (nullptr != this->m_netif) {
this->handle_disconnect();
}
this->m_netif = esp_netif_create_default_wifi_sta(); // Must be destroyed with esp_netif_destroy_default_wifi()
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
esp_wifi_init(&cfg);
esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, wifi_event_handler, this);
esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, wifi_event_handler, this);
wifi_config_t wifi_configuration;
wifi_configuration = {
.sta = {
}
};
std::string ssid = m_config_manager.get_wifi_ssid();
std::string pass = m_config_manager.get_wifi_password();
std::strncpy(reinterpret_cast<char *>(wifi_configuration.sta.ssid), ssid.c_str(), 32);
std::strncpy(reinterpret_cast<char *>(wifi_configuration.sta.password), pass.c_str(), 64);
wifi_configuration.sta.ssid[31] = '\0';
wifi_configuration.sta.password[63] = '\0';
esp_wifi_set_mode(WIFI_MODE_STA);
esp_wifi_set_config(static_cast<wifi_interface_t>(ESP_IF_WIFI_STA), &wifi_configuration);
esp_wifi_start();
esp_wifi_connect();
return 0;
}
int WifiManager::handle_connecting() {
if (this->m_attempts > NUM_CONNECT_ATTEMPTS) {
handle_disconnect();
update_state(wifi_state::broadcast);
}
return 0;
}
int WifiManager::handle_disconnect() {
if (nullptr != this->m_netif) {
esp_netif_destroy_default_wifi(this->m_netif);
this->m_netif = nullptr;
}
esp_event_handler_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, wifi_event_handler);
esp_event_handler_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, wifi_event_handler);
esp_wifi_scan_stop();
esp_wifi_disconnect();
esp_wifi_stop();
esp_wifi_clear_ap_list();
esp_wifi_deinit();
return 0;
}
int WifiManager::handle_broadcasting() {
ESP_LOGI(TAG, "In softap mode, scanning for known networks");
wifi_scan_config_t scan_config {};
scan_config.ssid = reinterpret_cast<uint8_t *>(m_config_manager.get_wifi_ssid().data());
scan_config.scan_time = {.passive = 500};
if (const auto err = esp_wifi_scan_start(&scan_config, false); ESP_OK != err) {
ESP_LOGE(TAG, "Failed to scan for wifi networks, err: %d", err);
esp_wifi_clear_ap_list(); // must call to free memory allocated by scan.
return -1;
}
vTaskDelay(1000 / portTICK_PERIOD_MS);
uint16_t found_aps = 0;
if (const auto err = esp_wifi_scan_get_ap_num(&found_aps); ESP_OK != err) {
ESP_LOGE(TAG, "Failed to get count of scanned aps");
esp_wifi_clear_ap_list();
return -1;
}
if (found_aps > 1) {
ESP_LOGI(TAG, "Found a known network, switching to station mode");
update_state(wifi_state::disconnect);
}
esp_wifi_clear_ap_list(); // must call to free memory allocated by scan.
return 0;
}
int WifiManager::init_softap() {
if (nullptr != this->m_netif) {
this->handle_disconnect();
}
this->m_netif = esp_netif_create_default_wifi_ap();
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
esp_wifi_init(&cfg);
esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, wifi_event_handler, this);
wifi_config_t wifi_configuration = {
.ap = {
.ssid = WIFI_SSID,
.password = "",
.channel = SOFTAP_CHANNEL,
.authmode = WIFI_AUTH_OPEN,
.ssid_hidden = 0,
.max_connection = SOFTAP_MAX_CONNECTIONS,
.beacon_interval = 100,
.csa_count = 3,
.dtim_period = 1,
},
};
esp_wifi_set_mode(WIFI_MODE_APSTA); // enable both ap and station mode for scanning
esp_wifi_set_config(static_cast<wifi_interface_t>(ESP_IF_WIFI_AP), &wifi_configuration);
esp_wifi_start();
return 0;
}
void WifiManager::update_state(const wifi_state state) {
xSemaphoreTake(this->m_mutex, portMAX_DELAY);
this->m_attempts = 0;
this->m_state = state;
xSemaphoreGive(this->m_mutex);
}
void WifiManager::wifi_event_handler(void *event_handler_arg, esp_event_base_t event_base, const int32_t event_id, void *event_data) {
// Passed in as a parameter since c (freertos) cannot call the member function directly.
const auto that = static_cast<WifiManager *>(event_handler_arg);
if (WIFI_EVENT_STA_START == event_id) {
ESP_LOGI(TAG, "Station mode started\n");
} else if (WIFI_EVENT_STA_CONNECTED == event_id) {
ESP_LOGI(TAG, "Connected to wifi in station mode\n");
that->update_state(wifi_state::connected);
} else if (WIFI_EVENT_STA_DISCONNECTED == event_id) {
ESP_LOGI(TAG, "Station mode shutdown\n");
xSemaphoreTake(that->m_mutex, portMAX_DELAY);
if (that->m_state == wifi_state::connected) {
xSemaphoreGive(that->m_mutex);
that->handle_disconnect();
} else {
xSemaphoreGive(that->m_mutex);
}
} else if (IP_EVENT_STA_GOT_IP == event_id) {
ESP_LOGI(TAG, "Got IP as station\n");
} else if (WIFI_EVENT_AP_STACONNECTED == event_id) {
ESP_LOGI(TAG, "User connected to AP\n");
} else if (WIFI_EVENT_AP_STADISCONNECTED == event_id) {
ESP_LOGI(TAG, "User disconnected from AP\n");
} else if (WIFI_EVENT_AP_START == event_id) {
ESP_LOGI(TAG, "AP started\n");
}
}

View File

@@ -0,0 +1,57 @@
//
// Created by Johnathon Slightham on 2025-05-25.
//
#include <string>
#include <format>
#include <sstream>
#include "mdns.h"
#include "ConfigManager.h"
#include "wireless/mDNSDiscoveryService.h"
#include "constants/tcp.h"
mDNSDiscoveryService::mDNSDiscoveryService() {
mdns_init();
const auto& config_manager = ConfigManager::get_instance();
mdns_hostname_set(std::format("botchain-{}", config_manager.get_module_id()).c_str());
mdns_instance_name_set(std::format("BotChain Robot Module {}", config_manager.get_module_id()).c_str());
mdns_service_add(nullptr, "_robotcontrol", "_tcp", TCP_PORT, nullptr, 0);
mdns_service_instance_name_set("_robotcontrol", "_tcp", "Robot Control TCP Server");
mdns_txt_item_t service_txt_data[3] = {
{"module_id",std::to_string(config_manager.get_module_id()).c_str()},
{"module_type",std::to_string(config_manager.get_module_type()).c_str()},
{"connected_modules",""},
};
mdns_service_txt_set("_robotcontrol", "_tcp", service_txt_data, 3);
}
mDNSDiscoveryService::~mDNSDiscoveryService() {
mdns_free();
}
void mDNSDiscoveryService::set_connected_boards(const std::vector<int>& boards) {
std::stringstream ss;
const auto& config_manager = ConfigManager::get_instance();
for (int i = 0; i < boards.size(); i++) {
ss << std::to_string(boards[i]);
if (i < boards.size() - 1) {
ss << ',';
}
}
mdns_txt_item_t service_txt_data[3] = {
{"module_id",std::to_string(config_manager.get_module_id()).c_str()},
{"module_type",std::to_string(config_manager.get_module_type()).c_str()},
{"connected_modules",ss.str().c_str()},
};
mdns_service_txt_set("_robotcontrol", "_tcp", service_txt_data, 3);
}