// ESP32 Dev Module

#include "Wire.h"

#include <OSCBoards.h>
#include <OSCMessage.h>
/*
Make an OSC message and send it over serial
 */

#ifdef BOARD_HAS_USB_SERIAL
#include <SLIPEncodedUSBSerial.h>
SLIPEncodedUSBSerial SLIPSerial( thisBoardsSerialUSB );
#else
#include <SLIPEncodedSerial.h>
 SLIPEncodedSerial SLIPSerial(Serial); // Change to Serial1 or Serial2 etc. for boards with multiple serial ports that don’t have Serial
#endif

/*
#include <BluetoothSerial.h>
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

BluetoothSerial SerialBT;
*/

const int MPU_addr=0x68; // I2C address of the MPU-6050 

// Sem dobimo vrednosti
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;

void setup() {
  Wire.begin();
  SLIPSerial.begin(9600);   // set this as high as you can reliably run on your platform 
  
  Wire.begin(21, 22, 100000); // sda, scl, clock speed
  //check_I2c(MPU_addr);
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B); // PWR_MGMT_1 register
  Wire.write(0); // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
  delay(30); // Ensure gyro has enough time to power up
  /*
  SerialBT.begin("MotionGlove");
  */
}

void loop() {
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true); // request a total of 14 registers
  AcX=Wire.read()<<8|Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp=Wire.read()<<8|Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  GyX=Wire.read()<<8|Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  GyZ=Wire.read()<<8|Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)

  OSCMessage msg("/accel/");
  msg.add(AcX);
  msg.add(AcY);
  msg.add(AcZ);
  
  SLIPSerial.beginPacket();
  msg.send(SLIPSerial);
  SLIPSerial.endPacket();
  msg.empty();

  OSCMessage gmsg("/gyro/");
  gmsg.add(GyX);
  gmsg.add(GyY);
  gmsg.add(GyZ);
  
  SLIPSerial.beginPacket();
  gmsg.send(SLIPSerial);
  SLIPSerial.endPacket();
  gmsg.empty();

  OSCMessage tmsg("/temp/");
  tmsg.add(Tmp); 
  
  SLIPSerial.beginPacket();
  tmsg.send(SLIPSerial);
  SLIPSerial.endPacket();
  tmsg.empty();
}

byte check_I2c(byte addr){
  Serial.println("Looking for sensor...");
  
  // We are using the return value of
  // the Write.endTransmisstion to see if
  // a device did acknowledge to the address.
  byte error;
  Wire.beginTransmission(addr);
  error = Wire.endTransmission();
   
  if (error == 0) {
    Serial.print(" Device Found at 0x");
    Serial.println(addr,HEX);
  } else {
    Serial.print(" No Device Found at 0x");
    Serial.println(addr,HEX);
  }
  return error;
}
