#include <Adafruit_MPU6050.h>
#include <WiFi.h>
#include <PubSubClient.h>

Adafruit_MPU6050 mpu;

// Establecemos la comunicación WiFi
const char* ssid ="Wokwi-GUEST";
const char* password = "";

// Inicializamos el broker MQTT disponible para uso
const char* mqtt_server = "io.adafruit.com";
const char* mqtt_username = "ginirocha45";
const char* mqtt_password = "aio_MMvH3605MYZ6LWL48P7oPk0Ug9Jj";

// Generamos los tópicos a usar
const char* SUBTOPIC_TEMP = "ginirocha45/f/temp";
const char* SUBTOPIC_ACEL_X = "ginirocha45/f/acel_x";
const char* SUBTOPIC_ACEL_Y = "ginirocha45/f/acel_y";
const char* SUBTOPIC_ACEL_Z = "ginirocha45/f/acel_z";

WiFiClient espClient;
PubSubClient client(espClient);

//Inicializamos la conexión a internet 
void setup_wifi() {
  delay(10);
  Serial.print("Conectando a ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi conectado");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

//Inicializamos la conexión al broker MQTT 
void reconnect() {
  while (!client.connected()) {
    Serial.println("Intentado conexión MQTT ...");
    String clientId = "esp32-mpu6050-clientId-";
    clientId += String(random(0xffff), HEX);
    if (client.connect(clientId.c_str(),mqtt_username,mqtt_password)) {
      Serial.println("Conectado");
      Serial.println("Topicos Suscritos");
    } else {
      Serial.print("Conexión fallida");
      Serial.print(client.state());
      Serial.println(" Intente en 5 segundos");
      delay(5000);
    }
  }
}

//Inicializamos la publicación de nuestros tópicos
void callback(char *topic, byte *payload, unsigned int length) {
  Serial.print("Topicos recibidos: ");
  Serial.println(topic);

  Serial.print("Payload: ");
  String data = "";
  for (int i = 0; i < length; i++) {
    data += (char)payload[i]; 
  }
  Serial.println(data);
  Serial.print("Tamaño de mensaje: ");
  Serial.println(length);
  
  // Lectura del tópico LED
  /*if (String(topic) == "Jplr1992/f/LED") {
   if (data =="ON") {
     Serial.print("Status LED: ");
     Serial.println(data);
     Serial.println("");
     digitalWrite(LED_PIN, HIGH);
   }
   else {
     digitalWrite(LED_PIN, LOW);
   }
  }*/
}

void setup(void) {
  Serial.begin(115200);

  while (!mpu.begin()) {
    Serial.println("MPU6050 not connected!");
    delay(1000);
  }
  Serial.println("MPU6050 ready!");

  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

sensors_event_t a,g,t;

void loop() {

  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  mpu.getAccelerometerSensor()->getEvent(&a);
  mpu.getTemperatureSensor()->getEvent(&t);
  float ax = a.acceleration.x;
  float ay = a.acceleration.y;
  float az = a.acceleration.z;
  float temp = t.temperature;

  Serial.print("[");
  Serial.print(millis());
  Serial.print("] X: ");
  Serial.print(ax);
  Serial.print(", Y: ");
  Serial.print(ay);
  Serial.print(", Z: ");
  Serial.print(az);
  Serial.println(" m/s^2");
  Serial.println(temp);

  client.publish(SUBTOPIC_TEMP, String(temp, 4).c_str());
  client.publish(SUBTOPIC_ACEL_Z, String(az, 3).c_str());
  client.publish(SUBTOPIC_ACEL_Y, String(ay, 2).c_str());
  client.publish(SUBTOPIC_ACEL_X, String(ax, 1).c_str());

  delay(2000);

}