Skip to content

Commit

Permalink
Small tweaks
Browse files Browse the repository at this point in the history
  • Loading branch information
mihai-dinculescu committed Mar 29, 2024
1 parent 040be15 commit a9fdd53
Show file tree
Hide file tree
Showing 6 changed files with 43 additions and 29 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,15 @@ file. This change log follows the conventions of

- The implementation of `ApiClient::new` has been improved to allow for the return of `ApiClient` instead of `Result<ApiClient, Error>`.
- The default timeout for all requests has been reduced to 30 seconds from 300 seconds.
- `ApiClient::with_timeout` has been added to allow for the setting of a custom timeout for all requests (thanks to @skoky).

## [Python Unreleased][Unreleased]

### Changed

- The default timeout for all requests has been reduced to 30 seconds from 300 seconds.
- The `timeout_s` optional parameter has been added to the `ApiClient` constructor to allow for the setting of a custom timeout for all requests (thanks to @skoky).

## [Rust v0.7.9][v0.7.9] - 2024-01-27

### Changed
Expand Down
2 changes: 1 addition & 1 deletion tapo-py/examples/tapo_p100.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ async def main():
tapo_password = os.getenv("TAPO_PASSWORD")
ip_address = os.getenv("IP_ADDRESS")

client = ApiClient(tapo_username, tapo_password, timeout_secs=10)
client = ApiClient(tapo_username, tapo_password)
device = await client.p100(ip_address)

print("Turning device on...")
Expand Down
16 changes: 12 additions & 4 deletions tapo-py/src/api_client.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::time::Duration;
use pyo3::prelude::*;
use std::time::Duration;
use tapo::ApiClient;

