#include <Arduino.h>
#include <SPI.h>
#include <RadioLib.h>

#ifndef LORA_FREQ
#define LORA_FREQ 915.000
#endif

#ifndef LORA_SF
#define LORA_SF 7
#endif

#ifndef LORA_BW
#define LORA_BW 125
#endif

#ifndef LORA_CR
#define LORA_CR 5
#endif

/**
 * This sketch is intended to be used as a quick test of the LoRa radio on the 
 * T-Beam Supreme board, to verify that the radio is functional and can be used 
 * in a USB-connected application.
 * It will attempt to initialize the radio, and then repeatedly transmit a test 
 * frame and call startReceive() to verify that the radio is responsive.
 * Note that this sketch is not intended to be a full test of the radio's 
 * functionality, but rather a quick check that the radio can be initialized 
 * and used without errors. If you are seeing  -706 or -707 errors, it likely means 
 * that the radio is not starting up correctly, which can be caused by incorrect 
 * pin connections or power issues. If you are seeing other errors, it may indicate 
 * a different issue with the radio or the code.
 */

// SX1262 on T-Beam Supreme (tbeam-s3-core pinout)
SX1262 radio = new Module(LORA_CS, LORA_DIO1, LORA_RESET, LORA_BUSY);
int state; // = radio.begin(915.0, 125.0, 7, 5, 0x12, 14);

/*
  @brief Setup function. Initializes the radio and prints the result to the serial console.
*/
void setup() {
  Serial.begin(115200);
  delay(2000);   // give USB time to enumerate
  Serial.println("Booting LoRa test...");
  Serial.println();

  Serial.println("Initializing radio...");
  SPI.begin(LORA_SCK, LORA_MISO, LORA_MOSI, LORA_CS);
  Serial.printf("Radio chip: SX1262\r\n");
  Serial.printf("Frequency: %.3f MHz\r\n", (double)LORA_FREQ);
  Serial.printf("SF: %d BW: %d CR: %d\r\n", LORA_SF, LORA_BW, LORA_CR);

  int state = radio.begin(915.0, 125.0, 7, 5, 0x12, 14);
  
  Serial.printf("radio.begin returned: %d\r\n", state);



}
/*
  @brief Loop function. Transmits a test frame and calls startReceive() to verify that 
  the radio is responsive. Repeats every second.
*/
void loop() {
  static uint32_t counter = 0;
  Serial.printf("alive %lu\n", counter++);
  
  Serial.println("Sending test frame...");
  int tx = radio.transmit("USB RADIO CHECK");
  Serial.printf("TX state: %d\r\n", tx);

  // we're not expecting to receive anything, just testing that we
  // can call Receive()
  Serial.println("Starting receive...");
  state = radio.startReceive();
  Serial.printf("startReceive returned: %d\r\n", state);
  delay(1000);
}
