daniloc / PicoW_HomeAssistant_Starter

Everything you need to get started with your own Intranet of Things, using the high-quality, low-cost Pico W as the backbone.
MIT License
198 stars 20 forks source link

Reconnect to router / HA after router power cycle. #12

Open JacobChrist opened 12 months ago

JacobChrist commented 12 months ago

Recently I've noticed that if my router is power cycled that the PicoPi either doesn't reconnect to the router or HA (not sure which yet). Not sure if this issue is best addressed by this project or the upstream arduino-home-assistant project.

daniloc commented 12 months ago

Entirely possible this implementation doesn't handle reconnects well, but impossible to say more without some basic investigation legwork done first. With the device connected to your machine so you can view the console, add some logging around the various network events. You can also enable debug logging for arduino-home-assistant:

#define ARDUINOHA_DEBUG

Add that BEFORE the a-h-a library is imported.

Then deliberately power cycle your router and see what happens.

JacobChrist commented 4 months ago

I have a solution to this issue, I'm not sure if its the best way to do it but it seems to be working. I modified Network.cpp so that is looks like this:

#include <WiFi.h>
#include "Network.h"
#include "Credentials.h"

uint8_t status;

void Network::connect() {
  do {

    Serial.print("Attempting to connect to WPA SSID: ");

    Serial.println(WIFI_SSID);

    // Connect to WPA/WPA2 network:

    status = WiFi.begin(WIFI_SSID, WIFI_PASSWORD); //Set these credentials

    // wait to connect:

    delay(5000);

  } while (status != WL_CONNECTED);

  Serial.print("Connected to ");
  Serial.println(WIFI_SSID);
}

void Network::disconnect() {
  do {
    Serial.println("Attempting to disconnect from WiFi");
    status = WiFi.disconnect();
    delay(1000);
  } while (status != WL_DISCONNECTED);

  Serial.print("Disconnected from ");
  Serial.println(WIFI_SSID);
}

And loop() looks like this:

void loop() {
  uint8_t wifi_status = WiFi.status();
  if(wifi_status == WL_CONNECTED){
    integration.loop();
  }
  else{
    Network::disconnect();
    Network::connect();
  }
}