/*
 * dfPlayer auf Wemos D1: https://forum.arduino.cc/t/dfplayer-mini-mit-wemos-d1-uno/677980/3
 */

#include "DFRobotDFPlayerMini.h"
#include "ESP8266WiFi.h"

#include <SPI.h>
#include <Ethernet.h>


DFRobotDFPlayerMini dfPlayer;
int volume = 5;

byte mac[] = { 0x02, 0x60, 0x0D, 0xF0, 0x0D, 0x04 };
IPAddress ip(192, 168, 178, 60);
EthernetServer server(80);


void setup() {
  WiFi.mode(WIFI_OFF);

  Serial.begin(115200);
  Serial.println();
  Serial.println("Starting server");
  
  Ethernet.init(5); // W5500 CS PIN auf D1
  Ethernet.begin(mac, ip);

  if (Ethernet.hardwareStatus() == EthernetNoHardware) {
    Serial.println("Ethernet shield not found");
    while (true) {
      delay(1);
    }
  }
  if (Ethernet.linkStatus() == LinkOFF) {
    Serial.println("Ethernet cable is not connected.");
  }

  
  Serial1.begin(9600);// TX liegt auf Pin D4 RX geht nicht !!

  dfPlayer.begin(Serial1);
  delay(100);
  dfPlayer.setTimeOut(500); // Set serial communication time out 500ms
  dfPlayer.volume(volume);  // Set volume value (0~30).
  dfPlayer.EQ(DFPLAYER_EQ_NORMAL);
  dfPlayer.outputDevice(DFPLAYER_DEVICE_SD);
  dfPlayer.play(2);

  server.begin();
  Serial.println(Ethernet.localIP());

}

void loop() {
  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
    bool currentLineIsBlank = true;

    byte trigger = 0;
    char uri[64];
    byte idx = 0;
    boolean uriLine = false;

    while (client.connected()) {
      if (client.available()) {
        char c = client.read();

        if (currentLineIsBlank && c == 'G') {
          uriLine = true;
          uri[idx] = c;
          idx++;
        }
        else if (uriLine) {
          if (c == '\n') {
            uriLine = false;
            uri[idx] = '\0';
          }
          else {
            uri[idx] = c;
            idx++;
          }
        }

        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/plain");
          client.println("Connection: close");  // the connection will be closed after completion of the response
          client.println();
          client.println("bonjour");
          dfPlayer.play(1);
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        } else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(10);
    // close the connection:
    client.stop();
    Serial.println("client disconnected");
  }
}