use crate::errors::ErrorWrapper;
Expand All @@ -16,9 +16,17 @@ pub struct PyApiClient {
#[pymethods]
impl PyApiClient {
#[new]
pub fn new(tapo_username: String, tapo_password: String, timeout_secs: Option<u64>) -> Result<Self, ErrorWrapper> {
let client = ApiClient::new(tapo_username, tapo_password)
.with_timeout(Duration::from_secs(timeout_secs.unwrap_or(30)));
pub fn new(
tapo_username: String,
tapo_password: String,
timeout_s: Option<u64>,
) -> Result<Self, ErrorWrapper> {
let client = match timeout_s {
Some(timeout_s) => ApiClient::new(tapo_username, tapo_password)
.with_timeout(Duration::from_secs(timeout_s)),
None => ApiClient::new(tapo_username, tapo_password),
};

Ok(Self { client })
}

Expand Down
12 changes: 6 additions & 6 deletions tapo-py/tapo-py/tapo/api_client.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,13 @@ Example:
See [more examples](https://github.com/mihai-dinculescu/tapo/tree/main/tapo-py/examples).
"""

from typing import Optional
from .color_light_handler import ColorLightHandler
from .generic_device_handler import GenericDeviceHandler
from .light_handler import LightHandler
from .plug_energy_monitoring_handler import PlugEnergyMonitoringHandler
from .plug_handler import PlugHandler


class ApiClient:
"""Tapo API Client.
Expand All @@ -52,13 +52,13 @@ class ApiClient:
See [more examples](https://github.com/mihai-dinculescu/tapo/tree/main/tapo-py/examples).
"""

def __init__(self, tapo_username: str, tapo_password: str, timeout_secs: int = 10) -> None:
def __init__(self, tapo_username: str, tapo_password: str, timeout_s: int = 30) -> None:
"""Returns a new instance of `ApiClient`.
Args:
tapo_username (str): The Tapo username
tapo_password (str): The Tapo password
timeout_secs (int): connection timeout secs, default value 10secs
tapo_username (str): The Tapo username.
tapo_password (str): The Tapo password.
timeout_s (int): The connection timeout in seconds. The default value is 30 seconds.
Returns:
ApiClient: Tapo API Client.
Expand All @@ -70,7 +70,7 @@ class ApiClient:
async def main():
client = ApiClient("[email protected]", "tapo-password", 10)
client = ApiClient("[email protected]", "tapo-password")
device = await client.l530("192.168.1.100")
await device.on()
Expand Down
1 change: 0 additions & 1 deletion tapo/examples/tapo_p100.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let ip_address = env::var("IP_ADDRESS")?;

let device = ApiClient::new(tapo_username, tapo_password)
.with_timeout(Duration::from_secs(3))
.p100(ip_address)
.await?;

Expand Down
35 changes: 18 additions & 17 deletions tapo/src/api/api_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,24 @@ use std::fmt;
use std::time::Duration;

use async_trait::async_trait;
use isahc::HttpClient;
use isahc::prelude::Configurable;
use isahc::HttpClient;
use log::debug;
use serde::de::DeserializeOwned;

use crate::api::protocol::{TapoProtocol, TapoProtocolExt};
use crate::api::{
ColorLightHandler, ColorLightStripHandler, GenericDeviceHandler, HubHandler, LightHandler,
PlugEnergyMonitoringHandler, PlugHandler,
};
use crate::api::protocol::{TapoProtocol, TapoProtocolExt};
use crate::error::{Error, TapoResponseError};
use crate::requests::{
ControlChildParams, EmptyParams, EnergyDataInterval, GetEnergyDataParams, LightingEffect,
MultipleRequestParams, TapoParams, TapoRequest,
};
use crate::responses::{
ControlChildResult, CurrentPowerResult, DecodableResultExt, EnergyDataResult,
EnergyUsageResult, TapoMultipleResponse, TapoResponseExt, TapoResult, validate_response,
validate_response, ControlChildResult, CurrentPowerResult, DecodableResultExt,
EnergyDataResult, EnergyUsageResult, TapoMultipleResponse, TapoResponseExt, TapoResult,
};

const TERMINAL_UUID: &str = "00-00-00-00-00-00";
Expand Down Expand Up @@ -68,7 +68,8 @@ impl ApiClient {
/// * `tapo_username` - the Tapo username
/// * `tapo_password` - the Tapo password
///
/// Note: uses default connection timeout value of 30 secs
/// Note: The default connection timeout is 30 seconds.
/// Use [`ApiClient::with_timeout`] to change it.
pub fn new(tapo_username: impl Into<String>, tapo_password: impl Into<String>) -> ApiClient {
Self {
tapo_username: tapo_username.into(),
Expand All @@ -78,11 +79,11 @@ impl ApiClient {
}
}

/// changes connection timout from default value to new custom value
/// Changes the connection timeout from the default value to the given value.
///
/// # Arguments
///
/// * `timeout` - the timeout value
/// * `timeout` - The new connection timeout value.
pub fn with_timeout(mut self, timeout: Duration) -> ApiClient {
self.timeout = Some(timeout);
self
Expand Down Expand Up @@ -494,8 +495,8 @@ impl ApiClient {
}

pub(crate) async fn get_device_info<R>(&self) -> Result<R, Error>
where
R: fmt::Debug + DeserializeOwned + TapoResponseExt + DecodableResultExt,
where
R: fmt::Debug + DeserializeOwned + TapoResponseExt + DecodableResultExt,
{
debug!("Get Device info...");
let request = TapoRequest::GetDeviceInfo(TapoParams::new(EmptyParams));
Expand All @@ -508,8 +509,8 @@ impl ApiClient {
}

pub(crate) async fn get_device_usage<R>(&self) -> Result<R, Error>
where
R: fmt::Debug + DeserializeOwned + TapoResponseExt,
where
R: fmt::Debug + DeserializeOwned + TapoResponseExt,
{
debug!("Get Device usage...");
let request = TapoRequest::GetDeviceUsage(TapoParams::new(EmptyParams));
Expand Down Expand Up @@ -574,8 +575,8 @@ impl ApiClient {
}

pub(crate) async fn get_child_device_list<R>(&self) -> Result<R, Error>
where
R: fmt::Debug + DeserializeOwned + TapoResponseExt + DecodableResultExt,
where
R: fmt::Debug + DeserializeOwned + TapoResponseExt + DecodableResultExt,
{
debug!("Get Child device list...");
let request = TapoRequest::GetChildDeviceList(TapoParams::new(EmptyParams));
Expand All @@ -588,8 +589,8 @@ impl ApiClient {
}

pub(crate) async fn get_child_device_component_list<R>(&self) -> Result<R, Error>
where
R: fmt::Debug + DeserializeOwned + TapoResponseExt + DecodableResultExt,
where
R: fmt::Debug + DeserializeOwned + TapoResponseExt + DecodableResultExt,
{
debug!("Get Child device component list...");
let request = TapoRequest::GetChildDeviceComponentList(TapoParams::new(EmptyParams));
Expand All @@ -606,8 +607,8 @@ impl ApiClient {
device_id: String,
child_request: TapoRequest,
) -> Result<Option<R>, Error>
where
R: fmt::Debug + DeserializeOwned + TapoResponseExt,
where
R: fmt::Debug + DeserializeOwned + TapoResponseExt,
{
debug!("Control child...");
let params = MultipleRequestParams::new(vec![child_request]);
Expand Down

0 comments on commit a9fdd53

Please sign in to comment.