Crates.io | volt-client-rs |
lib.rs | volt-client-rs |
version | 0.1.12 |
source | src |
created_at | 2024-08-08 15:33:51.52273 |
updated_at | 2024-08-08 15:33:51.52273 |
description | Volt websocket client library |
homepage | https://docs.tdxvolt.com |
repository | https://github.com/tdxvolt/tdxvolt-rs |
max_upload_size | |
id | 1329676 |
size | 49,163 |
This library provides a Rust client for the Volt API via websockets.
The client uses JSON to send requests and receive responses from the Volt.
cargo build
The following demonstrates creating and initialising a VoltClient
instance, and calling the get_resource
method to retrieve a resource from the Volt.
use serde_json::json;
use volt_client_rs::{
volt_client::VoltClient,
websocket_rpc::{Event, EventType},
};
#[tokio::main]
async fn main() {
// Load the Volt configuration JSON.
let config_json = match std::fs::read_to_string("volt.config.json") {
Ok(config_json) => config_json,
Err(e) => {
println!("failed to read config file: {:?}", e);
return;
}
};
// Create the Volt API client
let mut client = match VoltClient::create(&config_json).await {
Ok(client) => client,
Err(e) => {
println!("failed to create API client: {:?}", e);
return;
}
};
// Call methods on the client
let get_request = json!({
"resource_id": "did:volt:46c42b5f-22f1-4a7a-af76-c2eb78dbc8ca",
});
match client.get_resource(&get_request).await {
Ok(response) => println!("main: received response: {:?}", response),
Err(e) => println!("failed to get resource: {:?}", e),
}
// Keep the main thread alive to listen for incoming messages
tokio::signal::ctrl_c()
.await
.expect("Failed to listen for ctrl_c signal");
}
The get_resource
method used above is a unary RPC, i.e. it sends a single request and receives a single response. The VoltClient
also supports server streaming and client streaming RPCs.
// Start a `connect` call to the Volt.
let connect_call = match client.connect(&serde_json::Value::Null).await {
Ok(connect1) => connect1,
Err(e) => {
println!("failed to connect: {:?}", e);
return;
}
};
{
// Register a callback for the `Data` event.
let connect_rpc = connect_call.lock().await;
connect_rpc.on(EventType::Data, |response| {
if let Event::Data(data) = response {
// Do something with the data
println!("main: received data response: {:?}", data);
}
});
// Send the initial connect request.
let connect_request = json!({
"hello": {
"subscribe_resource_events": true,
"accept_invocation": false,
"ping_interval": 10000,
},
});
let _ = connect_rpc.send(&connect_request).await;
}