Files
OptoTest/OpticalChannelTester/Radio.cpp

73 lines
2.9 KiB
C++

#include "Radio.h"
#include "Config.h"
#include "Log.h"
#include <WiFi.h>
#include <esp_wifi.h>
#include <string.h>
Radio *Radio::instance_ = nullptr;
static const uint8_t BROADCAST_MAC[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
bool Radio::begin() {
if (active_) { Log::event("ESP-NOW", "already active"); return true; }
WiFi.mode(WIFI_STA); WiFi.disconnect();
if (esp_wifi_set_channel(ESPNOW_WIFI_CHANNEL, WIFI_SECOND_CHAN_NONE) != ESP_OK) {
Log::event("ESP-NOW", "Wi-Fi channel setup FAILED"); return false;
}
queue_ = xQueueCreate(8, sizeof(ReceivedPacket));
if (!queue_ || esp_now_init() != ESP_OK) { Log::event("ESP-NOW", "initialization FAILED"); return false; }
instance_ = this;
if (esp_now_register_recv_cb(onReceive) != ESP_OK) { end(); return false; }
active_ = true;
const bool ok = ensurePeer(BROADCAST_MAC);
Log::printf("ESP-NOW", "started channel=%u broadcast-peer=%s", ESPNOW_WIFI_CHANNEL, ok ? "OK" : "FAILED");
return ok;
}
void Radio::end() {
if (active_) { esp_now_unregister_recv_cb(); esp_now_deinit(); }
if (queue_) { vQueueDelete(queue_); queue_ = nullptr; }
active_ = false; if (instance_ == this) instance_ = nullptr;
Log::event("ESP-NOW", "stopped");
}
bool Radio::ensurePeer(const uint8_t mac[6]) {
if (esp_now_is_peer_exist(mac)) return true;
esp_now_peer_info_t peer = {};
memcpy(peer.peer_addr, mac, 6); peer.channel = ESPNOW_WIFI_CHANNEL; peer.encrypt = false;
return esp_now_add_peer(&peer) == ESP_OK;
}
bool Radio::sendBroadcast(ProtocolPacket p) { return sendTo(BROADCAST_MAC, p); }
bool Radio::sendTo(const uint8_t mac[6], ProtocolPacket p) {
char peer[20]; macText(mac, peer, sizeof(peer));
if (!active_ || !ensurePeer(mac)) {
Log::printf("ESP-NOW", "TX %s to %s FAILED: inactive/peer", messageName(static_cast<MessageType>(p.type)), peer);
return false;
}
finalizePacket(p);
const bool ok = esp_now_send(mac, reinterpret_cast<const uint8_t *>(&p), sizeof(p)) == ESP_OK;
Log::printf("ESP-NOW", "TX %s to %s session=%08lX stage=%u seq=%u %s",
messageName(static_cast<MessageType>(p.type)), peer, p.session, p.stage, p.sequence, ok ? "QUEUED" : "FAILED");
return ok;
}
bool Radio::receive(ReceivedPacket &r) {
return queue_ && xQueueReceive(queue_, &r, 0) == pdTRUE;
}
void Radio::flush() { if (queue_) xQueueReset(queue_); }
void Radio::onReceive(const esp_now_recv_info_t *info, const uint8_t *data, int length) {
if (!instance_ || !instance_->queue_ || !info || length != sizeof(ProtocolPacket)) return;
ReceivedPacket item;
memcpy(item.mac, info->src_addr, 6); memcpy(&item.packet, data, sizeof(item.packet));
if (!validPacket(item.packet)) return;
xQueueSend(instance_->queue_, &item, 0); // Wi-Fi task callback: copy only, never block
}
void Radio::macText(const uint8_t mac[6], char *out, size_t n) {
snprintf(out, n, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
}