// LoRa 9x_TX
// -*- mode: C++ -*-
// Example sketch showing how to create a simple messaging client (transmitter)
// with the RH_RF95 class. RH_RF95 class does not provide for addressing or
// reliability, so you should only use RH_RF95 if you do not need the higher
// level messaging abilities.
// It is designed to work with the other example LoRa9x_RX

//

//                           INSTRUCTIONS
//To USE: By default, motors will be off. Open the serial
//monitor and type "motor on" to run the Rover drive motors at max speed.
//To stop motors, send "C" over the serial motitor and motors will stop.

//
 
#include <SPI.h>
#include <RH_RF95.h>
 
#define RFM95_CS 4
#define RFM95_RST 2
#define RFM95_INT 3
 
// Change to 434.0 or other frequency, must match RX's freq!
#define RF95_FREQ 915.0
 
// Singleton instance of the radio driver
RH_RF95 rf95(RFM95_CS, RFM95_INT);
char transmit[20] = "COM ESTABLISHED";
char message_buf[20] = "init";
String input;
String new_message;
void setup() 
{
  
  pinMode(RFM95_RST, OUTPUT);
  digitalWrite(RFM95_RST, HIGH);
 
  while (!Serial);
  Serial.begin(9600);
  delay(100);
 
  Serial.println("Arduino LoRa TX Test!");
 
  // manual reset
  digitalWrite(RFM95_RST, LOW);
  delay(10);
  digitalWrite(RFM95_RST, HIGH);
  delay(10);
 
  while (!rf95.init()) {
    Serial.println("LoRa radio init failed");
    while (1);
  }
  Serial.println("LoRa radio init OK!");
 
  // Defaults after init are 434.0MHz, modulation GFSK_Rb250Fd250, +13dbM
  if (!rf95.setFrequency(RF95_FREQ)) {
    Serial.println("setFrequency failed");
    while (1);
  }
  Serial.print("Set Freq to: "); Serial.println(RF95_FREQ);
  
 
  rf95.setTxPower(23, false);
}
 
int16_t packetnum = 0;  // packet counter, we increment per xmission

 
void loop()
{
  new_message=Serial.readString();
new_message.toCharArray(message_buf, 20);
Serial.println(message_buf);
delay(10);
 //if (!strcmp(message_buf , "COM ESTABLISHED")){
 if(message_buf[0]==0x43){
   Serial.println("Motor is off");
   transmit[0] = 0x43;
   Serial.println(transmit);

 }
   
   Serial.println("Sending to rf95_server");
  // Send a message to rf95_server
  
 // CODE TO SEND MESSAGE STORED IN TRANSMIT
  Serial.print("Sending: "); Serial.println(transmit);
  
  Serial.println("Sending..."); delay(10);
  rf95.send((uint8_t *)transmit, 20);
 
  Serial.println("Waiting for packet to complete..."); delay(10);
  rf95.waitPacketSent();

  uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
  uint8_t len = sizeof(buf);

  Serial.println("Message Transmit Complete"); 


// CHANGE VALUE OF TRANSMIT BACK TO COM ESTABLISHED

 
//Serial.println(transmit);

     // WAIT FOR USER INPUT. INPUT MESSAGE 'motor on' TO BEGIN
   delay(1000);
    while(transmit[0]==0x43|strlen(transmit)<2){
    // Serial.println("Waiting for input...");
  //   delay(100);
    input = Serial.readString();
      input.toCharArray(transmit, 20);
        Serial.println("Waiting to Send");
  // Send a message to rf95_server
    }

  }

