Skip to main content

appium_client/commands/
network.rs

1//! Network management
2use async_trait::async_trait;
3use bitflags::bitflags;
4use fantoccini::error::CmdError;
5use http::Method;
6use serde_json::json;
7use crate::{AndroidClient, AppiumClientTrait};
8use crate::commands::AppiumCommand;
9
10bitflags! {
11    #[repr(transparent)]
12    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
13    pub struct ConnectionState: u16 {
14        const AIRPLANE_MODE_MASK = 0b001;
15        const WIFI_MASK = 0b010;
16        const DATA_MASK = 0b100;
17    }
18}
19
20/// Check network status (wifi, mobile data, airplane, or change status in emulator)
21#[async_trait]
22pub trait HasNetworkState: AppiumClientTrait {
23    async fn set_connection(&self, state: &ConnectionState) -> Result<(), CmdError> {
24        let bitmask = state.bits();
25
26        self.issue_cmd(AppiumCommand::Custom(
27            Method::POST,
28            "network_connection".to_string(),
29            Some(json!({
30                "name": "network_connection",
31                "parameters": {
32                    "type": bitmask
33                }
34            })),
35        )).await?;
36
37        Ok(())
38    }
39
40    async fn get_connection(&self) -> Result<ConnectionState, CmdError> {
41        let value = self.issue_cmd(AppiumCommand::Custom(
42            Method::GET,
43            "network_connection".to_string(),
44            None,
45        )).await?;
46
47        let bits: u16 = serde_json::from_value(value)?;
48
49        Ok(ConnectionState::from_bits_truncate(bits))
50    }
51}
52
53#[async_trait]
54impl HasNetworkState for AndroidClient {}
55
56/// Toggle network status
57#[async_trait]
58pub trait SupportsNetworkStateManagement: AppiumClientTrait {
59
60    async fn toggle_wifi(&self) -> Result<(), CmdError> {
61        self.issue_cmd(AppiumCommand::Custom(
62            Method::POST,
63            "appium/device/toggle_wifi".to_string(),
64            None,
65        )).await?;
66
67        Ok(())
68    }
69
70    async fn toggle_airplane_mode(&self) -> Result<(), CmdError> {
71        self.issue_cmd(AppiumCommand::Custom(
72            Method::POST,
73            "appium/device/toggle_airplane_mode".to_string(),
74            None,
75        )).await?;
76
77        Ok(())
78    }
79
80    async fn toggle_data(&self) -> Result<(), CmdError> {
81        self.issue_cmd(AppiumCommand::Custom(
82            Method::POST,
83            "appium/device/toggle_data".to_string(),
84            None,
85        )).await?;
86
87        Ok(())
88    }
89}
90
91#[async_trait]
92impl SupportsNetworkStateManagement for AndroidClient {}