Skip to content

Commit

Permalink
Remove callback API
Browse files Browse the repository at this point in the history
  • Loading branch information
fmckeogh committed Oct 26, 2023
1 parent 3148db6 commit 2141dac
Show file tree
Hide file tree
Showing 4 changed files with 88 additions and 97 deletions.
36 changes: 0 additions & 36 deletions usb-pd/src/callback.rs

This file was deleted.

1 change: 0 additions & 1 deletion usb-pd/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

use core::ops::Not;

pub mod callback;
pub mod header;
pub mod message;
pub mod pdo;
Expand Down
127 changes: 74 additions & 53 deletions usb-pd/src/sink.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use crate::{
callback::{CallbackFn, Event as CallbackEvent, Response},
header::{DataMessageType, Header, SpecificationRevision},
message::Message,
pdo::FixedVariableRequestDataObject,
Instant, PowerRole,
};
use defmt::warn;
use {crate::pdo::PowerDataObject, defmt::Format, heapless::Vec};

pub trait Driver {
fn init(&mut self);
Expand All @@ -19,6 +19,31 @@ pub trait Driver {
fn state(&mut self) -> DriverState;
}

/// Sink events
#[derive(Format)]
pub enum Event {
/// Power delivery protocol has changed
ProtocolChanged,
/// Source capabilities have changed (immediately request power)
SourceCapabilitiesChanged(Vec<PowerDataObject, 8>),
/// Requested power has been accepted (but not ready yet)
PowerAccepted,
/// Requested power has been rejected
PowerRejected,
/// Requested power is now ready
PowerReady,
}

/// Requests made to sink
#[derive(Format)]
pub enum Request {
RequestPower {
/// Index of the desired PowerDataObject
index: usize,
current: u16,
},
}

/// Driver state
#[derive(PartialEq, Clone, Copy)]
pub enum DriverState {
Expand Down Expand Up @@ -57,12 +82,10 @@ pub struct Sink<DRIVER> {

/// Specification revision (of last message)
spec_rev: u8,

callback: CallbackFn,
}

impl<DRIVER: Driver> Sink<DRIVER> {
pub fn new(driver: DRIVER, callback: CallbackFn) -> Self {
pub fn new(driver: DRIVER) -> Self {
Self {
driver,
protocol: Protocol::Usb20,
Expand All @@ -71,7 +94,6 @@ impl<DRIVER: Driver> Sink<DRIVER> {
active_voltage: 5000,
active_max_current: 900,
spec_rev: 1,
callback,
}
}

Expand All @@ -80,25 +102,30 @@ impl<DRIVER: Driver> Sink<DRIVER> {
self.update_protocol();
}

pub fn poll(&mut self, now: Instant) {
// process events from PD controller
loop {
self.driver.poll(now);

let Some(evt) = self.driver.get_event() else {
break;
};

match evt {
DriverEvent::StateChanged => {
if self.update_protocol() {
self.notify(CallbackEvent::ProtocolChanged);
}
}
DriverEvent::MessageReceived(message) => {
self.handle_msg(message);
/// Call continously until `None` is returned.
pub fn poll(&mut self, now: Instant) -> Option<Event> {
// poll inner driver
self.driver.poll(now);

let Some(evt) = self.driver.get_event() else {
return None;
};

match evt {
DriverEvent::StateChanged => {
if self.update_protocol() {
Some(Event::ProtocolChanged)
} else {
None
}
}
DriverEvent::MessageReceived(message) => self.handle_msg(message),
}
}

pub fn request(&mut self, request: Request) {
match request {
Request::RequestPower { index, current } => self.request_power(current, index),
}
}

Expand All @@ -116,55 +143,49 @@ impl<DRIVER: Driver> Sink<DRIVER> {
self.protocol != old_protocol
}

fn handle_msg(&mut self, message: Message) {
fn handle_msg(&mut self, message: Message) -> Option<Event> {
match message {
Message::Accept => self.notify(CallbackEvent::PowerAccepted),
Message::Accept => Some(Event::PowerAccepted),
Message::Reject => {
self.requested_voltage = 0;
self.requested_max_current = 0;
self.notify(CallbackEvent::PowerRejected);
Some(Event::PowerRejected)
}
Message::Ready => {
self.active_voltage = self.requested_voltage;
self.active_max_current = self.requested_max_current;
self.requested_voltage = 0;
self.requested_max_current = 0;
self.notify(CallbackEvent::PowerReady);
}
Message::SourceCapabilities(caps) => {
self.notify(CallbackEvent::SourceCapabilitiesChanged(caps))
Some(Event::PowerReady)
}
Message::VendorDefined(payload) => match payload {
crate::pdo::VDMHeader::Structured(hdr) => {
warn!(
"UNHANDLED: Structured VDM! CMD_TYPE: {:?}, CMD: {:?}",
hdr.command_type(),
hdr.command()
);
}
crate::pdo::VDMHeader::Unstructured(hdr) => {
warn!(
"UNHANDLED: Unstructured VDM! SVID: {:x}, DATA: {:x}",
hdr.standard_or_vid(),
hdr.data()
);
Message::SourceCapabilities(caps) => Some(Event::SourceCapabilitiesChanged(caps)),
Message::VendorDefined(payload) => {
match payload {
crate::pdo::VDMHeader::Structured(hdr) => {
warn!(
"UNHANDLED: Structured VDM! CMD_TYPE: {:?}, CMD: {:?}",
hdr.command_type(),
hdr.command()
);
}
crate::pdo::VDMHeader::Unstructured(hdr) => {
warn!(
"UNHANDLED: Unstructured VDM! SVID: {:x}, DATA: {:x}",
hdr.standard_or_vid(),
hdr.data()
);
}
}
},
None
}
Message::SoftReset => {
warn!("UNHANDLED: Soft RESET request.");
None
}
Message::Unknown => unimplemented!(),
}
}

fn notify(&mut self, event: CallbackEvent) {
if let Some(response) = (self.callback)(event) {
match response {
Response::RequestPower { index, current } => self.request_power(current, index),
}
}
}

fn request_power(&mut self, max_current: u16, index: usize) {
// Create 'request' message
let mut payload = [0; 4];
Expand Down Expand Up @@ -215,7 +236,7 @@ pub enum SupplyType {
}

/// Power deliver protocol
#[derive(PartialEq, Clone, Copy)]
#[derive(Format, PartialEq, Clone, Copy)]
enum Protocol {
/// No USB PD communication (5V only)
Usb20,
Expand Down
21 changes: 14 additions & 7 deletions zy12pdn/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,8 @@ use {
timers::Timer,
},
usb_pd::{
callback::{Event, Response},
pdo::PowerDataObject,
sink::Sink,
sink::{Event, Request, Sink},
},
};

Expand All @@ -31,9 +30,10 @@ type PdSink = Sink<Fusb302b<I2cBB<PA10<Output<PushPull>>, PA9<Output<OpenDrain>>

#[app(device = stm32f0xx_hal::pac, peripherals = true, dispatchers = [SPI1])]
mod app {
use crate::handle_event;

use {
crate::{
callback,
rgb::{Color, Rgb},
Led, PdSink,
},
Expand Down Expand Up @@ -121,7 +121,7 @@ mod app {
let mut pd = {
let clk = Timer::tim3(cx.device.TIM3, 400.khz(), &mut rcc);
let i2c = I2cBB::new(scl, sda, clk);
Sink::new(Fusb302b::new(i2c), &callback)
Sink::new(Fusb302b::new(i2c))
};

pd.init();
Expand All @@ -138,7 +138,14 @@ mod app {
#[idle(local = [pd])]
fn idle(cx: idle::Context) -> ! {
loop {
cx.local.pd.poll(monotonics::now());
cx.local
.pd
// poll PD driver
.poll(monotonics::now())
// handle event if one was returned from sink
.and_then(handle_event)
// make request if one was returned from handler
.map(|req| cx.local.pd.request(req));
}
}

Expand All @@ -154,7 +161,7 @@ mod app {
}
}

fn callback(event: Event) -> Option<Response> {
fn handle_event(event: Event) -> Option<Request> {
match event {
Event::SourceCapabilitiesChanged(caps) => {
info!("Capabilities changed: {}", caps.len());
Expand All @@ -181,7 +188,7 @@ fn callback(event: Event) -> Option<Response> {

info!("requesting supply {:?}@{}", supply, index);

return Some(Response::RequestPower {
return Some(Request::RequestPower {
index,
current: supply.max_current() * 10,
});
Expand Down

0 comments on commit 2141dac

Please sign in to comment.