// MuTech Robotics - SF1 Sleep Curve Fan (ESP32 + IR transmitter + OLED)
// OLED: 3V3 -> VCC, GND -> GND, GPIO22 -> SCL, GPIO21 -> SDA
// IR transmitter module: GPIO4 -> SIG, 5V -> VCC, GND -> GND. Face it towards the fan.
// Libraries: IRremoteESP8266, Adafruit SSD1306, Adafruit GFX
//
// For fans with an IR remote (most BLDC fans). On the phone page, enter once the code your remote sends
// for each speed (protocol, hex code, bits: read them with any IR receiver sketch), then set the sleep curve.
// Strictly follow the description given with this video.
#include <WiFi.h>
#include <WebServer.h>
#include <Preferences.h>
#include <time.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <IRremoteESP8266.h>
#include <IRsend.h>
#include <IRutils.h>

const char *WIFI_SSID = "YOUR_WIFI";
const char *WIFI_PASS = "YOUR_PASSWORD";
const int IR_PIN = 4, SPEEDS = 5;

IRsend irsend(IR_PIN);
WebServer server(80);
Preferences prefs;
Adafruit_SSD1306 oled(128, 64, &Wire, -1);

int stepMin[3] = {23 * 60, 3 * 60, 5 * 60};
int stepSpeed[3] = {5, 3, 2};
int lastSent = -1;

String key(const char *k, int i) { return String(k) + i; }

void sendSpeed(int speed) {
  prefs.begin("sleepfan", true);
  String p = prefs.getString(key("p", speed).c_str(), "");
  uint64_t c = prefs.getULong64(key("c", speed).c_str(), 0);
  uint16_t b = prefs.getUShort(key("b", speed).c_str(), 0);
  prefs.end();
  if (p == "" || !b) { Serial.printf("No code saved for speed %d\n", speed); return; }
  irsend.send(strToDecodeType(p.c_str()), c, b);
  Serial.printf("Fan speed %d sent\n", speed);
}

String hhmm(int m) { char s[6]; snprintf(s, 6, "%02d:%02d", m / 60, m % 60); return s; }

void handleRoot() {
  if (server.hasArg("m0")) {
    prefs.begin("sleepfan", false);
    for (int i = 0; i < 3; i++) {
      String t = server.arg(key("m", i));
      stepMin[i] = t.substring(0, 2).toInt() * 60 + t.substring(3, 5).toInt();
      stepSpeed[i] = constrain(server.arg(key("s", i)).toInt(), 1, SPEEDS);
      prefs.putInt(key("m", i).c_str(), stepMin[i]); prefs.putInt(key("s", i).c_str(), stepSpeed[i]);
    }
    prefs.end(); lastSent = -1;
  }
  if (server.hasArg("sp")) {
    int sp = server.arg("sp").toInt();
    prefs.begin("sleepfan", false);
    prefs.putString(key("p", sp).c_str(), server.arg("p"));
    prefs.putULong64(key("c", sp).c_str(), strtoull(server.arg("c").c_str(), nullptr, 16));
    prefs.putUShort(key("b", sp).c_str(), server.arg("b").toInt());
    prefs.end();
  }
  String h = F("<!doctype html><meta name=viewport content='width=device-width,initial-scale=1'><title>Fan sleep curve</title>"
               "<body style='font-family:sans-serif;padding:14px;background:#eef1f5'><h2>Fan sleep curve</h2><form>");
  for (int i = 0; i < 3; i++) h += "Step " + String(i + 1) + ": <input type=time name=m" + i + " value=" + hhmm(stepMin[i]) + "> speed <input type=number min=1 max=5 name=s" + i + " value=" + stepSpeed[i] + " style=width:60px><br>";
  h += F("<button>Save curve</button></form><h3>Remote codes</h3>");
  for (int s = 1; s <= SPEEDS; s++)
    h += "<form>Speed " + String(s) + " <input type=hidden name=sp value=" + s + "><input name=p size=6 placeholder=NEC><input name=c size=10 placeholder=hex><input name=b size=3 placeholder=32><button>Save</button></form>";
  server.send(200, "text/html", h);
}

void setup() {
  Serial.begin(115200);
  Wire.begin(21, 22);
  oled.begin(SSD1306_SWITCHCAPVCC, 0x3C); oled.setTextColor(SSD1306_WHITE);
  irsend.begin();
  prefs.begin("sleepfan", true);
  for (int i = 0; i < 3; i++) { stepMin[i] = prefs.getInt(key("m", i).c_str(), stepMin[i]); stepSpeed[i] = prefs.getInt(key("s", i).c_str(), stepSpeed[i]); }
  prefs.end();
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  while (WiFi.status() != WL_CONNECTED) delay(300);
  configTzTime("IST-5:30", "pool.ntp.org");
  server.on("/", handleRoot);
  server.begin();
}

void loop() {
  server.handleClient();
  struct tm t;
  if (!getLocalTime(&t, 10)) return;
  int nowMin = t.tm_hour * 60 + t.tm_min, active = 0, bestAgo = 1440;
  for (int i = 0; i < 3; i++) { int ago = (nowMin - stepMin[i] + 1440) % 1440; if (ago < bestAgo) { bestAgo = ago; active = i; } }
  if (bestAgo == 0 && lastSent != active) { sendSpeed(stepSpeed[active]); lastSent = active; }
  static unsigned long lastDraw = 0;
  if (millis() - lastDraw > 1000) {
    lastDraw = millis();
    oled.clearDisplay(); oled.setTextSize(1); oled.setCursor(0, 0); oled.print(WiFi.localIP());
    oled.setTextSize(2); oled.setCursor(0, 16); oled.printf("%02d:%02d", t.tm_hour, t.tm_min);
    oled.setCursor(0, 40); oled.printf("Fan %d", stepSpeed[active]); oled.display();
  }
}
