#include <Wire.h>
#include <DHT.h>
#include <Wire.h>
#include <LoRa.h>

#define DHTPIN 2
#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);

const int MPU_addr = 0x68;
int16_t AcX, AcY, AcZ, GyX, GyY, GyZ;
float temperature, humidity;

void setup() {
  Serial.begin(9600);
  while (!Serial);

  if (!LoRa.begin(915E6)) {
    Serial.println("LoRa initialization failed. Check your connections.");
    while (1);
  }

  Wire.begin();
  dht.begin();
}

void loop() {
  // Read DHT11 sensor data
  humidity = dht.readHumidity();
  temperature = dht.readTemperature();

  // Read MPU6050 accelerometer and gyroscope data
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr, 14, true);
  AcX = Wire.read()<<8|Wire.read();
  AcY = Wire.read()<<8|Wire.read();
  AcZ = Wire.read()<<8|Wire.read();
  GyX = Wire.read()<<8|Wire.read();
  GyY = Wire.read()<<8|Wire.read();
  GyZ = Wire.read()<<8|Wire.read();

  // Prepare data payload
  String payload = "{\"temperature\":" + String(temperature) + ",\"humidity\":" + String(humidity) +
                   ",\"accelX\":" + String(AcX) + ",\"accelY\":" + String(AcY) + ",\"accelZ\":" + String(AcZ) +
                   ",\"gyroX\":" + String(GyX) + ",\"gyroY\":" + String(GyY) + ",\"gyroZ\":" + String(GyZ) + "}";

  // Send payload over LoRa
  LoRa.beginPacket();
  LoRa.print(payload);
  LoRa.endPacket();

  Serial.println("Data sent: " + payload);

  delay(10000);  // Send data every 10 seconds
}