Skip to main content

hive_client/client/wrapper/
product.rs

1use crate::products::{Product, States};
2use crate::{ApiError, Client};
3
4impl Client {
5    /// Get all of the Hive products setup in the Hive account.
6    ///
7    /// For example, the Heating or Hot Water products.
8    ///
9    /// # Examples
10    ///
11    /// ```no_run
12    /// use hive_client::authentication::{TrustedDevice, User};
13    /// use hive_client::products::{Product, ProductData, State, States};
14    ///
15    /// # tokio_test::block_on(async {
16    /// let client = hive_client::Client::new("Home Automation");
17    ///
18    /// let trusted_device = Some(TrustedDevice::new(
19    ///     "device_password",
20    ///     "device_group_key",
21    ///     "device_key"
22    /// ));
23    ///
24    /// let attempt = client.login(User::new("example@example.com", "example"), trusted_device).await;
25    ///
26    /// if let Ok(_) = attempt {
27    ///     // Login was successful
28    ///
29    ///     let products = client.get_products()
30    ///         .await
31    ///         .expect("Products should be retrieved");
32    ///     
33    ///     println!("{:?}", products);
34    /// }
35    /// # })
36    /// ```
37    ///
38    /// # Errors
39    ///
40    /// Returns an error if the list of products could not be retrieved.
41    pub async fn get_products(&self) -> Result<Vec<Product<'_>>, ApiError> {
42        self.api
43            .get_product_data(&*self.refresh_tokens_if_needed().await?)
44            .await
45            .map(|products| {
46                products
47                    .into_iter()
48                    .map(|data| Product::new(self, data))
49                    .collect()
50            })
51    }
52
53    /// Set a series of states on a product by a given ID.
54    ///
55    /// Wrapped by [`Product::set_state`] to set the states on a returned Product.
56    pub(crate) async fn set_product_state(
57        &self,
58        product_id: &str,
59        r#type: &str,
60        states: States,
61    ) -> Result<bool, ApiError> {
62        self.api
63            .set_product_state(
64                &*self.refresh_tokens_if_needed().await?,
65                product_id,
66                r#type,
67                states,
68            )
69            .await
70    }
71}