Skip to content

Commit

Permalink
Update documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
LostQuasar committed Jun 13, 2024
1 parent 6855665 commit 91310b2
Show file tree
Hide file tree
Showing 6 changed files with 96 additions and 12 deletions.
4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ version = "0.1.0"
edition = "2021"

[dependencies]
dotenv = "0.15.0"
reqwest = { version = "0.11.27" }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
strum_macros = "0.26.4"
strum = "0.26.2"
tokio = { version = "1.21.2", features = ["macros", "rt-multi-thread"] }

[dev-dependencies]
dotenv = "0.15.0"
28 changes: 27 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,29 @@
# rzap

A rust library for connecting to an openshock server
This library provides an interface to controll shocker devices via [OpenShock](http://openshock.org)'s API

NOTE: This is an un-official API iterface created by someone who has just started learning rust, no guarantees are made and contributions are greatly welcomed

```
[dependencies]
reqwest = { version = "0.11.27" }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
strum_macros = "0.26.4"
strum = "0.26.2"
tokio = { version = "1.21.2", features = ["macros", "rt-multi-thread"] }
```

## Example

A simple request to retrieve the API key user's id

```rs
dotenv().ok();
let user_test_id = dotenv::var("USER_TEST_ID").expect("missing USER_TEST_ID");
let openshock_token = dotenv::var("OPENSHOCK_TOKEN").expect("missing OPENSHOCK_TOKEN");

let openshock_api = OpenShockAPI::new(None, openshock_token);
println!(openshock_api.get_user_info(None).await.unwrap().id);
```

30 changes: 26 additions & 4 deletions src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,22 @@ use reqwest::header;
use std::{error::Error, fmt::Debug};
use strum_macros::EnumString;

/// All methods contain an `Option<String>` to provide an alternate api key to use if it differs from the default
pub struct OpenShockAPI {
client: reqwest::Client,
base_url: String,
default_key: String,
}

/// Which list of shockers to return
#[derive(EnumString, Debug)]
pub enum ShockerSource {
pub enum ListShockerSource {
Own,
Shared,
}

impl OpenShockAPI {
/// Create a new instance of the api interface with a default key and the base_url, because OpenShock can be self hosted `base_url` can be any url without the leading `/` if `None` is provided the default of <https://api.shocklink.net> is used.
pub fn new(base_url: Option<String>, default_key: String) -> Self {
let mut headers = header::HeaderMap::new();
headers.insert(
Expand All @@ -38,6 +41,7 @@ impl OpenShockAPI {
}
}

/// Gets user info from the provided API key, the default key from the instance is used if `None` is provided
pub async fn get_user_info(
&self,
api_key: Option<String>,
Expand All @@ -56,9 +60,10 @@ impl OpenShockAPI {
Ok(self_base_response.data.unwrap())
}

/// Gets a list of shockers that the user has access to from either their own shockers or ones shared with them
pub async fn get_shockers(
&self,
source: ShockerSource,
source: ListShockerSource,
api_key: Option<String>,
) -> Result<Vec<ListShockersResponse>, Box<dyn Error>> {
let resp = self
Expand All @@ -75,18 +80,35 @@ impl OpenShockAPI {
Ok(list_shockers_response.data.unwrap())
}

///Sends a control request to the api and returns the response message which should be "Successfully sent control messages" exactly if it was successful
pub async fn post_control(
&self,
id: String,
control_type: ControlType,
intensity: u8,
duration: u16,
api_key: Option<String>,
) -> Result<String, Box<dyn Error>> {
match intensity {
1..=100 => {}
_ => {
panic!("Intensity is outside of bounds");
}
}

match duration {
300..=30000 => {}
_ => {
panic!("Duration is outside of bounds");
}
}

let control_request = serde_json::to_string(&ControlRequest {
shocks: vec![Shock {
id: id,
control_type: control_type,
intensity: 1,
duration: 300,
intensity: intensity,
duration: duration,
exclusive: true,
}],
custom_name: "rusty".to_string(),
Expand Down
8 changes: 8 additions & 0 deletions src/data_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
use serde::{Deserialize, Serialize};
use strum_macros::EnumString;

/// Response provided when a request is sent to retrieve the list of available shockers
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ListShockersResponse {
Expand All @@ -11,6 +12,7 @@ pub struct ListShockersResponse {
pub created_on: String,
}

/// Contains data about a shocker such as it's ID and model
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ShockerResponse {
Expand All @@ -29,6 +31,7 @@ pub enum ShockerModel {
Petrainer998DR,
}

/// The base response used for most of the OpenShock API endpoints
#[derive(Serialize, Deserialize, Debug)]
pub struct BaseResponse<T> {
pub message: Option<String>,
Expand All @@ -42,20 +45,25 @@ pub enum ControlType {
Vibrate,
Sound,
}

/// The format of which outgoing control requests should be formatted as can send multiple shocks at the same time as long as they use the same API key
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ControlRequest {
pub shocks: Vec<Shock>,
pub custom_name: String,
}

/// Describes how the shock should to send to the device
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Shock {
pub id: String,
#[serde(rename = "type")]
pub control_type: ControlType,
/// minimum of 1 and maximum of 100, measured in percentage
pub intensity: u8,
/// minimum of 300 and maximum of 30000, measured in ms
pub duration: u16,
pub exclusive: bool,
}
Expand Down
32 changes: 29 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,32 @@
//! # rzap
//!
//! A rust library for connecting to an openshock server
//! # rzap
//!
//! This library provides an interface to controll shocker devices via [OpenShock](http://openshock.org)'s API
//!
//! **NOTE:** This is an un-official API iterface created by someone who has just started learning rust, no guarantees are made and contributions are greatly welcomed
//!
//! ```toml
//! [dependencies]
//! reqwest = { version = "0.11.27" }
//! serde = { version = "1.0", features = ["derive"] }
//! serde_json = "1.0"
//! strum_macros = "0.26.4"
//! strum = "0.26.2"
//! tokio = { version = "1.21.2", features = ["macros", "rt-multi-thread"] }
//! ```
//!
//! ## Example
//!
//! A simple request to retrieve the API key user's id
//!
//! ```rs
//! dotenv().ok();
//! let user_test_id = dotenv::var("USER_TEST_ID").expect("missing USER_TEST_ID");
//! let openshock_token = dotenv::var("OPENSHOCK_TOKEN").expect("missing OPENSHOCK_TOKEN");
//!
//! let openshock_api = OpenShockAPI::new(None, openshock_token);
//! println!(openshock_api.get_user_info(None).await.unwrap().id);
//! ```
//!

pub mod api;
pub mod data_type;
6 changes: 3 additions & 3 deletions tests/tests.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use dotenv::dotenv;
use rzap::{api::{OpenShockAPI, ShockerSource}, data_type::ControlType};
use rzap::{api::{OpenShockAPI, ListShockerSource}, data_type::ControlType};
use std::hash::{DefaultHasher, Hash, Hasher};


Expand All @@ -19,7 +19,7 @@ async fn get_shockers_test() {

let openshock_api = OpenShockAPI::new(None, openshock_token);

let result = openshock_api.get_shockers(ShockerSource::Own, None).await;
let result = openshock_api.get_shockers(ListShockerSource::Own, None).await;
assert_eq!(
calculate_hash(&result.unwrap()[0].shockers[0].id),
calculate_hash(&shocker_test_id)
Expand All @@ -36,7 +36,7 @@ async fn post_control_test() {

let openshock_api = OpenShockAPI::new(None, openshock_token);
let result = openshock_api
.post_control(shocker_test_id, ControlType::Sound, None)
.post_control(shocker_test_id, ControlType::Sound, 101, 1, None)
.await;
assert_eq!(&result.unwrap(), &"Successfully sent control messages");
}
Expand Down

0 comments on commit 91310b2

Please sign in to comment.