codex init
This commit is contained in:
59
OpticalChannelTester/Radio.cpp
Normal file
59
OpticalChannelTester/Radio.cpp
Normal file
@@ -0,0 +1,59 @@
|
||||
#include "Radio.h"
|
||||
#include "Config.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_) return true;
|
||||
WiFi.mode(WIFI_STA); WiFi.disconnect();
|
||||
if (esp_wifi_set_channel(ESPNOW_WIFI_CHANNEL, WIFI_SECOND_CHAN_NONE) != ESP_OK) return false;
|
||||
queue_ = xQueueCreate(8, sizeof(ReceivedPacket));
|
||||
if (!queue_ || esp_now_init() != ESP_OK) return false;
|
||||
instance_ = this;
|
||||
if (esp_now_register_recv_cb(onReceive) != ESP_OK) { end(); return false; }
|
||||
active_ = true;
|
||||
return ensurePeer(BROADCAST_MAC);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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) {
|
||||
if (!active_ || !ensurePeer(mac)) return false;
|
||||
finalizePacket(p);
|
||||
return esp_now_send(mac, reinterpret_cast<const uint8_t *>(&p), sizeof(p)) == ESP_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]);
|
||||
}
|
||||
Reference in New Issue
Block a user