Auto pairing via broadcast

half done - can add slave mac to peers, but can’t add master mac to peers

would glad any halp =^-^=

i think there should be a straight forward example for such common stuff, but i struggle to find it :pensive:

master

#include <esp_now.h>
#include <esp_wifi.h>
#include <WiFi.h>
const uint8_t encryptionKey[16] = {0x30, 0x32, 0x30, 0x34, 0x30, 0x32, 0x30, 0x34, 0x30, 0x32, 0x30, 0x34, 0x30, 0x32, 0x30, 0x34}; // Example key
uint8_t slaveMACAddress[6];
void printMAC(const uint8_t *mac, const char *label)
{
    Serial.print(label);
    for (int i = 0; i < 6; i++)
    {
        Serial.printf("%02X", mac[i]);
        if (i < 5)
            Serial.print(":");
    }
    Serial.println();
}
void addPeer(const uint8_t *peer_addr)
{
    esp_now_peer_info_t peerInfo;
    memset(&peerInfo, 0, sizeof(peerInfo));
    memcpy(peerInfo.peer_addr, peer_addr, 6);
    peerInfo.channel = 0; // Default channel
    peerInfo.encrypt = true;
    memcpy(peerInfo.lmk, encryptionKey, 16);
    esp_err_t result = esp_now_add_peer(&peerInfo);
    if (result != ESP_OK)
    {
        Serial.printf("Failed to add peer: %d\n", result);
    }
    else
    {
        Serial.println("Peer added successfully");
    }
}
void sendMACAddress(const uint8_t *mac_addr)
{
    uint8_t myMAC[6];
    esp_wifi_get_mac(WIFI_IF_STA, myMAC);
    printMAC(myMAC, "Sending back our MAC address: ");
    esp_err_t result = esp_now_send(mac_addr, myMAC, 6);
    if (result == ESP_OK)
    {
        Serial.println("Sent back our MAC address");
    }
    else
    {
        Serial.printf("Error sending data: %d\n", result);
    }
}
void OnDataRecv(const uint8_t *mac_addr, const uint8_t *data, int len)
{
    Serial.println("Received data:");
    printMAC(mac_addr, "  From MAC: ");
    Serial.print("  Data: ");
    for (int i = 0; i < len; i++)
    {
        Serial.printf("%02X ", data[i]);
    }
    Serial.println();
    if (len == 16 && memcmp(data, encryptionKey, 16) == 0)
    {
        memcpy(slaveMACAddress, mac_addr, 6);
        printMAC(slaveMACAddress, "Slave MAC Address: ");
        if (!esp_now_is_peer_exist(slaveMACAddress))
        {
            addPeer(slaveMACAddress);
        }
        else
        {
            Serial.println("Slave is already added as a peer");
        }
        sendMACAddress(slaveMACAddress);
    }
    else
    {
        Serial.println("Received data does not match the encryption key");
    }
}
void setup()
{
    Serial.begin(115200);
    WiFi.mode(WIFI_STA);
    if (esp_now_init() != ESP_OK)
    {
        Serial.println("Error initializing ESP-NOW");
        return;
    }
    esp_now_register_recv_cb(OnDataRecv);
    Serial.println("Master is ready to receive broadcast data");
}
void loop()
{
    // Master is primarily waiting for data and sending responses, so nothing needed in loop.
}

slave

