1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
//! # Kasa
//! A library for interacting with [TP-Link Kasa](https://www.kasasmart.com/) API

use std::error::Error as StdError;
use std::fmt;

use futures::future;
use futures::future::Future;
use futures::stream::Stream;

use hyper;

use uuid;

pub mod error;

use crate::kasa::error::*;

const ENDPOINT: &str = "https://wap.tplinkcloud.com/";

/// A client for interacting with API
pub struct Client<T> {
    client: hyper::Client<T>,
    token: String,
}

impl<T> Client<T>
where
    T: hyper::client::connect::Connect + Sync + 'static,
{
    /// Creates a new client with http client, credentials, and an app name (arbitrary string).
    ///
    /// This method returns a future and should be called in a [tokio](https://tokio.rs) runtime.
    pub fn new(
        client: hyper::Client<T>,
        app: String,
        username: String,
        password: String,
    ) -> impl Future<Item = Client<T>, Error = Error> {
        Self::query(
            &client,
            None,
            Request {
                method: "login".to_string(),
                params: AuthParams::new(app, username, password),
            },
        )
        .and_then(|auth_response: Response<AuthResult>| {
            if let Some(result) = auth_response.result {
                future::ok(Self {
                    client,
                    token: result.token,
                })
            } else {
                future::err(
                    ErrorKind::EmptyAuthResponse(
                        auth_response.error_code,
                        auth_response.message.unwrap_or_else(|| "".to_string()),
                    )
                    .into(),
                )
            }
        })
    }

    /// Send a request to API with an optional token.
    fn query<Q, R>(
        client: &hyper::Client<T>,
        token: Option<&String>,
        request: Request<Q>,
    ) -> impl Future<Item = Response<R>, Error = Error>
    where
        Q: serde::ser::Serialize + std::fmt::Debug,
        R: serde::de::DeserializeOwned + std::fmt::Debug,
    {
        let request_body = match serde_json::to_string(&request)
            .map_err(|e| Error::with_chain(e, ErrorKind::Serialization(format!("{:?}", request))))
        {
            Err(e) => return future::Either::A(future::err(e)),
            Ok(request_body) => request_body,
        };

        let mut http_request = hyper::Request::new(hyper::Body::from(request_body));

        let mut uri = ENDPOINT.to_string();
        if let Some(value) = token {
            uri = uri + &"?token=".to_string() + &value
        }

        let request_uri = match uri.parse().map_err(From::from) {
            Err(e) => return future::Either::A(future::err(e)),
            Ok(request_uri) => request_uri,
        };

        *http_request.method_mut() = hyper::Method::POST;
        *http_request.uri_mut() = request_uri;

        http_request.headers_mut().insert(
            hyper::header::CONTENT_TYPE,
            hyper::header::HeaderValue::from_static("application/json"),
        );

        if cfg!(feature = "kasa_debug") {
            println!("> request:\n{:#?}", request);
        }

        future::Either::B(
            client
                .request(http_request)
                .from_err::<Error>()
                .and_then(|http_response| http_response.into_body().concat2().from_err())
                .and_then(|body| {
                    let body_vec = body.to_vec();
                    serde_json::from_slice(&body_vec).map_err(|e| {
                        Error::with_chain(
                            e,
                            ErrorKind::Serialization(
                                String::from_utf8(body_vec)
                                    .unwrap_or_else(|e| e.description().to_string()),
                            ),
                        )
                    })
                })
                .map(|resp| {
                    if cfg!(feature = "kasa_debug") {
                        println!("< response:\n{:#?}", resp);
                    }
                    resp
                }),
        )
    }

    /// Sends an authenticated request with a token provided by auth request.
    fn token_query<Q, R>(&self, req: Request<Q>) -> impl Future<Item = Response<R>, Error = Error>
    where
        Q: serde::ser::Serialize + std::fmt::Debug,
        R: serde::de::DeserializeOwned + std::fmt::Debug,
    {
        Self::query(&self.client, Some(&self.token), req)
    }

    /// Sends a request directly to device via API.
    fn passthrough_query<R>(
        &self,
        device_id: &str,
        req: &PassthroughParamsData,
    ) -> impl Future<Item = Response<R>, Error = Error>
    where
        R: serde::de::DeserializeOwned + std::fmt::Debug,
    {
        match PassthroughParams::new(device_id.to_owned(), req) {
            Ok(params) => future::Either::A(self.token_query(Request {
                method: "passthrough".to_string(),
                params,
            })),
            Err(e) => future::Either::B(future::err(e.chain_err(|| ErrorKind::PassthtoughParams))),
        }
    }

    /// Returns list of devices available to the client.
    pub fn get_device_list(&self) -> impl Future<Item = Response<DeviceListResult>, Error = Error> {
        self.token_query(Request {
            method: "getDeviceList".to_string(),
            params: DeviceListParams::new(),
        })
    }

    /// Returns emeter measurements from a supplied device.
    pub fn emeter(&self, device_id: &str) -> impl Future<Item = EmeterResult, Error = Error> {
        self.passthrough_query(
            device_id,
            &PassthroughParamsData::new().add_emeter(EMeterParams::new().add_realtime()),
        )
        .and_then(
            |response: Response<PassthroughResult>| match response.result {
                Some(result) => match result.unpack() {
                    Ok(emeter) => future::ok(emeter),
                    Err(e) => future::err(e),
                },
                None => future::err(ErrorKind::EmptyPassthroughResponse.into()),
            },
        )
        .and_then(|w: EmeterResultWrapper| match w.emeter {
            Some(emeter) => future::ok(emeter),
            None => future::err(ErrorKind::EmptyEmeterResponse.into()),
        })
    }
}

