use anyhow::{Result, anyhow};
use embedded_hal::digital::OutputPin;
use pico_de_gallo_hal::{Gpio, GpioDirection, GpioPull, Hal, SpiDev, SpiPhase, SpiPolarity};
use crate::flash::BusAccess;
const GPIO_CS: u8 = 0; const GPIO_WP: u8 = 1; const GPIO_HOLD: u8 = 2; const GPIO_CRESET: u8 = 3;
pub struct HostBus {
wp: Gpio,
hold: Gpio,
creset: Gpio,
reset: bool,
}
impl BusAccess for HostBus {
type Error = pico_de_gallo_hal::GpioHalError;
fn acquire(&mut self) -> Result<(), Self::Error> {
self.wp.set_config(GpioDirection::Output, GpioPull::None)?;
self.wp.set_high()?;
self.hold
.set_config(GpioDirection::Output, GpioPull::None)?;
self.hold.set_high()?;
if self.reset {
self.creset
.set_config(GpioDirection::Output, GpioPull::None)?;
self.creset.set_low()?;
}
Ok(())
}
fn release(&mut self) -> Result<(), Self::Error> {
if self.reset {
self.creset
.set_config(GpioDirection::Output, GpioPull::None)?;
self.creset.set_high()?;
}
Ok(())
}
}
pub struct Connected {
pub spi: SpiDev,
pub bus: HostBus,
}
pub fn connect(serial: Option<&str>, freq_hz: u32, reset: bool) -> Result<Connected> {
let mut hal = match serial {
Some(sn) => Hal::new_validated_with_serial_number(sn),
None => Hal::new_validated(),
}
.map_err(|e| anyhow!("connect/validate failed (device attached? firmware current?): {e:?}"))?;
let _ = hal.system_reset_subscriptions();
hal.spi_set_config(
freq_hz,
SpiPhase::CaptureOnFirstTransition,
SpiPolarity::IdleLow,
)
.map_err(|e| anyhow!("spi_set_config failed: {e:?}"))?;
let spi = hal
.spi_device(GPIO_CS)
.map_err(|e| anyhow!("spi_device({GPIO_CS}) failed: {e:?}"))?;
let bus = HostBus {
wp: hal.gpio(GPIO_WP),
hold: hal.gpio(GPIO_HOLD),
creset: hal.gpio(GPIO_CRESET),
reset,
};
drop(hal);
Ok(Connected { spi, bus })
}