#include <esp_now.h>
#include <esp_wifi.h>
#include <WiFi.h>
uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
const uint8_t encryptionKey[16] = {0x30, 0x32, 0x30, 0x34, 0x30, 0x32, 0x30, 0x34, 0x30, 0x32, 0x30, 0x34, 0x30, 0x32, 0x30, 0x34}; // Example key
uint8_t masterMACAddress[6];
bool isMasterAdded = false;
void printMAC(const uint8_t *mac, const char *label)
{
  Serial.print(label);
  for (int i = 0; i < 6; i++)
  {
    Serial.printf("%02X", mac[i]);
    if (i < 5)
      Serial.print(":");
  }
  Serial.println();
}
void addPeer(const uint8_t *peer_addr)
{
  esp_now_peer_info_t peerInfo;
  memset(&peerInfo, 0, sizeof(peerInfo));
  memcpy(peerInfo.peer_addr, peer_addr, 6);
  peerInfo.channel = 0; // Default channel
  peerInfo.encrypt = true;
  memcpy(peerInfo.lmk, encryptionKey, 16);
  esp_err_t result = esp_now_add_peer(&peerInfo);
  if (result != ESP_OK)
  {
    Serial.printf("Failed to add peer: %d\n", result);
  }
  else
  {
    Serial.println("Peer added successfully");
  }
}
void OnDataRecv(const uint8_t *mac_addr, const uint8_t *data, int len)
{
  Serial.println("Received data:");
  printMAC(mac_addr, "  From MAC: ");
  Serial.print("  Data: ");
  for (int i = 0; i < len; i++)
  {
    Serial.printf("%02X ", data[i]);
  }
  Serial.println();
  if (len == 6)
  {
    memcpy(masterMACAddress, data, 6);
    isMasterAdded = true;
    printMAC(masterMACAddress, "Master MAC Address: ");
    if (!esp_now_is_peer_exist(masterMACAddress))
    {
      addPeer(masterMACAddress);
    }
    else
    {
      Serial.println("Master is already added as a peer");
    }
  }
  else
  {
    Serial.println("Received data length does not match expected MAC address length");
  }
}
void sendBroadcastMessage()
{
  uint8_t message[16];
  memcpy(message, encryptionKey, 16);
  esp_err_t result = esp_now_send(broadcastAddress, message, sizeof(message));
  if (result == ESP_OK)
  {
    Serial.println("Sent broadcast message with encryption key");
  }
  else
  {
    Serial.printf("Error sending data: %d\n", result);
  }
}
void setup()
{
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  if (esp_now_init() != ESP_OK)
  {
    Serial.println("Error initializing ESP-NOW");
    return;
  }
  esp_now_register_recv_cb(OnDataRecv);
  esp_now_peer_info_t peerInfo;
  memset(&peerInfo, 0, sizeof(peerInfo));
  memcpy(peerInfo.peer_addr, broadcastAddress, 6);
  peerInfo.channel = 0; // Default channel
  peerInfo.encrypt = false;
  if (esp_now_add_peer(&peerInfo) != ESP_OK)
  {
    Serial.println("Failed to add broadcast peer");
    return;
  }
  Serial.println("Slave is ready to send broadcast messages");
}
void loop()
{
  sendBroadcastMessage();
  delay(3000); // Send data every 3 seconds
  if (!isMasterAdded)
  {
    Serial.println("Master is not added yet!");
  }
  if (isMasterAdded)
  {
    printMAC(masterMACAddress, "Master MAC Address: ");
  }
}

isMasterAdded never matched

So what’s the serial output on the slave side? Is OnDataRecv never called? Is it called but the length doesn’t match 6?

yep

Not sure exactly, but if ESP-NOW only reacts to the registered peers, wouldn’t the master have to send the its MAC address to the broadcast address instead of the slave address, because the master’s MAC address is not yet registered at the slave?

get even worse :hot_face:

m

