
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include "config.h" // if this file doesn't exist, copy config.h.example to it and edit

IPAddress local_IP(192, 168, 115, 23);
IPAddress gateway(192, 168, 115, 1); // bogus
IPAddress subnet(255, 255, 255, 0);


/* Set these to your desired credentials. */
const char *ssid = APSSID;
const char *password = APPSK;

ESP8266WebServer server(80);

const int trigPin = 12;
const int echoPin = 13;


unsigned long measureDistance() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  unsigned long duration = pulseIn(echoPin, HIGH);
  return (duration * 343) / 2000; // speed of sound is 0.343 mm/microsec (halve because 2 way)
}

void handleRoot() {
  struct station_info *stat_info;
  stat_info = wifi_softap_get_station_info();
  uint8_t client_count = wifi_softap_get_station_num();
  u32_t address;
  String str = "Number of clients = ";
  str += String(client_count);
  str += "<br/>\r\nList of clients : <br/>\r\n";
  int i = 1;
  while (stat_info != NULL) {
    str += "Station #";
    str += String(i);
    str += " : ";
    str += String(stat_info->bssid[0], HEX);
    str += ":";
    str += String(stat_info->bssid[1], HEX);
    str += ":";
    str += String(stat_info->bssid[2], HEX);
    str += ":";
    str += String(stat_info->bssid[3], HEX);
    str += ":";
    str += String(stat_info->bssid[4], HEX);
    str += ":";
    str += String(stat_info->bssid[5], HEX);
    str += " ";
    address = (&stat_info->ip)->addr;
    str += ((unsigned char*)&address)[0];
    str += ".";
    str += ((unsigned char*)&address)[1];
    str += ".";
    str += ((unsigned char*)&address)[2];
    str += ".";
    str += ((unsigned char*)&address)[3];
    str += "<br/>\r\n";
    i++;
    stat_info = STAILQ_NEXT(stat_info, next);
  }
  str += "<a target=\"_blank\" href=\"d\">Distance</a><br/>\r\n";
  server.send(200, "text/html", str);
}

void handleDistance() {
  unsigned long distance = measureDistance();
  // Serial.println(distance);
  String str = "{\"distance\":" + String(distance, DEC) + "}";
  server.send(200, "application/json", str);
}

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  delay(1000);
  Serial.begin(115200);
  Serial.println();
  Serial.print("Configuring access point...");
  /* You can remove the password parameter if you want the AP to be open. */
  Serial.print("Setting soft-AP configuration ... ");
  Serial.println(WiFi.softAPConfig(local_IP, gateway, subnet) ? "Ready" : "Failed!");

  WiFi.softAP(ssid, password);

  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);
  server.on("/", handleRoot);
  server.on("/d", handleDistance);
  server.begin();
  Serial.println("HTTP server started");
}

void loop() {
  server.handleClient();
}
