/*********
  Adrian Zilly
  Briefmelder Fernueberwachung
  Hardware Lib: ESP8622 NodeMCU 1.0 (ESP12E-Module)
  Upload mit GPIO_0 auf Masse
  V1.3 - Batterie auslesen angepasst und verbessert.
*********/

#include <SPI.h>
#include <LoRa.h>
#include <ESP8266WiFi.h>

//--------------------------------------------------
//Define Variables
int Digits = 0;
int DigitsCor = 0;
int BattVolt = 0;
int BattPerc = 0;
int valA0 = 0;

//DEFINE RFM95 LoRa Modul
#define ss 16
#define rst 5
#define dio0 15

//DEFINE GPIO Pins
#define BattVoltIn A0
int BattMess = 4;

//--------------------------------------------------
void BattRead() {
  //Ladestatus auslesen
  digitalWrite(4, HIGH);
  delay(5000);
  //Ampere auslesen
  Digits = analogRead(BattVoltIn);
  DigitsCor = Digits + 0;
  BattVolt = map(DigitsCor, 0, 1002, 0, 4097);
  BattPerc = map(DigitsCor, 840, 1002, 0, 100);
  if (BattPerc > 100) {
    BattRead();
  }
  else {
    digitalWrite(4, LOW);
  }
}

//---------------
void setup() {
  //Cleanup ESP Config
  ESP.eraseConfig();

  //Disable WLAN
  WiFi.mode( WIFI_OFF );
  WiFi.forceSleepBegin();
  delay(100);

  //Pins einstellen
  pinMode(BattMess, OUTPUT);

  //initialize Serial Monitor
  Serial.begin(115200);

  //setup LoRa transceiver module
  LoRa.setPins(ss, rst, dio0);
  while (!LoRa.begin(868E6)) {
    delay(500);
  }
  while (!Serial);
  // The sync word assures you don't get LoRa messages from other LoRa transceiver
  //define the Code for Sending
  //ranges from 0x00-0xff (HEX)
  LoRa.setSyncWord(0x84);
}

//---------------
void loop() {
  BattRead();

  if (BattPerc > 100) {
    BattRead();
  }

  //Send LoRa packet to receiver
  LoRa.beginPacket();
  LoRa.print("Brief erkannt.");
  LoRa.print("BattVolt:");
  LoRa.print(BattVolt);
  LoRa.print("BattPerc:");
  LoRa.print(BattPerc);
  LoRa.endPacket();

  //Cleanup for going to Very Deepsleep
  LoRa.end();
  SPI.end();
  pinMode(ss, INPUT_PULLUP);
  pinMode(rst, INPUT_PULLUP);
  pinMode(dio0, INPUT_PULLUP);
  WiFi.disconnect( true );
  delay( 100 );
  digitalWrite(4, LOW);
  ESP.deepSleep(0, WAKE_RF_DISABLED);
  delay(2000);
}
//--------------------------------------------------
