#include <zephyr/kernel.h>
#include <zephyr/device.h>
#include <zephyr/drivers/can.h>
#include <zephyr/sys/printk.h>

#define CAN_NODE DT_CHOSEN(zephyr_canbus)

static const struct device *can_dev = DEVICE_DT_GET(CAN_NODE);

static void can_rx_callback(const struct device *dev,
                            struct can_frame *frame,
                            void *user_data)
{
    printk("CAN RX ID: 0x%03X DLC: %d Data: ",
           frame->id, frame->dlc);

    for (int i = 0; i < frame->dlc; i++) {
        printk("%02X ", frame->data[i]);
    }

    printk("\n");
}

int main(void)
{
    int ret;

    printk("nRF9160 CAN receive test\n");

    if (!device_is_ready(can_dev)) {
        printk("CAN device not ready\n");
        return 0;
    }


    struct can_filter filter = {
        .flags = 0,
        .id = 0x100,
        .mask = CAN_STD_ID_MASK,
    };

    ret = can_add_rx_filter(can_dev, can_rx_callback, NULL, &filter);
    printk("RX filter added successfully\n");
    if (ret < 0) {
        printk("Failed to add CAN RX filter: %d\n", ret);
        return 0;
    }

    ret = can_start(can_dev);
    
    if (ret != 0) {
        printk("Failed to start CAN: %d\n", ret);
        return 0;
    }
    printk("CAN started successfully\n");

    printk("CAN ready, waiting for any CAN message...\n");

    while (1) {
        k_sleep(K_SECONDS(1));
    }
}