I am trying to design a fancy switch. Pressing the switch sends a message to the master device via ESP NOW. I also want OTA capability via WiFi on that switch as it will be in a remote place. Because ESP NOW and WiFi cannot work at the same time, my idea is that every hour (SYSTEM_INTERVAL) device disconnects from ESP NOW, connects to WiFi, checks if the versions of the software are the same, and if not it updates. If the versions are the same the device disconnects from WiFi and reconnects to ESP now to keep working as a regular switch.
I have been messing with this for a week now and cannot get it to work. It either communicates with the master via ESP now, but cannot connect to WiFi, connects to WiFi but will not communicate via ESP NOW, or cannot connect to WiFi and will not send messages via ESP NOW. I am not sure if I am on the right track as I am a hardware guy and not very proficient with the WiFi/ESP NOW stack (How to connect, how to disconnect, inits, channels, ...). Below is a snippet of my code, and would be very grateful if you could check it out and suggest anything that I am doing wrong:
Code: Select all
#define SYSTEM_INTERVAL 360000
unsigned long lastSystemRequest = 0;
const char* ssid = "Example";
const char* password = "Password123";
const uint8_t MASTER_MAC[6] = {0xe4, 0xb0, 0x63, 0x51, 0x01, 0x3c};
esp_now_peer_info_t peerInfo;
void loop(){
unsigned long currentTime = millis();
if (currentTime - lastSystemRequest >= SYSTEM_INTERVAL) {
esp_now_deinit();
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("\nConnecting");
int attempts = 0;
while (WiFi.status() != WL_CONNECTED && attempts < 20) {
Serial.print(".");
delay(100);
attempts++;
}
//Network available
if (WiFi.status() == WL_CONNECTED) {
Serial.println("Connected");
checkForOTAUpdate(); //In a separate file, not important for this discussion
}
//Network unavailable
else if(WiFi.status() != WL_CONNECTED && WiFi.status() == WL_NO_SSID_AVAIL){
Serial.println("No network available");
}
//No/wrong SSID/Password
else if(WiFi.status() != WL_CONNECTED && WiFi.status() != WL_NO_SSID_AVAIL) {
Serial.println("Wrong credentials");
}
WiFi.disconnect();
//reconnecting to ESP NOW
WiFi.mode(WIFI_STA);
// Initialize ESP-NOW
if (esp_now_init() != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
return;
}
esp_now_register_send_cb(OnDataSent);
memcpy(peerInfo.peer_addr, MASTER_MAC, 6);
peerInfo.channel = 0;
peerInfo.encrypt = false;
// Add master as peer
if (esp_now_add_peer(&peerInfo) != ESP_OK) {
Serial.println("Failed to add master as peer");
return;
}
//Serial.println("ESP-NOW initialized and master added as peer");
delay(100);
lastSystemRequest = currentTime;
}
}
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
if (instance == nullptr) return; // Safety check
if (status == ESP_NOW_SEND_SUCCESS) {
Serial.println("Message sent successfully");
} else {
Serial.println("**********Error sending message**********");
}
Marin