Skip to content

add support for up to 10 ESPNow remotes #4654

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
May 19, 2025
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions wled00/cfg.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,22 @@ bool deserializeConfig(JsonObject doc, bool fromFS) {
JsonObject nw = doc["nw"];
#ifndef WLED_DISABLE_ESPNOW
CJSON(enableESPNow, nw[F("espnow")]);
getStringFromJson(linked_remote, nw[F("linked_remote")], 13);
linked_remote[12] = '\0';
linked_remotes.clear();
JsonArray lrem = nw[F("linked_remote")]; // array of MAC addresses
if (!lrem.isNull()) {
for (size_t i = 0; i < lrem.size(); i++) {
std::array<char, 13> entry{};
getStringFromJson(entry.data(), lrem[i], 13);
entry[12] = '\0';
linked_remotes.push_back(entry); // TODO: need to check for invalid MAC?
}
}
else { // legacy support for single MAC address in config
std::array<char, 13> entry{};
getStringFromJson(entry.data(), nw[F("linked_remote")], 13);
entry[12] = '\0';
linked_remotes.push_back(entry);
}
#endif

size_t n = 0;
Expand Down Expand Up @@ -725,7 +739,10 @@ void serializeConfig(JsonObject root) {
JsonObject nw = root.createNestedObject("nw");
#ifndef WLED_DISABLE_ESPNOW
nw[F("espnow")] = enableESPNow;
nw[F("linked_remote")] = linked_remote;
JsonArray lrem = nw.createNestedArray(F("linked_remote"));
for (size_t i = 0; i < linked_remotes.size(); i++) {
lrem.add(linked_remotes[i].data());
}
#endif

JsonArray nw_ins = nw.createNestedArray("ins");
Expand Down
77 changes: 73 additions & 4 deletions wled00/data/settings_wifi.htm
Original file line number Diff line number Diff line change
Expand Up @@ -136,12 +136,75 @@
getLoc();
loadJS(getURL('/settings/s.js?p=1'), false); // If we set async false, file is loaded and executed, then next statement is processed
if (loc) d.Sf.action = getURL('/settings/wifi');
setTimeout(tE, 500); // wait for DOM to load before calling tE()
}

var rC = 0; // remote count
// toggle visibility of ESP-NOW remote list based on checkbox state
function tE() {
const e = d.querySelector('input[name="RE"]').checked;
const l = gId('rlc'); // remote list container
// keep the hidden input with MAC addresses, only toggle visibility of the list UI
if (l) l.style.display = e ? 'block' : 'none';
}
// reset remotes: initialize empty list (called from xml.cpp)
function rstR() {
gId('rml').innerHTML = ''; // clear remote list
rC = 0;
uR(); // update remote list
}
// add remote MAC to the list
function aR(id, mac) {
if (!/^[0-9A-F]{12}$/i.test(mac)) return; // check for valid hex string
if (rC >= 10) return;
let inputs = gId('rml').getElementsByTagName('input');
for (let i = 0; i < inputs.length; i++) {
if (inputs[i].value === mac) return;
}
let list = gId('rml');
let row = cE('div');
let inp = cE('input');
inp.type = 'text';
inp.name = id;
inp.value = mac;
inp.maxLength = 12;
inp.minLength = 12;
inp.onchange = uR;
row.appendChild(inp);
let btn = d.createElement('button');
btn.type = 'button';
btn.className = 'btn btn-xs';
btn.innerText = 'Remove';
btn.onclick = function() {
rR(row);
};
row.appendChild(btn);
list.appendChild(row);
rC++;
uR();
}
// remove a remote from the list
function rR(e) {
e.remove();
uR();
}
// update remote list
function uR() {
let macs = [];
let inputs = gId('rml').getElementsByTagName('input');
for (let i = 0; i < inputs.length; i++) {
if (inputs[i].value && inputs[i].value !== '') {
macs.push(inputs[i].value);
}
}
gId('rmacs').value = JSON.stringify(macs);
return true; // Allow form submission to continue
}
</script>
<style>@import url("style.css");</style>
</head>
<body onload="S()">
<form id="form_s" name="Sf" method="post">
<form id="form_s" name="Sf" method="post" onsubmit="return uR()">
<div class="toprow">
<div class="helpB"><button type="button" onclick="H('features/settings/#wifi-settings')">?</button></div>
<button type="button" onclick="B()">Back</button><button type="submit">Save & Connect</button><hr>
Expand Down Expand Up @@ -202,11 +265,17 @@ <h3>ESP-NOW Wireless</h3>
<i class="warn">This firmware build does not include ESP-NOW support.<br></i>
</div>
<div id="ESPNOW">
Enable ESP-NOW: <input type="checkbox" name="RE"><br>
Enable ESP-NOW: <input type="checkbox" name="RE" onchange="tE()"><br>
<i>Listen for events over ESP-NOW<br>
Keep disabled if not using a remote or wireless sync, increases power consumption.<br></i>
Paired Remote MAC: <input type="text" name="RMAC" minlength="12" maxlength="12"><br>
Last device seen: <span class="rlid" onclick="d.Sf.RMAC.value=this.textContent;" style="cursor:pointer;">None</span> <br>
<div id="rlc">
Last device seen: <span class="rlid" id="ld">None</span>
<button type="button" class="btn btn-xs" onclick="aR('RM'+rC,gId('ld').textContent)">Add</button><br>
Linked MACs:<br>
<div id="rml">
</div>
</div>
<input type="hidden" name="RMA" id="rmacs">
</div>

<div id="ethd">
Expand Down
8 changes: 1 addition & 7 deletions wled00/remote.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -181,16 +181,10 @@ static bool remoteJson(int button)
return parsed;
}

// Callback function that will be executed when data is received
// Callback function that will be executed when data is received from a linked remote
void handleWiZdata(uint8_t *incomingData, size_t len) {
message_structure_t *incoming = reinterpret_cast<message_structure_t *>(incomingData);

if (strcmp(last_signal_src, linked_remote) != 0) {
DEBUG_PRINT(F("ESP Now Message Received from Unlinked Sender: "));
DEBUG_PRINTLN(last_signal_src);
return;
}

if (len != sizeof(message_structure_t)) {
DEBUG_PRINTF_P(PSTR("Unknown incoming ESP Now message received of length %u\n"), len);
return;
Expand Down
17 changes: 15 additions & 2 deletions wled00/set.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,21 @@ void handleSettingsSet(AsyncWebServerRequest *request, byte subPage)
bool oldESPNow = enableESPNow;
enableESPNow = request->hasArg(F("RE"));
if (oldESPNow != enableESPNow) forceReconnect = true;
strlcpy(linked_remote, request->arg(F("RMAC")).c_str(), 13);
strlwr(linked_remote); //Normalize MAC format to lowercase
linked_remotes.clear(); // clear old remotes
for (size_t n = 0; n < 10; n++) {
char rm[4];
snprintf(rm, sizeof(rm), "RM%d", n); // "RM0" to "RM9"
if (request->hasArg(rm)) {
const String& arg = request->arg(rm);
if (arg.isEmpty()) continue;
std::array<char, 13> mac{};
strlcpy(mac.data(), request->arg(rm).c_str(), 13);
strlwr(mac.data());
if (mac[0] != '\0') {
linked_remotes.push_back(mac);
}
}
}
#endif

#if defined(ARDUINO_ARCH_ESP32) && defined(WLED_USE_ETHERNET)
Expand Down
18 changes: 13 additions & 5 deletions wled00/udp.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -959,14 +959,22 @@ void espNowReceiveCB(uint8_t* address, uint8_t* data, uint8_t len, signed int rs
// usermods hook can override processing
if (UsermodManager::onEspNowMessage(address, data, len)) return;

// handle WiZ Mote data
if (data[0] == 0x91 || data[0] == 0x81 || data[0] == 0x80) {
handleWiZdata(data, len);
bool knownRemote = false;
for (const auto& mac : linked_remotes) {
if (strlen(mac.data()) == 12 && strcmp(last_signal_src, mac.data()) == 0) {
knownRemote = true;
break;
}
}
if (!knownRemote) {
DEBUG_PRINT(F("ESP Now Message Received from Unlinked Sender: "));
DEBUG_PRINTLN(last_signal_src);
return;
}

if (strlen(linked_remote) == 12 && strcmp(last_signal_src, linked_remote) != 0) {
DEBUG_PRINTLN(F("ESP-NOW unpaired remote sender."));
// handle WiZ Mote data
if (data[0] == 0x91 || data[0] == 0x81 || data[0] == 0x80) {
handleWiZdata(data, len);
return;
}

Expand Down
3 changes: 2 additions & 1 deletion wled00/wled.h
Original file line number Diff line number Diff line change
Expand Up @@ -538,7 +538,8 @@ WLED_GLOBAL bool serialCanTX _INIT(false);
WLED_GLOBAL bool enableESPNow _INIT(false); // global on/off for ESP-NOW
WLED_GLOBAL byte statusESPNow _INIT(ESP_NOW_STATE_UNINIT); // state of ESP-NOW stack (0 uninitialised, 1 initialised, 2 error)
WLED_GLOBAL bool useESPNowSync _INIT(false); // use ESP-NOW wireless technology for sync
WLED_GLOBAL char linked_remote[13] _INIT(""); // MAC of ESP-NOW remote (Wiz Mote)
//WLED_GLOBAL char linked_remote[13] _INIT(""); // MAC of ESP-NOW remote (Wiz Mote)
WLED_GLOBAL std::vector<std::array<char, 13>> linked_remotes; // MAC of ESP-NOW remotes (Wiz Mote)
WLED_GLOBAL char last_signal_src[13] _INIT(""); // last seen ESP-NOW sender
#endif

Expand Down
9 changes: 4 additions & 5 deletions wled00/xml.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,10 @@ void getSettingsJS(byte subPage, Print& settingsScript)

#ifndef WLED_DISABLE_ESPNOW
printSetFormCheckbox(settingsScript,PSTR("RE"),enableESPNow);
printSetFormValue(settingsScript,PSTR("RMAC"),linked_remote);
settingsScript.printf_P(PSTR("rstR();")); // reset remote list
for (size_t i = 0; i < linked_remotes.size(); i++) {
settingsScript.printf_P(PSTR("aR(\"RM%u\",\"%s\");"), i, linked_remotes[i].data()); // add remote to list
}
#else
//hide remote settings if not compiled
settingsScript.print(F("toggle('ESPNOW');")); // hide ESP-NOW setting
Expand Down Expand Up @@ -258,10 +261,6 @@ void getSettingsJS(byte subPage, Print& settingsScript)
#ifndef WLED_DISABLE_ESPNOW
if (strlen(last_signal_src) > 0) { //Have seen an ESP-NOW Remote
printSetClassElementHTML(settingsScript,PSTR("rlid"),0,last_signal_src);
} else if (!enableESPNow) {
printSetClassElementHTML(settingsScript,PSTR("rlid"),0,(char*)F("(Enable ESP-NOW to listen)"));
} else {
printSetClassElementHTML(settingsScript,PSTR("rlid"),0,(char*)F("None"));
}
#endif
}
Expand Down