#include <esp_now.h>
#include <esp_wifi.h>
#include <WiFi.h>
#include <stdlib.h>
const uint8_t encryptionKey[16] = {0x30, 0x32, 0x30, 0x34, 0x30, 0x32, 0x30, 0x34, 0x30, 0x32, 0x30, 0x34, 0x30, 0x32, 0x30, 0x34}; // Example key
uint8_t slaveMACAddress[6];
uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
void printMAC(const uint8_t *mac, const char *label)
{
    Serial.print(label);
    for (int i = 0; i < 6; i++)
    {
        Serial.printf("%02X", mac[i]);
        if (i < 5)
            Serial.print(":");
    }
    Serial.println();
}
void addPeer(const uint8_t *peer_addr)
{
    esp_now_peer_info_t peerInfo;
    memset(&peerInfo, 0, sizeof(peerInfo));
    memcpy(peerInfo.peer_addr, peer_addr, 6);
    peerInfo.channel = 0; // Default channel
    peerInfo.encrypt = true;
    memcpy(peerInfo.lmk, encryptionKey, 16);
    esp_err_t result = esp_now_add_peer(&peerInfo);
    if (result != ESP_OK)
    {
        Serial.printf("Failed to add peer: %d\n", result);
    }
    else
    {
        Serial.println("Peer added successfully");
    }
}
void sendMACAddress(const uint8_t *mac_addr)
{
    uint8_t myMAC[6];
    esp_wifi_get_mac(WIFI_IF_STA, myMAC);
    printMAC(myMAC, "Sending back our MAC address: ");
    esp_err_t result = esp_now_send(mac_addr, myMAC, 6);
    if (result == ESP_OK)
    {
        Serial.println("Sent back our MAC address");
    }
    else
    {
        Serial.printf("Error sending data: %d\n", result);
    }
}
void sendRandomData(const uint8_t *mac_addr)
{
    uint8_t randomData[6];
    for (int i = 0; i < 6; i++)
    {
        randomData[i] = random(256);
    }
    esp_err_t result = esp_now_send(mac_addr, randomData, sizeof(randomData));
    if (result == ESP_OK)
    {
        Serial.println("Sent random data");
    }
    else
    {
        Serial.printf("Error sending random data: %d\n", result);
    }
}
void sendBroadcastMessage()
{
    uint8_t myMAC[6];
    esp_wifi_get_mac(WIFI_IF_STA, myMAC);
    esp_err_t result = esp_now_send(broadcastAddress, myMAC, sizeof(myMAC));
    if (result == ESP_OK)
    {
        Serial.println("Sent broadcast message with MAC address");
    }
    else
    {
        Serial.printf("Error sending broadcast message: %d\n", result);
    }
}
void OnDataRecv(const uint8_t *mac_addr, const uint8_t *data, int len)
{
    Serial.println("Received data:");
    printMAC(mac_addr, "  From MAC: ");
    Serial.print("  Data: ");
    for (int i = 0; i < len; i++)
    {
        Serial.printf("%02X ", data[i]);
    }
    Serial.println();
    if (len == 6)
    {
        memcpy(slaveMACAddress, data, 6);
        printMAC(slaveMACAddress, "Slave MAC Address: ");
        if (!esp_now_is_peer_exist(slaveMACAddress))
        {
            addPeer(slaveMACAddress);
        }
        else
        {
            Serial.println("Slave is already added as a peer");
        }
        sendMACAddress(slaveMACAddress);
        sendRandomData(slaveMACAddress);
    }
    else
    {
        Serial.println("Received data length does not match expected MAC address length");
    }
}
void setup()
{
    Serial.begin(115200);
    WiFi.mode(WIFI_STA);
    if (esp_now_init() != ESP_OK)
    {
        Serial.println("Error initializing ESP-NOW");
        return;
    }
    else
    {
        Serial.println("ESP-NOW initialized successfully");
    }
    esp_now_register_recv_cb(OnDataRecv);
    Serial.println("Master is ready to receive broadcast data");
}
void loop()
{
    sendBroadcastMessage();
    delay(3000); // Send data every 3 seconds
}

s

