Files
esp8266-laser/esp8266-laser.ino
2017-10-25 01:10:32 +02:00

463 lines
12 KiB
C++

/*
https://github.com/0x1d/esp8266-laser
*/
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <FS.h>
#include <SoftwareSerial.h>
#include <ArduinoJson.h>
/*
some hard coded config, change if needed
*/
// Set how long the esp should try to connect to a network before starting it's own AP
int wifiTimeout = 15000; //ms
// Hardcoded Soft AP network parameters
char *ssidAP = "laserAp";
IPAddress apIP(192, 168, 4, 1);
IPAddress netMsk(255, 255, 255, 0);
// this is sent to server if invalid request
const char *metaRefreshStr = "<head><meta http-equiv=\"refresh\" content=\"3; url=/index.html\" /></head><body><p>redirecting...</p></body>";
/* hostname for mDNS. Should work at least on windows. Try http://esp8266.local */
const char *myHostname = "esplaser";
// espsoftwareserial
// SoftwareSerial(int receivePin, int transmitPin, bool inverse_logic = false, unsigned int buffSize = 64);
SoftwareSerial laserSerial(14, 12, false, 256);
/*
End of hard coded config
*/
String ssid = "";
String password = "";
int apMode = 1; // default value, will be overwriten with config from file
int _apMode = 0; // runtime apMode
// [0] laser[1] m1 [2] m2 [3] m3
byte lmValues[4] = {0, 0, 0, 0};
unsigned long previousMillis = 0;
// Web server
ESP8266WebServer server(80);
//format bytes
String formatBytes(size_t bytes) {
if (bytes < 1024) {
return String(bytes) + "B";
} else if (bytes < (1024 * 1024)) {
return String(bytes / 1024.0) + "KB";
} else if (bytes < (1024 * 1024 * 1024)) {
return String(bytes / 1024.0 / 1024.0) + "MB";
} else {
return String(bytes / 1024.0 / 1024.0 / 1024.0) + "GB";
}
}
String getContentType(String filename) {
if (server.hasArg("download")) return "application/octet-stream";
else if (filename.endsWith(".htm")) return "text/html";
else if (filename.endsWith(".html")) return "text/html";
else if (filename.endsWith(".ini")) return "text/plain";
else if (filename.endsWith(".css")) return "text/css";
else if (filename.endsWith(".js")) return "application/javascript";
else if (filename.endsWith(".png")) return "image/png";
else if (filename.endsWith(".gif")) return "image/gif";
else if (filename.endsWith(".jpg")) return "image/jpeg";
else if (filename.endsWith(".ico")) return "image/x-icon";
else if (filename.endsWith(".xml")) return "text/xml";
else if (filename.endsWith(".pdf")) return "application/x-pdf";
else if (filename.endsWith(".zip")) return "application/x-zip";
else if (filename.endsWith(".gz")) return "application/x-gzip";
return "text/plain";
}
bool handleFileRead(String path) {
Serial.println("handleFileRead: " + path);
if (path.endsWith("/")) path += "index.html";
String contentType = getContentType(path);
String pathWithGz = path + ".gz";
if (SPIFFS.exists(pathWithGz) || SPIFFS.exists(path)) {
if (SPIFFS.exists(pathWithGz))
path += ".gz";
File file = SPIFFS.open(path, "r");
size_t sent = server.streamFile(file, contentType);
file.close();
return true;
}
return false;
}
void handleFileList() {
if (!server.hasArg("dir")) {
server.send(500, "text/plain", "BAD ARGS");
return;
}
String path = server.arg("dir");
Serial.println("handleFileList: " + path);
Dir dir = SPIFFS.openDir(path);
path = String();
String output = "[";
while (dir.next()) {
File entry = dir.openFile("r");
if (output != "[") output += ',';
bool isDir = false;
output += "{\"type\":\"";
output += (isDir) ? "dir" : "file";
output += "\",\"name\":\"";
output += String(entry.name()).substring(1);
output += "\"}";
entry.close();
}
output += "]";
server.send(200, "text/json", output);
}
void handleLaser(String uri)
{
String laserValue = uri.substring(7);
if (laserValue.toInt() > 128) {
lmValues[0] = 128;
laserValue = "128";
}
else
{
lmValues[0] = laserValue.toInt();
}
String msg = "AT SLV ";
msg += laserValue;
Serial.println("Sent to Laser: " + msg);
laserSerial.println(msg);
String json = "{ \"handledLaser\":";
json += "{\"value\":\"" + laserValue + "\"}}";
//server.send(200, "text/plain", "blub");
server.send(200, "text/json", json);
json = String();
}
void handleMotor(String uri)
{
String motorNr = uri.substring(7, 8);
String motorValue = uri.substring(9);
if (motorValue.toInt() > 128) {
lmValues[motorNr.toInt()] = 128;
motorValue = "128";
}
else
{
lmValues[motorNr.toInt()] = motorValue.toInt();
}
String msg = "AT SMS ";
msg += motorNr;
msg += " ";
msg += motorValue;
Serial.println("Sent to Laser: " + msg);
laserSerial.println(msg);
String json = "{ \"handledMotor\": ";
json += "{ \"motor\":\"" + motorNr + "\", ";
json += "\"value\":\"" + motorValue + "\" }}";
//server.send(200, "text/plain", "blub");
server.send(200, "text/json", json);
json = String();
}
void handleReadValues()
{
String json = "{ \"handledReadValues\":";
json += "{\"laser\":\"" + (String)lmValues[0] + "\",";
json += "\"motors\": {\"1\":\"" + (String)lmValues[1] + "\",";
json += "\"2\":\"" + (String)lmValues[2] + "\",";
json += "\"3\":\"" + (String)lmValues[3] + "\"}}}";
server.send(200, "text/json", json);
json = String();
}
void hReadWifi()
{
// Serial.println("hReadWifi");
String responseBuffer = String();
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
JsonObject& data = root.createNestedObject("wificonfig");
data["apMode"] = apMode;
data["SSID"] = ssid;
data["Password"] = "***"; //password;
//data["save"] = "false";
//data["apply"] = "false";
root.prettyPrintTo(responseBuffer);
//root.prettyPrintTo(Serial);
server.send(200, "text/json", responseBuffer);
jsonBuffer.clear();
responseBuffer = String();
}
void hWriteWifi()
{
// Serial.println("hWriteWifi");
String responseBuffer = String();
boolean save = false;
boolean apply = false;
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
JsonObject& data = root.createNestedObject("wificonfig");
if (server.hasArg("apMode") ) {
apMode = server.arg("apMode").toInt();
data["apMode"] = apMode;
}
if (server.hasArg("SSID") ) {
ssid = server.arg("SSID");
data["SSID"] = ssid;
}
if (server.hasArg("password") ) {
password = server.arg("password");
data["Password"] = "***"; //password;
}
if (server.arg("save") == "true")
{
save = true;
data["save"] = "true";
}
if (server.arg("apply") == "true")
{
apply = true;
data["apply"] = "true";
}
root.prettyPrintTo(responseBuffer);
//root.prettyPrintTo(Serial);
server.send(200, "text/json", responseBuffer);
if (save) {
saveConfigFile();
}
if (apply) {
setupWifi();
}
jsonBuffer.clear();
responseBuffer = String();
}
bool saveConfigFile() {
StaticJsonBuffer<200> jsonBuffer;
JsonObject& json = jsonBuffer.createObject();
json["apMode"] = apMode;
json["SSID"] = ssid;
json["Password"] = password;
File configFile = SPIFFS.open("/wifi.json", "w");
if (!configFile) {
Serial.println("Failed to open config file for writing");
return false;
}
json.printTo(configFile);
return true;
}
void handleSaveConf() {
bool success = saveConfigFile();
if (success)
{
server.send(200, "text/plain", "saved config to file,<br> reset or /resetwifi to apply settings");
}
else
{
server.send(500, "text/plain", "error saving file");
}
}
boolean readConfigFile() {
Serial.println("Reading wifi.json");
File configFile = SPIFFS.open("/wifi.json", "r");
if (!configFile) {
Serial.println("Failed to open config file");
return false;
}
size_t size = configFile.size();
if (size > 1024) {
Serial.println("Config file size is too large");
return false;
}
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
configFile.readBytes(buf.get(), size);
StaticJsonBuffer<200> jsonBuffer;
JsonObject& json = jsonBuffer.parseObject(buf.get());
if (!json.success()) {
Serial.println("Failed to parse config file");
return false;
}
apMode = json["apMode"];
apMode = apMode;
const char* tSsid = json["SSID"];
const char* tPwd = json["Password"];
ssid = tSsid;
password = tPwd;
Serial.print("SSID: ");
Serial.println(ssid);
Serial.print("PW: ");
Serial.println(password);
return true;
}
boolean setupWifi() {
Serial.print("setupWifi apMode=");
Serial.println(apMode);
if (_apMode == 0)
{
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid.c_str(), password.c_str());
previousMillis = millis();
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
if (millis() - previousMillis >= wifiTimeout) {
Serial.println("");
Serial.println("connection timedout");
return false;
}
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
return true;
}
else
{
Serial.printf("Starting SoftAP %s\n", ssidAP);
WiFi.mode(WIFI_AP);
WiFi.softAP(ssidAP);
Serial.print("SoftAP started! IP address: ");
Serial.println ( WiFi.softAPIP() );
return true;
}
}
void setup(void) {
laserSerial.begin(9600);
laserSerial.flush();
Serial.begin(115200);
Serial.print("\n");
SPIFFS.begin();
// {
// Dir dir = SPIFFS.openDir("/");
// while (dir.next()) {
// String fileName = dir.fileName();
// size_t fileSize = dir.fileSize();
// Serial.printf("FS File: %s, size: %s\n", fileName.c_str(), formatBytes(fileSize).c_str());
// }
// Serial.printf("\n");
// }
//WIFI INIT
WiFi.disconnect();
delay(100);
if (!readConfigFile())
{
Serial.println("reading wifi config failed, start SoftAP");
_apMode = 1;
}
delay(100);
if (!setupWifi())
{
Serial.println("connect failed, start SoftAP");
_apMode = 1; // fallback to AP mode
setupWifi();
}
// Setup MDNS responder
if (!MDNS.begin(myHostname)) {
Serial.println("Error setting up MDNS responder!");
} else {
Serial.println("mDNS responder started");
// Add service to MDNS-SD
MDNS.addService("http", "tcp", 80);
}
//SERVER INIT
//list directory
server.on("/listFiles", HTTP_GET, handleFileList);
server.on("/saveconf", HTTP_GET, handleSaveConf);
server.on("/resetwifi", HTTP_GET, setupWifi);
server.on("/wificonfig", HTTP_GET, hReadWifi);
server.on("/wificonfig", HTTP_POST, hWriteWifi);
// server.on("/wificonfig", HTTP_POST, []() {
// hWriteWifi();
// });
server.on("/readvalues", HTTP_GET, handleReadValues);
server.on("/heap", HTTP_GET, []() {
String json = "{";
json += "\"heap\":" + String(ESP.getFreeHeap());
json += "}";
server.send(200, "text/json", json);
json = String();
});
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}
void handleNotFound() {
String uri = server.uri();
Serial.print("unhandled uri:");
Serial.println(uri);
if (uri.substring(0, 7) == "/motor/")
{
handleMotor(uri);
return;
}
if (uri.substring(0, 7) == "/laser/")
{
handleLaser(uri);
return;
}
if (uri.substring(0, 12) == "/wifi.json")
{
server.send(403, "text/plain", "Forbidden");
return;
}
if (!handleFileRead(server.uri()))
{
server.send(404, "text/html", metaRefreshStr);
// server.send(302, "text/plain", "blub");
}
}
void loop(void) {
server.handleClient();
}