Move ESP-NOW lighting control to lib

This commit is contained in:
Robert Marshall 2022-09-09 10:48:19 +01:00
parent 5b69f482c3
commit 76b8fed961
5 changed files with 33 additions and 34 deletions

View file

@ -0,0 +1,54 @@
#ifndef EspNowLightControlClient_cpp
#define EspNowLightControlClient_cpp
#include <esp_now.h>
#include <WiFi.h>
#include "LightControlPayload.cpp"
class EspNowLightControlClient {
uint8_t broadcastAddress[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
public:
bool init() {
WiFi.mode(WIFI_STA);
if (esp_now_init() != ESP_OK)
return false;
esp_now_peer_info_t peerInfo = {};
memcpy(peerInfo.peer_addr, broadcastAddress, 6);
peerInfo.channel = 0;
peerInfo.encrypt = false;
esp_err_t peerResult = esp_now_add_peer(&peerInfo);
if (peerResult != ESP_OK) {
Serial.println("Failed to add peer");
Serial.println(esp_err_to_name(peerResult));
return false;
}
return true;
}
void send() {
for (int i = 1; i <= 5; i++) {
LightControlPayload data = LightControlPayload();
data.id = i;
data.brightness = 1;
data.on = false;
data.timer = 0;
esp_err_t result = esp_now_send(broadcastAddress, (uint8_t*)&data, sizeof(data));
if (result == ESP_OK)
Serial.println("Sent with success");
else {
Serial.println("Error sending the data");
Serial.println(esp_err_to_name(result));
}
delay(100);
}
}
};
#endif

View file

@ -0,0 +1,35 @@
#ifndef EspNowLightControlServer_cpp
#define EspNowLightControlServer_cpp
#include <esp_now.h>
#include <WiFi.h>
#include "LedManager.cpp"
#include "LightControlPayload.cpp"
class EspNowLightControlServer {
static LedManager *_leds;
static void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) {
LightControlPayload data;
memcpy(&data, incomingData, sizeof(data));
_leds->setLedProperties(data.id, data.on, data.brightness, data.timer);
}
EspNowLightControlServer();
public:
static bool init(LedManager *leds) {
_leds = leds;
WiFi.mode(WIFI_STA);
if (esp_now_init() != ESP_OK)
return false;
esp_now_register_recv_cb(OnDataRecv);
return true;
}
};
#endif

View file

@ -0,0 +1,11 @@
#ifndef LightControlPayload_cpp
#define LightControlPayload_cpp
struct LightControlPayload {
int id;
bool on;
float brightness;
unsigned long timer;
};
#endif