wifi_util.cpp 1.73 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include "wifi_util.h"

namespace config {
  // WiFi config. See 'config.h' if you want to modify those values.
#ifdef WIFI_SSID
  const char *wifi_ssid = WIFI_SSID;
  const char *wifi_password = WIFI_PASSWORD;
#else
  const char *wifi_ssid = "NO_WIFI";
  const char *wifi_password = "";
#endif

#ifdef WIFI_TIMEOUT
  const uint8_t wifi_timeout = WIFI_TIMEOUT;  // [s] Will try to connect during wifi_timeout seconds before failing.
#else
  const uint8_t wifi_timeout = 60;  // [s] Will try to connect during wifi_timeout seconds before failing.
#endif
}

// Initialize Wi-Fi
void WiFiConnect(const String &hostname) {
  //NOTE: WiFi Multi could allow multiple SSID and passwords.
  if (strcmp(config::wifi_ssid, "NO_WIFI") == 0) {
    Serial.println("Please change WIFI_SSID in config.h if you want to connect.");
    WiFi.disconnect(true);
    WiFi.mode(WIFI_OFF);
    return;
  }
  WiFi.persistent(false); // Don't write user & password to Flash.
  WiFi.mode(WIFI_STA);  // Set ESP8266 to be a WiFi-client only
#if defined(ESP8266)
    WiFi.hostname(hostname);
Eric Duminil's avatar
Eric Duminil committed
33
#elif defined(ESP32)
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
  WiFi.setHostname(hostname.c_str());
#endif

  Serial.print("\nConnecting to ");
  Serial.println(config::wifi_ssid);
  WiFi.begin(config::wifi_ssid, config::wifi_password);

  // Wait for connection, at most wifi_timeout seconds
  for (int i = 0; i <= config::wifi_timeout && (WiFi.status() != WL_CONNECTED); i++) {
    LedEffects::showRainbowWheel();
    Serial.print(".");
  }
  if (WiFi.status() == WL_CONNECTED) {
    LedEffects::showKITTWheel(color::green);
    Serial.println();
    Serial.print("\nWiFi connected, IP address: ");
    Serial.println(WiFi.localIP());
  } else {
    LedEffects::showKITTWheel(color::red);
    Serial.println("\nConnection to WiFi failed");
  }
}