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 /// Please see the [`switchbot-cli` document] for the syntax.
43 ///
44 /// [`switchbot-cli` document]: https://github.com/kojiishi/switchbot-rs/tree/main/cli#command
45 /// ```
46 /// # use switchbot_api::CommandRequest;
47 /// assert_eq!(
48 /// CommandRequest::from("turnOn"),
49 /// CommandRequest {
50 /// command: "turnOn".into(),
51 /// ..Default::default()
52 /// }
53 /// );
54 /// assert_eq!(
55 /// CommandRequest::from("turnOn:parameter:colon/slash"),
56 /// CommandRequest {
57 /// command: "turnOn".into(),
58 /// parameter: "parameter:colon/slash".into(),
59 /// ..Default::default()
60 /// }
61 /// );
62 /// assert_eq!(
63 /// CommandRequest::from("customize/turnOn"),
64 /// CommandRequest {
65 /// command: "turnOn".into(),
66 /// command_type: "customize".into(),
67 /// ..Default::default()
68 /// }
69 /// );
70 /// assert_eq!(
71 /// CommandRequest::from("customize/turnOn:parameter:colon/slash"),
72 /// CommandRequest {
73 /// command: "turnOn".into(),
74 /// command_type: "customize".into(),
75 /// parameter: "parameter:colon/slash".into(),
76 /// }
77 /// );
78 /// ```
79 fn from(mut text: &str) -> Self {
80 let mut command = CommandRequest::default();
81 if let Some((name, parameter)) = text.split_once(':') {
82 command.parameter = parameter.into();
83 text = name;
84 }
85 if let Some((command_type, name)) = text.split_once('/') {
86 command.command_type = command_type.into();
87 text = name;
88 }
89 command.command = text.into();
90 command
91 }
92}