Improve ESP-NOW connection

Implement auto-pairing.
Make key optional.
Remove re-sends.
Add command for uploading proxy to makefile.
This commit is contained in:
Oleg Kalachev
2026-05-21 00:06:10 +03:00
parent 9ac57b246b
commit b316cc423a
5 changed files with 77 additions and 31 deletions
+39 -23
View File
@@ -7,16 +7,25 @@
#include <ESP32_NOW_Serial.h>
#include <MacAddress.h>
#include <MAVLink.h>
#include <Preferences.h>
#include "../../flix/util.h"
#include <vector>
const int CHANNEL = 6;
char key[ESP_NOW_KEY_LEN + 1] = {0}; // with trailing null
ESP_NOW_Serial_Class espnow(NULL, CHANNEL, WIFI_IF_AP);
MacAddress peerMac;
volatile bool peerFound = false;
Preferences storage;
std::vector<ESPNOWSerial *> peers;
void onNewPeer(const esp_now_recv_info_t *info, const uint8_t *data, int len, void *arg) {
peerMac = info->src_addr;
peerFound = true;
if (len != 4 || memcmp(data, "flix", 4) != 0) return; // check if discovery message
Serial.printf("New peer: " MACSTR "\n", MAC2STR(info->src_addr));
ESPNOWSerial *link = new ESPNOWSerial(info->src_addr, CHANNEL, WIFI_IF_AP);
link->begin();
link->setKey((const uint8_t *)key);
peers.push_back(link);
}
void setup() {
@@ -25,22 +34,28 @@ void setup() {
WiFi.setSleep(false);
WiFi.setChannel(CHANNEL);
// while (!WiFi.AP.started()) {
// delay(100);
// }
ESP_NOW.onNewPeer(onNewPeer, NULL);
ESP_NOW.begin();
while (!peerFound) {
Serial.printf("MAC: %s, waiting for peer...\n", WiFi.softAPmacAddress().c_str());
delay(1000);
storage.begin("espnow-proxy");
if (!storage.isKey("key")) {
generateRandomKey();
storage.putString("key", key);
}
Serial.printf("Peer found: %s\n", peerMac.toString().c_str());
strcpy(key, storage.getString("key").c_str());
espnow.addr(peerMac);
espnow.setChannel(CHANNEL);
espnow.begin();
// Discover the first peer
while (peers.empty()) {
Serial.printf("espnow %s %s\n", WiFi.softAPmacAddress().c_str(), key);
delay(500);
}
}
void generateRandomKey() {
const char chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*-_+=";
for (int i = 0; i < ESP_NOW_KEY_LEN; i++) {
key[i] = chars[random(0, strlen(chars))];
}
}
void loop() {
@@ -57,16 +72,17 @@ void loop() {
mavlink_status_t status;
if (mavlink_parse_char(MAVLINK_COMM_0, (uint8_t)b, &msg, &status)) {
int len = mavlink_msg_to_send_buffer(buf, &msg);
// ESP_NOW.write(buf, len);
espnow.write(buf, len);
// espnow.send(buf, len);
// esp_now_send(peerMac, buf, len);
for (ESPNOWSerial *link : peers) {
link->write(buf, len);
}
}
}
// Send from ESP-NOW to serial
int len = espnow.read(buf, sizeof(buf));
if (len > 0) {
Serial.write(buf, len);
for (ESPNOWSerial *link : peers) {
int len = link->read(buf, sizeof(buf));
if (len > 0) {
Serial.write(buf, len);
}
}
}