#include <esp_now.h>
#include <esp_wifi.h>
#include <WiFi.h>
#include <stdlib.h>
const uint8_t encryptionKey[16] = {0x30, 0x32, 0x30, 0x34, 0x30, 0x32, 0x30, 0x34, 0x30, 0x32, 0x30, 0x34, 0x30, 0x32, 0x30, 0x34}; // Example key
uint8_t masterMACAddress[6];
bool isMasterAdded = false;
uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
void printMAC(const uint8_t *mac, const char *label)
{
  Serial.print(label);
  for (int i = 0; i < 6; i++)
  {
    Serial.printf("%02X", mac[i]);
    if (i < 5)
      Serial.print(":");
  }
  Serial.println();
}
void addPeer(const uint8_t *peer_addr)
{
  esp_now_peer_info_t peerInfo;
  memset(&peerInfo, 0, sizeof(peerInfo));
  memcpy(peerInfo.peer_addr, peer_addr, 6);
  peerInfo.channel = 0; // Default channel
  peerInfo.encrypt = true;
  memcpy(peerInfo.lmk, encryptionKey, 16);
  esp_err_t result = esp_now_add_peer(&peerInfo);
  if (result != ESP_OK)
  {
    Serial.printf("Failed to add peer: %d\n", result);
  }
  else
  {
    Serial.println("Peer added successfully");
  }
}
void sendBroadcastMessage()
{
  uint8_t myMAC[6];
  esp_wifi_get_mac(WIFI_IF_STA, myMAC);
  esp_err_t result = esp_now_send(broadcastAddress, myMAC, sizeof(myMAC));
  if (result == ESP_OK)
  {
    Serial.println("Sent broadcast message with MAC address");
  }
  else
  {
    Serial.printf("Error sending broadcast message: %d\n", result);
  }
}
void sendRandomData(const uint8_t *mac_addr)
{
  uint8_t randomData[6];
  for (int i = 0; i < 6; i++)
  {
    randomData[i] = random(256);
  }
  esp_err_t result = esp_now_send(mac_addr, randomData, sizeof(randomData));
  if (result == ESP_OK)
  {
    Serial.println("Sent random data");
  }
  else
  {
    Serial.printf("Error sending random data: %d\n", result);
  }
}
void OnDataRecv(const uint8_t *mac_addr, const uint8_t *data, int len)
{
  Serial.println("Received data:");
  printMAC(mac_addr, "  From MAC: ");
  Serial.print("  Data: ");
  for (int i = 0; i < len; i++)
  {
    Serial.printf("%02X ", data[i]);
  }
  Serial.println();
  if (len == 6)
  {
    memcpy(masterMACAddress, data, 6);
    isMasterAdded = true;
    printMAC(masterMACAddress, "Master MAC Address: ");
    if (!esp_now_is_peer_exist(masterMACAddress))
    {
      addPeer(masterMACAddress);
    }
    else
    {
      Serial.println("Master is already added as a peer");
    }
    sendRandomData(masterMACAddress);
  }
  else
  {
    Serial.println("Received data length does not match expected MAC address length");
  }
}
void setup()
{
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  if (esp_now_init() != ESP_OK)
  {
    Serial.println("Error initializing ESP-NOW");
    return;
  }
  else
  {
    Serial.println("ESP-NOW initialized successfully");
  }
  esp_now_register_recv_cb(OnDataRecv);
  esp_now_peer_info_t peerInfo;
  memset(&peerInfo, 0, sizeof(peerInfo));
  memcpy(peerInfo.peer_addr, broadcastAddress, 6);
  peerInfo.channel = 0; // Default channel
  peerInfo.encrypt = false;
  if (esp_now_add_peer(&peerInfo) != ESP_OK)
  {
    Serial.println("Failed to add broadcast peer");
    return;
  }
  else
  {
    Serial.println("Broadcast peer added successfully");
  }
  Serial.println("Slave is ready to send broadcast messages");
}
void loop()
{
  sendBroadcastMessage();
  delay(3000); // Send data every 3 seconds
  if (!isMasterAdded)
  {
    Serial.println("Master is not added yet!");
  }
  if (isMasterAdded)
  {
    printMAC(masterMACAddress, "Master MAC Address: ");
  }
}

output

Received data:
  From MAC: 34:B7:DA:59:66:8C
  Data: 34 B7 DA 59 66 8C 
Slave MAC Address: 34:B7:DA:59:66:8C
Slave is already added as a peer
Sending back our MAC address: E8:6B:EA:F6:F0:B4
Sent back our MAC address
Sent random data
Error sending broadcast message: 12393

Master is not added yet!
Sent broadcast message with MAC address
Master is not added yet!
Sent broadcast message with MAC address
Master is not added yet!

i guess start the server and write mac by hand from my phone is would be easier, so freaking hard make that works :cold_sweat:

// main
#include "broadcast.h"
#include "receive.h"
#include "common.h"
unsigned long broadcastStartTime;
bool broadcastActive = true;
void setup()
{
    Serial.begin(115200);
    initBroadcast();
    esp_now_register_recv_cb(OnDataRecv);
    broadcastStartTime = millis();
    String macAddress = WiFi.macAddress();
    Serial.print("Peer: ");
    Serial.print(macAddress);
    Serial.println(" is ready");
}
void loop()
{
    if (broadcastActive)
    {
        if (millis() - broadcastStartTime < 10000)
        {
            sendBroadcastMessage();
        }
        else
        {
            broadcastActive = false;
            Serial.println("Broadcast stopped");
        }
    }
    else
    {
        // Send random data to all peers every 5 seconds
        static unsigned long lastSendTime = 0;
        if (millis() - lastSendTime >= 5000)
        {
            sendRandomDataToPeers();
            lastSendTime = millis();
        }
    }
    delay(1000);
}
#ifndef COMMON_H
#define COMMON_H

#define MAX_PEERS 20

#include <esp_now.h>
#include <esp_wifi.h>

#include <WiFi.h>

// Define the structure for the message
typedef struct struct_message
{
    uint8_t keyword[16];
    bool toggle1;
    bool toggle2;
    uint8_t macAddr[6];
    uint8_t randomData[6];
} struct_message;

