/**
 * usbc_mux.c
 *
 * Low level control of the PI3USB31532 USB-C crossbar multiplexer over I2C.
 * 
 * Copyright (c) 2022 Bigscreen, Inc.
 */

#include <asf.h>
#include "adc.h"
#include "i2c.h"
#include "usbc_mux.h"

void usbc_mux_flip(I2C_Handle* hi2c, USB_Flip_State_t flip) {
	I2C_Transaction_Request i2ctxn;
	uint8_t dummy_byte;
	
	i2ctxn.cb = NULL;
	i2ctxn.dev_addr = USBC_MUX_ADDR;
	i2ctxn.shift = I2C_Unshifted;
	i2ctxn.internal_addr = 0; // Using 0 as internal address, this byte is actually ignored
	i2ctxn.data = &dummy_byte;
	i2ctxn.len = 1;
	i2ctxn.ttype = I2C_INT_ADDR_WRITE;
	// Sets the multiplexer flip depending on the orientation of the USBC plug
	i2c_lock(hi2c);
	if(flip == Flip_CC1) {
		dummy_byte = USBC_MUX_FLIP_CC2; // oops I had it backwardses

		i2c_transact_blocking(hi2c, &i2ctxn, DEFAULT_I2C_WAIT_TIME);
	} else if(flip == Flip_CC2) {
		dummy_byte = USBC_MUX_FLIP_CC1; // oops I had it backwardses
		i2c_transact_blocking(hi2c, &i2ctxn, DEFAULT_I2C_WAIT_TIME);
	} else {
		// Disable the mux if incorrect flip state received
		dummy_byte = USBC_MUX_DISABLE;
		i2c_transact_blocking(hi2c, &i2ctxn, DEFAULT_I2C_WAIT_TIME);
	}
	i2c_unlock(hi2c);
}
