/*
 * Hub Casa - teste isolado fauxmoESP + RF 433 MHz
 * Placa: NodeMCU ESP8266
 *
 * Comandos confirmados anteriormente:
 *   Luz ventilador (botao toggle): 0x66326456
 *   Velocidade 0 / desligado:      0x66326B6A
 *   Velocidade 1 / ligado:         0x66326878
 *
 * Todos: 32 bits, protocolo 1, pulso 250 us, 10 repeticoes.
 * Este sketch e independente do firmware atual do Hub Casa.
 */

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <fauxmoESP.h>
#include <RCSwitch.h>
#include <string.h>

// Preencha com os dados da sua rede Wi-Fi.
const char WIFI_SSID[] = "seu wi-fi";
const char WIFI_PASSWORD[] = "a senha do seu wi-fi";

// Pinos utilizados pelo projeto Hub Casa.
static const uint8_t RF_TX_PIN = D1; // GPIO5

// Codigos RF registrados anteriormente pelo usuario.
static const unsigned long RF_LUZ_TOGGLE = 0x66326456UL;
static const unsigned long RF_VENT_VEL0   = 0x66326B6AUL;
static const unsigned long RF_VENT_VEL1   = 0x66326878UL;
static const unsigned long RF_VENT_VEL3   = 0x66326E18UL;

static const unsigned int RF_BITS = 32;
static const unsigned int RF_PROTOCOL = 1;
static const unsigned int RF_PULSE_US = 250;
static const unsigned int RF_REPEATS = 10;

fauxmoESP fauxmo;
RCSwitch mySwitch;

void enviarRF(unsigned long codigo, const char *descricao) {
  Serial.printf("[RF] %s | 0x%08lX\n", descricao, codigo);
  mySwitch.send(codigo, RF_BITS);
}

void conectarWiFi() {
  WiFi.mode(WIFI_STA);
  WiFi.persistent(false);
  WiFi.setAutoReconnect(true);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

  Serial.printf("[WIFI] Conectando a %s", WIFI_SSID);
  const unsigned long inicio = millis();

  while (WiFi.status() != WL_CONNECTED && millis() - inicio < 30000UL) {
    delay(250);
    Serial.print('.');
    yield();
  }

  Serial.println();
  if (WiFi.status() == WL_CONNECTED) {
    Serial.printf("[WIFI] Conectado. IP: %s\n", WiFi.localIP().toString().c_str());
  } else {
    Serial.println(F("[WIFI] Falha ao conectar. Reinicie apos conferir SSID e senha."));
  }
}

void setup() {
  Serial.begin(115200);
  delay(100);
  Serial.println();
  Serial.println(F("=== HUB CASA | TESTE FAUXMO + RF ==="));

  // Inicializa transmissor RF na mesma configuracao usada pelo Hub Casa.
  mySwitch.enableTransmit(RF_TX_PIN);
  mySwitch.setProtocol(RF_PROTOCOL);
  mySwitch.setPulseLength(RF_PULSE_US);
  mySwitch.setRepeatTransmit(RF_REPEATS);

  conectarWiFi();
  if (WiFi.status() != WL_CONNECTED) return;

  // fauxmo precisa da porta TCP 80 para compatibilidade com dispositivos Alexa recentes.
  // Este teste e independente: nao inicie outro servidor HTTP na porta 80.
  fauxmo.createServer(true);
  fauxmo.setPort(80);

  // Dispositivos virtuais exibidos na descoberta da Alexa.
  fauxmo.addDevice("Ventilador da sala");
  fauxmo.addDevice("Luz da sala");

  fauxmo.onSetState([](unsigned char device_id,
                       const char *device_name,
                       bool state,
                       unsigned char value) {
    (void)device_id;
    (void)value;



    if (strcmp(device_name, "Ventilador da sala") == 0) {
      // Liga = velocidade 1; desliga = velocidade 0.
      if (state) {
        enviarRF(RF_VENT_VEL3, "Ventilador - velocidade 3");
      } else {
        enviarRF(RF_VENT_VEL0, "Ventilador - velocidade 0");
      }
    }
    else if (strcmp(device_name, "Luz da sala") == 0) {
      // O controle original possui um unico codigo para alternar a luz.
      // Por isso o mesmo codigo e enviado tanto ao ligar quanto ao desligar.
      enviarRF(RF_LUZ_TOGGLE, "Luz da sala - alternar");
    }
  });

  fauxmo.enable(true);
  //Serial.println(F("[FAUXMO] Ativo. Abra a Alexa e procure dispositivos."));
  //Serial.printf("[SYS] Heap livre apos inicializacao: %u bytes\n", ESP.getFreeHeap());
}

void loop() {
  if (WiFi.status() == WL_CONNECTED) {
    fauxmo.handle();
  }

  static unsigned long ultimoDiagnostico = 0;
  if (millis() - ultimoDiagnostico >= 5000UL) {
    ultimoDiagnostico = millis();
    Serial.printf("[SYS] Heap livre: %u bytes\n", ESP.getFreeHeap());
  }
  yield();
}
