Skip to content

Instantly share code, notes, and snippets.

@desarrollogis
Last active September 28, 2015 00:09
Show Gist options
  • Save desarrollogis/3a4ce0f0032649fddb01 to your computer and use it in GitHub Desktop.
Save desarrollogis/3a4ce0f0032649fddb01 to your computer and use it in GitHub Desktop.
Configuration code for ESP8266
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266httpUpdate.h>
#include <EEPROM.h>
#define DEBUG
ESP8266WebServer g_server(80);
const char* g_root = R"(<html>
<body>
<a href='/'>Home</a>
<hr />
<form method='post' action='/'>
<input type='text' name='ssid'/>
<br />
<input type='text' name='password'/>
<br />
<input type='submit' value='connect'/>
</form>
<hr />
<form method='post' action='/'>
<input type='text' name='url'/>
<br />
<input type='submit' value='upgrade'/>
</form>
</body>
</html>)";
const char* g_ssid = "esp8266-server";
bool g_AP = false;
ESP8266HTTPUpdate g_update;
extern void setuped();
extern void looped();
#ifdef DEBUG
void configDebug(const String& msg, bool newline = true) {
static bool bInitialized = false;
if (!bInitialized) {
Serial.begin(9600);
Serial.setDebugOutput(false);
Serial.setDebugOutput(true);
bInitialized = true;
}
if (newline) {
Serial.println(msg);
}
else {
Serial.print(msg);
}
}
#else
void configDebug(const String& msg, bool newline = true) {
}
#endif
void configRoot() {
configDebug("configRoot");
if (g_server.hasArg("ssid") && g_server.hasArg("password")) {
String ssid = g_server.arg("ssid");
String password = g_server.arg("password");
WiFi.mode(WIFI_OFF);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid.c_str(), password.c_str());
while (WiFi.status() != WL_CONNECTED) {
delay(100);
}
EEPROM.write(0, 1);
EEPROM.commit();
ESP.reset();
return;
}
if (g_server.hasArg("url")) {
String url = g_server.arg("url");
url.replace("%3A", ":");
url.replace("%2F", "/");
int pos = url.indexOf("/", 9);
if (pos > 9) {
String host = url.substring(0, pos);
int port = 0;
url = url.substring(pos);
if (host.startsWith("http://")) {
port = 80;
host.replace("http://", "");
}
else if (host.startsWith("https://")) {
port = 443;
host.replace("https://", "");
}
if (port > 0) {
g_update.update(host, port, url, "1.0");
return;
}
}
}
g_server.send(200, "text/html", g_root);
}
void configConnect() {
configDebug("configConnect");
g_server.send(200, "text/html", g_root);
}
void setup() {
configDebug("setup");
EEPROM.begin(1);
if (EEPROM.read(0) == 1) {
WiFi.mode(WIFI_STA);
WiFi.begin("");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
setuped();
return;
}
WiFi.softAP(g_ssid);
g_server.on("/", configRoot);
g_server.begin();
g_AP = true;
}
void configReset() {
configDebug("configReset");
EEPROM.write(0, 0);
EEPROM.commit();
ESP.reset();
}
void loop() {
if (g_AP) {
g_server.handleClient();
return;
}
looped();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment