Search This Blog

Monday 4 February 2019

"Stupid" code examples and WiFI startup times

I frequently moan about the standard of example code "out there". I also roundly deride the "standard" technique of using WIFi.begin in setup() as opposed to monitoring WiFI events... The main reason being that the former requires a reboot in the event of router / net failure and will almost certainly hang or crash + reboot cycle. The "sensible" method can continue to run hardware and simply reconnect automatically when the router comes back up... I have also known that the startup time is longer in the "stupid" version, but never got around to actually measuring it. The reason I call it it "stupid" is because DOING NOTHING AT ALL works just as well, i.e. the code is utterly redundant as well as being slower! While shaving nearly half a second off your start time may not seem amazing, how about shaving 3.35 seconds off? Since the sensible method start running the loop almost immediately after setup, your critical hardware is up and running in microseconds, literally (716 in the code that follows) whereas the "stupid" method cannot start the loop until it has connected - in my house about 3.3secs. The actual values are here: Stupid LoopStart Sensible Loop Start 3502034 3502043 3019311 715 3001939 3001948 3012237 714 3002018 3002027 2925192 718 3502023 3502032 2908446 718 3502016 3502025 3011961 714 3502019 3502028 2927768 716 3001946 3001955 3013314 718 3502024 3502033 2922075 715 3502023 3502032 2909590 719 3502020 3502029 2921998 715 AVG 3352006.2 3352015.2 2957189.2 716.2 Diffs: WiFi 394817 Loop 3351299 So, the sensible method is 0.4s faster to connect to WiFi, 3.35 seconds faster starting the "real" code...is less code to write and allows automatic re-connection whereas the other usually crashes or hangs... Dr Phil's surgery is now open to listen to anyone who would care to justify using the "classic" method...

#include <ESP8266WiFi.h>

uint32_t baseline = 0;
uint32_t loopStart = 0;
volatile uint32_t connected = 0;

#define STUPID

#ifdef STUPID
const char* method = "stupid";
#else
const char* method = "sensible";
void onWifiEvent(WiFiEvent_t event) {
  if (event == WIFI_EVENT_STAMODE_GOT_IP) connected = micros();
}
#endif

void setup() {
  baseline = micros();
  Serial.begin(74880);
  Serial.printf("T+%d WiFi startup timer using %s method baseline=%d\n",micros()-baseline,method,baseline);
#ifdef STUPID
  WiFi.begin("LaPique", "");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  connected = micros();
#else
  WiFi.onEvent(onWifiEvent);
#endif
}

void loop() {
  if (!loopStart) {
    loopStart = micros() - baseline;
    Serial.printf("T+%d Loop started\n",loopStart);
  }
  if (connected) {
    Serial.printf("T+%d WiFi was connected after %d uSec\n", micros()-baseline, connected - baseline);
    connected = 0;
    ESP.restart();
  }
}

No comments:

Post a Comment