#include "ky_038.h"
#include <zephyr/drivers/gpio.h>
#include <zephyr/device.h>
#include <zephyr/devicetree.h>
#include <zephyr/devicetree/gpio.h>

#define KY038_GPIO_PIN  DT_GPIO_PIN(DT_ALIAS(ky038), output_gpios)
#define KY038_GPIO_FLAGS DT_GPIO_FLAGS(DT_ALIAS(ky038), output_gpios)

static const struct device *gpio_dev;
// Define the node ID directly
#define KY038_SENSOR_NODE DT_NODELABEL(ky038_sensor)  // Use the node label defined in your overlay

static const struct device *gpio_dev;

/**
 * @brief Initialize KY-038 sensor
 */
int ky_038_init(void)
{
    // Get the GPIO device from the node defined in the DeviceTree
    // gpio_dev = device_get_binding(DT_GPIO_LABEL(KY038_SENSOR_NODE, output_gpios));
    if (gpio_dev == NULL) {
        printk("Error: Failed to bind GPIO device\n");
        return -1;
    }

    // Configure the GPIO pin
    gpio_pin_configure(gpio_dev, DT_GPIO_PIN(KY038_SENSOR_NODE, output_gpios), GPIO_INPUT | DT_GPIO_FLAGS(KY038_SENSOR_NODE, output_gpios));
    return 0;
}
/**
 * @brief Check KY-038 sensor status
 * 
 * @return int
 *      1 if sound is detected, 0 if no sound, -1 on error
 */
int ky_038_check_status(void)
{
    if (gpio_dev == NULL) {
        printk("KY-038 sensor not initialized\n");
        return -1;
    }

    int val = gpio_pin_get(gpio_dev, KY038_GPIO_PIN);
    if (val < 0) {
        printk("Error reading KY-038 sensor\n");
        return -1;
    }

    return val;
}
