Skip to main content

spiritlevel_async/link/
mod.rs

1//! The async driver: [`TmdsLink`] runs spiritlevel's procedures over an async [`TmdsScdc`],
2//! an async `TmdsPhy`, a `Clock` and an async `Delay`, with an optional [`Cancel`] flag.
3
4use core::time::Duration;
5
6use spiritlevel::procedure::{self, TmdsIo};
7
8use crate::{
9    BringUpConfig, BringUpError, BringUpOutcome, Cancel, Clock, Delay, NoCancel, ReconnectCheck,
10    RestoreError, Restored, ScramblingStatus, SinkPresence, SinkTmdsConfig, SinkTmdsFacts,
11    TearDownConfig, TearDownError, Timestamp, TmdsConfigReading, TmdsEvent, TmdsLinkParams,
12    TmdsPhy, TmdsPhyConfig, TmdsScdc, TmdsVideo, TornDown, UpdateError,
13};
14
15/// What a bring-up returns, over the parts' error types.
16type BringUpResult<S, P> = Result<
17    BringUpOutcome<<S as TmdsScdc>::Error, <P as TmdsPhy>::Error>,
18    BringUpError<<S as TmdsScdc>::Error, <P as TmdsPhy>::Error>,
19>;
20
21/// What a quick restore returns, over the parts' error types.
22type RestoreResult<S, P> = Result<
23    Restored<<S as TmdsScdc>::Error>,
24    RestoreError<<S as TmdsScdc>::Error, <P as TmdsPhy>::Error>,
25>;
26
27/// What a tear-down returns, over the parts' error types.
28type TearDownResult<S, P> = Result<
29    TornDown<<S as TmdsScdc>::Error>,
30    TearDownError<<S as TmdsScdc>::Error, <P as TmdsPhy>::Error>,
31>;
32
33#[cfg(test)]
34mod tests;
35
36/// The TMDS procedures over async parts: the sink's SCDC, the PHY, a clock and a delay, and a
37/// cancel flag ([`NoCancel`] unless [`with_cancel`](Self::with_cancel) gives one).
38///
39/// The API is `spiritlevel::TmdsLink`'s, with the procedures `async`: each `.await`s the
40/// parts' calls and the delay, so a procedure yields to the executor wherever the I/O or a
41/// wait does. The driver keeps no state between procedures.
42///
43/// One clock-and-delay value can serve as both: implement `Clock` and `Delay` for a reference
44/// to it, and pass the reference twice. For a `Send` future the shared value must then be
45/// `Sync` (an atomic rather than a `Cell`), or the clock and the delay kept separate.
46#[derive(Debug)]
47pub struct TmdsLink<S, P, K, D, X = NoCancel> {
48    scdc: S,
49    phy: P,
50    clock: K,
51    delay: D,
52    cancel: X,
53}
54
55impl<S: TmdsScdc, P: TmdsPhy, K: Clock, D: Delay> TmdsLink<S, P, K, D, NoCancel> {
56    /// The driver over its parts, never cancelled.
57    pub fn new(scdc: S, phy: P, clock: K, delay: D) -> Self {
58        Self {
59            scdc,
60            phy,
61            clock,
62            delay,
63            cancel: NoCancel,
64        }
65    }
66}
67
68impl<S: TmdsScdc, P: TmdsPhy, K: Clock, D: Delay, X: Cancel> TmdsLink<S, P, K, D, X> {
69    /// The same driver with `cancel` as its cancel flag.
70    ///
71    /// A flag shared with another task is passed by reference, as `&AtomicBool`: [`Cancel`]
72    /// is implemented for the `AtomicBool` and references to it, not for an `Arc` of one.
73    pub fn with_cancel<X2: Cancel>(self, cancel: X2) -> TmdsLink<S, P, K, D, X2> {
74        TmdsLink {
75            scdc: self.scdc,
76            phy: self.phy,
77            clock: self.clock,
78            delay: self.delay,
79            cancel,
80        }
81    }
82
83    /// The parts back.
84    pub fn into_parts(self) -> (S, P, K, D, X) {
85        (self.scdc, self.phy, self.clock, self.delay, self.cancel)
86    }
87
88    /// The SCDC client.
89    pub fn scdc(&self) -> &S {
90        &self.scdc
91    }
92
93    /// The SCDC client, mutably: between procedures, for reads of the caller's own.
94    pub fn scdc_mut(&mut self) -> &mut S {
95        &mut self.scdc
96    }
97
98    /// The PHY.
99    pub fn phy(&self) -> &P {
100        &self.phy
101    }
102
103    /// The PHY, mutably: between procedures, to power it on or off, read its capabilities, or
104    /// drive it in another mode.
105    pub fn phy_mut(&mut self) -> &mut P {
106        &mut self.phy
107    }
108
109    /// The clock the procedures stamp their events from, so a caller can stamp its own on
110    /// the same timebase.
111    pub fn clock(&self) -> &K {
112        &self.clock
113    }
114
115    /// Stops the TMDS link `link` describes; see [`procedure::tear_down`].
116    ///
117    /// Not stopped by the cancel flag: tear-down is the recovery. If its future is dropped
118    /// before it completes, call it again.
119    ///
120    /// # Errors
121    ///
122    /// [`TearDownError`] when a PHY step failed; every step was still attempted.
123    pub async fn tear_down(
124        &mut self,
125        link: &TmdsLinkParams,
126        config: &TearDownConfig,
127        presence: SinkPresence,
128    ) -> TearDownResult<S, P> {
129        self.tear_down_with_events(link, config, presence, &mut |_| {})
130            .await
131    }
132
133    /// [`tear_down`](Self::tear_down), calling `record` with each event, at most
134    /// [`MAX_TEAR_DOWN_EVENTS`](crate::MAX_TEAR_DOWN_EVENTS).
135    ///
136    /// # Errors
137    ///
138    /// As [`tear_down`](Self::tear_down).
139    pub async fn tear_down_with_events(
140        &mut self,
141        link: &TmdsLinkParams,
142        config: &TearDownConfig,
143        presence: SinkPresence,
144        record: &mut impl FnMut(TmdsEvent),
145    ) -> TearDownResult<S, P> {
146        procedure::tear_down(&mut AsyncIo(self), link, config, presence, record).await
147    }
148
149    /// Brings up the TMDS link `link` describes, carrying `video`; see
150    /// [`procedure::bring_up`], which says where the cancel flag is read and what each
151    /// outcome leaves.
152    ///
153    /// Stop it through the cancel flag, never by dropping its future: a dropped bring-up
154    /// stops at whichever `.await` it was suspended on, with no tear-down, and may leave the
155    /// sink holding a new `TMDS_Config` and the PHY configured or transmitting. After one,
156    /// call [`tear_down`](Self::tear_down) with the same `link` before anything else.
157    ///
158    /// # Errors
159    ///
160    /// [`BringUpError`] when a step failed in a way that stops the bring-up.
161    pub async fn bring_up(
162        &mut self,
163        link: &TmdsLinkParams,
164        video: TmdsVideo,
165        config: &BringUpConfig,
166    ) -> BringUpResult<S, P> {
167        self.bring_up_with_events(link, video, config, &mut |_| {})
168            .await
169    }
170
171    /// [`bring_up`](Self::bring_up), calling `record` with each event, at most
172    /// [`MAX_BRING_UP_EVENTS`](crate::MAX_BRING_UP_EVENTS).
173    ///
174    /// # Errors
175    ///
176    /// As [`bring_up`](Self::bring_up).
177    pub async fn bring_up_with_events(
178        &mut self,
179        link: &TmdsLinkParams,
180        video: TmdsVideo,
181        config: &BringUpConfig,
182        record: &mut impl FnMut(TmdsEvent),
183    ) -> BringUpResult<S, P> {
184        procedure::bring_up(&mut AsyncIo(self), link, video, config, record).await
185    }
186
187    /// Checks whether the sink still holds the `TMDS_Config` `link` needs, given the sink's
188    /// facts now; see [`procedure::check_reconnect`].
189    ///
190    /// Not stopped by the cancel flag: it is one read. A dropped check needs nothing done
191    /// after it, since it only reads.
192    pub async fn check_reconnect(
193        &mut self,
194        link: &TmdsLinkParams,
195        current_sink: SinkTmdsFacts,
196    ) -> ReconnectCheck<S::Error> {
197        self.check_reconnect_with_events(link, current_sink, &mut |_| {})
198            .await
199    }
200
201    /// [`check_reconnect`](Self::check_reconnect), calling `record` with each event, at most
202    /// [`MAX_RECONNECT_CHECK_EVENTS`](crate::MAX_RECONNECT_CHECK_EVENTS).
203    pub async fn check_reconnect_with_events(
204        &mut self,
205        link: &TmdsLinkParams,
206        current_sink: SinkTmdsFacts,
207        record: &mut impl FnMut(TmdsEvent),
208    ) -> ReconnectCheck<S::Error> {
209        procedure::check_reconnect(&mut AsyncIo(self), link, current_sink, record).await
210    }
211
212    /// Restores the sink's `TMDS_Config` on the running link `link` without a new bring-up;
213    /// see [`procedure::quick_restore`], which says which settings of `config` it reads.
214    ///
215    /// The cancel flag stops only its scrambling check, read before each of the check's
216    /// reads: the write and the scrambler call always run, and a cancelled check is
217    /// `CheckResult::Cancelled`, with the link left running. Never stop it by dropping its
218    /// future; after a dropped one, call [`tear_down`](Self::tear_down) with the same `link`
219    /// before anything else, or call `quick_restore` again.
220    ///
221    /// # Errors
222    ///
223    /// [`RestoreError`] when the sink's write or the scrambler call failed in a way that
224    /// stops it; no tear-down follows.
225    pub async fn quick_restore(
226        &mut self,
227        link: &TmdsLinkParams,
228        config: &BringUpConfig,
229    ) -> RestoreResult<S, P> {
230        self.quick_restore_with_events(link, config, &mut |_| {})
231            .await
232    }
233
234    /// [`quick_restore`](Self::quick_restore), calling `record` with each event, at most
235    /// [`MAX_QUICK_RESTORE_EVENTS`](crate::MAX_QUICK_RESTORE_EVENTS).
236    ///
237    /// # Errors
238    ///
239    /// As [`quick_restore`](Self::quick_restore).
240    pub async fn quick_restore_with_events(
241        &mut self,
242        link: &TmdsLinkParams,
243        config: &BringUpConfig,
244        record: &mut impl FnMut(TmdsEvent),
245    ) -> RestoreResult<S, P> {
246        procedure::quick_restore(&mut AsyncIo(self), link, config, record).await
247    }
248}
249
250/// [`TmdsIo`] over a [`TmdsLink`]'s parts: each operation `.await`s the part's call.
251struct AsyncIo<'a, S, P, K, D, X>(&'a mut TmdsLink<S, P, K, D, X>);
252
253impl<S: TmdsScdc, P: TmdsPhy, K: Clock, D: Delay, X: Cancel> TmdsIo for AsyncIo<'_, S, P, K, D, X> {
254    type ScdcError = S::Error;
255    type PhyError = P::Error;
256
257    async fn write_tmds_config(&mut self, config: SinkTmdsConfig) -> Result<(), S::Error> {
258        self.0.scdc.write_tmds_config(config).await
259    }
260
261    async fn update_tmds_config(
262        &mut self,
263        config: SinkTmdsConfig,
264    ) -> Result<(), UpdateError<S::Error>> {
265        self.0.scdc.update_tmds_config(config).await
266    }
267
268    async fn read_tmds_config(&mut self) -> Result<TmdsConfigReading, S::Error> {
269        self.0.scdc.read_tmds_config().await
270    }
271
272    async fn read_scrambling_status(&mut self) -> Result<ScramblingStatus, S::Error> {
273        self.0.scdc.read_scrambling_status().await
274    }
275
276    async fn read_sink_version(&mut self) -> Result<u8, S::Error> {
277        self.0.scdc.read_sink_version().await
278    }
279
280    async fn write_source_version(&mut self, version: u8) -> Result<(), S::Error> {
281        self.0.scdc.write_source_version(version).await
282    }
283
284    async fn clear_frl_rate(&mut self) -> Result<(), S::Error> {
285        self.0.scdc.clear_frl_rate().await
286    }
287
288    async fn clear_flt_update(&mut self) -> Result<bool, UpdateError<S::Error>> {
289        self.0.scdc.clear_flt_update().await
290    }
291
292    async fn configure(&mut self, config: TmdsPhyConfig) -> Result<(), P::Error> {
293        self.0.phy.configure(config).await
294    }
295
296    async fn set_scrambling(&mut self, enabled: bool) -> Result<(), P::Error> {
297        self.0.phy.set_scrambling(enabled).await
298    }
299
300    async fn start_output(&mut self) -> Result<(), P::Error> {
301        self.0.phy.start_output().await
302    }
303
304    async fn stop_output(&mut self) -> Result<(), P::Error> {
305        self.0.phy.stop_output().await
306    }
307
308    fn now(&self) -> Timestamp {
309        self.0.clock.now()
310    }
311
312    async fn delay(&mut self, duration: Duration) {
313        self.0.delay.delay(duration).await;
314    }
315
316    fn cancelled(&self) -> bool {
317        self.0.cancel.is_cancelled()
318    }
319}