#include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
#include <zephyr/drivers/gpio.h>
#include "power.h"
#include "lora.h"

LOG_MODULE_REGISTER(main);

const struct device* lora_dev = DEVICE_DT_GET(DT_ALIAS(lora0)); // spi2 is connected to lora module


/* ============================================================
 *  main()
 * ============================================================ */

int main(void)
{
    LOG_INF("LoRA Application Started\n");

    int ret = 0; 


    /************************ LoRA *******************************/
    k_msleep(5000); // Wait for monitor to be connected (debugging)
    LOG_INF("LORAWAN INIT");
    uint8_t channel = 5; // Uplink channel to use (0-7 for EU868)
    lorawan_init(lora_dev, LORAWAN_DR_2, channel); // Initialize LoRaWAN (possible chhannels: 0 through 7 for EU868)


    while (1) {
        uint8_t data[] = {0x01, 0x02, 0x03}; // Test data
        LOG_INF("Sending data... \n");
        ret = lorawan_send_data(data, 3); // Try sending data
        if (ret == -ENOTCONN) { // If we are not joined, join the network
            LOG_INF("Rejoining...");
            lorawan_join_network();
            // Send data
            LOG_INF("Sending data... \n");
            ret = lorawan_send_data(data, 3);
        }
        else if (ret != 0) {
            LOG_ERR("Failed to send data: %d", ret);
        }
        else {
            LOG_INF("Data sent successfully");
        }

        k_msleep(10000); // Wait for 10 seconds before sending the next data
    }
}