extern const uint8_t encryptionKey[16];
extern uint8_t slaveMACAddress[6];
extern uint8_t peers[MAX_PEERS][6];
extern int peerCount;

#endif
#ifndef RECEIVE_H
#define RECEIVE_H

#include "common.h"

void OnDataRecv(const uint8_t *mac_addr, const uint8_t *data, int len)
{
    Serial.print("Received from MAC: ");
    for (int i = 0; i < 6; i++)
    {
        Serial.printf("%02X", mac_addr[i]);
        if (i < 5)
            Serial.print(":");
    }
    Serial.println();

    Serial.print("Received data: ");
    for (int i = 0; i < len; i++)
    {
        Serial.printf("%02X ", data[i]);
    }
    Serial.println();

    // Check if received data matches the encryption key
    struct_message receivedData;
    memcpy(&receivedData, data, sizeof(receivedData));

    if (memcmp(receivedData.keyword, encryptionKey, 16) == 0)
    {
        bool alreadyAdded = false;
        for (int i = 0; i < peerCount; i++)
        {
            if (memcmp(peers[i], mac_addr, 6) == 0)
            {
                alreadyAdded = true;
                break;
            }
        }

        if (!alreadyAdded && peerCount < MAX_PEERS)
        {
            memcpy(peers[peerCount], mac_addr, 6);
            peerCount++;
            esp_now_peer_info_t peerInfo;
            memset(&peerInfo, 0, sizeof(peerInfo));
            memcpy(peerInfo.peer_addr, mac_addr, 6);
            peerInfo.channel = 0;
            peerInfo.encrypt = false;

            if (esp_now_add_peer(&peerInfo) != ESP_OK)
            {
                Serial.println("Failed to add peer");
            }
            else
            {
                Serial.println("New peer added");
            }
        }
        else if (alreadyAdded)
        {
            Serial.println("Peer already added");
        }
    }
    else
    {
        Serial.println("Received data does not match the encryption key");
    }
}

#endif
#ifndef BROADCAST_H
#define BROADCAST_H

#include "common.h"

const uint8_t encryptionKey[16] = {0x30, 0x32, 0x30, 0x34, 0x30, 0x32, 0x30, 0x34, 0x30, 0x32, 0x30, 0x34, 0x30, 0x32, 0x30, 0x34}; // Example key
uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
uint8_t slaveMACAddress[6];
uint8_t peers[MAX_PEERS][6];
int peerCount = 0;

void initBroadcast()
{
    WiFi.mode(WIFI_STA);

    if (esp_now_init() != ESP_OK)
    {
        Serial.println("Error initializing ESP-NOW");
        return;
    }
    Serial.println("ESP-NOW initialized");

    esp_now_peer_info_t peerInfo;
    memset(&peerInfo, 0, sizeof(peerInfo));
    memcpy(peerInfo.peer_addr, broadcastAddress, 6);
    peerInfo.channel = 0;
    peerInfo.encrypt = false;

    if (esp_now_add_peer(&peerInfo) != ESP_OK)
    {
        Serial.println("Failed to add broadcast peer");
        return;
    }
    Serial.println("Broadcast peer added");
}

void sendBroadcastMessage()
{
    struct_message message;
    memcpy(message.keyword, encryptionKey, 16);
    message.toggle1 = true; // Example toggle values
    message.toggle2 = false;
    esp_wifi_get_mac(WIFI_IF_STA, message.macAddr);

    if (esp_now_send(broadcastAddress, (uint8_t *)&message, sizeof(message)) == ESP_OK)
    {
        Serial.println("Sent broadcast message with encryption key");
    }
    else
    {
        Serial.println("Error sending broadcast message");
    }
}

void sendRandomDataToPeers()
{
    struct_message message;
    memcpy(message.keyword, encryptionKey, 16); // Use the same encryptionKey for simplicity
    message.toggle1 = false;                    // Example toggle values
    message.toggle2 = true;
    esp_wifi_get_mac(WIFI_IF_STA, message.macAddr);

    for (int i = 0; i < 6; i++)
    {
        message.randomData[i] = random(256);
    }

    for (int i = 0; i < peerCount; i++)
    {
        if (esp_now_send(peers[i], (uint8_t *)&message, sizeof(message)) == ESP_OK)
        {
            Serial.println("Sent random data to peer");
        }
        else
        {
            Serial.println("Error sending random data");
        }
    }
}

#endif