#include <stdio.h>
#include <string.h>
#include "pico/stdlib.h"
#include "pico/binary_info.h"
#include "LoRa-RP2040.h"
#include "Config.h"
#include "KISS.h"

bool startRadio();

int main() {
  
    /* Among others, this initializes the USB-serial port at 115200bps 8N1 */
    stdio_init_all();
    
    printf("Hello, world!\n");
    
/*      while (1) {
      printf("1");
      sleep_ms(1000);
    }
*/

  // override the default CS, reset, and IRQ pins (optional)
  // LoRa.setPins(7, 6, 1); // set CS, reset, IRQ pin

  sleep_ms(5000);
  printf("loraFrequency = %u\n", loraFrequency);
  startRadio();
    
int counter = 0;
   
   while (1) {
      int packetSize = LoRa.parsePacket();
      if (packetSize) {
         // received a packet
         printf("Received packet \n");

         // TODO: read packet into array and check if APRS header is correct (header  = 0x3C 0xFF 0x01)
         // If it all checks out, remove the header from the string
         while (LoRa.available()) {
            printf("%c", LoRa.read());
         }

         // print RSSI of packet
         printf(" (RSSI = %idBm)\n",LoRa.packetRssi());
      }
  }    
  
  return 0;
}

/*
 * Initializes the LoRa module with the parameters set in config.h
 */
bool startRadio() {
    
  printf("Starting LoRa radio");
  if (!LoRa.begin(loraFrequency)) {
    //kissIndicateError(ERROR_INITRADIO);
    printf("  [ FAILED ]\n");
    while(1);
  }
  else {
    LoRa.setPreambleLength(loraPreamble);
    LoRa.setSignalBandwidth(loraBandwidth);
    LoRa.setTxPower(loraTxPower,LoRaPaSelect);
    LoRa.setSpreadingFactor(loraSpreadingFactor);
    LoRa.setCodingRate4(loraCodingRate);
    LoRa.enableCrc();
    //LoRa.onReceive(receiveCallback);
    //LoRa.receive();
    printf("  [ DONE ]\n");
  }
}
