Skip to main content

appium_client/commands/
android.rs

1//! Android-specific features
2use std::collections::HashMap;
3use async_trait::async_trait;
4use fantoccini::elements::Element;
5use fantoccini::error::CmdError;
6use http::Method;
7use serde_derive::Serialize;
8use serde_repr::Serialize_repr;
9use serde_json::{json, Value};
10use crate::{AndroidClient, AppiumClientTrait};
11use crate::commands::AppiumCommand;
12
13pub struct AndroidActivity {
14    pub app_package: String,
15    pub app_activity: String,
16    pub app_wait_package: String,
17    pub app_wait_activity: String,
18    pub intent_action: String,
19    pub intent_category: String,
20    pub intent_flags: String,
21    pub optional_intent_arguments: String,
22    pub stop_app: bool,
23}
24
25/// Start or check Android actitivies
26#[async_trait]
27pub trait StartsActivity: AppiumClientTrait {
28    async fn start_activity(&self, activity: AndroidActivity) -> Result<(), CmdError> {
29        self.issue_cmd(AppiumCommand::Custom(
30            Method::POST,
31            "appium/device/start_activity".to_string(),
32            Some(json!({
33                "appPackage": activity.app_package,
34                "appWaitPackage": activity.app_wait_package,
35                "appWaitActivity": activity.app_wait_activity,
36                "dontStopAppOnReset": !activity.stop_app,
37                "intentAction": activity.intent_action,
38                "intentCategory": activity.intent_category,
39                "intentFlags": activity.intent_flags,
40                "optionalIntentArguments": activity.optional_intent_arguments
41            }))
42        )).await?;
43
44        Ok(())
45    }
46
47    async fn current_activity(&self) -> Result<String, CmdError> {
48        let value = self.issue_cmd(AppiumCommand::Custom(
49            Method::POST,
50            "appium/device/current_activity".to_string(),
51            None
52        )).await?;
53
54        Ok(serde_json::from_value(value)?)
55    }
56
57    async fn current_package(&self) -> Result<String, CmdError> {
58        let value = self.issue_cmd(AppiumCommand::Custom(
59            Method::POST,
60            "appium/device/current_package".to_string(),
61            None
62        )).await?;
63
64        Ok(serde_json::from_value(value)?)
65    }
66}
67
68#[async_trait]
69impl StartsActivity for AndroidClient {}
70
71/// Android device details
72#[async_trait]
73pub trait HasAndroidDeviceDetails :AppiumClientTrait {
74    async fn display_density(&self) -> Result<u64, CmdError> {
75        let value = self.issue_cmd(AppiumCommand::Custom(
76            Method::GET,
77            "appium/device/display_density".to_string(),
78            None
79        )).await?;
80
81        Ok(serde_json::from_value(value)?)
82    }
83
84    async fn system_bars(&self) -> Result<HashMap<String, HashMap<String, Value>>, CmdError> {
85        let value = self.issue_cmd(AppiumCommand::Custom(
86            Method::GET,
87            "appium/device/system_bars".to_string(),
88            None
89        )).await?;
90
91        Ok(serde_json::from_value(value)?)
92    }
93}
94
95#[async_trait]
96impl HasAndroidDeviceDetails for AndroidClient {}
97
98/// Device traits that Appium is able to read
99#[async_trait]
100pub trait HasSupportedPerformanceDataType : AppiumClientTrait {
101    async fn supported_performance_data_type(&self) -> Result<Vec<String>, CmdError> {
102        let value = self.issue_cmd(AppiumCommand::Custom(
103            Method::POST,
104            "appium/performanceData/types".to_string(),
105            None
106        )).await?;
107
108        Ok(serde_json::from_value(value)?)
109    }
110
111    async fn performance_data(&self, package: &str, data_type: &str, read_timeout: u32) -> Result<Vec<Vec<Value>>, CmdError> {
112        let value = self.issue_cmd(AppiumCommand::Custom(
113            Method::POST,
114            "appium/performanceData/types".to_string(),
115            Some(json!({
116                "packageName": package,
117                "dataType": data_type,
118                "dataReadTimeout": read_timeout
119            }))
120        )).await?;
121
122        Ok(serde_json::from_value(value)?)
123    }
124}
125
126#[async_trait]
127impl HasSupportedPerformanceDataType for AndroidClient {}
128
129#[derive(Debug, Serialize, Eq, PartialEq)]
130#[serde(rename_all = "lowercase")]
131pub enum GsmCallAction {
132    Call,
133    Accept,
134    Cancel,
135    Hold,
136}
137
138#[derive(Debug, Serialize_repr, Eq, PartialEq)]
139#[repr(u8)]
140pub enum GsmSignalStrength {
141    NoneOrUnknown = 0,
142    Poor = 1,
143    Moderate = 2,
144    Good = 3,
145    Great = 4,
146}
147
148#[derive(Debug, Serialize, Eq, PartialEq)]
149#[serde(rename_all = "lowercase")]
150pub enum GsmVoiceState {
151    ON,
152    OFF,
153    Denied,
154    Searching,
155    Roaming,
156    Home,
157    Unregistered,
158}
159
160#[derive(Debug, Serialize, Eq, PartialEq)]
161#[serde(rename_all = "lowercase")]
162pub enum NetworkSpeed {
163    GSM,
164    SCSD,
165    GPRS,
166    EDGE,
167    UMTS,
168    HSDPA,
169    LTE,
170    EVDO,
171    FULL,
172}
173
174/// Special Android emulator commands like "send SMS"
175#[async_trait]
176pub trait SupportsSpecialEmulatorCommands : AppiumClientTrait {
177
178    async fn send_sms(&self, phone_number: &str, message: &str) -> Result<(), CmdError> {
179        self.issue_cmd(AppiumCommand::Custom(
180            Method::POST,
181            "appium/device/send_sms".to_string(),
182            Some(json!({
183                "phoneNumber": phone_number,
184                "message": message
185            }))
186        )).await?;
187
188        Ok(())
189    }
190
191    async fn make_gsm_call(&self, phone_number: &str, action: GsmCallAction) -> Result<(), CmdError> {
192        self.issue_cmd(AppiumCommand::Custom(
193            Method::POST,
194            "appium/device/gsm_call".to_string(),
195            Some(json!({
196                "phoneNumber": phone_number,
197                "action": action
198            }))
199        )).await?;
200
201        Ok(())
202    }
203
204    async fn set_signal_strength(&self, strength: GsmSignalStrength) -> Result<(), CmdError> {
205        self.issue_cmd(AppiumCommand::Custom(
206            Method::POST,
207            "appium/device/gsm_signal".to_string(),
208            Some(json!({
209                "signalStrengh": strength,
210                "signalStrength": strength
211            }))
212        )).await?;
213
214        Ok(())
215    }
216
217    async fn set_gsm_voice_state(&self, state: GsmVoiceState) -> Result<(), CmdError> {
218        self.issue_cmd(AppiumCommand::Custom(
219            Method::POST,
220            "appium/device/gsm_voice".to_string(),
221            Some(json!({
222                "state": state
223            }))
224        )).await?;
225
226        Ok(())
227    }
228
229    async fn set_network_speed(&self, speed: NetworkSpeed) -> Result<(), CmdError> {
230        self.issue_cmd(AppiumCommand::Custom(
231            Method::POST,
232            "appium/device/network_speed".to_string(),
233            Some(json!({
234                "netspeed": speed
235            }))
236        )).await?;
237
238        Ok(())
239    }
240
241    async fn set_power_capacity(&self, percent: u8) -> Result<(), CmdError> {
242        if percent > 100 {
243            return Err(CmdError::InvalidArgument(
244                "percent".to_string(),
245                format!("{percent} should be between 0 and 100.")
246            ))
247        }
248
249        self.issue_cmd(AppiumCommand::Custom(
250            Method::POST,
251            "appium/device/power_capacity".to_string(),
252            Some(json!({
253                "percent": percent
254            }))
255        )).await?;
256
257        Ok(())
258    }
259
260    async fn set_power_ac(&self, power: bool) -> Result<(), CmdError> {
261        let state = if power {
262            "on"
263        } else {
264            "off"
265        };
266
267        self.issue_cmd(AppiumCommand::Custom(
268            Method::POST,
269            "appium/device/power_ac".to_string(),
270            Some(json!({
271                "state": state
272            }))
273        )).await?;
274
275        Ok(())
276    }
277}
278
279#[async_trait]
280impl SupportsSpecialEmulatorCommands for AndroidClient {}
281
282/// Chrome DevTools protocol commands (Chrome and webview)
283#[async_trait]
284pub trait ExecutesCDP : AppiumClientTrait {
285    async fn execute_cdp_command(&self, command: &str, params: Option<HashMap<String, Value>>) -> Result<HashMap<String, Value>, CmdError> {
286        let value = self.issue_cmd(AppiumCommand::Custom(
287            Method::POST,
288            "goog/cdp/execute".to_string(),
289            Some(json!({
290                "cmd": command,
291                "params": params
292            }))
293        )).await?;
294
295        Ok(serde_json::from_value(value)?)
296    }
297}
298
299#[async_trait]
300impl ExecutesCDP for AndroidClient {}
301
302/// Replacing element value (instead of retyping into field)
303#[async_trait]
304pub trait CanReplaceValue: AppiumClientTrait {
305    async fn replace_value(&self, element: &Element, value: &str) -> Result<(), CmdError> {
306        let id = element.element_id().to_string();
307        self.issue_cmd(AppiumCommand::Custom(
308            Method::POST,
309            format!("appium/element/{}/replace_value", id),
310            Some(json!({
311                "id": id,
312                "value": value
313            }))
314        )).await?;
315
316        Ok(())
317    }
318}
319
320#[async_trait]
321impl CanReplaceValue for AndroidClient {}