/*
 * Copyright (c) 2018 Aapo Vienamo
 *
 * SPDX-License-Identifier: Apache-2.0
 */

#include <init.h>
#include <drivers/gpio.h>
#include <sys/printk.h>
#include <kernel.h>

#define VDD_PWR_CTRL_GPIO_PIN 		2
#define UART_OE_PWR_CTRL_GPIO_PIN	0
#define MUX_SPS30_PWR_CTRL_GPIO_PIN	1

struct pwr_ctrl_cfg {
	const char *port;
	uint32_t pin;
};

static int pwr_ctrl_init(const struct device *dev)
{
	const struct pwr_ctrl_cfg *cfg = dev->config;
	const struct device *gpio;

	gpio = device_get_binding(cfg->port);
	if (!gpio) {
		printk("Could not bind device \"%s\"\n", cfg->port);
		return -ENODEV;
	}

	gpio_pin_configure(gpio, cfg->pin, GPIO_OUTPUT_HIGH);

#ifdef CONFIG_MULTITHREADING
	k_sleep(K_MSEC(100));
#else
	k_busy_wait(100000);
#endif
	//k_sleep(K_MSEC(100)); /* Wait for the rail to come up and stabilize */

	return 0;
}

static const struct pwr_ctrl_cfg vdd_pwr_ctrl_cfg = {
	.port = DT_LABEL(DT_NODELABEL(gpio0)),
	.pin = VDD_PWR_CTRL_GPIO_PIN,
};

static const struct pwr_ctrl_cfg uart_oe_pwr_ctrl_cfg = {
	.port = DT_LABEL(DT_NODELABEL(gpio0)),
	.pin = UART_OE_PWR_CTRL_GPIO_PIN,
};

static const struct pwr_ctrl_cfg mux_sps30_pwr_ctrl_cfg = {
	.port = DT_LABEL(DT_NODELABEL(gpio0)),
	.pin = MUX_SPS30_PWR_CTRL_GPIO_PIN,
};

DEVICE_DEFINE(vdd_pwr_ctrl_init, "", pwr_ctrl_init, NULL, NULL,
	      &vdd_pwr_ctrl_cfg,
	      POST_KERNEL, 50,
	      NULL);

DEVICE_DEFINE(uart_oe_pwr_ctrl_init, "", pwr_ctrl_init, NULL, NULL,
	      &uart_oe_pwr_ctrl_cfg,
	      POST_KERNEL, 50,
	      NULL);

DEVICE_DEFINE(mux_sps30_pwr_ctrl_init, "", pwr_ctrl_init, NULL, NULL,
	      &mux_sps30_pwr_ctrl_cfg,
	      POST_KERNEL, 50,
	      NULL);