Skip to main content

device_tests/
connected.rs

1use core::ops::Deref;
2
3use ql_qmi::{ClientBuilder, Connection, Disconnect};
4use tokio::task::JoinHandle;
5
6use crate::device::REQUEST_TIMEOUT;
7
8/// A client whose connection runs in a task.
9#[derive(Debug)]
10pub struct Connected<C> {
11    client: C,
12    connection: JoinHandle<Result<(), Disconnect>>,
13}
14
15impl<C> Connected<C> {
16    /// Connects a client with [`REQUEST_TIMEOUT`] and spawns the connection.
17    ///
18    /// # Errors
19    ///
20    /// Returns an error if the client can't connect.
21    pub fn connect<S>(builder: ClientBuilder<S, C>) -> Result<Self, ql_qmi::Error>
22    where
23        C: From<ql_qmi::Client<S>>,
24    {
25        builder.timeout(REQUEST_TIMEOUT).connect().map(Self::spawn)
26    }
27
28    /// Spawns the connection.
29    pub fn spawn((client, connection): (C, Connection)) -> Self {
30        Self {
31            client,
32            connection: tokio::spawn(connection.run()),
33        }
34    }
35
36    /// Drops the client and waits until the connection has stopped.
37    ///
38    /// Returns how the connection ended, or `None` if its task failed.
39    pub async fn close(self) -> Option<Result<(), Disconnect>> {
40        let Self { client, connection } = self;
41        drop(client);
42        connection.await.ok()
43    }
44}
45
46impl<C> Deref for Connected<C> {
47    type Target = C;
48
49    fn deref(&self) -> &C {
50        &self.client
51    }
52}