impl<T> fmt::Debug for Client<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Kasa {{ token: {} }}", self.token)
    }
}

/// A request to Kasa API.
#[derive(Debug, serde_derive::Serialize)]
struct Request<T> {
    method: String,
    params: T,
}

/// Parameters for authentication request.
#[derive(Debug, serde_derive::Serialize)]
struct AuthParams {
    #[serde(rename = "appType")]
    app_type: String,

    #[serde(rename = "cloudUserName")]
    cloud_user_name: String,

    #[serde(rename = "cloudPassword")]
    cloud_password: String,

    #[serde(rename = "terminalUUID")]
    terminal_uuid: String,
}

impl AuthParams {
    /// Creates authentication request parameters with given credentials.
    fn new(app_type: String, username: String, password: String) -> Self {
        Self {
            app_type,
            cloud_user_name: username,
            cloud_password: password,
            terminal_uuid: uuid::Uuid::new_v4().to_string(),
        }
    }
}

/// A generic response from Kasa API.
#[derive(Debug, serde_derive::Deserialize)]
pub struct Response<T> {
    pub error_code: i32,
    #[serde(rename = "msg")]
    pub message: Option<String>,
    pub result: Option<T>,
}

/// An authentication response data.
#[derive(Debug, serde_derive::Deserialize)]
struct AuthResult {
    #[serde(rename = "accountId")]
    account_id: String,

    email: String,

    token: String,
}

/// Parameters for device list request.
#[derive(Debug, serde_derive::Serialize)]
struct DeviceListParams {}

impl DeviceListParams {
    /// Creates empty device list parameters.
    fn new() -> Self {
        Self {}
    }
}

/// List of devices.
#[derive(Debug, serde_derive::Deserialize)]
pub struct DeviceListResult {
    #[serde(rename = "deviceList")]
    pub device_list: Vec<DeviceListEntry>,
}

/// Device data from listing response.
#[derive(Debug, serde_derive::Deserialize)]
pub struct DeviceListEntry {
    pub alias: String,

    pub status: i32,

    #[serde(rename = "deviceModel")]
    pub model: String,

    #[serde(rename = "deviceId")]
    pub device_id: String,

    #[serde(rename = "deviceHwVer")]
    pub hardware_version: String,

    #[serde(rename = "fwVer")]
    pub firmware_version: String,
}

/// A wrapper for parameters for passthrough (going directly to device) requests.
#[derive(Debug, serde_derive::Serialize)]
struct PassthroughParams {
    #[serde(rename = "deviceId")]
    device_id: String,

    #[serde(rename = "requestData")]
    request_data: String,
}

impl PassthroughParams {
    /// Creates empty passthrough parameters.
    fn new<T: serde::ser::Serialize>(device_id: String, req: &T) -> Result<Self> {
        let request_data = serde_json::to_string(req)?;

        Ok(Self {
            device_id,
            request_data,
        })
    }
}

/// Response data for passthrough requests.
#[derive(Debug, serde_derive::Deserialize)]
pub struct PassthroughResult {
    #[serde(rename = "responseData")]
    response_data: String,
}

impl PassthroughResult {
    /// Unpacks double-encoded passthrough result.
    fn unpack<T>(&self) -> Result<T>
    where
        T: serde::de::DeserializeOwned,
    {
        serde_json::from_str(&self.response_data).map_err(|e| {
            Error::with_chain(e, ErrorKind::Deserialization(self.response_data.clone()))
        })
    }
}

/// Parameters for passthrough requests.
#[derive(Debug, serde_derive::Serialize)]
struct PassthroughParamsData {
    #[serde(skip_serializing_if = "Option::is_none")]
    emeter: Option<EMeterParams>,
}

impl PassthroughParamsData {
    /// Creates empty passthrough parameters.
    fn new() -> Self {
        Self { emeter: None }
    }

    /// Adds query for emeter data.
    fn add_emeter(mut self, emeter: EMeterParams) -> Self {
        self.emeter = Some(emeter);
        self
    }
}

/// Parameters for emeter requests.
#[derive(Debug, serde_derive::Serialize)]
struct EMeterParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    get_realtime: Option<EMeterGetRealtimeParams>,
}

impl EMeterParams {
    /// Creates empty emeter parameters.
    fn new() -> Self {
        Self { get_realtime: None }
    }

    /// Adds query for realtime data.
    fn add_realtime(mut self) -> Self {
        self.get_realtime = Some(EMeterGetRealtimeParams {});
        self
    }
}

/// Parameters for realtime emeter data.
#[derive(Debug, serde_derive::Serialize)]
struct EMeterGetRealtimeParams {}

/// A wrapper for emeter results.
#[derive(Debug, serde_derive::Deserialize)]
struct EmeterResultWrapper {
    emeter: Option<EmeterResult>,
}

/// Results of an emeter request.
#[derive(Debug, serde_derive::Deserialize)]
pub struct EmeterResult {
    pub get_realtime: Option<EmeterGetRealtimeResult>,
}

/// Realtime measurements from an emeter request.
#[derive(Debug, serde_derive::Deserialize)]
pub struct EmeterGetRealtimeResult {
    pub error_code: Option<i32>,
    pub current: Option<f64>,
    pub voltage: Option<f64>,
    pub power: Option<f64>,
}