/* Copyright 2021 The Chromium OS Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

/* Volteer family-specific USB-C configuration */

#include "common.h"
#include "charge_manager.h"
#include "charge_ramp.h"
#include "charge_state.h"
#include "gpio.h"
#include "task.h"
#ifdef CONFIG_ZEPHYR
#include "usbc_config.h"
#include "baseboard_usbc_config.h"
#endif
#include "usbc_ppc.h"
#include "usb_pd.h"
#include "usb_charge.h"
#include "util.h"
#include "driver/charger/isl9241_public.h"

/******************************************************************************/
void tcpc_alert_event(enum gpio_signal signal)
{
	/* TODO: b/140572591 - check correct operation for Volteer */

	int port = -1;

	switch (signal) {
	case GPIO_USB_C0_TCPC_INT_ODL:
		port = USBC_PORT_C0;
		break;
	case GPIO_USB_C1_TCPC_INT_ODL:
		port = USBC_PORT_C1;
		break;
	default:
		return;
	}

	schedule_deferred_pd_interrupt(port);
}

void bc12_interrupt(enum gpio_signal signal)
{
	switch (signal) {
	case GPIO_USB_C0_BC12_INT_ODL:
		task_set_event(TASK_ID_USB_CHG_P0, USB_CHG_EVENT_BC12);
		break;

	case GPIO_USB_C1_BC12_INT_ODL:
		task_set_event(TASK_ID_USB_CHG_P1, USB_CHG_EVENT_BC12);
		break;

	default:
		break;
	}
}

/**
 * Return if VBUS is too low
 */
int board_is_vbus_too_low(int port, enum chg_ramp_vbus_state ramp_state)
{
	int voltage;

	if (charger_get_vbus_voltage(port, &voltage))
		voltage = 0;

	/*
	 * For legacy BC1.2 charging with CONFIG_CHARGE_RAMP_SW, ramp up input
	 * current until voltage drops to the minimum input voltage of the
	 * charger, 4.096V.
	 */
	return voltage < ISL9241_BC12_MIN_VOLTAGE;
}
