switchbot_api/command_request.rs
1/// A command request to send to the [SwitchBot API].
2///
3/// For more details of each field, please refer to the [SwitchBot
4/// documentation about device control commands][send-device-control-commands].
5///
6/// # Examples
7/// ```
8/// # use switchbot_api::CommandRequest;
9/// let command = CommandRequest {
10/// command: "turnOn".into(),
11/// ..Default::default()
12/// };
13/// ```
14///
15/// [SwitchBot API]: https://github.com/OpenWonderLabs/SwitchBotAPI
16/// [send-device-control-commands]: https://github.com/OpenWonderLabs/SwitchBotAPI/blob/main/README.md#send-device-control-commands
17#[derive(Debug, PartialEq, serde::Serialize)]
18#[serde(rename_all = "camelCase")]
19pub struct CommandRequest {
20 /// The command.
21 pub command: String,
22 /// The command parameters.
23 /// The default value is `default`.
24 pub parameter: String,
25 /// The command type.
26 /// The default value is `command`.
27 pub command_type: String,
28}
29
30impl Default for CommandRequest {
31 fn default() -> Self {
32 Self {
33 command: String::default(),
34 parameter: "default".into(),
35 command_type: "command".into(),
36 }
37 }
38}
39
40impl From<&str> for CommandRequest {
41 /// Parse a string into a [`CommandRequest`].
42 /// ```
43 /// # use switchbot_api::CommandRequest;
44 /// assert_eq!(
45 /// CommandRequest::from("turnOn"),
46 /// CommandRequest {
47 /// command: "turnOn".into(),
48 /// ..Default::default()
49 /// }
50 /// );
51 /// assert_eq!(
52 /// CommandRequest::from("turnOn:parameter:colon/slash"),
53 /// CommandRequest {
54 /// command: "turnOn".into(),
55 /// parameter: "parameter:colon/slash".into(),
56 /// ..Default::default()
57 /// }
58 /// );
59 /// assert_eq!(
60 /// CommandRequest::from("customize/turnOn"),
61 /// CommandRequest {
62 /// command: "turnOn".into(),
63 /// command_type: "customize".into(),
64 /// ..Default::default()
65 /// }
66 /// );
67 /// assert_eq!(
68 /// CommandRequest::from("customize/turnOn:parameter:colon/slash"),
69 /// CommandRequest {
70 /// command: "turnOn".into(),
71 /// command_type: "customize".into(),
72 /// parameter: "parameter:colon/slash".into(),
73 /// }
74 /// );
75 /// ```
76 fn from(mut text: &str) -> Self {
77 let mut command = CommandRequest::default();
78 if let Some((name, parameter)) = text.split_once(':') {
79 command.parameter = parameter.into();
80 text = name;
81 }
82 if let Some((command_type, name)) = text.split_once('/') {
83 command.command_type = command_type.into();
84 text = name;
85 }
86 command.command = text.into();
87 command
88 }
89}