repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/executor/test_util.rs
crates/executor/test_util.rs
use deno_core::serde_json::Value; use three_em_arweave::arweave::{LoadedContract, TransactionData}; use three_em_arweave::gql_result::{ GQLAmountInterface, GQLBlockInterface, GQLEdgeInterface, GQLNodeInterface, GQLOwnerInterface, GQLTagInterface, }; use three_em_arweave::miscellaneous::ContractType; pub fn generate_fake_interaction( input: Value, id: &str, block_id: Option<String>, block_height: Option<usize>, owner_address: Option<String>, recipient: Option<String>, extra_tag: Option<GQLTagInterface>, quantity: Option<GQLAmountInterface>, fee: Option<GQLAmountInterface>, block_timestamp: Option<usize>, ) -> GQLEdgeInterface { let mut tags = vec![GQLTagInterface { name: String::from("Input"), value: input.to_string(), }]; if extra_tag.is_some() { tags.push(extra_tag.unwrap()); } GQLEdgeInterface { cursor: String::new(), node: GQLNodeInterface { id: String::from(id), anchor: None, signature: None, recipient, owner: GQLOwnerInterface { address: owner_address.unwrap_or(String::new()), key: None, }, fee, quantity, data: None, tags, block: GQLBlockInterface { id: block_id.unwrap_or(String::new()), timestamp: block_timestamp.unwrap_or(0), height: block_height.unwrap_or(0), previous: None, }, parent: None, bundledIn: None, }, } } pub fn generate_fake_loaded_contract_data( contract_source: &[u8], contract_type: ContractType, init_state: String, ) -> LoadedContract { let contract_id = String::from("test"); LoadedContract { id: contract_id, contract_src_tx_id: String::new(), contract_src: contract_source.to_vec(), contract_type, init_state, min_fee: None, contract_transaction: TransactionData { format: 0, id: String::new(), last_tx: String::new(), owner: String::new(), tags: Vec::new(), target: String::new(), quantity: String::new(), data: String::new(), reward: String::new(), signature: String::new(), data_size: String::new(), data_root: String::new(), }, } }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/executor/utils.rs
crates/executor/utils.rs
use deno_core::serde_json::Value; use three_em_arweave::gql_result::{ GQLAmountInterface, GQLBlockInterface, GQLEdgeInterface, GQLNodeInterface, GQLOwnerInterface, GQLTagInterface, }; const ONE_AR: f64 = (1000000000000 as i64) as f64; pub fn ar_to_winston(ar: f64) -> f64 { ar * ONE_AR } pub fn winston_to_ar(winston: f64) -> f64 { winston / ONE_AR } pub fn create_simulated_transaction( id: String, owner: String, quantity: String, reward: String, target: Option<String>, tags: Vec<GQLTagInterface>, block_height: Option<String>, block_hash: Option<String>, block_timestamp: Option<String>, input: String, ) -> GQLEdgeInterface { let mut current_tags = tags; current_tags.push(GQLTagInterface { name: String::from("Input"), value: input, }); let height = block_height .unwrap_or_else(|| String::from("0")) .parse::<usize>() .unwrap_or(0 as usize); let timestamp = block_timestamp .unwrap_or_else(|| String::from("0")) .parse::<usize>() .unwrap_or(0 as usize); GQLEdgeInterface { cursor: String::new(), node: GQLNodeInterface { id, anchor: None, signature: None, recipient: target, owner: GQLOwnerInterface { address: owner, key: None, }, quantity: Some(GQLAmountInterface { winston: Some(quantity), ar: None, }), fee: Some(GQLAmountInterface { winston: Some(reward), ar: None, }), data: None, tags: current_tags, block: GQLBlockInterface { height, timestamp, id: block_hash.unwrap_or_else(|| String::new()), previous: None, }, parent: None, bundledIn: None, }, } }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/executor/executor.rs
crates/executor/executor.rs
use crate::{get_input_from_interaction, nop_cost_fn}; use deno_core::error::AnyError; use deno_core::serde_json; use deno_core::serde_json::Value; use deno_core::OpState; use deno_ops::op; use indexmap::map::IndexMap; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use three_em_arweave::arweave::get_cache; use three_em_arweave::arweave::LoadedContract; use three_em_arweave::arweave::{Arweave, ArweaveProtocol}; use three_em_arweave::cache::ArweaveCache; use three_em_arweave::cache::CacheExt; use three_em_arweave::cache::StateResult; use three_em_arweave::gql_result::{ GQLAmountInterface, GQLEdgeInterface, GQLNodeInterface, }; use three_em_arweave::miscellaneous::ContractType; use three_em_evm::{ExecutionState, Machine, Storage}; use three_em_exm_base_ops::ExmContext; use three_em_js::CallResult; use three_em_js::Runtime; use three_em_smartweave::{ InteractionBlock, InteractionContext, InteractionTx, }; use three_em_wasm::WasmRuntime; /* * Questions: * opsmartweavereadcontract - uses executecontract instead of simulate * * */ pub type ValidityTable = IndexMap<String, Value>; pub type CachedState = Option<Value>; pub type ExecErrors = HashMap<String, String>; #[derive(Clone)] pub struct V8Result { pub state: Value, pub result: Option<Value>, pub validity: ValidityTable, pub context: ExmContext, pub updated: bool, pub errors: HashMap<String, String>, } #[derive(Clone)] pub enum ExecuteResult { V8(V8Result), Evm(Storage, Vec<u8>, ValidityTable), } pub type OnCached = dyn Fn() -> ExecuteResult; pub fn get_execution_context( maybe_context: Result<ExmContext, AnyError>, ) -> ExmContext { if let Ok(exm_known_context) = maybe_context { //Check for existence of maybe_context, else create new hashmap exm_known_context } else { ExmContext { requests: HashMap::new(), kv: HashMap::new(), //data: Data::new(), } } } // Grabs the result of an execution and packages data to be given back to FE pub fn process_execution( execute_result: ExecuteResult, show_validity: bool, ) -> Value { match execute_result { ExecuteResult::V8(result) => { if show_validity { serde_json::json!({ "state": result.state, "validity": result.validity, "exm": result.context }) } else { result.state } } ExecuteResult::Evm(store, result, validity_table) => { let store = hex::encode(store.raw()); let result = hex::encode(result); if show_validity { serde_json::json!({ "result": result, "store": store, "validity": validity_table }) } else { serde_json::json!({ "result": result, "store": store, }) } } } } #[op] pub async fn op_smartweave_read_contract( state: Rc<RefCell<OpState>>, (contract_id, height, show_validity): (String, Option<usize>, Option<bool>), _: (), ) -> Result<Value, AnyError> { //Reads the state in the contract, not write to it let op_state = state.borrow(); let info = op_state.borrow::<three_em_smartweave::ArweaveInfo>(); //Borrow data in ArweaveInfo type let cl = Arweave::new( info.port, info.host.clone(), info.protocol.clone(), ArweaveCache::new(), ); let state = crate::execute_contract(contract_id, height, true, false, None, None, &cl) .await?; Ok(process_execution(state, show_validity.unwrap_or(false))) } pub fn generate_interaction_context( tx: &GQLNodeInterface, ) -> InteractionContext { InteractionContext { transaction: InteractionTx { id: tx.id.to_owned(), owner: (tx.owner.to_owned()).address, target: tx .recipient .to_owned() .unwrap_or_else(|| String::from("null")), quantity: tx .quantity .to_owned() .unwrap_or_else(|| GQLAmountInterface { winston: Some(String::new()), ar: Some(String::new()), }) .winston .unwrap(), reward: tx .fee .to_owned() .unwrap_or_else(|| GQLAmountInterface { winston: Some(String::new()), ar: Some(String::new()), }) .winston .unwrap(), tags: tx.tags.to_owned(), }, block: InteractionBlock { indep_hash: tx.block.id.to_owned(), height: tx.block.height.to_owned(), timestamp: tx.block.timestamp.to_owned(), }, } } #[allow(clippy::too_many_arguments)] pub async fn raw_execute_contract< CachedCallBack: FnOnce(ValidityTable, CachedState, ExecErrors) -> ExecuteResult, >( contract_id: String, loaded_contract: LoadedContract, interactions: Vec<GQLEdgeInterface>, mut validity: IndexMap<String, Value>, cache_state: Option<Value>, needs_processing: bool, show_errors: bool, on_cached: CachedCallBack, shared_client: &Arweave, settings: HashMap<String, deno_core::serde_json::Value>, maybe_exm_context: Option<deno_core::serde_json::Value>, ) -> ExecuteResult { let transaction = (&loaded_contract.contract_transaction).to_owned(); let cache = cache_state.is_some(); let arweave_info = ( shared_client.port.to_owned(), shared_client.host.to_owned(), match shared_client.protocol.to_owned() { ArweaveProtocol::HTTPS => String::from("https"), ArweaveProtocol::HTTP => String::from("http"), }, ); let mut is_state_updated = false; let mut errors: HashMap<String, String> = HashMap::new(); match loaded_contract.contract_type { ContractType::JAVASCRIPT => { if needs_processing { let state: Value = cache_state.unwrap_or_else(|| { deno_core::serde_json::from_str(&loaded_contract.init_state).unwrap() }); let mut rt = Runtime::new( &(String::from_utf8(loaded_contract.contract_src).unwrap()), state, arweave_info.to_owned(), op_smartweave_read_contract::decl(), settings.clone(), maybe_exm_context.clone(), ) .await .unwrap(); let mut latest_result: Option<Value> = None; // let mut i = 0; for interaction in interactions { let tx = interaction.node; let input = get_input_from_interaction(&tx); // TODO: has_multiple_interactions // https://github.com/ArweaveTeam/SmartWeave/blob/4d09c66d832091805f583ba73e8da96cde2c0190/src/contract-read.ts#L68 let js_input_maybe: serde_json::Result<Value> = deno_core::serde_json::from_str(input); if let Ok(js_input) = js_input_maybe { let call_input = serde_json::json!({ "input": js_input, "caller": tx.owner.address }); let interaction_context = generate_interaction_context(&tx); let valid = match rt.call(call_input, Some(interaction_context)).await { Ok(None) => { latest_result = None; serde_json::Value::Bool(true) } Ok(Some(CallResult::Evolve(evolve))) => { let contract = shared_client .load_contract( contract_id.clone(), Some(evolve), None, None, true, false, false, ) .await .unwrap(); let state: Value = rt.get_contract_state().unwrap(); rt = Runtime::new( &(String::from_utf8_lossy(&contract.contract_src)), state, arweave_info.to_owned(), op_smartweave_read_contract::decl(), settings.clone(), maybe_exm_context.clone(), ) .await .unwrap(); latest_result = None; serde_json::Value::Bool(true) } Ok(Some(CallResult::Result(result_value, state_updated))) => { let result_to_value = rt.to_value::<Value>(&result_value); if result_to_value.is_ok() { latest_result = Some(result_to_value.unwrap()); } if state_updated && !is_state_updated { is_state_updated = state_updated; } serde_json::Value::Bool(true) } Err(err) => { let err_str = err.to_string(); errors.insert(tx.id.clone(), err_str.clone()); latest_result = None; if show_errors { println!("{}", err); } if show_errors { serde_json::Value::String(err_str) } else { serde_json::Value::Bool(false) } } }; validity.insert(tx.id, valid); } else { validity.insert(tx.id, deno_core::serde_json::Value::Bool(false)); } } let state_val: Value = rt.get_contract_state().unwrap(); let exm_context: ExmContext = get_execution_context(rt.get_exm_context::<ExmContext>()); if cache { get_cache().lock().unwrap().cache_states( contract_id, StateResult { state: state_val.clone(), validity: validity.clone(), }, ); } ExecuteResult::V8(V8Result { state: state_val, result: latest_result, validity, context: exm_context, updated: is_state_updated, errors, }) } else { on_cached(validity, cache_state, errors) } } ContractType::WASM => { if needs_processing { let wasm = loaded_contract.contract_src.as_slice(); let init_state_wasm = if cache_state.is_some() { let cache_state_unwrapped = cache_state.unwrap(); let state_str = cache_state_unwrapped.to_string(); state_str.as_bytes().to_vec() } else { loaded_contract.init_state.as_bytes().to_vec() }; let mut state = init_state_wasm; let mut rt = WasmRuntime::new(wasm).unwrap(); for interaction in interactions { let tx = interaction.node; let input = get_input_from_interaction(&tx); let maybe_wasm_input: serde_json::Result<Value> = deno_core::serde_json::from_str(input); if let Ok(wasm_input) = maybe_wasm_input { let call_input = serde_json::json!({ "input": wasm_input, "caller": tx.owner.address, }); let interaction_context = generate_interaction_context(&tx); let mut input = deno_core::serde_json::to_vec(&call_input).unwrap(); let exec = rt.call(&mut state, &mut input, interaction_context); let valid_with_result = match exec { Ok(result) => (serde_json::Value::Bool(true), Some(result)), Err(err) => { if show_errors { println!("{}", err); } if show_errors { (serde_json::Value::String(err.to_string()), None) } else { (serde_json::Value::Bool(false), None) } } }; let valid = valid_with_result.0; if valid.is_boolean() && valid.as_bool().unwrap() { state = valid_with_result.1.unwrap(); } validity.insert(tx.id, valid); } else { validity.insert(tx.id, deno_core::serde_json::Value::Bool(false)); } } let state: Value = deno_core::serde_json::from_slice(&state).unwrap(); /// TODO: WASM Context // let exm_context = // get_execution_context(rt.get_exm_context::<ExmContext>()); if cache { get_cache().lock().unwrap().cache_states( contract_id, StateResult { state: state.clone(), validity: validity.clone(), }, ); } ExecuteResult::V8(V8Result { state, validity, context: Default::default(), result: None, updated: false, errors: errors, }) } else { on_cached(validity, cache_state, errors) } } ContractType::EVM => { // Contract source bytes. let bytecode = hex::decode(loaded_contract.contract_src.as_slice()) .expect("Failed to decode contract bytecode"); let store = hex::decode(loaded_contract.init_state.as_bytes()) .expect("Failed to decode account state"); let mut account_store = Storage::from_raw(&store); let mut result = vec![]; for interaction in interactions { let tx = interaction.node; let block_info = shared_client.get_transaction_block(&tx.id).await.unwrap(); let block_info = three_em_evm::BlockInfo { timestamp: three_em_evm::U256::from(block_info.timestamp), difficulty: three_em_evm::U256::from_str_radix(&block_info.diff, 10) .unwrap(), block_hash: three_em_evm::U256::from( block_info.indep_hash.as_bytes(), ), number: three_em_evm::U256::from(block_info.height), }; let input = get_input_from_interaction(&tx); let call_data = hex::decode(input).expect("Failed to decode input"); let mut machine = Machine::new_with_data(nop_cost_fn, call_data); machine.set_storage(account_store.clone()); machine.set_fetcher(Box::new(|address: &three_em_evm::U256| { let mut id = [0u8; 32]; address.to_big_endian(&mut id); let id = String::from_utf8_lossy(&id).to_string(); let contract = deno_core::futures::executor::block_on( shared_client .load_contract(id, None, None, None, cache, false, false), ) .expect("evm call: Failed to load contract"); let bytecode = hex::decode(contract.contract_src.as_slice()) .expect("Failed to decode contract bytecode"); let store = hex::decode(contract.init_state.as_bytes()) .expect("Failed to decode account state"); let store = Storage::from_raw(&store); Some(three_em_evm::ContractInfo { store, bytecode }) })); match machine.execute(&bytecode, block_info) { ExecutionState::Abort(_) | ExecutionState::Revert => { validity.insert(tx.id, serde_json::Value::Bool(false)); } ExecutionState::Ok => { account_store = machine.storage; result = machine.result; validity.insert(tx.id, serde_json::Value::Bool(true)); } } } ExecuteResult::Evm(account_store, result, validity) } } } #[cfg(test)] mod tests { use crate::executor::{raw_execute_contract, ExecuteResult}; use crate::test_util::{ generate_fake_interaction, generate_fake_loaded_contract_data, }; use deno_core::serde_json; use deno_core::serde_json::Value; use indexmap::map::IndexMap; use std::collections::HashMap; use three_em_arweave::arweave::Arweave; use three_em_arweave::arweave::{LoadedContract, TransactionData}; use three_em_arweave::cache::ArweaveCache; use three_em_arweave::cache::CacheExt; use three_em_arweave::gql_result::{ GQLAmountInterface, GQLBlockInterface, GQLEdgeInterface, GQLNodeInterface, GQLOwnerInterface, GQLTagInterface, }; use three_em_arweave::miscellaneous::ContractType; #[tokio::test] async fn test_globals_js() { let init_state = serde_json::json!({}); let fake_contract = generate_fake_loaded_contract_data( include_bytes!("../../testdata/contracts/globals_contract.js"), ContractType::JAVASCRIPT, init_state.to_string(), ); let mut transaction1 = generate_fake_interaction( serde_json::json!({}), "tx1123123123123123123213213123", Some(String::from("ABCD-EFG")), Some(2), Some(String::from("SUPERMAN1293120")), Some(String::from("RECIPIENT1234")), Some(GQLTagInterface { name: String::from("MyTag"), value: String::from("Christpoher Nolan is awesome"), }), Some(GQLAmountInterface { winston: Some(String::from("100")), ar: None, }), Some(GQLAmountInterface { winston: Some(String::from("100")), ar: None, }), Some(12301239), ); let fake_interactions = vec![transaction1]; let result = raw_execute_contract( String::from("10230123021302130"), fake_contract, fake_interactions, IndexMap::new(), None, true, false, |_, _, _| { panic!("not implemented"); }, &Arweave::new( 443, "arweave.net".to_string(), String::from("https"), ArweaveCache::new(), ), HashMap::new(), None, ) .await; if let ExecuteResult::V8(result) = result { assert_eq!( result.state, serde_json::json!({"txId":"tx1123123123123123123213213123","txOwner":"SUPERMAN1293120","txTarget":"RECIPIENT1234","txQuantity":"100","txReward":"100","txTags":[{"name":"Input","value":"{}"},{"name":"MyTag","value":"Christpoher Nolan is awesome"}],"txHeight":2,"txIndepHash":"ABCD-EFG","txTimestamp":12301239,"winstonToAr":true,"arToWinston":true,"compareArWinston":1}) ); } else { panic!("Unexpected entry"); } } #[tokio::test] async fn test_error_logs() { let init_state = serde_json::json!({ "counts": 0 }); let fake_contract = generate_fake_loaded_contract_data( include_bytes!("../../testdata/contracts/counter_error.js"), ContractType::JAVASCRIPT, init_state.to_string(), ); let mut transaction1 = generate_fake_interaction( serde_json::json!({}), "tx1123123123123123123213213123", Some(String::from("ABCD-EFG")), Some(2), Some(String::from("SUPERMAN1293120")), Some(String::from("RECIPIENT1234")), Some(GQLTagInterface { name: String::from("MyTag"), value: String::from("Christpoher Nolan is awesome"), }), Some(GQLAmountInterface { winston: Some(String::from("100")), ar: None, }), Some(GQLAmountInterface { winston: Some(String::from("100")), ar: None, }), Some(12301239), ); let fake_interactions_2 = vec![transaction1.clone(), transaction1.clone()]; let result = raw_execute_contract( String::from("10230123021302130"), fake_contract.clone(), fake_interactions_2, IndexMap::new(), None, true, false, |_, _, _| { panic!("not implemented"); }, &Arweave::new( 443, "arweave.net".to_string(), String::from("https"), ArweaveCache::new(), ), HashMap::new(), None, ) .await; if let ExecuteResult::V8(result) = result { assert_eq!(result.errors.len(), 1); assert!(result .errors .get("tx1123123123123123123213213123") .unwrap() .as_str() .contains("An error has been thrown")); } else { panic!("Unexpected entry"); } } #[tokio::test] async fn test_counter_result_js() { let init_state = serde_json::json!({ "counts": 0 }); let fake_contract = generate_fake_loaded_contract_data( include_bytes!("../../testdata/contracts/counter.js"), ContractType::JAVASCRIPT, init_state.to_string(), ); let mut transaction1 = generate_fake_interaction( serde_json::json!({}), "tx1123123123123123123213213123", Some(String::from("ABCD-EFG")), Some(2), Some(String::from("SUPERMAN1293120")), Some(String::from("RECIPIENT1234")), Some(GQLTagInterface { name: String::from("MyTag"), value: String::from("Christpoher Nolan is awesome"), }), Some(GQLAmountInterface { winston: Some(String::from("100")), ar: None, }), Some(GQLAmountInterface { winston: Some(String::from("100")), ar: None, }), Some(12301239), ); let fake_interactions = vec![transaction1.clone()]; let fake_interactions_2 = vec![transaction1.clone(), transaction1.clone()]; let result = raw_execute_contract( String::from("10230123021302130"), fake_contract.clone(), fake_interactions, IndexMap::new(), None, true, false, |_, _, _| { panic!("not implemented"); }, &Arweave::new( 443, "arweave.net".to_string(), String::from("https"), ArweaveCache::new(), ), HashMap::new(), None, ) .await; if let ExecuteResult::V8(result) = result { assert_eq!(result.result.is_some(), true); assert_eq!( result.result.unwrap(), Value::String(String::from("Some result")) ); } else { panic!("Unexpected entry"); } let result = raw_execute_contract( String::from("10230123021302130"), fake_contract, fake_interactions_2, IndexMap::new(), None, true, false, |_, _, _| { panic!("not implemented"); }, &Arweave::new( 443, "arweave.net".to_string(), String::from("https"), ArweaveCache::new(), ), HashMap::new(), None, ) .await; if let ExecuteResult::V8(result) = result { assert_eq!(result.state.get("counts").unwrap().as_i64().unwrap(), 2); assert_eq!(result.result.is_some(), false); } else { panic!("Unexpected entry"); } } #[tokio::test] async fn test_js_read_contract() { let init_state = serde_json::json!({}); let fake_contract = generate_fake_loaded_contract_data( include_bytes!("../../testdata/contracts/read_contact.js"), ContractType::JAVASCRIPT, init_state.to_string(), ); let mut transaction1 = generate_fake_interaction( serde_json::json!({}), "tx1123123123123123123213213123", Some(String::from("ABCD-EFG")), Some(2), Some(String::from("SUPERMAN1293120")), Some(String::from("RECIPIENT1234")), Some(GQLTagInterface { name: String::from("MyTag"), value: String::from("Christpoher Nolan is awesome"), }), Some(GQLAmountInterface { winston: Some(String::from("100")), ar: None, }), Some(GQLAmountInterface { winston: Some(String::from("100")), ar: None, }), Some(12301239), ); let fake_interactions = vec![transaction1]; let result = raw_execute_contract( String::from("10230123021302130"), fake_contract, fake_interactions, IndexMap::new(), None, true, true, |_, _, _| { panic!("not implemented"); }, &Arweave::new( 443, "arweave.net".to_string(), String::from("https"), ArweaveCache::new(), ), HashMap::new(), None, ) .await; if let ExecuteResult::V8(result) = result { let x = serde_json::json!({ "state": result.state, "validity": result.validity }); assert_eq!(result.state["ticker"], serde_json::json!("ARCONFT67")); } else { panic!("Unexpected entry"); } } #[tokio::test] pub async fn test_executor_js() { let init_state = serde_json::json!({ "users": [] }); let fake_contract = generate_fake_loaded_contract_data( include_bytes!("../../testdata/contracts/users_contract.js"), ContractType::JAVASCRIPT, init_state.to_string(), ); let fake_interactions = vec![ generate_fake_interaction( serde_json::json!({ "function": "add", "name": "Andres" }), "tx1", None, None, None, None, None, None, None, None, ), generate_fake_interaction( serde_json::json!({ "function": "none", "name": "Tate" }), "tx2", None, None, None, None, None, None, None, None, ), generate_fake_interaction( serde_json::json!({ "function": "add", "name": "Divy" }), "tx3", None, None, None, None, None, None, None, None, ), ]; let execute = || async { let result = raw_execute_contract( String::new(), fake_contract, fake_interactions, IndexMap::new(), None, true, false, |_, _, _| { panic!("not implemented"); }, &Arweave::new( 443, "arweave.net".to_string(), String::from("https"), ArweaveCache::new(), ), HashMap::new(), None, ) .await; result }; if let ExecuteResult::V8(result) = execute().await { let validity = result.validity; let value = result.state; assert_eq!(validity.len(), 3); let (tx1, tx2, tx3) = ( validity.get("tx1"), validity.get("tx2"), validity.get("tx3"), ); assert_eq!(tx1.is_some(), true); assert_eq!(tx2.is_some(), true); assert_eq!(tx3.is_some(), true); assert_eq!((tx1.unwrap()).to_owned(), true); assert_eq!((tx2.unwrap()).to_owned(), false); assert_eq!((tx3.unwrap()).to_owned(), true); let value_state = value.get("users"); assert_eq!(value_state.is_some(), true); let users = value_state .unwrap() .to_owned() .as_array() .unwrap() .to_owned(); assert_eq!( users.get(0).unwrap().to_owned(), serde_json::json!("Andres") ); assert_eq!(users.get(1).unwrap().to_owned(), serde_json::json!("Divy")); assert_eq!(result.result.is_some(), true); assert_eq!(result.result.unwrap(), 2); } else { panic!("Failed"); } } #[tokio::test] async fn test_contract_evolve() { let init_state = serde_json::json!({ "canEvolve": true, "v": 0, "i": 0, "pi": 0 }); let fake_contract = generate_fake_loaded_contract_data( include_bytes!("../../testdata/evolve/evolve1.js"), ContractType::JAVASCRIPT, init_state.to_string(), ); let fake_interactions = vec![ generate_fake_interaction( serde_json::json!({ "function": "evolve", // Contract Source for "Zwp7r7Z10O0TuF6lmFApB7m5lJIrE5RbLAVWg_WKNcU" "value": "C0F9QvOOJNR2DDIicWeL9B-C5vFrtczmOjpW_3FCQBQ", }), "tx1", None, None, None, None, None, None, None, None, ), generate_fake_interaction( serde_json::json!({ "function": "contribute", }), "tx2", None, None, None, None, None, None, None, None, ), ]; let result = raw_execute_contract( String::from("Zwp7r7Z10O0TuF6lmFApB7m5lJIrE5RbLAVWg_WKNcU"), fake_contract, fake_interactions, IndexMap::new(), None, true, false, |_, _, _| { panic!("not implemented"); }, &Arweave::new( 443, "arweave.net".to_string(), String::from("https"), ArweaveCache::new(), ), HashMap::new(), None, ) .await; if let ExecuteResult::V8(result) = result { let validity = result.validity; let value = result.state; // tx1 is the evolve action. This must not fail. // All network calls happen here and runtime is // re-initialized. assert_eq!(validity.get("tx1").unwrap(), &true); // tx2 is the interaction to the evolved source. // In this case, the pi contract. assert_eq!(validity.get("tx2").unwrap(), &true); let value_state = value.get("canEvolve"); assert_eq!(value_state.is_some(), true); assert_eq!(value.get("v").unwrap(), 0.6666666666666667_f64); } } #[tokio::test] async fn test_wasm_contract_interactions_context() { let init_state = serde_json::json!({ "txId": "", "owner": "", "height": 0 }); let fake_contract = generate_fake_loaded_contract_data( include_bytes!("../../testdata/03_wasm/03_wasm.wasm"), ContractType::WASM, init_state.to_string(), ); let fake_interactions = vec![ generate_fake_interaction( serde_json::json!({}), "POCAHONTAS", None, Some(100), Some(String::from("ADDRESS")), None, None, None, None, None, ), generate_fake_interaction( serde_json::json!({}), "STARWARS", None, Some(200), Some(String::from("ADDRESS2")), None, None, None, None, None, ), ]; let result = raw_execute_contract( String::from("WHATEVA"), fake_contract, fake_interactions, IndexMap::new(), None, true, false, |_, _, _| { panic!("not implemented"); }, &Arweave::new( 443, "arweave.net".to_string(), String::from("https"), ArweaveCache::new(), ), HashMap::new(), None, ) .await; if let ExecuteResult::V8(result) = result { let value = result.state; assert_eq!(value.get("txId").unwrap(), "STARWARS"); assert_eq!(value.get("owner").unwrap(), "ADDRESS2"); assert_eq!(value.get("height").unwrap(), 200); } else { panic!("Invalid operation"); } } }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/cli/dry_run.rs
crates/cli/dry_run.rs
use deno_core::error::AnyError; use indexmap::map::IndexMap; use serde::Deserialize; use serde::Serialize; use serde_json::Value; use std::collections::HashMap; use std::error::Error; use std::path::Path; use three_em_arweave::arweave::Arweave; use three_em_arweave::cache::ArweaveCache; use three_em_arweave::cache::CacheExt; use three_em_arweave::gql_result::{ GQLAmountInterface, GQLEdgeInterface, GQLTagInterface, }; use three_em_arweave::miscellaneous::ContractType; use three_em_executor::executor::{raw_execute_contract, ExecuteResult}; use three_em_executor::test_util::{ generate_fake_interaction, generate_fake_loaded_contract_data, }; #[derive(Deserialize, Serialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct RawInteractions { id: String, caller: String, input: Value, #[serde(skip_serializing_if = "Option::is_none")] #[serde(default)] block_id: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(default)] block_height: Option<usize>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(default)] block_timestamp: Option<usize>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(default)] quantity: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(default)] reward: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(default)] tags: Option<GQLTagInterface>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(default)] recipient: Option<String>, } #[derive(Deserialize, Serialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct DryRunFile { contract_type: ContractType, contract_source: String, initial_state: Value, interactions: Vec<RawInteractions>, } #[allow(clippy::too_many_arguments)] pub async fn dry_run_result( port: i32, host: String, protocol: String, file: String, ) -> ExecuteResult { let dry = read_dry_run_file(file); let file = std::fs::read(dry.contract_source).expect("File source does not exist"); let dry_contract = generate_fake_loaded_contract_data( file.as_slice(), dry.contract_type, dry.initial_state.to_string(), ); let interactions = dry .interactions .iter() .map(|data| { generate_fake_interaction( data.input.to_owned(), &(data.id.to_owned())[..], data.block_id.to_owned(), data.block_height.to_owned(), Some(data.caller.to_owned()), data.recipient.to_owned(), None, Some(GQLAmountInterface { winston: { let quantity = data.quantity.to_owned(); if quantity.is_some() { Some(quantity.unwrap()) } else { Some(String::from("0")) } }, ar: None, }), Some(GQLAmountInterface { winston: { let reward = data.reward.to_owned(); if reward.is_some() { Some(reward.unwrap()) } else { Some(String::from("0")) } }, ar: None, }), data.block_timestamp, ) }) .collect::<Vec<GQLEdgeInterface>>(); let execution = raw_execute_contract( String::from(""), dry_contract, interactions, IndexMap::new(), None, true, true, |_, _, _| panic!("Unimplemented"), &Arweave::new(port, host, protocol, ArweaveCache::new()), HashMap::new(), None, ) .await; execution } #[allow(clippy::too_many_arguments)] pub async fn dry_run( port: i32, host: String, protocol: String, pretty_print: bool, show_validity: bool, file: String, ) -> Result<(), AnyError> { let execution = dry_run_result(port, host, protocol, file).await; if let ExecuteResult::V8(data) = execution { let (state, validity, result) = ( data.state, data.validity, data.result.unwrap_or(Value::default()), ); let value = if show_validity { serde_json::json!({ "state": state, "validity": validity, "result": result }) } else { state }; if pretty_print { println!("{}", serde_json::to_string_pretty(&value).unwrap()); } else { println!("{}", value); } } else { panic!("Dry run is only implemented for WASM and JS contracts"); } Ok(()) } fn read_dry_run_file<P: AsRef<Path>>(path: P) -> DryRunFile { let data = std::fs::read_to_string(path).expect("Unable to read input file"); let res: DryRunFile = serde_json::from_str(&data).expect("Unable to parse input file"); res } #[cfg(test)] mod tests { use crate::dry_run::{dry_run, dry_run_result}; use three_em_executor::executor::ExecuteResult; #[tokio::test] async fn test_dry_run() { let execution = dry_run_result( 443, String::from("arweave.net"), String::from("https"), // Exit cargo directory String::from("../../testdata/contracts/dry_run_users_contract.json"), ) .await; if let ExecuteResult::V8(data) = execution { let value = data.state; let validity_table = data.validity; assert_eq!( value, serde_json::json!({ "users": ["Andres Pirela", "Divy", "Some Other"] }) ); assert_eq!( validity_table.get_index(2).unwrap().1.to_owned(), "Error: Invalid operation\n at handle (file:///main.js:5:12)" ); } else { panic!("Unexpected result"); } } }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/cli/print_help.rs
crates/cli/print_help.rs
use indoc::indoc; pub fn print_help(sub_command: Option<&str>) { let help = match sub_command.unwrap_or("none") { "dry-run" => indoc! {" three_em dry-run [options] Runs a local contract with local interactions provided in a configuration file. Options: --host Gateway url to be used by SmartWeave APIs (Default: arweave.net) [string] --port Gateway port to be used (Default: 443) [string] --protocol Protocol to be used for gateway communication (Default: https) [http|https] --pretty-print Whether state result should be in JSON prettified form (Default: false) [boolean] --show-validity Whether validity table should be included in output (Default: false) [boolean] --file Path to configuration file to be used (Required) [string] "}, "run" => indoc! {" three_em run [options] Runs a contract deployed to the Arweave network. Options: --contract-id ID of contract to be evaluated (Required) [string] --host Gateway url to be used by Executor & SmartWeave APIs (Default: arweave.net) [string] --port Gateway port to be used (Default: 443) [string] --protocol Protocol to be used for gateway communication (Default: https) [http|https] --pretty-print Whether state result should be in JSON prettified form (Default: false) [boolean] --show-validity Whether validity table should be included in output (Default: false) [boolean] --no-print Whether no output should be displayed (Default: false) [boolean] --benchmark Whether execution time should be displayed (Default: false) [boolean] --no-cache Whether cache system should be used for evaluation (Default: true) [boolean] --show-errors Whether exceptions thrown during evaluation should be shown (Default: false) [boolean] --save Path to file where output will be saved [string] --height Maximum height to be evaluated [number] "}, "serve" => indoc! {" three_em serve [options] Creates a server with an API to evaluate contracts. Options: --host Host to be used by the server (Default: 127.0.0.1) [string] --port Port to be used by the server (Default: 5400) [number] "}, "none" | _ => indoc! {" three_em <command> [options] Commands: three_em run [options] Evaluates the latest state of a deployed contract. three_em dry-run [options] Evaluates the latest state of a local contract. three_em serve [options] Spawns a local server with an endpoint to evaluate contracts. "}, }; println!("{}", help); }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/cli/node.rs
crates/cli/node.rs
use crate::utils::{parse_node_ip, usize_to_u8_array}; use serde::{Deserialize, Serialize}; use std::io::{Read, Write}; use std::net::TcpStream; #[derive(Serialize, Deserialize)] pub struct Node { pub ip: String, pub port: i32, } impl Node { pub fn new(host: &str, port: i32) -> Node { Node { ip: String::from(host), port, } } pub fn is_not(&self, node: &Node) -> bool { let current_node = parse_node_ip(self); let diff_node = parse_node_ip(node); current_node != diff_node } #[allow(clippy::inherent_to_string)] pub fn to_string(&self) -> String { parse_node_ip(self) } } // TODO: Implement length approach pub async fn send_message( message: String, node: &Node, ) -> Result<Vec<u8>, &str> { let result = match TcpStream::connect(node.to_string()) { Ok(mut stream) => { let future = tokio::task::spawn(async move { let message_as_bytes = message.as_bytes(); let message_len = message_as_bytes.len(); let message_length = &usize_to_u8_array(message_len.to_owned() as u32); let magic_number = 0x69_u8; let mut final_message: Vec<u8> = Vec::new(); final_message.extend_from_slice(message_length); final_message.extend_from_slice(message_as_bytes); final_message.extend_from_slice(&[magic_number]); let as_bytes = &final_message[..]; stream.write_all(as_bytes).unwrap(); let mut result: Vec<u8> = Vec::new(); loop { let mut buf = [0; 1024]; let n = stream.read(&mut buf[..]).unwrap(); if n == 0 { break; } result.extend_from_slice(&buf); } result }); let result = future.await; Ok(result.unwrap()) } Err(_) => Err("Could not send message"), }; result } #[cfg(test)] mod tests { use crate::node::Node; #[tokio::test] async fn test_is_not() { let node1 = Node::new("127.0.0.1", 9999); let node2 = Node::new("127.0.0.1", 9898); assert!(node1.is_not(&node2)); let node1 = Node::new("127.0.0.1", 9999); let node2 = Node::new("127.0.0.1", 9999); assert!(!(node1.is_not(&node2))); } #[tokio::test] async fn test_to_string() { let node1 = Node::new("127.0.0.1", 9999); assert_eq!(node1.to_string(), "127.0.0.1:9999"); } }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/cli/lib.rs
crates/cli/lib.rs
mod node; mod utils;
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/cli/core_nodes.rs
crates/cli/core_nodes.rs
use crate::node::Node; pub static CORE_NODES: &str = include_str!("metadata/core_nodes.txt"); pub fn get_core_nodes() -> Vec<Node> { let nodes: Vec<String> = CORE_NODES .to_owned() .split('\n') .map(String::from) .collect(); let nodes: Vec<String> = nodes.iter().filter(|&p| !(p.eq(""))).cloned().collect(); let result = nodes .iter() .map(|content| { let data: Vec<String> = content.split(':').map(String::from).collect(); let ip = data.get(0).unwrap(); let port = data.get(1).unwrap().parse::<i32>().unwrap(); Node::new(ip, port) }) .collect(); result }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/cli/local_server.rs
crates/cli/local_server.rs
use deno_core::error::AnyError; use hyper::http::response::Parts; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Method, Request, Response, Server, StatusCode}; use indoc::indoc; use routerify::prelude::RequestExt; use routerify::{RequestInfo, Router, RouterService}; use std::collections::HashMap; use std::convert::Infallible; use std::net::{IpAddr, SocketAddr}; use std::num::ParseIntError; use std::str::{FromStr, ParseBoolError}; use three_em_arweave::arweave::Arweave; use three_em_arweave::cache::{ArweaveCache, CacheExt}; use three_em_executor::execute_contract; use three_em_executor::executor::ExecuteResult; use url::Url; pub struct ServerConfiguration { pub port: u16, pub host: IpAddr, } pub fn build_error(message: &str) -> Response<Body> { Response::builder() .status(400) .body(Body::from( serde_json::json!({ "status": 400, "message": message}) .to_string(), )) .unwrap() } async fn echo(req: Request<Body>) -> Result<Response<Body>, hyper::Error> { match (req.method(), req.uri().path()) { (&Method::GET, "/evaluate") => { let params: HashMap<String, String> = req .uri() .query() .map(|v| { url::form_urlencoded::parse(v.as_bytes()) .into_owned() .collect() }) .unwrap_or_else(HashMap::new); let contract_id = params.get("contractId").map(|i| i.to_owned()); let height = params.get("height").map(|i| i.to_owned()); let gateway_host = params.get("gatewayHost").map(|i| i.to_owned()).unwrap_or(String::from("arweave.net")); let gateway_port = params.get("gatewayPort").map(|i| i.to_owned()).unwrap_or(String::from("443")); let gateway_protocol = params.get("gatewayProtocol").map(|i| i.to_owned()).unwrap_or(String::from("https")); let show_validity = params.get("showValidity").map(|i| i.to_owned()).unwrap_or(String::from("false")); let cache = params.get("cache").map(|i| i.to_owned()).unwrap_or(String::from("false")); let show_errors = params.get("showErrors").map(|i| i.to_owned()).unwrap_or(String::from("false")); let height = height.map(|h| h.parse::<usize>().unwrap_or(usize::MAX)); let show_validity = show_validity.parse::<bool>().unwrap_or(false); let cache = cache.parse::<bool>().unwrap_or(false); let show_errors = show_errors.parse::<bool>().unwrap_or(false); let port = gateway_port.parse::<i32>().unwrap_or(443); let mut response_result: Option<Response<Body>> = None; if contract_id.is_none() { response_result = Some(build_error("contractId was not provided in query parameters. A contract id must be provided.")); } else { let arweave = Arweave::new(port, gateway_host.to_owned(), gateway_protocol.to_owned(), ArweaveCache::new()); let execute_result = execute_contract( contract_id.unwrap().to_owned(), height, cache, show_errors, None, None, &arweave).await; match execute_result { Ok(result) => { match result { ExecuteResult::V8(data) => { let val = data.state; let validity = data.validity; let result = data.result.unwrap_or(serde_json::Value::Null); if show_validity { response_result = Some(Response::new(Body::from( serde_json::json!({ "state": val, "validity": validity, "result": result }).to_string() ))); } else { response_result = Some(Response::new(Body::from( serde_json::json!({ "state": val, "result": result }).to_string() ))); } }, ExecuteResult::Evm(_, _, _) => { response_result = Some(build_error("EVM evaluation is disabled")); } } }, Err(e) => { response_result = Some(build_error(e.to_string().as_str())); } } } Ok(response_result.unwrap()) } _ => { Ok(Response::new(Body::from( "Try POSTing data to /echo such as: `curl localhost:3000/echo -XPOST -d 'hello world'`", ))) } } } pub async fn start_local_server(config: ServerConfiguration) { let addr = SocketAddr::from((config.host, config.port)); let service = make_service_fn(|_conn| async { Ok::<_, Infallible>(service_fn(echo)) }); println!("Serving {}", addr.to_string()); println!( "{}", indoc! { " Endpoints: GET /evaluate Evaluates a contract state given a contract id ?contractId Id of contract to be evaluated (Required) [string] ?height Height to be used during evaluation [number] ?gatewayHost Gateway to be used for and during evaluation (Default: arweave.net) [string] ?gatewayPort Port to be used for gateway communication (Default: 443) [number] ?gatewayProtocol Protocol to be used for gateway communication (Default: https) [string] ?showValidity Whether validity table should be included in the JSON response (Default: false) [boolean] ?cache Whether built-in cache system should be used during execution (Default: true) [boolean] ?showErrors Whether server console should print out execution exceptions (Default: false) [boolean] "} ); let server = Server::bind(&addr).executor(LocalExec).serve(service); server.await.unwrap(); } #[derive(Clone, Copy, Debug)] struct LocalExec; impl<F> hyper::rt::Executor<F> for LocalExec where F: std::future::Future + 'static, // not requiring `Send` { fn execute(&self, fut: F) { // This will spawn into the currently running `LocalSet`. tokio::task::spawn_local(fut); } }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/cli/utils.rs
crates/cli/utils.rs
use crate::node::Node; use sha2::Digest; pub fn parse_node_ip(node: &Node) -> String { parse_basic_ip(node.ip.to_string(), node.port) } pub fn parse_basic_ip(ip: String, port: i32) -> String { format!("{}:{}", ip, port) } pub fn usize_to_u8_array(num: u32) -> [u8; 4] { u32::to_le_bytes(num) } pub fn u8_array_to_usize(bytes: [u8; 4]) -> usize { u32::from_le_bytes(bytes) as usize } pub fn hasher(data: &[u8]) -> Vec<u8> { let mut hasher = sha2::Sha256::new(); hasher.update(data); hasher.finalize()[..].to_vec() } #[cfg(test)] mod tests { use crate::utils::{u8_array_to_usize, usize_to_u8_array}; #[tokio::test] async fn test_usize_to_u8_array() { let message = "Hello".repeat(100000); let bytes = message.as_bytes(); let len = bytes.len(); assert_eq!(len, 500000_usize); let to_u8_array = usize_to_u8_array(len as u32); let expected: [u8; 4] = [32, 161, 7, 0]; assert_eq!(to_u8_array, expected); assert_eq!(500000_usize, u8_array_to_usize(to_u8_array)); assert_eq!(usize_to_u8_array(500000), expected.to_owned()); } }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/cli/run.rs
crates/cli/run.rs
use deno_core::error::AnyError; use std::io::Write; use three_em_arweave::arweave::Arweave; use three_em_arweave::cache::ArweaveCache; use three_em_arweave::cache::CacheExt; use three_em_executor::execute_contract; use three_em_executor::executor::ExecuteResult; #[allow(clippy::too_many_arguments)] pub async fn run( port: i32, host: String, protocol: String, tx: String, pretty_print: bool, no_print: bool, show_validity: bool, save: bool, benchmark: bool, save_path: String, height: Option<usize>, no_cache: bool, show_errors: bool, ) -> Result<(), AnyError> { // Create a new Arweave Object with a new cache let arweave = Arweave::new(port, host, protocol, ArweaveCache::new()); let start = std::time::Instant::now(); //Run contract based on contract id - this is only a runtime so no input is sent here let execution: ExecuteResult = execute_contract(tx, height, !no_cache, show_errors, None, None, &arweave) .await?; if benchmark { let elapsed = start.elapsed(); println!("Took {}ms to execute contract", elapsed.as_millis()); } match execution { ExecuteResult::V8(data) => { let state = data.state; let validity_table = data.validity; let result = data.result.unwrap_or(serde_json::Value::Null); // return state and result when endpoint is reached. let value = if show_validity { serde_json::json!({ "state": state, "validity": validity_table, "result": result }) } else { state }; if !no_print { if pretty_print { println!("{}", serde_json::to_string_pretty(&value).unwrap()); } else { println!("{}", value); } } if save { let mut file = std::fs::File::create(save_path).unwrap(); file .write_all(serde_json::to_vec(&value).unwrap().as_slice()) .unwrap(); } } ExecuteResult::Evm(store, result, validity_table) => { let store = hex::encode(store.raw()); let result = hex::encode(result); let value = if show_validity { serde_json::json!({ "result": result, "store": store, "validity": validity_table }) } else { serde_json::json!({ "result": result, "store": store, }) }; if !no_print { if pretty_print { println!("{}", serde_json::to_string_pretty(&value).unwrap()); } else { println!("{}", value); } } } } Ok(()) }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/cli/main.rs
crates/cli/main.rs
/** * @Purpose * Parses cmd arguments. * Initiates a runtime to manage concurrency and schedule tasks * * */ // Imports the moduls in the sister files next to main mod cli; mod core_nodes; mod dry_run; mod local_server; mod messages; mod node; mod print_help; mod run; mod utils; use crate::cli::parse; use crate::cli::parse::{Flags, ParseResult}; use deno_core::error::AnyError; use crate::local_server::{start_local_server, ServerConfiguration}; use std::env; use std::net::IpAddr; use std::ops::Deref; use std::str::FromStr; fn main() -> Result<(), AnyError> { let parse_result = parse::parse()?; /** * @Runtime * Will Manage Concurrent Tasks with Ease * Such as async operations, start/pause/schedule tasks * * What is a runtime? * A layer on top of the OS. * Executable files are placed into RAM, the processor turns the executable into machine code and runs the program. * The lifetime execution of the program is the runtime. * * Why use Runtime? * Rust has built in async/await and thread operations * But more complex ops such as task scheduling, thread pools, or asynchronous I/O * need an external system to manage this for us. * Building a thread pool from scratch would require use to manually make * a dedicated Worker struct that saves JoinHandle types responsible for tracking a thread. * And of course there are tons of other features we would have to build that tokio automates. * * @Note Functions to learn * `block_on` - entry point into the runtime, WILL BLOCK main thread - need to see why this was picked. * `future` - a future task to be completed * `DryRun` - testing the programming logic without starting the program * * @Note Flags::Run is the entry point to execute an instance of the contract ready for IO-bound operations * */ let rt = tokio::runtime::Runtime::new()?; match parse_result { ParseResult::Help { cmd } => { print_help::print_help(Some(cmd.deref())); //Prints message containing list of cmds, options etc. } ParseResult::Known { flag } => { // Match whether user wants Run, DryRun, Serve match flag { Flags::Run { port, host, protocol, tx, pretty_print, no_print, show_validity, save, save_path, benchmark, height, no_cache, show_errors, } => { if tx.is_none() { print_help::print_help(Some("run")); println!("{}", "Option '--contract-id' is required"); } else { //run a new Arweave object w/ cache established - blocking the thread until future task complete rt.block_on(run::run( port, host, protocol, tx.unwrap(), pretty_print, no_print, show_validity, save, benchmark, save_path, height, no_cache, show_errors, ))?; } } Flags::DryRun { // Used to test code host, port, protocol, pretty_print, show_validity, file, } => { if file.is_none() { print_help::print_help(Some("dry-run")); println!("{}", "Option '--file' is required"); } else { rt.block_on(dry_run::dry_run( port, host, protocol, pretty_print, show_validity, file.unwrap(), ))?; } } Flags::Serve { //Spins up a local testnet server_port, server_host, } => { let ip_addr = IpAddr::from_str(server_host.as_str()); if let Err(_) = ip_addr { print_help::print_help(Some("serve")); println!("{}", "Invalid IP Address provided in '--server-host'"); } else { // Spawn the !Send future in the currently running // local task set. let local = tokio::task::LocalSet::new(); local.block_on( &rt, start_local_server(ServerConfiguration { host: ip_addr.unwrap(), port: server_port, }), ); } } }; } } Ok(()) }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/cli/three_em_arweave_docs.rs
crates/cli/three_em_arweave_docs.rs
use crate::cache::ArweaveCache; use crate::cache::CacheExt; use crate::gql_result::GQLNodeParent; use crate::gql_result::GQLResultInterface; use crate::gql_result::GQLTransactionsResultInterface; use crate::gql_result::{GQLBundled, GQLEdgeInterface}; use crate::miscellaneous::get_contract_type; use crate::miscellaneous::ContractType; use crate::utils::decode_base_64; use deno_core::error::AnyError; use deno_core::futures::stream; use deno_core::futures::StreamExt; use once_cell::sync::OnceCell; use reqwest::Client; use serde::Deserialize; use serde::Serialize; use std::fmt::Debug; use std::sync::Arc; use std::sync::Mutex; #[derive(Deserialize, Serialize, Clone)] pub struct NetworkInfo { pub network: String, pub version: usize, pub release: usize, pub height: usize, pub current: String, pub blocks: usize, pub peers: usize, pub queue_length: usize, pub node_state_latency: usize, } #[derive(Deserialize, Serialize, Default, Clone, Debug)] pub struct Tag { pub name: String, pub value: String, } #[derive(Deserialize, Serialize, Default, Clone)] pub struct TransactionData { pub format: usize, pub id: String, pub last_tx: String, pub owner: String, pub tags: Vec<Tag>, pub target: String, pub quantity: String, pub data: String, pub reward: String, pub signature: String, pub data_size: String, pub data_root: String, } #[derive(Deserialize, Serialize, Default, Clone)] pub struct BlockInfo { pub timestamp: u64, pub diff: String, pub indep_hash: String, pub height: u64, } #[derive(Deserialize, Serialize, Default, Clone)] pub struct TransactionStatus { pub block_indep_hash: String, } impl TransactionData { pub fn get_tag(&self, tag: &str) -> Result<String, AnyError> { // Encodes the tag instead of decoding the keys. let encoded_tag = base64::encode_config(tag, base64::URL_SAFE_NO_PAD); self .tags .iter() .find(|t| t.name == encoded_tag) .map(|t| Ok(String::from_utf8(base64::decode(&t.value)?)?)) .ok_or_else(|| AnyError::msg(format!("{} tag not found", tag)))? } } #[derive(Clone)] pub enum ArweaveProtocol { HTTP, HTTPS, } #[derive(Clone)] pub struct Arweave { pub host: String, pub port: i32, pub protocol: ArweaveProtocol, client: Client, } #[derive(Deserialize, Serialize, Clone)] pub struct TagFilter { name: String, values: Vec<String>, } #[derive(Deserialize, Serialize, Clone)] pub struct BlockFilter { max: usize, } #[derive(Deserialize, Serialize, Clone)] #[serde(rename_all = "camelCase")] pub struct InteractionVariables { tags: Vec<TagFilter>, block_filter: BlockFilter, first: usize, #[serde(skip_serializing_if = "Option::is_none")] #[serde(default)] after: Option<String>, } #[derive(Deserialize, Serialize)] pub struct GraphqlQuery { query: String, variables: InteractionVariables, } #[derive(Deserialize, Serialize, Clone)] pub struct LoadedContract { pub id: String, pub contract_src_tx_id: String, pub contract_src: Vec<u8>, pub contract_type: ContractType, pub init_state: String, pub min_fee: Option<String>, pub contract_transaction: TransactionData, } enum State { Next(Option<String>, InteractionVariables), #[allow(dead_code)] End, } pub static MAX_REQUEST: usize = 100; /** * @Purpose - Hold a lazy initiated value representing Arweave Cache * * @Note * `OnceCell` - Lazy initiates values, good for performance * `Arc` - Smart pointer allowing data to be shared between threads * `Mutex` - Allows one user of the cache at a time. * * `dyn` - dynamic trait object - will take any type as long as it executes the other traits * `CacheExt` - trait w/ function signatures on contract & cache manipulation * `Send` - trait allowing data to be sent between threads i.e. transfer of ownership of data * `Sync` - data can be shared between threads, no transfer of ownership in data * * @NOTE - CacheExt trait included in bottom of file. */ static ARWEAVE_CACHE: OnceCell<Arc<Mutex<dyn CacheExt + Send + Sync>>> = OnceCell::new(); pub fn get_cache() -> &'static Arc<Mutex<dyn CacheExt + Send + Sync>> { ARWEAVE_CACHE.get().expect("cache is not initialized") } impl Arweave { pub fn new<T>(port: i32, host: String, protocol: String, cache: T) -> Arweave where T: CacheExt + Send + Sync + Debug + 'static, { ARWEAVE_CACHE.set(Arc::new(Mutex::new(cache))); Arweave { port, host, protocol: match &protocol[..] { "http" => ArweaveProtocol::HTTP, "https" | _ => ArweaveProtocol::HTTPS, }, client: Client::new(), } } pub async fn get_transaction( &self, transaction_id: &str, ) -> reqwest::Result<TransactionData> { let request = self .client .get(format!("{}/tx/{}", self.get_host(), transaction_id)) .send() .await .unwrap(); let transaction = request.json::<TransactionData>().await; transaction } pub async fn get_transaction_data(&self, transaction_id: &str) -> Vec<u8> { let request = self .client .get(format!("{}/{}", self.get_host(), transaction_id)) .send() .await .unwrap(); request.bytes().await.unwrap().to_vec() } pub async fn get_transaction_block( &self, transaction_id: &str, ) -> reqwest::Result<BlockInfo> { let request = self .client .get(format!("{}/tx/{}/status", self.get_host(), transaction_id)) .send() .await?; let status = request.json::<TransactionStatus>().await?; let block_hash = status.block_indep_hash; let request = self .client .get(format!("{}/block/hash/{}", self.get_host(), block_hash)) .send() .await?; request.json::<BlockInfo>().await } pub async fn get_network_info(&self) -> NetworkInfo { let info = self .client .get(format!("{}/info", self.get_host())) .send() .await .unwrap() .json::<NetworkInfo>() .await .unwrap(); info } pub async fn get_interactions( &self, contract_id: String, height: Option<usize>, cache: bool, ) -> Result<(Vec<GQLEdgeInterface>, usize, bool), AnyError> { let mut interactions: Option<Vec<GQLEdgeInterface>> = None; let height_result = match height { Some(size) => size, None => self.get_network_info().await.height, }; if cache { if let Some(cache_interactions) = get_cache() .lock() .unwrap() .find_interactions(contract_id.to_owned()) { if !cache_interactions.is_empty() { if height.is_some() { return Ok((cache_interactions, 0, false)); } interactions = Some(cache_interactions); } } } let variables = self .get_default_gql_variables(contract_id.to_owned(), height_result) .await; let mut final_result: Vec<GQLEdgeInterface> = Vec::new(); let mut new_transactions = false; let mut new_interactions_index: usize = 0; if let Some(mut cache_interactions) = interactions { let last_transaction_edge = cache_interactions.last().unwrap(); let has_more_from_last_interaction = self .has_more(&variables, last_transaction_edge.cursor.to_owned()) .await?; if has_more_from_last_interaction { // Start from what's going to be the next interaction. if doing len - 1, that would mean we will also include the last interaction cached: not ideal. new_interactions_index = cache_interactions.len(); let fetch_more_interactions = self .stream_interactions( Some(last_transaction_edge.cursor.to_owned()), variables.to_owned(), ) .await; for result in fetch_more_interactions { let mut new_tx_infos = result.edges.clone(); cache_interactions.append(&mut new_tx_infos); } new_transactions = true; } final_result.append(&mut cache_interactions); } else { let transactions = self .get_next_interaction_page(variables.clone(), false, None) .await?; let mut tx_infos = transactions.edges.clone(); let mut cursor: Option<String> = None; let max_edge = self.get_max_edges(&transactions.edges); let maybe_edge = transactions.edges.get(max_edge); if let Some(data) = maybe_edge { let owned = data; cursor = Some(owned.cursor.to_owned()); } let results = self.stream_interactions(cursor, variables).await; for result in results { let mut new_tx_infos = result.edges.clone(); tx_infos.append(&mut new_tx_infos); } final_result.append(&mut tx_infos); new_transactions = true; } let to_return: Vec<GQLEdgeInterface>; if new_transactions { let filtered: Vec<GQLEdgeInterface> = final_result .into_iter() .filter(|p| { (p.node.parent.is_none()) || p .node .parent .as_ref() .unwrap_or(&GQLNodeParent { id: None }) .id .is_none() || (p.node.bundledIn.is_none()) || p .node .bundledIn .as_ref() .unwrap_or(&GQLBundled { id: None }) .id .is_none() }) .collect(); if cache { get_cache() .lock() .unwrap() .cache_interactions(contract_id, &filtered); } to_return = filtered; } else { to_return = final_result; } let are_there_new_interactions = cache && new_transactions; Ok(( to_return, new_interactions_index, are_there_new_interactions, )) } async fn get_next_interaction_page( &self, mut variables: InteractionVariables, from_last_page: bool, max_results: Option<usize>, ) -> Result<GQLTransactionsResultInterface, AnyError> { let mut query = String::from( r#"query Transactions($tags: [TagFilter!]!, $blockFilter: BlockFilter!, $first: Int!, $after: String) { transactions(tags: $tags, block: $blockFilter, first: $first, sort: HEIGHT_ASC, after: $after) { pageInfo { hasNextPage } edges { node { id owner { address } recipient tags { name value } block { height id timestamp } fee { winston } quantity { winston } parent { id } } cursor } } }"#, ); if from_last_page { query = query.replace("HEIGHT_ASC", "HEIGHT_DESC"); variables.first = max_results.unwrap_or(100); } let graphql_query = GraphqlQuery { query, variables }; let req_url = format!("{}/graphql", self.get_host()); let result = self .client .post(req_url) .json(&graphql_query) .send() .await .unwrap(); let data = result.json::<GQLResultInterface>().await?; Ok(data.data.transactions) } pub async fn load_contract( &self, contract_id: String, contract_src_tx_id: Option<String>, contract_type: Option<String>, cache: bool, ) -> Result<LoadedContract, AnyError> { let mut result: Option<LoadedContract> = None; if cache { result = get_cache() .lock() .unwrap() .find_contract(contract_id.to_owned()); } if result.is_some() { Ok(result.unwrap()) } else { let contract_transaction = self.get_transaction(&contract_id).await?; let contract_src = contract_src_tx_id .or_else(|| contract_transaction.get_tag("Contract-Src").ok()) .ok_or_else(|| { AnyError::msg("Contract-Src tag not found in transaction") })?; let min_fee = contract_transaction.get_tag("Min-Fee").ok(); let contract_src_tx = self.get_transaction(&contract_src).await?; let contract_src_data = self.get_transaction_data(&contract_src_tx.id).await; let mut state: String; if let Ok(init_state_tag) = contract_transaction.get_tag("Init-State") { state = init_state_tag; } else if let Ok(init_state_tag_txid) = contract_transaction.get_tag("Init-State-TX") { let init_state_tx = self.get_transaction(&init_state_tag_txid).await?; state = decode_base_64(init_state_tx.data); } else { state = decode_base_64(contract_transaction.data.to_owned()); if state.is_empty() { state = String::from_utf8( self.get_transaction_data(&contract_transaction.id).await, ) .unwrap(); } } let contract_type = get_contract_type( contract_type, &contract_transaction, &contract_src_tx, )?; let final_result = LoadedContract { id: contract_id, contract_src_tx_id: contract_src, contract_src: contract_src_data, contract_type, init_state: state, min_fee, contract_transaction, }; if cache { get_cache().lock().unwrap().cache_contract(&final_result); } Ok(final_result) } } fn get_host(&self) -> String { let protocol = match self.protocol { ArweaveProtocol::HTTP => "http", ArweaveProtocol::HTTPS => "https", }; if self.port == 80 { format!("{}://{}", protocol, self.host) } else { format!("{}://{}:{}", protocol, self.host, self.port) } } async fn get_default_gql_variables( &self, contract_id: String, height: usize, ) -> InteractionVariables { let app_name_tag: TagFilter = TagFilter { name: "App-Name".to_owned(), values: vec!["SmartWeaveAction".to_owned()], }; let contract_tag: TagFilter = TagFilter { name: "Contract".to_owned(), values: vec![contract_id], }; let variables: InteractionVariables = InteractionVariables { tags: vec![app_name_tag, contract_tag], block_filter: BlockFilter { max: height }, first: MAX_REQUEST, after: None, }; variables } async fn stream_interactions( &self, cursor: Option<String>, variables: InteractionVariables, ) -> Vec<GQLTransactionsResultInterface> { stream::unfold(State::Next(cursor, variables), |state| async move { match state { State::End => None, State::Next(cursor, variables) => { let mut new_variables: InteractionVariables = variables.clone(); new_variables.after = cursor; let tx = self .get_next_interaction_page(new_variables, false, None) .await .unwrap(); if tx.edges.is_empty() { None } else { let max_requests = self.get_max_edges(&tx.edges); let edge = tx.edges.get(max_requests); if let Some(result_edge) = edge { let cursor = (&result_edge.cursor).to_owned(); Some((tx, State::Next(Some(cursor), variables))) } else { None } } } } }) .collect::<Vec<GQLTransactionsResultInterface>>() .await } fn get_max_edges(&self, data: &[GQLEdgeInterface]) -> usize { let len = data.len(); if len == MAX_REQUEST { MAX_REQUEST - 1 } else if len == 0 { len } else { len - 1 } } async fn has_more( &self, variables: &InteractionVariables, cursor: String, ) -> Result<bool, AnyError> { let mut variables = variables.to_owned(); variables.after = Some(cursor); variables.first = 1; let load_transactions = self .get_next_interaction_page(variables, false, None) .await?; Ok(!load_transactions.edges.is_empty()) } } #[cfg(test)] mod tests { use crate::arweave::Arweave; use crate::arweave::ArweaveCache; use crate::cache::CacheExt; #[tokio::test] pub async fn test_build_host() { let arweave = Arweave::new( 80, String::from("arweave.net"), String::from("http"), ArweaveCache::new(), ); assert_eq!(arweave.get_host(), "http://arweave.net"); let arweave = Arweave::new( 443, String::from("arweave.net"), String::from("https"), ArweaveCache::new(), ); assert_eq!(arweave.get_host(), "https://arweave.net:443"); let arweave = Arweave::new( 500, String::from("arweave.net"), String::from("adksad"), ArweaveCache::new(), ); assert_eq!(arweave.get_host(), "https://arweave.net:500"); } } pub trait CacheExt: Debug { fn new() -> Self where Self: Sized; fn find_contract(&mut self, contract_id: String) -> Option<LoadedContract>; fn find_interactions( &mut self, contract_id: String ) -> Option<Vec<GQLEdgeInterface>>; fn find_state(&mut self, contract_id: String) -> Option<StateResult>; fn cache_contract(&mut self, loaded_contract: &LoadedContract); fn cache_interactions( &mut self, contract_id: String, interactions: &[GQLEdgeInterface] ); fn cache_states(&mut self, contract_id: String, state: StateResult); }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/cli/messages/get_addr.rs
crates/cli/messages/get_addr.rs
use crate::node::Node; pub fn get_addr(my_node: &Node) -> String { format!( "command:{}\nhost:{}\nversion:{}", "getAddr", my_node.to_string(), env!("CARGO_PKG_VERSION") ) }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/cli/messages/mod.rs
crates/cli/messages/mod.rs
pub mod get_addr;
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/cli/cli/parse.rs
crates/cli/cli/parse.rs
/** * * @Purpose: Parse cmd arguments so main.rs has data to execute other libs. * Parse Command Arguments and determine whether cmd is 'Run', 'DryRun' or 'Serve'. * Upon Match, grab the rest of the data from 'pargs' and feed it into the 'Flags' enum. * ParseResult enum which houses the Flags enum is then returned inside Ok() * * @Note: Code to understand right away * `subcommand()` - grabs first argument in cmd i.e. 'Run', 'DryRun' or 'Serve' * `opt_value_from_str(key)` - sees if an optional key was provided & extracts value, ex. [--height, 42] -> 42 * `unwrap_or_else()` - extract value or do something else, ex. Option<String> becomes String * `as_deref()` - converts an Option<String> into Option<&str> so we can borrow and not clone any values, more efficient. * */ use crate::print_help::print_help; use pico_args::Arguments; use std::ops::Deref; #[derive(Debug)] pub enum Flags { Run { host: String, port: i32, protocol: String, tx: Option<String>, pretty_print: bool, no_print: bool, show_validity: bool, save: bool, benchmark: bool, save_path: String, height: Option<usize>, no_cache: bool, show_errors: bool, }, DryRun { host: String, port: i32, protocol: String, pretty_print: bool, show_validity: bool, file: Option<String>, }, Serve { server_host: String, server_port: u16, }, } #[derive(Debug)] pub enum ParseResult { Help { cmd: String }, Known { flag: Flags }, } fn parse_node_limit( arguments: &mut Arguments, ) -> Result<i32, pico_args::Error> { let node_limit = arguments.opt_value_from_str("--node-limit")?.unwrap_or(8); if node_limit < 8 { panic!("At least 8 nodes are needed."); } Ok(node_limit) } pub fn parse() -> Result<ParseResult, pico_args::Error> { let mut pargs = Arguments::from_env(); //Ex. -> Arguments(["arg1", "arg2", "arg3"]) let is_help = pargs.contains("--help"); //Checks if user entered help flag /** * subcommand -> Ok(Some("arg1")) grabs first argument * as_deref -> Peels back the Ok() wrapper so its Some("arg1") * unwrap_or -> Peels back <Some> or panics * to_string -> Converts back to mutable string */ let cmd = pargs .subcommand()? .as_deref() .unwrap_or("Unknown") .to_string(); if is_help { //Store cmd with --help flag inside Help struct Ok(ParseResult::Help { cmd: String::from(cmd), }) } else { //CHECK IF subcommand was dry-run, run or serve #[allow(clippy::wildcard_in_or_patterns)] let flags = match cmd.deref() { "dry-run" => ParseResult::Known { flag: Flags::DryRun { host: pargs .opt_value_from_str("--host")? .unwrap_or_else(|| String::from("arweave.net")), port: pargs.opt_value_from_str("--port")?.unwrap_or(80), protocol: pargs .opt_value_from_str("--protocol")? .unwrap_or_else(|| String::from("https")), pretty_print: pargs.contains("--pretty-print"), show_validity: pargs.contains("--show-validity"), file: pargs.opt_value_from_str("--file").unwrap(), }, }, "run" => ParseResult::Known { flag: Flags::Run { host: pargs .opt_value_from_str("--host")? .unwrap_or_else(|| String::from("arweave.net")), port: pargs.opt_value_from_str("--port")?.unwrap_or(80), protocol: pargs .opt_value_from_str("--protocol")? .unwrap_or_else(|| String::from("https")), tx: pargs.opt_value_from_str("--contract-id").unwrap(), pretty_print: pargs.contains("--pretty-print"), no_print: pargs.contains("--no-print"), show_validity: pargs.contains("--show-validity"), save: pargs.contains("--save"), benchmark: pargs.contains("--benchmark"), save_path: pargs .opt_value_from_str("--save")? .unwrap_or_else(|| String::from("")), height: { pargs.opt_value_from_str("--height").unwrap() }, no_cache: pargs.contains("--no-cache"), show_errors: pargs.contains("--show-errors"), }, }, "serve" => ParseResult::Known { flag: Flags::Serve { server_host: pargs .opt_value_from_str("--host")? .unwrap_or_else(|| String::from("127.0.0.1")), server_port: pargs.opt_value_from_str("--port")?.unwrap_or(5400), }, }, "Unknown" | _ => ParseResult::Help { cmd: String::from("none"), }, }; Ok(flags) } }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/crates/cli/cli/mod.rs
crates/cli/cli/mod.rs
pub mod parse;
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/testdata/01_wasm/01_wasm.rs
testdata/01_wasm/01_wasm.rs
use serde::Deserialize; use serde::Serialize; use serde_json::Value; use std::alloc::alloc; use std::alloc::dealloc; use std::alloc::Layout; use std::panic; use std::sync::Once; #[link(wasm_import_module = "3em")] extern "C" { fn smartweave_read_state( // `ptr` is the pointer to the base64 URL encoded sha256 txid. ptr: *const u8, ptr_len: usize, // Pointer to the 4 byte array to store the length of the state. result_len_ptr: *mut u8, ) -> *mut u8; fn throw_error(ptr: *const u8, len: usize); } #[derive(Deserialize)] pub struct Tag { pub name: String, pub value: String, } #[derive(Deserialize)] pub struct ContractTx { pub id: String, pub owner: String, pub tags: Vec<Tag>, pub target: String, pub quantity: String, pub reward: String, } #[derive(Deserialize)] pub struct ContractBlock { pub height: usize, pub indep_hash: String, pub timestamp: usize, } #[derive(Deserialize)] pub struct ContractInfo { pub transaction: ContractTx, pub block: ContractBlock, } #[no_mangle] pub unsafe fn _alloc(len: usize) -> *mut u8 { let align = std::mem::align_of::<usize>(); let layout = Layout::from_size_align_unchecked(len, align); alloc(layout) } #[no_mangle] pub unsafe fn _dealloc(ptr: *mut u8, size: usize) { let align = std::mem::align_of::<usize>(); let layout = Layout::from_size_align_unchecked(size, align); dealloc(ptr, layout); } #[no_mangle] pub fn panic_hook(info: &panic::PanicInfo) { let payload = info.payload(); let payload_str = match payload.downcast_ref::<&str>() { Some(s) => s, None => match payload.downcast_ref::<String>() { Some(s) => s, None => "Box<Any>", }, }; let msg = format!("{}", payload_str); let msg_ptr = msg.as_ptr(); let msg_len = msg.len(); unsafe { throw_error(msg_ptr, msg_len); } std::mem::forget(msg); } #[derive(Serialize, Deserialize, Default)] pub struct State { counter: i32, } #[derive(Deserialize)] pub struct Action {} fn neat_read_state(tx_id: &[u8]) -> Value { let mut len = [0u8; 4]; let state_ptr = unsafe { smartweave_read_state(tx_id.as_ptr(), tx_id.len(), len.as_mut_ptr()) }; let len = u32::from_le_bytes(len) as usize; let state = unsafe { Vec::from_raw_parts(state_ptr, len, len) }; serde_json::from_slice(&state).unwrap() } fn neat_handle( state: State, _action: Action, contract_info: ContractInfo, ) -> State { assert_eq!(contract_info.transaction.id, ""); assert_eq!(contract_info.transaction.owner, ""); assert_eq!(contract_info.transaction.tags.len(), 0); assert_eq!(contract_info.transaction.target, ""); assert_eq!(contract_info.transaction.quantity, ""); assert_eq!(contract_info.transaction.reward, ""); assert_eq!(contract_info.block.height, 0); assert_eq!(contract_info.block.indep_hash, ""); assert_eq!(contract_info.block.timestamp, 0); let tx_id = b"t9T7DIOGxx4VWXoCEeYYarFYeERTpWIC1V3y-BPZgKE"; let other_state = neat_read_state(tx_id); State { counter: state.counter + 1, } } static mut LEN: usize = 0; #[no_mangle] pub extern "C" fn get_len() -> usize { unsafe { LEN } } #[no_mangle] pub extern "C" fn handle( state: *mut u8, state_size: usize, action: *mut u8, action_size: usize, contract_info_ptr: *mut u8, contract_info_size: usize, ) -> *const u8 { static SET_HOOK: Once = Once::new(); SET_HOOK.call_once(|| { panic::set_hook(Box::new(panic_hook)); }); let state_buf = unsafe { Vec::from_raw_parts(state, state_size, state_size) }; let state: State = serde_json::from_slice(&state_buf).unwrap(); let action_buf = unsafe { Vec::from_raw_parts(action, action_size, action_size) }; let action: Action = serde_json::from_slice(&action_buf).unwrap(); let contract_info_buf = unsafe { Vec::from_raw_parts( contract_info_ptr, contract_info_size, contract_info_size, ) }; let contract_info: ContractInfo = serde_json::from_slice(&contract_info_buf).unwrap(); let output_state = neat_handle(state, action, contract_info); let output_buf = serde_json::to_vec(&output_state).unwrap(); let output = output_buf.as_slice().as_ptr(); unsafe { LEN = output_buf.len(); } std::mem::forget(state_buf); std::mem::forget(action_buf); std::mem::forget(contract_info_buf); output }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
three-em/3em
https://github.com/three-em/3em/blob/3c0ffd8ad90850c5bb226b672bcbe2aba0b76228/testdata/03_wasm/03_wasm.rs
testdata/03_wasm/03_wasm.rs
use serde::Deserialize; use serde::Serialize; use serde_json::Value; use std::alloc::alloc; use std::alloc::dealloc; use std::alloc::Layout; #[link(wasm_import_module = "3em")] extern "C" { fn smartweave_read_state( // `ptr` is the pointer to the base64 URL encoded sha256 txid. ptr: *const u8, ptr_len: usize, // Pointer to the 4 byte array to store the length of the state. result_len_ptr: *mut u8, ) -> *mut u8; } #[derive(Deserialize)] pub struct Tag { pub name: String, pub value: String, } #[derive(Deserialize)] pub struct ContractTx { pub id: String, pub owner: String, pub tags: Vec<Tag>, pub target: String, pub quantity: String, pub reward: String, } #[derive(Deserialize)] pub struct ContractBlock { pub height: usize, pub indep_hash: String, pub timestamp: usize, } #[derive(Deserialize)] pub struct ContractInfo { pub transaction: ContractTx, pub block: ContractBlock, } #[no_mangle] pub unsafe fn _alloc(len: usize) -> *mut u8 { let align = std::mem::align_of::<usize>(); let layout = Layout::from_size_align_unchecked(len, align); alloc(layout) } #[no_mangle] pub unsafe fn _dealloc(ptr: *mut u8, size: usize) { let align = std::mem::align_of::<usize>(); let layout = Layout::from_size_align_unchecked(size, align); dealloc(ptr, layout); } #[derive(Serialize, Deserialize, Default)] pub struct State { txId: String, owner: String, height: usize, } #[derive(Deserialize)] pub struct Action {} fn neat_read_state(tx_id: &[u8]) -> Value { let mut len = [0u8; 4]; let state_ptr = unsafe { smartweave_read_state(tx_id.as_ptr(), tx_id.len(), len.as_mut_ptr()) }; let len = u32::from_le_bytes(len) as usize; let state = unsafe { Vec::from_raw_parts(state_ptr, len, len) }; serde_json::from_slice(&state).unwrap() } fn neat_handle( state: State, _action: Action, contract_info: ContractInfo, ) -> State { State { txId: contract_info.transaction.id, owner: contract_info.transaction.owner, height: contract_info.block.height, } } static mut LEN: usize = 0; #[no_mangle] pub extern "C" fn get_len() -> usize { unsafe { LEN } } #[no_mangle] pub extern "C" fn handle( state: *mut u8, state_size: usize, action: *mut u8, action_size: usize, contract_info_ptr: *mut u8, contract_info_size: usize, ) -> *const u8 { let state_buf = unsafe { Vec::from_raw_parts(state, state_size, state_size) }; let state: State = serde_json::from_slice(&state_buf).unwrap(); let action_buf = unsafe { Vec::from_raw_parts(action, action_size, action_size) }; let action: Action = serde_json::from_slice(&action_buf).unwrap(); let contract_info_buf = unsafe { Vec::from_raw_parts( contract_info_ptr, contract_info_size, contract_info_size, ) }; let contract_info: ContractInfo = serde_json::from_slice(&contract_info_buf).unwrap(); let output_state = neat_handle(state, action, contract_info); let output_buf = serde_json::to_vec(&output_state).unwrap(); let output = output_buf.as_slice().as_ptr(); unsafe { LEN = output_buf.len(); } std::mem::forget(state_buf); std::mem::forget(action_buf); std::mem::forget(contract_info_buf); output }
rust
MIT
3c0ffd8ad90850c5bb226b672bcbe2aba0b76228
2026-01-04T20:20:32.953016Z
false
r4gus/nodus
https://github.com/r4gus/nodus/blob/853a0f42a05913674b30e2a3b0a79317887422ba/src/lib.rs
src/lib.rs
pub mod world2d;
rust
MIT
853a0f42a05913674b30e2a3b0a79317887422ba
2026-01-04T20:19:46.997032Z
false
r4gus/nodus
https://github.com/r4gus/nodus/blob/853a0f42a05913674b30e2a3b0a79317887422ba/src/radial_menu.rs
src/radial_menu.rs
use bevy::prelude::*; use bevy_prototype_lyon::entity::ShapeBundle; use bevy_prototype_lyon::geometry::Geometry; use bevy_prototype_lyon::prelude::*; use lyon_tessellation::path::path::Builder; use nodus::world2d::camera2d::MainCamera; pub struct RadialMenu; impl Plugin for RadialMenu { fn build(&self, app: &mut App) { app.insert_resource(MenuSettings::default()) .add_event::<OpenMenuEvent>() .add_event::<UpdateCursorPositionEvent>() .add_event::<PropagateSelectionEvent>() .add_system_set( SystemSet::new() .label("RadialMenu") .with_system(open_menu_system.system()) .with_system(execute_and_close_system.system()) .with_system(update_system.system()), ); } } struct MenuSettings { outer_radius: f32, inner_radius: f32, main_color: Color, second_color: Color, select_color: Color, } impl MenuSettings { pub fn default() -> Self { MenuSettings { outer_radius: 220.0, inner_radius: 120.0, main_color: Color::rgba(1., 1., 1., 0.85), second_color: Color::rgba(0., 0., 0., 0.85), select_color: Color::TEAL, } } } #[derive(Component)] pub struct Menu { position: Vec2, mouse_button: MouseButton, items: usize, selected: Entity, } #[derive(Component)] struct MenuItem { id: usize, text: String, range: Vec2, } #[derive(Component)] struct ItemInfo; pub struct OpenMenuEvent { pub position: Vec2, pub mouse_button: MouseButton, pub items: Vec<(Handle<Image>, String, Vec2)>, } struct MenuItemShape { radians_distance: f32, inner_radius: f32, outer_radius: f32, item_nr: usize, } impl Geometry for MenuItemShape { fn add_geometry(&self, b: &mut Builder) { let path = create_menu_item_path( self.radians_distance, self.inner_radius, self.outer_radius, self.item_nr, ); b.concatenate(&[path.0.as_slice()]); } } fn create_menu_item_path( radians_distance: f32, inner_radius: f32, outer_radius: f32, item_nr: usize, ) -> Path { let inner_point = Vec2::new( (radians_distance * (item_nr + 1) as f32).cos() * inner_radius, (radians_distance * (item_nr + 1) as f32).sin() * inner_radius, ); let outer_point = Vec2::new( (radians_distance * item_nr as f32).cos() * outer_radius, (radians_distance * item_nr as f32).sin() * outer_radius, ); let mut arc_path = PathBuilder::new(); arc_path.move_to(inner_point); arc_path.arc( Vec2::new(0.0, 0.0), Vec2::new(inner_radius, inner_radius), -radians_distance, 0.0, ); arc_path.line_to(outer_point); arc_path.arc( Vec2::new(0.0, 0.0), Vec2::new(outer_radius, outer_radius), radians_distance, 0., ); arc_path.close(); arc_path.build() } fn create_menu_item_visual( radians_distance: f32, inner_radius: f32, outer_radius: f32, item_nr: usize, color: Color, ) -> ShapeBundle { GeometryBuilder::build_as( &MenuItemShape { radians_distance, inner_radius, outer_radius, item_nr, }, DrawMode::Fill(FillMode::color(color)), Transform::from_xyz(0., 0., 0.), ) } fn open_menu_system( mut commands: Commands, mut ev_open: EventReader<OpenMenuEvent>, settings: Res<MenuSettings>, q_menu: Query<&Menu>, asset_server: Res<AssetServer>, q_camera: Query<&mut Transform, With<MainCamera>>, ) { if let Ok(_) = q_menu.get_single() { return; } let scale = if let Ok(transform) = q_camera.get_single() { transform.scale.x } else { 1.0 }; for ev in ev_open.iter() { let radians_distance = (std::f32::consts::PI * 2.) / ev.items.len() as f32; // Create the required menu items. let mut evec = Vec::new(); for i in 0..ev.items.len() { let center = radians_distance * i as f32 + radians_distance * 0.5; let factor = settings.inner_radius + (settings.outer_radius - settings.inner_radius) * 0.5; evec.push( commands .spawn_bundle(create_menu_item_visual( radians_distance, settings.inner_radius, settings.outer_radius, i, if i == 0 { settings.select_color } else { settings.main_color }, )) .insert(MenuItem { id: i, text: ev.items[i].1.clone(), range: Vec2::new( radians_distance * i as f32, radians_distance * (i + 1) as f32, ), }) .with_children(|parent| { parent.spawn_bundle(SpriteBundle { texture: ev.items[i].0.clone(), transform: Transform::from_xyz( center.cos() * factor, center.sin() * factor, 1., ), sprite: Sprite { custom_size: Some(ev.items[i].2), ..Default::default() }, ..Default::default() }); }) .id(), ); } commands .spawn() .insert( GlobalTransform::from_xyz(ev.position.x, ev.position.y, 100.) .with_scale(Vec3::new(scale, scale, scale)), ) .insert( Transform::from_xyz(ev.position.x, ev.position.y, 100.) .with_scale(Vec3::new(scale, scale, scale)), ) .insert(Menu { position: ev.position, mouse_button: ev.mouse_button, items: ev.items.len(), selected: evec[0], }) .push_children(&evec) .with_children(|parent| { let inner_circle = GeometryBuilder::build_as( &shapes::Circle { radius: settings.inner_radius * 0.9, center: Vec2::new(0., 0.), }, DrawMode::Fill(FillMode::color(settings.second_color)), Transform::from_xyz(0., 0., 0.), ); parent .spawn_bundle(inner_circle) .insert(ItemInfo) .with_children(|parent| { parent.spawn_bundle(Text2dBundle { text: Text::with_section( &ev.items[0].1, TextStyle { font: asset_server.load("fonts/hack.bold.ttf"), font_size: 20.0, color: Color::WHITE, }, TextAlignment { horizontal: HorizontalAlign::Center, ..Default::default() }, ), transform: Transform::from_xyz(0., 0., 1.), ..Default::default() }); }); }); } } /// Information about the item selected by the user. pub struct PropagateSelectionEvent { /// Index/ ID of the selected item. pub id: usize, /// Center of the radial menu. pub position: Vec2, } fn execute_and_close_system( mut commands: Commands, mb: Res<Input<MouseButton>>, q_menu: Query<(Entity, &Menu), ()>, q_item: Query<&MenuItem>, mut ev_propagate: EventWriter<PropagateSelectionEvent>, ) { // There should only be one radial menu open at // any given moment. if let Ok((entity, menu)) = q_menu.get_single() { if mb.just_pressed(menu.mouse_button) { if let Ok(item) = q_item.get(menu.selected) { ev_propagate.send(PropagateSelectionEvent { id: item.id, position: menu.position, }); } commands.entity(entity).despawn_recursive(); } } } pub struct UpdateCursorPositionEvent(pub Vec2); fn update_system( mut commands: Commands, mut ev_open: EventReader<UpdateCursorPositionEvent>, settings: Res<MenuSettings>, mut q_menu: Query<(&Children, &mut Menu), ()>, q_item: Query<(Entity, &MenuItem)>, q_item_info: Query<(Entity, &Children), With<ItemInfo>>, asset_server: Res<AssetServer>, _q_camera: Query<&mut Transform, With<MainCamera>>, ) { if let Ok((children, mut menu)) = q_menu.get_single_mut() { for ev in ev_open.iter() { let distance = ev.0 - menu.position; let mut rad = distance.y.atan2(distance.x); if rad < 0.0 { rad = rad + std::f32::consts::PI * 2.; } for &child in children.iter() { if let Ok((entity, item)) = q_item.get(child) { if rad >= item.range.x && rad < item.range.y { if entity != menu.selected { let radians_distance = (std::f32::consts::PI * 2.) / menu.items as f32; // Highlight the new selected item. commands.entity(entity).remove_bundle::<ShapeBundle>(); commands .entity(entity) .insert_bundle(create_menu_item_visual( radians_distance, settings.inner_radius, settings.outer_radius, item.id, settings.select_color, )); // Remove highlighting from old item. if let Ok((_, item)) = q_item.get(menu.selected) { commands .entity(menu.selected) .remove_bundle::<ShapeBundle>(); commands.entity(menu.selected).insert_bundle( create_menu_item_visual( radians_distance, settings.inner_radius, settings.outer_radius, item.id, settings.main_color, ), ); } // Update info text. if let Ok((entity, children)) = q_item_info.get_single() { for &child in children.iter() { commands.entity(child).despawn_recursive(); } let id = commands .spawn_bundle(Text2dBundle { text: Text::with_section( &item.text, TextStyle { font: asset_server.load("fonts/hack.bold.ttf"), font_size: 20.0, color: Color::WHITE, }, TextAlignment { horizontal: HorizontalAlign::Center, ..Default::default() }, ), transform: Transform::from_xyz(0., 0., 1.), ..Default::default() }) .id(); commands.entity(entity).push_children(&[id]); } menu.selected = entity; } break; } } } } } }
rust
MIT
853a0f42a05913674b30e2a3b0a79317887422ba
2026-01-04T20:19:46.997032Z
false
r4gus/nodus
https://github.com/r4gus/nodus/blob/853a0f42a05913674b30e2a3b0a79317887422ba/src/gate.rs
src/gate.rs
pub mod core; pub mod file_browser; pub mod graphics; pub mod serialize; pub mod systems; pub mod ui; pub mod undo; use crate::gate::{ core::*, graphics::{ background::*, clk::*, connection_line::*, connector::*, gate::*, highlight::*, light_bulb::*, selector::*, toggle_switch::*, segment_display::*, }, serialize::*, systems::*, ui::*, undo::*, }; use crate::rmenu::*; use bevy::prelude::*; use super::GameState; pub struct LogicComponentSystem; const NODE_GROUP: u32 = 1; const CONNECTOR_GROUP: u32 = 2; impl Plugin for LogicComponentSystem { fn build(&self, app: &mut App) { app.add_event::<ConnectEvent>() .add_event::<ChangeInput>() .add_event::<DisconnectEvent>() .add_event::<SaveEvent>() .add_event::<LoadEvent>() .add_event::<InsertGateEvent>() .add_event::<NewConnectionEstablishedEvent>() .add_plugin(GateMenuPlugin) .add_plugin(UndoPlugin) .insert_resource(LineResource { count: 0., timestep: 0.5, update: false, }) .insert_resource(GuiMenu { option: GuiMenuOptions::None, open: false, }) .add_startup_system(update_ui_scale_factor) .add_startup_system(load_gui_assets) .add_system_set( SystemSet::on_update(GameState::InGame) .before("interaction2d") .label("level3_node_set") .with_system(ui_node_info_system.label("ui_info")) .with_system(ui_top_panel_system.label("ui_panel")) .with_system(ui_scroll_system.label("ui_scroll")) .with_system(ui_gui_about.label("ui_about")) .with_system( ui_reset_input .after("ui_info") .after("ui_panel") .after("ui_scroll") .after("ui_about") ) ) .add_system_set( SystemSet::on_update(GameState::InGame) .label("level2_node_set") .after("interaction2d") // It's important to run disconnect before systems that delete // nodes (and therefore connectors) because disconnect_event // wants to insert(Free) connectors even if they are queued for // deletion. .with_system(disconnect_event_system.system().label("disconnect")) .with_system(delete_gate_system.system().after("disconnect")) .with_system(change_input_system.system().after("disconnect")) .with_system(delete_line_system.system().after("disconnect")) .with_system(transition_system.system().label("transition")) .with_system(propagation_system.system().after("transition")) .with_system(highlight_connector_system.system()) .with_system(drag_gate_system.system()) .with_system(drag_connector_system.system().label("drag_conn_system")) .with_system(connect_event_system.system().after("drag_conn_system")) .with_system(insert_gate_system.after("handle_rad_event")) // Draw Line inserts a new bundle into an entity that might has been // deleted by delete_line_system, i.e. we run it before any deletions // to prevent an segfault. .with_system( draw_line_system .system() .label("draw_line") .before("disconnect"), ) //.with_system(draw_data_flow.system().after("draw_line")) .with_system(highlight_system.before("disconnect")) .with_system(remove_highlight_system.before("disconnect")) .with_system(change_highlight_system.before("disconnect")) .with_system(light_bulb_system.system().before("disconnect")) .with_system(segment_system.before("disconnect")) .with_system(toggle_switch_system.system().before("disconnect")) .with_system(line_selection_system.system().after("draw_line")) .with_system(draw_background_grid_system) .with_system(clk_system), ) .add_system_set( SystemSet::on_update(GameState::InGame) .label("level1_node_set") .after("level2_node_set") .with_system(selector_system) .with_system(save_event_system.before("new_file")) // The link_gates_system requires entities spawned by the // load_event_system. To make sure the entities can be // queried the link_gates_system must always run before the // load_event_system, so one can be sure that all entites // have been inserted into the world. .with_system(link_gates_system.label("link_gates_system")) .with_system(load_event_system.after("link_gates_system")) .with_system(shortcut_system) .with_system(update_lock), ) .add_system_set( SystemSet::on_enter(GameState::InGame) .with_system(setup.system()) ); info!("NodePlugin loaded"); } } pub fn setup(mut commands: Commands) { }
rust
MIT
853a0f42a05913674b30e2a3b0a79317887422ba
2026-01-04T20:19:46.997032Z
false
r4gus/nodus
https://github.com/r4gus/nodus/blob/853a0f42a05913674b30e2a3b0a79317887422ba/src/world2d.rs
src/world2d.rs
use crate::world2d::camera2d::Camera2DPlugin; use crate::world2d::interaction2d::Interaction2DPlugin; use bevy::prelude::*; /// Ugly solution for ignoring input. pub struct Lock(pub bool); #[derive(Debug, Clone, PartialEq, Eq)] pub enum InteractionMode { Select, Pan, } pub struct NodusWorld2DPlugin; impl Plugin for NodusWorld2DPlugin { fn build(&self, app: &mut App) { app.insert_resource(InteractionMode::Select) .insert_resource(Lock(false)) .add_plugin(Camera2DPlugin) .add_plugin(Interaction2DPlugin); } } /* fn update_cursor_system( mut mode: ResMut<InteractionMode>, mut wnds: ResMut<Windows>, ) { if mode.is_changed() { eprintln!("change"); let window = wnds.get_primary_mut().unwrap(); match *mode { InteractionMode::Select => { window.set_cursor_icon(CursorIcon::Hand); }, InteractionMode::Pan => { window.set_cursor_icon(CursorIcon::Hand); }, } window.set_cursor_icon(CursorIcon::Hand); eprintln!("{:?}", window.cursor_icon()); } } */ pub mod camera2d { use super::{InteractionMode, Lock}; use bevy::input::mouse::{MouseMotion, MouseWheel}; use bevy::prelude::*; use core::ops::{Deref, DerefMut}; pub struct Camera2DPlugin; impl Plugin for Camera2DPlugin { fn build(&self, app: &mut App) { app.insert_resource(MouseWorldPos(Vec2::new(0., 0.))) .add_startup_system(setup.system()) .add_system(cursor_system.system()) .add_system(pan_zoom_camera_system.system()); } } /// Used to help identify the main camera. #[derive(Component)] pub struct MainCamera; /// Position resource of the mouse cursor within the 2d world. pub struct MouseWorldPos(pub Vec2); impl Deref for MouseWorldPos { type Target = Vec2; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for MouseWorldPos { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } pub fn setup(mut commands: Commands) { // Spawn main camera with the orthographic projection // camera bundle. commands .spawn_bundle(OrthographicCameraBundle::new_2d()) .insert(MainCamera); } /// Calculate the cursor position within a 2d world. /// This updates the MouseWorldPos resource. pub fn cursor_system( // need to get window dimensions. wnds: Res<Windows>, // need to update the mouse world position. mut mw: ResMut<MouseWorldPos>, // query to get camera transform. q_camera: Query<&Transform, With<MainCamera>>, ) { // get the primary window. let wnd = wnds.get_primary().unwrap(); // check if the cursor is in the primary window. if let Some(pos) = wnd.cursor_position() { // get the size of the window. let size = Vec2::new(wnd.width() as f32, wnd.height() as f32); // the default orthographic projection is in pixels from the center, // so we need to undo the translation. let p = pos - size / 2.; // assuming there is exacly one main camera entity, so this is ok. let camera_transform = q_camera.single(); // apply the camera transform. let pos_wld = camera_transform.compute_matrix() * p.extend(0.).extend(1.); //eprintln!("{}:{}", pos_wld.x, pos_wld.y); mw.x = pos_wld.x; mw.y = pos_wld.y; } } pub fn pan_zoom_camera_system( mut ev_motion: EventReader<MouseMotion>, mut ev_scroll: EventReader<MouseWheel>, input_mouse: Res<Input<MouseButton>>, mut q_camera: Query<&mut Transform, With<MainCamera>>, time: Res<Time>, mode: Res<InteractionMode>, lock: Res<Lock>, ) { if lock.0 { return; } let mut pan = Vec2::ZERO; let mut scroll = 0.0; if *mode == InteractionMode::Pan && input_mouse.pressed(MouseButton::Left) { for ev in ev_motion.iter() { pan += ev.delta; } } for ev in ev_scroll.iter() { scroll += ev.y; } // assuming there is exacly one main camera entity, so this is ok. if let Ok(mut transform) = q_camera.get_single_mut() { if pan.length_squared() > 0.0 { let scale = transform.scale.x; transform.translation.x -= pan.x * scale; transform.translation.y += pan.y * scale; } else if scroll.abs() > 0.0 { let scale = (transform.scale.x - scroll * time.delta_seconds()).clamp(1.0, 5.0); transform.scale = Vec3::new(scale, scale, scale); } } } pub fn get_primary_window_size(windows: &Res<Windows>) -> Vec2 { let window = windows.get_primary().unwrap(); let window = Vec2::new(window.width() as f32, window.height() as f32); window } } pub mod interaction2d { use super::camera2d::MouseWorldPos; use super::{InteractionMode, Lock}; use bevy::prelude::*; pub struct Interaction2DPlugin; impl Plugin for Interaction2DPlugin { fn build(&self, app: &mut App) { app.add_system_set( SystemSet::new() .label("interaction2d") .with_system(interaction_system.system().label("interaction")) .with_system(selection_system.system().after("interaction")) .with_system(drag_system.system()), ); } } /// Marker component for selected entities. #[derive(Debug, Component)] pub struct Selected; /// Component that marks an entity as selectable. #[derive(Component)] pub struct Selectable; /// Component that marks an entity interactable. #[derive(Component)] pub struct Interactable { /// The bounding box defines the area where the mouse /// can interact with the entity. bounding_box: (Vec2, Vec2, Vec2, Vec2, Vec2), /// The group this interactable entity belongs to. This /// can be a item, enemy, ... or just use one group for /// everything. group: u32, } impl Interactable { /// Create a new interactable component. /// /// # Arguments /// /// * `position` - The position of the bounding box within the world. /// * `dimensions` - The width and the height of the bounding box. /// * `group` - The group the selectable entity belongs to. /// /// The `position` marks the center of the bounding box. pub fn new(position: Vec2, dimensions: Vec2, group: u32) -> Self { Self { bounding_box: ( Vec2::new( // upper left position.x - dimensions.x / 2., position.y - dimensions.y / 2., ), Vec2::new( // upper right position.x + dimensions.x / 2., position.y - dimensions.y / 2., ), Vec2::new( // lower left position.x - dimensions.x / 2., position.y + dimensions.y / 2., ), Vec2::new( // lower right position.x + dimensions.x / 2., position.y + dimensions.y / 2., ), dimensions, ), group, } } pub fn update_size(&mut self, x: f32, y: f32, width: f32, height: f32) { self.bounding_box.0 = Vec2::new(x - width / 2., y - height / 2.); self.bounding_box.1 = Vec2::new(x + width / 2., y - height / 2.); self.bounding_box.2 = Vec2::new(x - width / 2., y + height / 2.); self.bounding_box.3 = Vec2::new(x + width / 2., y + height / 2.); self.bounding_box.4 = Vec2::new(width, height); } } /// Marker component to indicate that the mouse /// currently hovers over the given entity. #[derive(Component)] pub struct Hover; /// Component that marks an entity as draggable. #[derive(Component)] pub struct Draggable { /// The drag system should automatically update /// the entities transformation while being dragged /// [y/ n]. pub update: bool, } /// Marker component to indicate that the /// given entity is currently dragged. #[derive(Component)] pub struct Drag { /// The click offset is the distance between the /// translation of the clicked entity and the position /// where the click occured. click_offset: Vec2, } /// Check if the mouse interacts with interactable entities in the world. /// /// If the mouse hovers over an interactable entity, the `Hover` marker /// component is inserted. Otherwise the marker component is removed. /// /// To check if the mouse hovers over an entity, the system uses the bounding /// box of the entity relative to its global transform. pub fn interaction_system( mut commands: Commands, // we need the mouse position within the world. mw: Res<MouseWorldPos>, // query to get all interactable entities. q_interact: Query<(Entity, &Interactable, &GlobalTransform)>, ) { for (entity, interactable, transform) in q_interact.iter() { let a = transform.rotation.to_axis_angle().1; // Rotate each point around the origin let mut p1 = Vec2::new( interactable.bounding_box.0.x * a.cos() - interactable.bounding_box.0.y * a.sin(), interactable.bounding_box.0.x * a.sin() - interactable.bounding_box.0.y * a.cos(), ); let mut p2 = Vec2::new( interactable.bounding_box.1.x * a.cos() - interactable.bounding_box.1.y * a.sin(), interactable.bounding_box.1.x * a.sin() - interactable.bounding_box.1.y * a.cos(), ); let mut p3 = Vec2::new( interactable.bounding_box.2.x * a.cos() - interactable.bounding_box.2.y * a.sin(), interactable.bounding_box.2.x * a.sin() - interactable.bounding_box.2.y * a.cos(), ); let mut p4 = Vec2::new( interactable.bounding_box.3.x * a.cos() - interactable.bounding_box.3.y * a.sin(), interactable.bounding_box.3.x * a.sin() - interactable.bounding_box.3.y * a.cos(), ); // Then apply the actual offset to each point p1.x += transform.translation.x; p1.y += transform.translation.y; p2.x += transform.translation.x; p2.y += transform.translation.y; p3.x += transform.translation.x; p3.y += transform.translation.y; p4.x += transform.translation.x; p4.y += transform.translation.y; // Calculate the dot product of three points let dot = |p1: Vec2, p2: Vec2, p3: Vec2| -> f32 { ((p2.x - p1.x) * (p3.x - p1.x)) + ((p2.y - p1.y) * (p3.y - p1.y)) }; let mut hover = true; // Check if the muse cursor is within the rotated rectangle if dot(p1, p2, **mw) <= 0.0 || dot(p2, p4, **mw) <= 0.0 || dot(p4, p3, **mw) <= 0.0 || dot(p3, p1, **mw) <= 0.0 { hover = false; } if hover { //eprintln!("hover {:?}", entity); commands.entity(entity).insert(Hover); } else { commands.entity(entity).remove::<Hover>(); } } } /// Select interactable elements. /// /// A left click on an interactable entity will move it into its dedicated group. pub fn selection_system( mut commands: Commands, mw: Res<MouseWorldPos>, mb: ResMut<Input<MouseButton>>, mode: Res<InteractionMode>, // query all entities that are selectable and that // the mouse currently hovers over. q_select: Query< (Entity, &Transform, &Interactable, Option<&Draggable>), // Filter (With<Selectable>, With<Hover>), >, q_selected: Query<Entity, With<Selected>>, q_drag: Query<&Transform, With<Draggable>>, lock: Res<Lock>, ) { if !lock.0 && *mode == InteractionMode::Select && mb.just_pressed(MouseButton::Left) { let mut e: Option<Entity> = None; let mut greatest: f32 = -1.; let mut drag: bool = false; let mut pos: Vec2 = Vec2::new(0., 0.); for (entity, transform, _interact, draggable) in q_select.iter() { if transform.translation.z > greatest { greatest = transform.translation.z; drag = if let Some(_) = draggable { true } else { false }; pos.x = transform.translation.x; pos.y = transform.translation.y; e = Some(entity); } } let mut entities = Vec::new(); for entity in q_selected.iter() { entities.push(entity); } if entities.len() > 1 { if let Some(entity) = e { if entities.contains(&entity) { for &e in entities.iter() { if let Ok(t) = q_drag.get(e) { let p = Vec2::new(t.translation.x, t.translation.y); commands.entity(e).insert(Drag { click_offset: p - **mw, }); } } } else { for e in entities { commands.entity(e).remove::<Selected>(); } if drag { commands.entity(entity).insert(Drag { click_offset: pos - **mw, }); } commands.entity(entity).insert(Selected); } } else { // Clicked on empty space -> deselect all for entity in entities { commands.entity(entity).remove::<Selected>(); } } } else { for entity in entities { commands.entity(entity).remove::<Selected>(); } if let Some(entity) = e { if drag { commands.entity(entity).insert(Drag { click_offset: pos - **mw, }); } commands.entity(entity).insert(Selected); } } } } pub fn drag_system( mw: Res<MouseWorldPos>, mut q_drag: Query<(&mut Transform, &Draggable, &Drag), ()>, ) { for (mut transform, draggable, drag) in q_drag.iter_mut() { if draggable.update { transform.translation.x = mw.x + drag.click_offset.x; transform.translation.y = mw.y + drag.click_offset.y; } } } }
rust
MIT
853a0f42a05913674b30e2a3b0a79317887422ba
2026-01-04T20:19:46.997032Z
false
r4gus/nodus
https://github.com/r4gus/nodus/blob/853a0f42a05913674b30e2a3b0a79317887422ba/src/rmenu.rs
src/rmenu.rs
use crate::radial_menu::{OpenMenuEvent, PropagateSelectionEvent, UpdateCursorPositionEvent}; use crate::{GameState}; use bevy::prelude::*; use crate::gate::systems::InsertGateEvent; use bevy_asset_loader::AssetCollection; use nodus::world2d::camera2d::MouseWorldPos; pub struct GateMenuPlugin; impl Plugin for GateMenuPlugin { fn build(&self, app: &mut App) { app.insert_resource(MenuState(MenuStates::Idle)) .add_system_set( SystemSet::on_update(GameState::InGame) .with_system(open_radial_menu_system) .with_system(handle_radial_menu_event_system.label("handle_rad_event")) .with_system(update_radial_menu_system), ); } } #[derive(AssetCollection)] pub struct GateAssets { #[asset(path = "gates/not.png")] pub not: Handle<Image>, #[asset(path = "gates/NOT_BS.png")] pub not_bs: Handle<Image>, #[asset(path = "gates/and.png")] pub and: Handle<Image>, #[asset(path = "gates/AND_BS.png")] pub and_bs: Handle<Image>, #[asset(path = "gates/nand.png")] pub nand: Handle<Image>, #[asset(path = "gates/NAND_BS.png")] pub nand_bs: Handle<Image>, #[asset(path = "gates/or.png")] pub or: Handle<Image>, #[asset(path = "gates/OR_BS.png")] pub or_bs: Handle<Image>, #[asset(path = "gates/nor.png")] pub nor: Handle<Image>, #[asset(path = "gates/NOR_BS.png")] pub nor_bs: Handle<Image>, #[asset(path = "gates/xor.png")] pub xor: Handle<Image>, #[asset(path = "gates/XOR_BS.png")] pub xor_bs: Handle<Image>, #[asset(path = "gates/back.png")] pub back: Handle<Image>, #[asset(path = "gates/close.png")] pub close: Handle<Image>, #[asset(path = "gates/circuit.png")] pub circuit: Handle<Image>, #[asset(path = "gates/in.png")] pub inputs: Handle<Image>, #[asset(path = "gates/out.png")] pub outputs: Handle<Image>, #[asset(path = "gates/high.png")] pub high: Handle<Image>, #[asset(path = "gates/low.png")] pub low: Handle<Image>, #[asset(path = "gates/toggle.png")] pub toggle: Handle<Image>, #[asset(path = "gates/bulb.png")] pub bulb: Handle<Image>, #[asset(path = "gates/CLK.png")] pub clk: Handle<Image>, #[asset(path = "gates/sevenseg.png")] pub seg: Handle<Image>, } #[derive(Debug, Eq, PartialEq)] enum MenuStates { Idle, Select, LogicGates, Inputs, Outputs, } struct MenuState(MenuStates); fn open_radial_menu_system( mb: Res<Input<MouseButton>>, mw: Res<MouseWorldPos>, assets: Res<GateAssets>, mut ms: ResMut<MenuState>, mut ev_open: EventWriter<OpenMenuEvent>, ) { if mb.just_pressed(MouseButton::Right) && ms.0 == MenuStates::Idle { ev_open.send(OpenMenuEvent { position: Vec2::new(mw.x, mw.y), mouse_button: MouseButton::Left, items: vec![ ( assets.close.clone(), "close".to_string(), Vec2::new(80., 80.), ), ( assets.circuit.clone(), "Show Logic\nGates".to_string(), Vec2::new(80., 80.), ), ( assets.inputs.clone(), "Show Input\nControls".to_string(), Vec2::new(80., 80.), ), ( assets.outputs.clone(), "Show Output\nControls".to_string(), Vec2::new(80., 80.), ), ], }); ms.0 = MenuStates::Select; } } fn update_radial_menu_system( mw: Res<MouseWorldPos>, mut ev_update: EventWriter<UpdateCursorPositionEvent>, ) { ev_update.send(UpdateCursorPositionEvent(mw.0)); } fn handle_radial_menu_event_system( mut ev_radial: EventReader<PropagateSelectionEvent>, mut ev_open: EventWriter<OpenMenuEvent>, mut ev_insert: EventWriter<InsertGateEvent>, assets: Res<GateAssets>, mut ms: ResMut<MenuState>, ) { for ev in ev_radial.iter() { match ms.0 { MenuStates::Select => match ev.id { 1 => { ev_open.send(OpenMenuEvent { position: ev.position, mouse_button: MouseButton::Left, items: vec![ (assets.back.clone(), "back".to_string(), Vec2::new(80., 80.)), ( assets.and_bs.clone(), "AND gate".to_string(), Vec2::new(80., 80.), ), ( assets.nand_bs.clone(), "NAND gate".to_string(), Vec2::new(80., 80.), ), ( assets.or_bs.clone(), "OR gate".to_string(), Vec2::new(80., 80.), ), ( assets.nor_bs.clone(), "NOR gate".to_string(), Vec2::new(80., 80.), ), ( assets.not_bs.clone(), "NOT gate".to_string(), Vec2::new(80., 80.), ), ( assets.xor_bs.clone(), "XOR gate".to_string(), Vec2::new(80., 80.), ), ], }); ms.0 = MenuStates::LogicGates; } 2 => { ev_open.send(OpenMenuEvent { position: ev.position, mouse_button: MouseButton::Left, items: vec![ (assets.back.clone(), "back".to_string(), Vec2::new(80., 80.)), ( assets.high.clone(), "HIGH const".to_string(), Vec2::new(80., 80.), ), ( assets.low.clone(), "LOW const".to_string(), Vec2::new(80., 80.), ), ( assets.toggle.clone(), "Toggle Switch".to_string(), Vec2::new(80., 80.), ), (assets.clk.clone(), "Clock".to_string(), Vec2::new(70., 70.)), ], }); ms.0 = MenuStates::Inputs; } 3 => { ev_open.send(OpenMenuEvent { position: ev.position, mouse_button: MouseButton::Left, items: vec![ (assets.back.clone(), "back".to_string(), Vec2::new(80., 80.)), ( assets.bulb.clone(), "Light Bulb".to_string(), Vec2::new(80., 80.), ), ( assets.seg.clone(), "7-Segment Display".to_string(), Vec2::new(80., 80.), ), ], }); ms.0 = MenuStates::Outputs; } _ => { ms.0 = MenuStates::Idle; } }, MenuStates::LogicGates => match ev.id { 1 => { ev_insert.send(InsertGateEvent::and(ev.position)); ms.0 = MenuStates::Idle; } 2 => { ev_insert.send(InsertGateEvent::nand(ev.position)); ms.0 = MenuStates::Idle; } 3 => { ev_insert.send(InsertGateEvent::or(ev.position)); ms.0 = MenuStates::Idle; } 4 => { ev_insert.send(InsertGateEvent::nor(ev.position)); ms.0 = MenuStates::Idle; } 5 => { ev_insert.send(InsertGateEvent::not(ev.position)); ms.0 = MenuStates::Idle; } 6 => { ev_insert.send(InsertGateEvent::xor(ev.position)); ms.0 = MenuStates::Idle; } _ => { ev_open.send(OpenMenuEvent { position: ev.position, mouse_button: MouseButton::Left, items: vec![ ( assets.close.clone(), "close".to_string(), Vec2::new(80., 80.), ), ( assets.circuit.clone(), "Show Logic\nGates".to_string(), Vec2::new(80., 80.), ), ( assets.inputs.clone(), "Show Input\nControls".to_string(), Vec2::new(80., 80.), ), ( assets.outputs.clone(), "Show Output\nControls".to_string(), Vec2::new(80., 80.), ), ], }); ms.0 = MenuStates::Select; } }, MenuStates::Inputs => match ev.id { 1 => { ev_insert.send(InsertGateEvent::high(ev.position)); ms.0 = MenuStates::Idle; } 2 => { ev_insert.send(InsertGateEvent::low(ev.position)); ms.0 = MenuStates::Idle; } 3 => { ev_insert.send(InsertGateEvent::toggle(ev.position)); ms.0 = MenuStates::Idle; } 4 => { ev_insert.send(InsertGateEvent::clk(ev.position)); ms.0 = MenuStates::Idle; } _ => { ev_open.send(OpenMenuEvent { position: ev.position, mouse_button: MouseButton::Left, items: vec![ ( assets.close.clone(), "close".to_string(), Vec2::new(80., 80.), ), ( assets.circuit.clone(), "Show Logic\nGates".to_string(), Vec2::new(80., 80.), ), ( assets.inputs.clone(), "Show Input\nControls".to_string(), Vec2::new(80., 80.), ), ( assets.outputs.clone(), "Show Output\nControls".to_string(), Vec2::new(80., 80.), ), ], }); ms.0 = MenuStates::Select; } }, MenuStates::Outputs => match ev.id { 1 => { ev_insert.send(InsertGateEvent::light(ev.position)); ms.0 = MenuStates::Idle; }, 2 => { ev_insert.send(InsertGateEvent::seg(ev.position)); ms.0 = MenuStates::Idle; }, _ => { ev_open.send(OpenMenuEvent { position: ev.position, mouse_button: MouseButton::Left, items: vec![ ( assets.close.clone(), "close".to_string(), Vec2::new(80., 80.), ), ( assets.circuit.clone(), "Show Logic\nGates".to_string(), Vec2::new(80., 80.), ), ( assets.inputs.clone(), "Show Input\nControls".to_string(), Vec2::new(80., 80.), ), ( assets.outputs.clone(), "Show Output\nControls".to_string(), Vec2::new(80., 80.), ), ], }); ms.0 = MenuStates::Select; } }, MenuStates::Idle => {} // This should never happen } } }
rust
MIT
853a0f42a05913674b30e2a3b0a79317887422ba
2026-01-04T20:19:46.997032Z
false
r4gus/nodus
https://github.com/r4gus/nodus/blob/853a0f42a05913674b30e2a3b0a79317887422ba/src/main.rs
src/main.rs
use bevy::diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin}; use bevy::prelude::*; use bevy_asset_loader::{AssetCollection, AssetLoader}; use bevy_egui::EguiPlugin; use bevy_prototype_lyon::prelude::*; mod gate; mod radial_menu; mod rmenu; // specific usage of the radial_menu use crate::gate::file_browser::*; use gate::LogicComponentSystem; use nodus::world2d::NodusWorld2DPlugin; use rmenu::GateAssets; use radial_menu::RadialMenu; #[derive(Clone, Eq, PartialEq, Debug, Hash)] enum GameState { AssetLoading, InGame, } fn main() { let mut app = App::new(); AssetLoader::new(GameState::AssetLoading) .continue_to_state(GameState::InGame) .with_collection::<FontAssets>() .with_collection::<GateAssets>() .build(&mut app); app.add_state(GameState::AssetLoading) .insert_resource(Msaa { samples: 1 }) .insert_resource(ClearColor(Color::rgb(0.75, 0.75, 0.75))) .insert_resource(WindowDescriptor { title: "nodus".to_string(), width: 1920., height: 1080., vsync: true, ..Default::default() }) .add_plugins(DefaultPlugins) .add_plugin(EguiPlugin) .add_plugin(EguiFileBrowserPlugin) .add_plugin(ShapePlugin) // 2d drawing .add_plugin(LogDiagnosticsPlugin::default()) .add_plugin(FrameTimeDiagnosticsPlugin::default()) .add_plugin(NodusWorld2DPlugin) .add_plugin(LogicComponentSystem) .add_plugin(RadialMenu) .run(); } #[derive(AssetCollection)] pub struct FontAssets { #[asset(path = "fonts/hack.bold.ttf")] pub main: Handle<Font>, }
rust
MIT
853a0f42a05913674b30e2a3b0a79317887422ba
2026-01-04T20:19:46.997032Z
false
r4gus/nodus
https://github.com/r4gus/nodus/blob/853a0f42a05913674b30e2a3b0a79317887422ba/src/gate/graphics.rs
src/gate/graphics.rs
pub mod background; pub mod clk; pub mod connection_line; pub mod connector; pub mod gate; pub mod highlight; pub mod light_bulb; pub mod selector; pub mod toggle_switch; pub mod segment_display; use core::sync::atomic::AtomicI32; pub static Z_INDEX: AtomicI32 = AtomicI32::new(10); pub const GATE_SIZE: f32 = 128.; pub const GATE_WIDTH: f32 = 64.; pub const GATE_HEIGHT: f32 = 128.;
rust
MIT
853a0f42a05913674b30e2a3b0a79317887422ba
2026-01-04T20:19:46.997032Z
false
r4gus/nodus
https://github.com/r4gus/nodus/blob/853a0f42a05913674b30e2a3b0a79317887422ba/src/gate/core.rs
src/gate/core.rs
use bevy::prelude::*; use serde::{Deserialize, Serialize}; use std::{ collections::HashMap, ops::{Deref, DerefMut}, }; macro_rules! trans { ( $( $fun:expr ),* ) => { vec![ $( Box::new($fun) ),* ] }; ( $( $fun:expr ),+ ,) => { trans![ $( $fun ),* ] }; } pub(crate) use trans; /// The name of an entity. #[derive(Debug, Clone, PartialEq, Component, Reflect, Default)] #[reflect(Component)] pub struct Name(pub String); /// The input and output states of a logic gate. /// /// # States /// `None` - The state is unknown, for example because the gate /// doesn't get a value for each input. /// `High` - The sate is high (`1`). /// `Low` - The state is low (`0`). #[derive( Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, bevy::reflect::FromReflect, Serialize, Deserialize, )] pub enum State { None, High, Low, } impl Default for State { fn default() -> Self { Self::None } } /// Specify the minimum and maximum number a connectors for a logic component. #[derive(Debug, Copy, Clone, PartialEq, Reflect, Default)] pub struct NodeRange { pub min: u32, pub max: u32, } /// Gate ECS component. /// /// # Attributes /// /// * `inputs` - Current number of input connectors. /// * `outputs` - Current number of output connectors. /// * `in_range` - Allowed minimum and maximum of inputs connectors. /// * `out_range` - Allowed minimum and maximum of inputs connectors. #[derive(Debug, Clone, PartialEq, Component, Reflect, Default)] #[reflect(Component)] pub struct Gate { pub inputs: u32, pub outputs: u32, pub in_range: NodeRange, pub out_range: NodeRange, } impl Gate { #[allow(dead_code)] pub fn new( commands: &mut Commands, name: &str, in_range: NodeRange, out_range: NodeRange, functions: Vec<Box<dyn Fn(&[State]) -> State + Send + Sync>>, ) -> Entity { let gate = commands .spawn() .insert(Self { inputs: in_range.min, outputs: out_range.min, in_range, out_range, }) .insert(Name(name.to_string())) .insert(Inputs(vec![State::None; in_range.min as usize])) .insert(Outputs(vec![State::None; out_range.min as usize])) .insert(Transitions(functions)) .insert(Targets(vec![ TargetMap::from(HashMap::new()); out_range.min as usize ])) .id(); let mut connectors = Vec::new(); for i in 0..in_range.min as usize { connectors.push(Connector::new(commands, ConnectorType::In, i, format!("x{}", i))); } for i in 0..in_range.min as usize { connectors.push(Connector::new(commands, ConnectorType::Out, i, format!("y{}", i))); } commands.entity(gate).push_children(&connectors); gate } #[allow(dead_code)] pub fn from_world( world: &mut World, name: &str, in_range: NodeRange, out_range: NodeRange, functions: Vec<Box<dyn Fn(&[State]) -> State + Send + Sync>>, ) -> Entity { let gate = world .spawn() .insert(Self { inputs: in_range.min, outputs: out_range.min, in_range, out_range, }) .insert(Name(name.to_string())) .insert(Inputs(vec![State::None; in_range.min as usize])) .insert(Outputs(vec![State::None; out_range.min as usize])) .insert(Transitions(functions)) .insert(Targets(vec![ TargetMap::from(HashMap::new()); out_range.min as usize ])) .id(); let mut connectors = Vec::new(); for i in 0..in_range.min as usize { connectors.push(Connector::from_world(world, ConnectorType::In, i, format!("y{}", i))); } for i in 0..in_range.min as usize { connectors.push(Connector::from_world(world, ConnectorType::Out, i, format!("y{}", i))); } world.entity_mut(gate).push_children(&connectors); gate } } /// Input values of a gate. #[derive(Debug, Clone, PartialEq, Component, Reflect)] #[reflect(Component)] pub struct Inputs(pub Vec<State>); impl Default for Inputs { fn default() -> Self { Inputs(Vec::new()) } } impl Deref for Inputs { type Target = Vec<State>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for Inputs { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } /// Output values of a gate. #[derive(Debug, Clone, PartialEq, Component, Reflect)] #[reflect(Component)] pub struct Outputs(pub Vec<State>); impl Default for Outputs { fn default() -> Self { Outputs(Vec::new()) } } impl Deref for Outputs { type Target = Vec<State>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for Outputs { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } /// A set of transition functions `f: Inputs -> State`. /// /// For a gate there should be a transition function for each output, that /// calculates a new output value from the given inputs. #[derive(Component)] pub struct Transitions(pub Vec<Box<dyn Fn(&[State]) -> State + Send + Sync>>); impl Default for Transitions { fn default() -> Self { Transitions(Vec::new()) } } #[derive(Debug, Clone, PartialEq, Reflect, Default, Deserialize, Serialize)] pub struct TIndex(pub Vec<usize>); impl Deref for TIndex { type Target = Vec<usize>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for TIndex { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<Vec<usize>> for TIndex { fn from(v: Vec<usize>) -> Self { Self(v) } } /// Type that maps form a logc component (gate, input control, ...) to a set /// of inputs, specified by a index. /// /// The reason behind this is that the output of a logic component /// can be connected to multiple inputs of another logic component. /// This map is meant to keep track of all inputs of logic /// components a output is connected to. #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] pub struct TargetMap(pub HashMap<Entity, TIndex>); impl Deref for TargetMap { type Target = HashMap<Entity, TIndex>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for TargetMap { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<HashMap<Entity, TIndex>> for TargetMap { fn from(map: HashMap<Entity, TIndex>) -> Self { Self(map) } } /// A vector that maps from outputs to connected nodes. /// /// For a logic node, e.g. a gate, there should be a vector entry for /// each output. #[derive(Debug, Clone, PartialEq, Component, Deserialize, Serialize)] pub struct Targets(pub Vec<TargetMap>); impl Default for Targets { fn default() -> Self { Targets(Vec::new()) } } impl Deref for Targets { type Target = Vec<TargetMap>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for Targets { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } /// Type of a connector. #[derive(Debug, Copy, Clone, PartialEq, Hash)] pub enum ConnectorType { In, Out, } /// A connector acts as the interface of a logic component, /// e.g. logic gate. #[derive(Debug, Clone, PartialEq, Component)] pub struct Connector { /// The type of the connector. pub ctype: ConnectorType, /// Its index in the context of a logical node. /// The index of a connector, with a certain connection /// type, must be uniq in context of a logic component. pub index: usize, pub name: String, } impl Connector { pub fn new(commands: &mut Commands, ctype: ConnectorType, index: usize, name: String) -> Entity { commands .spawn() .insert(Connector { ctype, index, name }) .insert(Connections(Vec::new())) .insert(Free) .id() } pub fn from_world(world: &mut World, ctype: ConnectorType, index: usize, name: String) -> Entity { world .spawn() .insert(Connector { ctype, index, name }) .insert(Connections(Vec::new())) .insert(Free) .id() } } /// Connection lines connected to this connector. #[derive(Debug, Clone, PartialEq, Component)] pub struct Connections(pub Vec<Entity>); impl Deref for Connections { type Target = Vec<Entity>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for Connections { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl Connections { /// Return an iterator over all connections. fn iter(&self) -> impl Iterator<Item = &Entity> { self.0.iter() } } /// Marker component for free connectors. /// /// Output connectors are always free, i.e. /// one can connect them to multiple inputs. #[derive(Debug, Copy, Clone, PartialEq, Hash, Component)] pub struct Free; /// Associate a index with a entity. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct ConnInfo { pub entity: Entity, pub index: usize, } /// A connection between a output and a input. /// /// The `via` vector can be used to store path coordinates /// between two gates which can be helpful when visualizing /// the connection. #[derive(Debug, Clone, PartialEq, Component)] pub struct ConnectionLine { pub output: ConnInfo, pub via: Vec<Vec2>, pub input: ConnInfo, } impl ConnectionLine { pub fn new( commands: &mut Commands, output: ConnInfo, input: ConnInfo, positions: (Vec3, Vec3), ) -> Entity { commands .spawn() .insert(ConnectionLine { output, via: ConnectionLine::calculate_nodes( positions.0.x, positions.0.y, positions.1.x, positions.1.y, ), input, }) .id() } /// Calculate the nodes of a path between two points. /// The output is a vector with a start point, two control points and /// a end point. pub fn calculate_nodes(x1: f32, y1: f32, x2: f32, y2: f32) -> Vec<Vec2> { let dx = x2 - x1; let dy = y2 - y1; let dx2 = dx / 2.; let dy2 = dy / 2.; let point1 = Vec2::new(x1, y1); let point2 = if dx >= 0. { Vec2::new(x1 + dx2, y1) } else { Vec2::new(x1, y1 + dy2) }; let point3 = if dx >= 0. { Vec2::new(x1 + dx2, y1 + dy) } else { Vec2::new(x1 + dx, y1 + dy2) }; let point4 = Vec2::new(x1 + dx, y1 + dy); vec![point1, point2, point3, point4] } } /// System for calculating the state of each output using the corresponding /// transition functions. pub fn transition_system(mut query: Query<(&Inputs, &Transitions, &mut Outputs)>) { for (inputs, transitions, mut outputs) in query.iter_mut() { for i in 0..transitions.0.len() { outputs[i] = transitions.0[i](inputs); } } } /// System for writing the calculated output states to the inputs of each connected node. pub fn propagation_system( from_query: Query<(&Outputs, &Targets)>, mut to_query: Query<&mut Inputs>, ) { for (outputs, targets) in from_query.iter() { for i in 0..outputs.len() { for (&entity, idxvec) in targets[i].iter() { if let Ok(mut inputs) = to_query.get_mut(entity) { for &j in idxvec.iter() { if j < inputs.len() { inputs[j] = outputs[i]; } } } else { error!("Could not query inputs of given entity: {:?}", entity); } } } } } /// Event that asks the [`connect_event_system`] to connect /// the specified `output` to the given `input`. #[derive(Debug, Clone, PartialEq)] pub struct ConnectEvent { pub output: Entity, pub output_index: usize, pub input: Entity, pub input_index: usize, pub signal_success: bool, // Should signal success via NewConnectionEstablishedEvent. } /// A new connection has been established maybe somebody /// wants to know. #[derive(Debug, Clone, PartialEq)] pub struct NewConnectionEstablishedEvent { pub id: Entity, } /// Handle incomming connection events. /// /// This system handles incomming [`ConnectEvent`] events, /// connecting the output one entity to the input of another. pub fn connect_event_system( mut commands: Commands, mut ev_connect: EventReader<ConnectEvent>, mut ev_est: EventWriter<NewConnectionEstablishedEvent>, mut q_conns: Query<(&Parent, &mut Connections), ()>, mut q_parent: Query<&mut Targets>, ) { for ev in ev_connect.iter() { let line = connect(&mut commands, &mut q_conns, &mut q_parent, &ev); // Hey everybody, a new connection has been established! if ev.signal_success { ev_est.send(NewConnectionEstablishedEvent { id: line }); } } } pub fn connect( commands: &mut Commands, q_conns: &mut Query<(&Parent, &mut Connections), ()>, q_parent: &mut Query<&mut Targets>, ev: &ConnectEvent, ) -> Entity { let line = ConnectionLine::new( commands, ConnInfo { entity: ev.output, index: ev.output_index, }, ConnInfo { entity: ev.input, index: ev.input_index, }, ( // The points are not relevant for now and // can be updated later on. Vec3::new(0., 0., 0.), Vec3::new(0., 0., 0.), ), ); // Add the new connection line to the set of lines already connected to the gate. let input_parent = if let Ok((parent, mut connections)) = q_conns.get_mut(ev.input) { connections.0.push(line); parent.0 } else { return line; }; // From this moment on the input connector isn't free // any more, up to the point where the connection is // removed. commands.entity(ev.input).remove::<Free>(); // Also update the output connector. if let Ok((parent, mut connections)) = q_conns.get_mut(ev.output) { connections.0.push(line); // The target map hast to point to the input connector, // so it can receive updates. if let Ok(mut targets) = q_parent.get_mut(parent.0) { targets[ev.output_index] .entry(input_parent) .or_insert(TIndex::from(Vec::new())) .push(ev.input_index); } } line } /// Request to the [`disconnect_event_system`] to /// disconnect the given connection. #[derive(Debug, Clone, PartialEq)] pub struct DisconnectEvent { pub connection: Entity, pub in_parent: Option<Entity>, } /// Handle disconnect requests issued via a [`DisconnectEvent`]. pub fn disconnect_event_system( mut commands: Commands, mut ev_disconnect: EventReader<DisconnectEvent>, q_line: Query<&ConnectionLine>, mut q_conn: Query<(&Parent, Entity, &mut Connections)>, mut q_parent: Query<&mut Targets>, mut q_input: Query<&mut Inputs>, ) { for ev in ev_disconnect.iter() { disconnect(&mut commands, &q_line, &mut q_conn, &mut q_parent, &mut q_input, &ev); } } pub fn disconnect( commands: &mut Commands, q_line: &Query<&ConnectionLine>, q_conn: &mut Query<(&Parent, Entity, &mut Connections)>, q_parent: &mut Query<&mut Targets>, q_input: &mut Query<&mut Inputs>, ev: &DisconnectEvent, ) -> Option<(ConnInfo, ConnInfo, Entity)> { // Try to fetch the connection line. if let Ok(line) = q_line.get(ev.connection) { let in_parent: Option<Entity>; let mut in_idx = 0; let mut out_parent: Option<Entity> = None; let mut out_idx = 0; // Unlink input connector (right hand side) if let Ok((parent_in, entity_in, mut connections_in)) = q_conn.get_mut(line.input.entity) { in_parent = Some(parent_in.0); in_idx = line.input.index; // Reset input state of the given connector. if let Ok(mut inputs) = q_input.get_mut(parent_in.0) { inputs[line.input.index] = State::None; } // Clear the input line from the vector and // mark the connector as free. connections_in.0.clear(); commands.entity(entity_in).insert(Free); } else { in_parent = ev.in_parent; } // Unlink output connector (left hand side) if let Ok((parent_out, _entity_out, mut connections_out)) = q_conn.get_mut(line.output.entity) { out_parent = Some(parent_out.0); out_idx = line.output.index; let parent = in_parent.expect("There should always bee a parent set"); // Find and remove the given connection line. if let Some(idx) = connections_out.0.iter().position(|x| *x == ev.connection) { connections_out.0.remove(idx); } // Unlink propagation target. // Find the index of the input connector within the // target map of the gate the output connector belongs // to and remove the associated entry. if let Ok(mut targets) = q_parent.get_mut(parent_out.0) { let size = targets[line.output.index] .get(&parent) .expect("Should have associated entry") .len(); if size > 1 { if let Some(index) = targets[line.output.index] .get_mut(&parent) .expect("Should have associated entry") .iter() .position(|x| *x == line.input.index) { targets[line.output.index] .get_mut(&parent) .expect("Should have associated entry") .remove(index); } } else { targets[line.output.index].remove(&parent); } } } // Finally remove the connection line itself. commands.entity(ev.connection).despawn_recursive(); if in_parent.is_some() && out_parent.is_some() { return Some(( ConnInfo { entity: out_parent.unwrap(), index: out_idx, }, ConnInfo { entity: in_parent.unwrap(), index: in_idx, }, ev.connection, )); } } None } #[cfg(test)] mod tests { use super::{State, *}; use bevy::ecs::event::Events; #[test] fn test_connect() { // Setup world let mut world = World::default(); // First stage for event handling let mut first_stage = SystemStage::parallel(); first_stage.add_system(Events::<ConnectEvent>::update_system); first_stage.add_system(Events::<DisconnectEvent>::update_system); // Setup event resources world.insert_resource(Events::<ConnectEvent>::default()); world.insert_resource(Events::<DisconnectEvent>::default()); // Setup stage with our systems let mut update_stage = SystemStage::parallel(); update_stage.add_system(disconnect_event_system.system()); update_stage.add_system(transition_system.system().label("transition")); update_stage.add_system(propagation_system.system().after("transition")); update_stage.add_system(connect_event_system.system()); let not_gate1 = Gate::from_world( &mut world, "NOT Gate", NodeRange { min: 1, max: 1 }, NodeRange { min: 1, max: 1 }, trans![|inputs| { match inputs[0] { State::None => State::None, State::Low => State::High, State::High => State::Low, } },], ); let not_gate2 = Gate::from_world( &mut world, "NOT Gate", NodeRange { min: 1, max: 1 }, NodeRange { min: 1, max: 1 }, trans![|inputs| { match inputs[0] { State::None => State::None, State::Low => State::High, State::High => State::Low, } },], ); // Nothing should happen first_stage.run(&mut world); update_stage.run(&mut world); assert_eq!( world.entity(not_gate1).get::<Inputs>().unwrap()[0], State::None ); assert_eq!( world.entity(not_gate1).get::<Outputs>().unwrap()[0], State::None ); assert_eq!( world.entity(not_gate2).get::<Inputs>().unwrap()[0], State::None ); assert_eq!( world.entity(not_gate2).get::<Outputs>().unwrap()[0], State::None ); // Set input of gate 1 to low -> should update the output of gate 1 world.entity_mut(not_gate1).get_mut::<Inputs>().unwrap()[0] = State::Low; first_stage.run(&mut world); update_stage.run(&mut world); assert_eq!( world.entity(not_gate1).get::<Inputs>().unwrap()[0], State::Low ); assert_eq!( world.entity(not_gate1).get::<Outputs>().unwrap()[0], State::High ); assert_eq!( world.entity(not_gate2).get::<Inputs>().unwrap()[0], State::None ); assert_eq!( world.entity(not_gate2).get::<Outputs>().unwrap()[0], State::None ); // Now lets send a connection event /* world.get_resource_mut::<Events::<ConnectEvent>>().send( ConnectEvent { output: } ); */ } }
rust
MIT
853a0f42a05913674b30e2a3b0a79317887422ba
2026-01-04T20:19:46.997032Z
false
r4gus/nodus
https://github.com/r4gus/nodus/blob/853a0f42a05913674b30e2a3b0a79317887422ba/src/gate/systems.rs
src/gate/systems.rs
use super::{ core::{Name, *}, graphics::{clk::*, light_bulb::*, toggle_switch::*, segment_display::*}, serialize::*, undo::*, }; use bevy::prelude::*; use nodus::world2d::interaction2d::{Drag, Selected}; use nodus::world2d::{InteractionMode, Lock}; use crate::FontAssets; pub fn shortcut_system( mut mode: ResMut<InteractionMode>, input_keyboard: Res<Input<KeyCode>>, lock: Res<Lock>, ) { if lock.0 { return; } if input_keyboard.pressed(KeyCode::P) { *mode = InteractionMode::Pan; } else if input_keyboard.pressed(KeyCode::S) { *mode = InteractionMode::Select; } } /// Removes the drag state from draggable components. pub fn drag_gate_system( mut commands: Commands, mb: Res<Input<MouseButton>>, q_dragged: Query< Entity, ( With<Drag>, Or<(With<Gate>, With<LightBulb>, With<ToggleSwitch>, With<Clk>, With<SevenSegmentDisplay>)>, ), >, ) { if mb.just_released(MouseButton::Left) { for dragged_gate in q_dragged.iter() { commands.entity(dragged_gate).remove::<Drag>(); } } } /// Delete a selected gate, input control or output control. pub fn delete_gate_system( mut commands: Commands, input_keyboard: Res<Input<KeyCode>>, mut ev_disconnect: EventWriter<DisconnectEvent>, q_gate: Query< Entity, ( With<Selected>, Or<(With<Gate>, With<LightBulb>, With<ToggleSwitch>, With<Clk>, With<SevenSegmentDisplay>)>, ), >, children: Query<&Children>, q_connectors: Query<&Connections>, mut stack: ResMut<UndoStack>, q_node: Query<( Entity, &Name, Option<&Inputs>, Option<&Outputs>, Option<&Targets>, Option<&Clk>, &Transform, &NodeType, )>, q_line: Query<(Entity, &ConnectionLine)>, q_parent: Query<&Parent>, ) { if input_keyboard.pressed(KeyCode::Delete) { if let Some(ncs) = crate::gate::undo::remove( &mut commands, q_gate.iter().map(|e| e).collect(), &q_node, &children, &q_connectors, &q_line, &q_parent, &mut ev_disconnect ) { stack.undo.push(Action::Insert(ncs)); stack.redo.clear(); } } } #[derive(Debug, Clone)] pub struct InsertGateEvent { gate_type: NodeType, pub position: Vec2, } impl InsertGateEvent { pub fn and(position: Vec2) -> Self { Self { gate_type: NodeType::And, position, } } pub fn nand(position: Vec2) -> Self { Self { gate_type: NodeType::Nand, position, } } pub fn or(position: Vec2) -> Self { Self { gate_type: NodeType::Or, position, } } pub fn nor(position: Vec2) -> Self { Self { gate_type: NodeType::Nor, position, } } pub fn not(position: Vec2) -> Self { Self { gate_type: NodeType::Not, position, } } pub fn xor(position: Vec2) -> Self { Self { gate_type: NodeType::Xor, position, } } pub fn high(position: Vec2) -> Self { Self { gate_type: NodeType::HighConst, position, } } pub fn low(position: Vec2) -> Self { Self { gate_type: NodeType::LowConst, position, } } pub fn toggle(position: Vec2) -> Self { Self { gate_type: NodeType::ToggleSwitch, position, } } pub fn clk(position: Vec2) -> Self { Self { gate_type: NodeType::Clock, position, } } pub fn light(position: Vec2) -> Self { Self { gate_type: NodeType::LightBulb, position, } } pub fn seg(position: Vec2) -> Self { Self { gate_type: NodeType::SevenSegmentDisplay, position, } } } pub fn insert_gate_system( mut commands: Commands, mut ev_insert: EventReader<InsertGateEvent>, mut stack: ResMut<UndoStack>, font: Res<FontAssets>, ) { use crate::gate::core::State; for ev in ev_insert.iter() { let entity = match ev.gate_type { NodeType::And => { Some(Gate::and_gate_bs(&mut commands, ev.position, Quat::IDENTITY, font.main.clone())) }, NodeType::Nand => { Some(Gate::nand_gate_bs(&mut commands, ev.position, Quat::IDENTITY, font.main.clone())) }, NodeType::Or => { Some(Gate::or_gate_bs(&mut commands, ev.position, Quat::IDENTITY, font.main.clone())) }, NodeType::Nor => { Some(Gate::nor_gate_bs(&mut commands, ev.position, Quat::IDENTITY, font.main.clone())) }, NodeType::Xor => { Some(Gate::xor_gate_bs(&mut commands, ev.position, Quat::IDENTITY, font.main.clone())) }, NodeType::Xnor => { None }, NodeType::Not => { Some(Gate::not_gate_bs(&mut commands, ev.position, Quat::IDENTITY, font.main.clone())) }, NodeType::HighConst => { Some(Gate::high_const(&mut commands, ev.position, Quat::IDENTITY, font.main.clone())) }, NodeType::LowConst => { Some(Gate::low_const(&mut commands, ev.position, Quat::IDENTITY, font.main.clone())) }, NodeType::ToggleSwitch => { Some(ToggleSwitch::new(&mut commands, ev.position, Quat::IDENTITY, State::Low)) }, NodeType::Clock => { Some(Clk::spawn(&mut commands, ev.position, Quat::IDENTITY, 1.0, 0.0, State::Low)) }, NodeType::LightBulb => { Some(LightBulb::spawn(&mut commands, ev.position, Quat::IDENTITY, State::None)) }, NodeType::SevenSegmentDisplay => { Some(SevenSegmentDisplay::spawn(&mut commands, ev.position, Quat::IDENTITY)) } }; if let Some(entity) = entity { stack.undo.push(Action::Remove(vec![entity])); stack.redo.clear(); } } }
rust
MIT
853a0f42a05913674b30e2a3b0a79317887422ba
2026-01-04T20:19:46.997032Z
false
r4gus/nodus
https://github.com/r4gus/nodus/blob/853a0f42a05913674b30e2a3b0a79317887422ba/src/gate/serialize.rs
src/gate/serialize.rs
use crate::{ gate::{ core::{Name, State, *}, file_browser::*, graphics::{clk::*, light_bulb::*, toggle_switch::*, segment_display::*,}, }, FontAssets, }; use bevy::prelude::*; use chrono::prelude::*; use ron::ser::{to_string_pretty, PrettyConfig}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::fs::{self}; #[derive(Debug, Clone, Deserialize, Serialize)] pub struct Version { major: u8, minor: u8, } #[derive(Debug, Clone, Component, Deserialize, Serialize)] pub enum NodeType { And, Nand, Or, Nor, Xor, Xnor, Not, HighConst, LowConst, ToggleSwitch, Clock, LightBulb, SevenSegmentDisplay, } #[derive(Debug, Clone, Component, Deserialize, Serialize)] pub enum NodeState { ToggleSwitch(State), Clock(f32, f32, State), LightBulb(State), } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct NodusComponent { pub id: Entity, pub name: String, pub inputs: Option<usize>, pub outputs: Option<usize>, pub targets: Option<Targets>, pub position: Vec2, pub rotation: Option<Quat>, pub ntype: NodeType, pub state: Option<NodeState>, } #[derive(Debug, Deserialize, Serialize)] pub struct NodusSave { time: DateTime<chrono::Local>, application: String, version: Version, entities: Vec<NodusComponent>, } pub struct SaveEvent(pub String); pub struct LoadEvent(pub String); pub fn save_event_system( q_node: Query<( Entity, &Name, Option<&Inputs>, Option<&Outputs>, Option<&Targets>, Option<&Clk>, &Transform, &NodeType, )>, mut ev_save: EventReader<SaveEvent>, mut curr_open: ResMut<CurrentlyOpen>, ) { for ev in ev_save.iter() { let mut save = Vec::new(); for (e, n, ip, op, t, clk, tr, nt) in q_node.iter() { let i = if let Some(i) = ip { Some(i.len()) } else { None }; let o = if let Some(o) = op { Some(o.len()) } else { None }; let t = if let Some(t) = t { Some(t.clone()) } else { None }; let state = match &nt { NodeType::ToggleSwitch => Some(NodeState::ToggleSwitch(op.unwrap()[0])), NodeType::Clock => { let clk = clk.unwrap(); Some(NodeState::Clock(clk.0, clk.1, op.unwrap()[0])) } NodeType::LightBulb => Some(NodeState::LightBulb(ip.unwrap()[0])), _ => None, }; let nc = NodusComponent { id: e, name: n.0.to_string(), inputs: i, outputs: o, targets: t, position: Vec2::new(tr.translation.x, tr.translation.y), rotation: Some(tr.rotation), ntype: nt.clone(), state: state, }; save.push(nc); } let nsave = NodusSave { time: chrono::Local::now(), application: String::from("Nodus - A logic gate simulator"), version: Version { major: 0, minor: 1 }, entities: save, }; let pretty = PrettyConfig::new() .depth_limit(5) .separate_tuple_members(true) .enumerate_arrays(true); //eprintln!("RON: {}", to_string_pretty(&nsave, pretty).unwrap()); eprintln!("{}", &ev.0); if let Ok(_res) = fs::write(&ev.0, &to_string_pretty(&nsave, pretty).unwrap()) { curr_open.path = Some(ev.0.clone()); eprintln!("success"); } else { eprintln!("failure"); } } } #[derive(Component)] pub struct LoadMapper { map: HashMap<Entity, Entity>, save: NodusSave, } pub fn link_gates_system( mut commands: Commands, mut cev: EventWriter<ConnectEvent>, q_children: Query<&Children>, q_conn: Query<(Entity, &Connector)>, q_map: Query<(Entity, &LoadMapper)>, ) { if let Ok((e, map)) = q_map.get_single() { for e in &map.save.entities { if let Some(targets) = &e.targets { // Iterate over the slot of each output connector. for i in 0..targets.len() { // Get the associated output connector with index; let mut out_id: Option<Entity> = None; if let Ok(out_children) = q_children.get(map.map[&e.id]) { for &child in out_children.iter() { if let Ok((id, conn)) = q_conn.get(child) { if conn.index == i && conn.ctype == ConnectorType::Out { out_id = Some(id); break; } } } } if out_id == None { break; } for (gate, tidx) in targets[i].iter() { if let Ok(in_children) = q_children.get(map.map[&gate]) { for &child in in_children.iter() { if let Ok((id, conn)) = q_conn.get(child) { for &j in tidx.iter() { if conn.index == j && conn.ctype == ConnectorType::In { cev.send(ConnectEvent { output: out_id.unwrap(), output_index: i, input: id, input_index: j, signal_success: false, }); break; } } } } } } } } } commands.entity(e).despawn_recursive(); } } pub fn load_event_system( mut commands: Commands, mut ev_load: EventReader<LoadEvent>, font: Res<FontAssets>, mut curr_open: ResMut<CurrentlyOpen>, q_all: Query<Entity, Or<(With<NodeType>, With<ConnectionLine>)>>, ) { for ev in ev_load.iter() { if let Ok(loaded_save) = fs::read_to_string(&ev.0) { // Remove all entities currently in the world before inserting // the entities from the file. for e in q_all.iter() { commands.entity(e).despawn_recursive(); } let save: Result<NodusSave, _> = ron::from_str(&loaded_save); let mut id_map: HashMap<Entity, Entity> = HashMap::new(); if let Ok(save) = save { for e in &save.entities { let id = match e.ntype { NodeType::And => { Some(Gate::and_gate_bs_( &mut commands, e.position, e.rotation.unwrap_or(Quat::IDENTITY), e.inputs.unwrap(), e.outputs.unwrap(), font.main.clone(), )) } NodeType::Nand => { Some(Gate::nand_gate_bs_( &mut commands, e.position, e.rotation.unwrap_or(Quat::IDENTITY), e.inputs.unwrap(), e.outputs.unwrap(), font.main.clone(), )) } NodeType::Or => { Some(Gate::or_gate_bs_( &mut commands, e.position, e.rotation.unwrap_or(Quat::IDENTITY), e.inputs.unwrap(), e.outputs.unwrap(), font.main.clone(), )) } NodeType::Nor => { Some(Gate::nor_gate_bs_( &mut commands, e.position, e.rotation.unwrap_or(Quat::IDENTITY), e.inputs.unwrap(), e.outputs.unwrap(), font.main.clone(), )) } NodeType::Xor => { Some(Gate::xor_gate_bs_( &mut commands, e.position, e.rotation.unwrap_or(Quat::IDENTITY), e.inputs.unwrap(), e.outputs.unwrap(), font.main.clone(), )) } NodeType::Xnor => { None } NodeType::Not => { Some(Gate::not_gate_bs_( &mut commands, e.position, e.rotation.unwrap_or(Quat::IDENTITY), e.inputs.unwrap(), e.outputs.unwrap(), font.main.clone(), )) } NodeType::HighConst => { Some(Gate::high_const( &mut commands, e.position, e.rotation.unwrap_or(Quat::IDENTITY), font.main.clone() )) } NodeType::LowConst => { Some(Gate::low_const( &mut commands, e.position, e.rotation.unwrap_or(Quat::IDENTITY), font.main.clone() )) } NodeType::ToggleSwitch => { if let Some(NodeState::ToggleSwitch(state)) = e.state { Some(ToggleSwitch::new(&mut commands, e.position, e.rotation.unwrap_or(Quat::IDENTITY), state)) } else { None } } NodeType::Clock => { if let Some(NodeState::Clock(x1, x2, x3)) = e.state { Some(Clk::spawn(&mut commands, e.position, e.rotation.unwrap_or(Quat::IDENTITY), x1, x2, x3)) } else { None } } NodeType::LightBulb => { if let Some(NodeState::LightBulb(state)) = e.state { Some(LightBulb::spawn(&mut commands, e.position, e.rotation.unwrap_or(Quat::IDENTITY), state)) } else { None } } NodeType::SevenSegmentDisplay => { Some( SevenSegmentDisplay::spawn( &mut commands, e.position, e.rotation.unwrap_or(Quat::IDENTITY), ) ) } }; if let Some(id) = id { id_map.insert(e.id, id); } } // The different logical components must be connected to each other. This // is done in another system that always runs before this one to give the // ecs enough time to insert the spawned entities above into the world. commands.spawn().insert(LoadMapper { map: id_map, save: save, }); // Remember the path of the file. This allows to save the // file without specifying the path all the time. curr_open.path = Some(ev.0.clone()); eprintln!("file loaded and parsed"); } else { eprintln!("unable to parse file"); } } else { eprintln!("unable to load file"); } } }
rust
MIT
853a0f42a05913674b30e2a3b0a79317887422ba
2026-01-04T20:19:46.997032Z
false
r4gus/nodus
https://github.com/r4gus/nodus/blob/853a0f42a05913674b30e2a3b0a79317887422ba/src/gate/file_browser.rs
src/gate/file_browser.rs
use crate::gate::core::*; use crate::gate::serialize::*; use bevy::prelude::*; use bevy_egui::{egui, egui::RichText, EguiContext}; use dirs; use std::ffi::OsString; use std::fs::{self}; use std::io; use std::path::Path; pub struct EguiFileBrowserPlugin; impl Plugin for EguiFileBrowserPlugin { fn build(&self, app: &mut App) { app.add_event::<OpenBrowserEvent>(); app.add_event::<NewFileEvent>(); app.insert_resource(FileBrowser { open: false, path: dirs::home_dir() .expect("home dir to exist") .into_os_string(), fname: "".to_string(), file_type: FileType::Ron, title: String::from(""), action: BrowserAction::Open, }); app.insert_resource(CurrentlyOpen { path: None }); app.add_system(draw_browser_system); app.add_system(open_browser_event_system); app.add_system(new_file_event_system.label("new_file")); } } #[derive(Debug, Copy, Clone, PartialEq)] pub enum BrowserAction { Open, Save, } #[derive(Debug, Clone, PartialEq)] pub struct OpenBrowserEvent(pub BrowserAction); fn open_browser_event_system(mut ev: EventReader<OpenBrowserEvent>, mut fb: ResMut<FileBrowser>) { for ev in ev.iter() { match ev.0 { BrowserAction::Open => { fb.open = true; fb.path = dirs::home_dir() .expect("home dir to exist") .into_os_string(); fb.title = String::from("Open File"); fb.action = BrowserAction::Open; } BrowserAction::Save => { fb.open = true; fb.path = dirs::home_dir() .expect("home dir to exist") .into_os_string(); fb.title = String::from("Save File As..."); fb.action = BrowserAction::Save; } } } } #[derive(Debug, Clone, PartialEq)] enum FileType { Ron, } impl FileType { fn to_string(&self) -> String { match self { FileType::Ron => Self::RON.to_string(), } } fn ending(&self) -> &str { match self { FileType::Ron => Self::RON_ENDING, } } const RON: &'static str = "Rusty Object Notation"; const RON_ENDING: &'static str = "ron"; } pub struct FileBrowser { pub open: bool, path: OsString, fname: String, file_type: FileType, title: String, action: BrowserAction, } pub struct CurrentlyOpen { pub path: Option<String>, } fn draw_browser_system( egui_context: ResMut<EguiContext>, mut fb: ResMut<FileBrowser>, mut ev_save: EventWriter<SaveEvent>, mut ev_open: EventWriter<LoadEvent>, ) { if !fb.open { return; } let mut s = fb .path .clone() .into_string() .expect("OsString to be convertible"); egui::Window::new(&fb.title) .resizable(false) .collapsible(false) .default_size(egui::Vec2::new(640.0, 320.0)) .show(egui_context.ctx(), |ui| { ui.horizontal(|ui| { if ui .add(egui::Button::new("\u{1F3E0}")) .on_hover_text("Home Directory") .clicked() { if let Some(home_dir) = dirs::home_dir() { if let Ok(home_dir_str) = home_dir.into_os_string().into_string() { s = home_dir_str; } } } ui.separator(); if ui .add(egui::Button::new("\u{1F5C0}")) .on_hover_text("New Folder") .clicked() {} if ui .add(egui::Button::new("\u{274C}")) .on_hover_text("Delete") .clicked() {} }); ui.group(|ui| { egui::ScrollArea::vertical() .max_height(320.) .show(ui, |ui| { egui::ScrollArea::horizontal() .max_width(640.) .show(ui, |ui| { ui.set_min_width(640.); let path = dirs::home_dir().expect("home dir to exist"); let ftype = fb.file_type.clone(); visit_dirs(&path, ui, 0, &mut s, &mut fb.fname, ftype.ending()); }); }); }); egui::Grid::new("browser_grid") .num_columns(3) .spacing([10.0, 4.0]) .striped(false) .show(ui, |ui| { ui.label("Look in: "); ui.label(&s); ui.end_row(); ui.label("File name:"); ui.add(egui::TextEdit::singleline(&mut fb.fname).desired_width(480.)); if fb.action == BrowserAction::Save { let mut p = Path::new(&s).join(&fb.fname); if ui.add(egui::Button::new("Save")).clicked() { p.set_extension(fb.file_type.ending()); ev_save.send(SaveEvent(p.into_os_string().into_string().unwrap())); fb.open = false; } } else { let p = Path::new(&s).join(&fb.fname); if ui.add(egui::Button::new("Open")).clicked() { ev_open.send(LoadEvent(p.into_os_string().into_string().unwrap())); fb.open = false; } } ui.end_row(); ui.label("File type: "); egui::ComboBox::from_label("Type") .selected_text(format!("{}", fb.file_type.to_string())) .width(320.0) .show_ui(ui, |ui| { ui.selectable_value(&mut fb.file_type, FileType::Ron, FileType::RON); }); if ui.add(egui::Button::new("cancle")).clicked() { fb.open = false; } ui.end_row(); }); }); fb.path = OsString::from(&s); } fn visit_dirs( dir: &Path, ui: &mut egui::Ui, depth: usize, selected_path: &mut String, selected_file: &mut String, ending: &str, ) -> io::Result<()> { if dir.is_dir() { for entry in fs::read_dir(dir)? { let entry = entry?; let path = entry.path(); if let Ok(fname) = entry.file_name().into_string() { if !fname.starts_with('.') { if path.is_dir() { let response = egui::CollapsingHeader::new(format!("\u{1F5C0} {}", fname)) .selected(path.to_str().unwrap().to_string() == *selected_path) .show(ui, |ui| { visit_dirs( &path, ui, depth + 1, selected_path, selected_file, ending, ); }); if response.header_response.clicked() { *selected_path = path.to_str().unwrap().to_string(); } } else if fname.ends_with(ending) { if ui .add( egui::Label::new( RichText::new(format!("\u{1F5B9} {}", fname)).background_color( if fname == *selected_file { egui::Color32::from_rgba_premultiplied(0, 0, 255, 30) } else { egui::Color32::TRANSPARENT }, ), ) .sense(egui::Sense::click()), ) .clicked() { if let Some(parent) = path.parent() { *selected_path = parent.to_str().unwrap().to_string(); } *selected_file = fname; } } } } } } Ok(()) } pub struct NewFileEvent; pub fn new_file_event_system( mut commands: Commands, mut nev: EventReader<NewFileEvent>, q_all: Query<Entity, Or<(With<NodeType>, With<ConnectionLine>)>>, mut curr_open: ResMut<CurrentlyOpen>, ) { for _ev in nev.iter() { for e in q_all.iter() { commands.entity(e).despawn_recursive(); } curr_open.path = None; } }
rust
MIT
853a0f42a05913674b30e2a3b0a79317887422ba
2026-01-04T20:19:46.997032Z
false
r4gus/nodus
https://github.com/r4gus/nodus/blob/853a0f42a05913674b30e2a3b0a79317887422ba/src/gate/undo.rs
src/gate/undo.rs
use std::collections::hash_set::HashSet; use crate::gate::{ core::{Name, *}, graphics::{clk::*, light_bulb::*, toggle_switch::*, segment_display::*}, serialize::*, }; use bevy::prelude::*; use crate::GameState; pub struct UndoPlugin; impl Plugin for UndoPlugin { fn build(&self, app: &mut App) { app.add_event::<UndoEvent>() .add_event::<ReconnectGates>() .add_event::<DisconnectEventUndo>() .insert_resource(UndoStack { undo: Vec::new(), redo: Vec::new(), }) .add_system_set( SystemSet::on_update(GameState::InGame) .label("undo") .with_system(reconnect_gates_event_system.before("handle_undo")) // Not pretty but this system must run after the disconnect // system to prevent program crashes due to data races. .with_system(handle_undo_event_system.label("handle_undo").after("disconnect")) .with_system(listen_for_new_connections_system) // Alot of systems run after disconnect to prevent Segfaults, // i.e. we must run this system also before the others. .with_system(disconnect_event_system_undo.before("disconnect").after("draw_line")) ); } } #[derive(Debug, Clone, Copy, PartialEq)] pub enum UndoEvent { Undo, Redo, } #[derive(Debug, Clone)] pub enum Action { Insert((Vec<NodusComponent>, HashSet<(ConnInfo, ConnInfo, Entity)>)), Remove(Vec<Entity>), InsertConnection((ConnInfo, ConnInfo, Entity)), RemoveConnection(Entity), } #[derive(Debug, Clone)] pub struct UndoStack { pub undo: Vec<Action>, pub redo: Vec<Action>, } pub fn handle_undo_event_system( mut commands: Commands, mut stack: ResMut<UndoStack>, mut ev_undo: EventReader<UndoEvent>, server: Res<AssetServer>, q_node: Query<( Entity, &Name, Option<&Inputs>, Option<&Outputs>, Option<&Targets>, Option<&Clk>, &Transform, &NodeType, )>, children: Query<&Children>, q_connectors: Query<&Connections>, q_line: Query<(Entity, &ConnectionLine)>, q_parent: Query<&Parent>, mut ev_disconnect: EventWriter<DisconnectEvent>, mut ev_disconnect_undo: EventWriter<DisconnectEventUndo>, mut ev_conn: EventWriter<ReconnectGates>, ) { let font: Handle<Font> = server.load("fonts/hack.bold.ttf"); for ev in ev_undo.iter() { match ev { UndoEvent::Undo => { if let Some(action) = stack.undo.pop() { match action { Action::Insert(mut e) => { if let Some(entities) = insert( &mut commands, font.clone(), e.0.clone(), ) { if e.0.len() == entities.len() { for i in 0..e.0.len() { replace_entity_id( e.0[i].id, entities[i], &mut stack ); replace_entity_id_( e.0[i].id, entities[i], &mut e.1 ); } } ev_conn.send(ReconnectGates(e.1, None)); stack.redo.push(Action::Remove(entities)); } } Action::Remove(entities) => { if let Some(nc) = remove( &mut commands, entities, &q_node, &children, &q_connectors, &q_line, &q_parent, &mut ev_disconnect ) { stack.redo.push(Action::Insert(nc)); } } Action::RemoveConnection(c) => { ev_disconnect_undo.send(DisconnectEventUndo { connection: c, in_parent: None, action: UndoEvent::Redo, }); } Action::InsertConnection(con) => { let mut h = HashSet::new(); h.insert(con); ev_conn.send(ReconnectGates(h, Some(UndoEvent::Redo))); }, _ => { } } } } UndoEvent::Redo => { if let Some(action) = stack.redo.pop() { match action { Action::Insert(mut e) => { if let Some(entities) = insert( &mut commands, font.clone(), e.0.clone() ) { if e.0.len() == entities.len() { for i in 0..e.0.len() { replace_entity_id( e.0[i].id, entities[i], &mut stack ); replace_entity_id_( e.0[i].id, entities[i], &mut e.1 ); } } ev_conn.send(ReconnectGates(e.1, None)); stack.undo.push(Action::Remove(entities)); } }, Action::Remove(entities) => { if let Some(nc) = remove( &mut commands, entities, &q_node, &children, &q_connectors, &q_line, &q_parent, &mut ev_disconnect ) { stack.undo.push(Action::Insert(nc)); } }, Action::RemoveConnection(c) => { ev_disconnect_undo.send(DisconnectEventUndo { connection: c, in_parent: None, action: UndoEvent::Undo, }); }, Action::InsertConnection(con) => { let mut h = HashSet::new(); h.insert(con); ev_conn.send(ReconnectGates(h, Some(UndoEvent::Undo))); }, _ => { } } } } } } } pub struct ReconnectGates( pub HashSet<(ConnInfo, ConnInfo, Entity)>, Option<UndoEvent> ); fn reconnect_gates_event_system( mut ev_conn: EventReader<ReconnectGates>, q_children: Query<&Children>, q_conn: Query<(Entity, &Connector)>, mut commands: Commands, mut q_conns: Query<(&Parent, &mut Connections), ()>, mut q_parent: Query<&mut Targets>, mut stack: ResMut<UndoStack>, ) { for conns in ev_conn.iter() { for conn in conns.0.iter() { if let Ok(e) = reconnect_gates( &q_children, &q_conn, &mut commands, &mut q_conns, &mut q_parent, &mut stack, conn ) { if let Some(action) = conns.1 { match action { UndoEvent::Undo => { stack.undo.push(Action::RemoveConnection(e)); }, UndoEvent::Redo => { stack.redo.push(Action::RemoveConnection(e)); } } } } } } } fn reconnect_gates( q_children: &Query<&Children>, q_conn: &Query<(Entity, &Connector)>, commands: &mut Commands, q_conns: &mut Query<(&Parent, &mut Connections), ()>, q_parent: &mut Query<&mut Targets>, stack: &mut ResMut<UndoStack>, (lhs, rhs, old_id): &(ConnInfo, ConnInfo, Entity), ) -> Result<Entity, ()> { if let Ok(lhs_children) = q_children.get(lhs.entity) { if let Ok(rhs_children) = q_children.get(rhs.entity) { for &lhs_child in lhs_children.iter() { if let Ok((lhs_e, lhs_con)) = q_conn.get(lhs_child) { if lhs_con.index == lhs.index && lhs_con.ctype == ConnectorType::Out { for &rhs_child in rhs_children.iter() { if let Ok((rhs_e, rhs_con)) = q_conn.get(rhs_child) { if rhs_con.index == rhs.index && rhs_con.ctype == ConnectorType::In { let new_id = connect( commands, q_conns, q_parent, &ConnectEvent { output: lhs_e, output_index: lhs.index, input: rhs_e, input_index: rhs.index, signal_success: false, } ); replace_connection_entity_id_( *old_id, new_id, stack, ); return Ok(new_id); } } } } } } } } Err(()) } fn replace_entity_id_(old: Entity, new: Entity, con: &mut HashSet<(ConnInfo, ConnInfo, Entity)>) { let mut tmp = Vec::new(); for t in con.iter() { if let Some(t_new) = replace_entity_id3_(old, new, t.clone()) { tmp.push((t.clone(), t_new)); } } for (o, n) in tmp.drain(..) { con.remove(&o); con.insert(n); } } fn replace_entity_id3_(old: Entity, new: Entity, t: (ConnInfo, ConnInfo, Entity)) -> Option<(ConnInfo, ConnInfo, Entity)> { if t.0.entity == old && t.1.entity != old { Some( ( ConnInfo { entity: new, index: t.0.index }, t.1.clone(), t.2 ) ) } else if t.0.entity != old && t.1.entity == old { Some( ( t.0.clone(), ConnInfo { entity: new, index: t.1.index }, t.2 ) ) } else if t.0.entity == old && t.1.entity == old { Some( ( ConnInfo { entity: new, index: t.0.index }, ConnInfo { entity: new, index: t.1.index }, t.2, ) ) } else { None } } fn replace_entity_id2_(old: Entity, new: Entity, v: &mut Vec<Entity>) { for i in 0..v.len() { if v[i] == old { v[i] = new; } } } fn replace_connection_entity_id_(old: Entity, new: Entity, stack: &mut ResMut<UndoStack>) { for action in &mut stack.undo { match action { Action::RemoveConnection(ref mut id) => { if *id == old { *id = new; } }, _ => { } } } for action in &mut stack.redo { match action { Action::RemoveConnection(ref mut id) => { if *id == old { *id = new; } }, _ => { } } } } /// Replace the given `old` entity id with the `new` entity id within the /// target maps of all NodusComponent's of the undo/redo stack. fn replace_entity_id(old: Entity, new: Entity, stack: &mut ResMut<UndoStack>) { for action in &mut stack.undo { match action { Action::Insert(ncs) => { replace_entity_id_(old, new, &mut ncs.1); }, Action::Remove(ref mut es) => { replace_entity_id2_(old, new, es); }, Action::InsertConnection(ref mut con) => { if let Some(c_new) = replace_entity_id3_(old, new, con.clone()) { *con = c_new; } }, _ => { } } } for action in &mut stack.redo { match action { Action::Insert(ncs) => { replace_entity_id_(old, new, &mut ncs.1); }, Action::Remove(ref mut es) => { replace_entity_id2_(old, new, es); }, Action::InsertConnection(ref mut con) => { if let Some(c_new) = replace_entity_id3_(old, new, con.clone()) { *con = c_new; } }, _ => { } } } } fn insert( commands: &mut Commands, font: Handle<Font>, components: Vec<NodusComponent>, ) -> Option<Vec<Entity>> { let mut res = Vec::new(); for e in components { let entity = match e.ntype { NodeType::And => { Some( Gate::and_gate_bs_( commands, e.position, e.rotation.unwrap_or(Quat::IDENTITY), e.inputs.unwrap(), e.outputs.unwrap(), font.clone(), ) ) } NodeType::Nand => { Some( Gate::nand_gate_bs_( commands, e.position, e.rotation.unwrap_or(Quat::IDENTITY), e.inputs.unwrap(), e.outputs.unwrap(), font.clone(), ) ) } NodeType::Or => { Some( Gate::or_gate_bs_( commands, e.position, e.rotation.unwrap_or(Quat::IDENTITY), e.inputs.unwrap(), e.outputs.unwrap(), font.clone(), ) ) } NodeType::Nor => { Some( Gate::nor_gate_bs_( commands, e.position, e.rotation.unwrap_or(Quat::IDENTITY), e.inputs.unwrap(), e.outputs.unwrap(), font.clone(), ) ) } NodeType::Xor => { Some( Gate::xor_gate_bs_( commands, e.position, e.rotation.unwrap_or(Quat::IDENTITY), e.inputs.unwrap(), e.outputs.unwrap(), font.clone(), ) ) } NodeType::Xnor => { None } NodeType::Not => { Some( Gate::not_gate_bs_( commands, e.position, e.rotation.unwrap_or(Quat::IDENTITY), e.inputs.unwrap(), e.outputs.unwrap(), font.clone(), ) ) } NodeType::HighConst => { Some(Gate::high_const( commands, e.position, e.rotation.unwrap_or(Quat::IDENTITY), font.clone() )) } NodeType::LowConst => { Some(Gate::low_const( commands, e.position, e.rotation.unwrap_or(Quat::IDENTITY), font.clone() )) } NodeType::ToggleSwitch => { if let Some(NodeState::ToggleSwitch(state)) = e.state { Some(ToggleSwitch::new(commands, e.position, e.rotation.unwrap_or(Quat::IDENTITY), state)) } else { None } } NodeType::Clock => { if let Some(NodeState::Clock(x1, x2, x3)) = e.state { Some(Clk::spawn(commands, e.position, e.rotation.unwrap_or(Quat::IDENTITY), x1, x2, x3)) } else { None } } NodeType::LightBulb => { if let Some(NodeState::LightBulb(state)) = e.state { Some(LightBulb::spawn(commands, e.position, e.rotation.unwrap_or(Quat::IDENTITY), state)) } else { None } } NodeType::SevenSegmentDisplay => { Some(SevenSegmentDisplay::spawn(commands, e.position, e.rotation.unwrap_or(Quat::IDENTITY))) } }; if let Some(entity) = entity { res.push(entity); } } if res.len() > 0 { Some(res) } else { None } } pub fn remove( commands: &mut Commands, entities: Vec<Entity>, q_node: &Query<( Entity, &Name, Option<&Inputs>, Option<&Outputs>, Option<&Targets>, Option<&Clk>, &Transform, &NodeType, )>, children: &Query<&Children>, q_connectors: &Query<&Connections>, q_line: &Query<(Entity, &ConnectionLine)>, q_parent: &Query<&Parent>, ev_disconnect: &mut EventWriter<DisconnectEvent>, ) -> Option<(Vec<NodusComponent>, HashSet<(ConnInfo, ConnInfo, Entity)>)> { let mut res = Vec::new(); let mut con = HashSet::new(); for e in entities { if let Ok((e, n, ip, op, t, clk, tr, nt)) = q_node.get(e) { let i = if let Some(i) = ip { Some(i.len()) } else { None }; let o = if let Some(o) = op { Some(o.len()) } else { None }; let t = if let Some(t) = t { Some(t.clone()) } else { None }; let state = match &nt { NodeType::ToggleSwitch => { Some(NodeState::ToggleSwitch(op.unwrap()[0])) } NodeType::Clock => { let clk = clk.unwrap(); Some(NodeState::Clock(clk.0, clk.1, op.unwrap()[0])) } NodeType::LightBulb => { Some(NodeState::LightBulb(ip.unwrap()[0])) } _ => None, }; let nc = NodusComponent { id: e, name: n.0.to_string(), inputs: i, outputs: o, targets: t, position: Vec2::new(tr.translation.x, tr.translation.y), rotation: Some(tr.rotation), ntype: nt.clone(), state: state, }; if let Ok(children) = children.get(e) { for &child in children.iter() { if let Ok(conns) = q_connectors.get(child) { for &connection in conns.iter() { if let Ok((_entity, line)) = q_line.get(connection) { if let Ok(parent1) = q_parent.get(line.output.entity) { if let Ok(parent2) = q_parent.get(line.input.entity) { // By using a HashSet we dont need to check // if a connection already exists. let c = ( // ConnInfo usually holds a reference to a connector // and not the gate itself, but we gonna reuse it here. ConnInfo { entity: parent1.0, index: line.output.index }, ConnInfo { entity: parent2.0, index: line.input.index }, connection ); con.insert(c); eprintln!("line"); } } } ev_disconnect.send(DisconnectEvent { connection, in_parent: Some(e), }); } } } } commands.entity(e).despawn_recursive(); res.push(nc); } } if res.len() > 0 { Some((res, con)) } else { None } } fn listen_for_new_connections_system( mut ev_est: EventReader<NewConnectionEstablishedEvent>, mut stack: ResMut<UndoStack>, ) { for ev in ev_est.iter() { stack.undo.push(Action::RemoveConnection(ev.id)); stack.redo.clear(); } } #[derive(Debug, Clone, PartialEq)] pub struct DisconnectEventUndo { pub connection: Entity, pub in_parent: Option<Entity>, pub action: UndoEvent, } pub fn disconnect_event_system_undo( mut commands: Commands, mut ev_disconnect: EventReader<DisconnectEventUndo>, q_line: Query<&ConnectionLine>, mut q_conn: Query<(&Parent, Entity, &mut Connections)>, mut q_parent: Query<&mut Targets>, mut q_input: Query<&mut Inputs>, mut stack: ResMut<UndoStack>, ) { for ev in ev_disconnect.iter() { if let Some(con) = disconnect( &mut commands, &q_line, &mut q_conn, &mut q_parent, &mut q_input, &DisconnectEvent { connection: ev.connection, in_parent: ev.in_parent }) { match ev.action { UndoEvent::Undo => { stack.undo.push(Action::InsertConnection(con)); }, UndoEvent::Redo => { stack.redo.push(Action::InsertConnection(con)); } } } } }
rust
MIT
853a0f42a05913674b30e2a3b0a79317887422ba
2026-01-04T20:19:46.997032Z
false
r4gus/nodus
https://github.com/r4gus/nodus/blob/853a0f42a05913674b30e2a3b0a79317887422ba/src/gate/ui.rs
src/gate/ui.rs
use crate::gate::{ core::{Name, *}, file_browser::*, graphics::clk::Clk, graphics::gate::ChangeInput, serialize::*, undo::*, }; use crate::radial_menu::Menu; use bevy::app::AppExit; use bevy::prelude::*; use bevy_egui::{egui, EguiContext, EguiSettings}; use nodus::world2d::camera2d::MainCamera; use nodus::world2d::interaction2d::*; use nodus::world2d::*; const MIT: &str = "\ License Copyright (c) 2021-2022 David Pierre Sugar Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Software), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE."; const NODUS_LOGO_ID: u64 = 0; pub fn update_lock( mut lock: ResMut<Lock>, about: Res<GuiMenu>, browser: Res<FileBrowser>, q_menu: Query<&Menu>, ) { let menu = if let Ok(_) = q_menu.get_single() { true } else { false }; lock.0 = about.open || browser.open || menu; } pub fn update_ui_scale_factor(mut egui_settings: ResMut<EguiSettings>, windows: Res<Windows>) { if let Some(_window) = windows.get_primary() { egui_settings.scale_factor = 1.5; } } pub fn load_gui_assets(mut egui_context: ResMut<EguiContext>, assets: Res<AssetServer>) { let texture_handle = assets.load("misc/LOGO.png"); egui_context.set_egui_texture(NODUS_LOGO_ID, texture_handle); } /// Reset input if cursor hovers over egui window. /// This system must run before any "main" bevy system. pub fn ui_reset_input( egui_context: ResMut<EguiContext>, mut mb: ResMut<Input<MouseButton>>, ) { if egui_context.ctx().wants_pointer_input() { mb.reset(MouseButton::Left); } } pub fn ui_scroll_system( egui_context: ResMut<EguiContext>, mut q_camera: Query<&mut Transform, With<MainCamera>>, ) { if let Ok(mut transform) = q_camera.get_single_mut() { egui::Area::new("zoom_area") .anchor(egui::Align2::LEFT_BOTTOM, egui::Vec2::new(5., -5.)) .show(egui_context.ctx(), |ui| { let mut x = transform.scale.x; ui.horizontal(|ui| { ui.label( egui::RichText::new("\u{B1}") .strong() .color(egui::Color32::BLACK), ); ui.add(egui::Slider::new(&mut x, 1.0..=5.0).show_value(false)); ui.label( egui::RichText::new("\u{1F50E}") .strong() .color(egui::Color32::BLACK), ); }); transform.scale = Vec3::new(x, x, x); }).response; } } #[derive(Debug, Clone, PartialEq)] pub enum GuiMenuOptions { None, Handbook, About, } #[derive(Debug, Clone, PartialEq)] pub struct GuiMenu { pub option: GuiMenuOptions, pub open: bool, } pub fn ui_gui_about(egui_context: ResMut<EguiContext>, mut r: ResMut<GuiMenu>) { if let GuiMenuOptions::About = r.option { egui::Window::new("About") .resizable(false) .collapsible(false) .default_size(egui::Vec2::new(900.0, 600.0)) .open(&mut r.open) .show(egui_context.ctx(), |ui| { ui.horizontal(|ui| { ui.group(|ui| { ui.add(egui::widgets::Image::new( egui::TextureId::User(NODUS_LOGO_ID), [80., 80.], )); }); ui.group(|ui| { ui.vertical(|ui| { ui.label("Nodus v0.1"); ui.horizontal_wrapped(|ui| { ui.label("Nodus is a digital circuit simulator written in rust, using the"); ui.hyperlink_to( format!("bevy"), "https://bevyengine.org" ); ui.label("game engine."); }); ui.label("Copyright \u{A9} 2022 David Pierre Sugar <david(at)thesugar.de>.\n"); ui.collapsing("Third-party libraries", |ui| { ui.label("Nodus is built on the following free software libraries:"); ui.horizontal_wrapped(|ui| { ui.hyperlink_to( format!("Bevy Game Engine"), "https://bevyengine.org" ); ui.label("MIT/ Apache Version 2.0"); }); ui.horizontal_wrapped(|ui| { ui.hyperlink_to( format!("Bevy-Prototype-Lyon"), "https://github.com/Nilirad/bevy_prototype_lyon" ); ui.label("MIT/ Apache Version 2.0"); }); ui.horizontal_wrapped(|ui| { ui.hyperlink_to( format!("Bevy-Egui"), "https://github.com/mvlabat/bevy_egui" ); ui.label("MIT"); }); ui.horizontal_wrapped(|ui| { ui.hyperlink_to( format!("Egui"), "https://github.com/emilk/egui" ); ui.label("Apache Version 2.0"); }); ui.horizontal_wrapped(|ui| { ui.hyperlink_to( format!("Bevy-Asset-Loader"), "https://github.com/NiklasEi/bevy_asset_loader" ); ui.label("MIT/ Apache Version 2.0"); }); ui.horizontal_wrapped(|ui| { ui.hyperlink_to( format!("Lyon"), "https://github.com/nical/lyon" ); ui.label("Apache Version 2.0"); }); ui.horizontal_wrapped(|ui| { ui.hyperlink_to( format!("Rusty Object Notation"), "https://github.com/ron-rs/ron" ); ui.label("Apache Version 2.0"); }); }); ui.collapsing("Your Rights", |ui| { ui.label("Nodus is released under the MIT License."); ui.label("You are free to use Nodus for any purpose."); ui.with_layout( egui::Layout::top_down(egui::Align::LEFT).with_cross_justify(true), |ui| { ui.label(egui::RichText::new(MIT).small().weak()); }, ); }); }); }); }); }); } } pub fn ui_top_panel_system( egui_context: ResMut<EguiContext>, mut exit: EventWriter<AppExit>, mut fbe: EventWriter<OpenBrowserEvent>, mut ev_save: EventWriter<SaveEvent>, mut ev_new: EventWriter<NewFileEvent>, mut ev_undo: EventWriter<UndoEvent>, mut r: ResMut<GuiMenu>, curr_open: Res<CurrentlyOpen>, mut mode: ResMut<InteractionMode>, stack: Res<UndoStack>, ) { egui::TopBottomPanel::top("side").show(egui_context.ctx(), |ui| { ui.columns(2, |columns| { columns[0].horizontal(|ui| { ui.menu_button("File", |ui| { ui.add_enabled_ui(true, |ui| { if ui.button("\u{2B} New").clicked() { if let Some(path) = &curr_open.path { ev_save.send(SaveEvent(path.clone())); } ev_new.send(NewFileEvent); ui.close_menu(); } if ui.button("\u{1F5C1} Open").clicked() { fbe.send(OpenBrowserEvent(BrowserAction::Open)); ui.close_menu(); } ui.separator(); if ui.button("\u{1F4BE} Save").clicked() { if let Some(path) = &curr_open.path { ev_save.send(SaveEvent(path.clone())); } else { fbe.send(OpenBrowserEvent(BrowserAction::Save)); } ui.close_menu(); } if ui.button("\u{1F4BE} Save As...").clicked() { fbe.send(OpenBrowserEvent(BrowserAction::Save)); ui.close_menu(); } }); ui.separator(); if ui.button("Exit").clicked() { ui.close_menu(); exit.send(AppExit); } }); ui.menu_button("View", |ui| { if ui.button("Back to Origin").clicked() { ui.close_menu(); } }); ui.menu_button("Help", |ui| { ui.separator(); if ui.button("\u{FF1F} About Nodus").clicked() { r.option = GuiMenuOptions::About; r.open = true; ui.close_menu(); } }); }); columns[1].with_layout(egui::Layout::right_to_left(), |ui| { let blue = egui::Color32::BLUE; let grey = egui::Color32::DARK_GRAY; if ui .add( egui::Button::new("\u{1F542}").fill(if *mode == InteractionMode::Pan { blue } else { grey }), ) .on_hover_text("Pan Camera") .on_hover_cursor(egui::CursorIcon::PointingHand) .clicked() { // pan *mode = InteractionMode::Pan; } if ui .add( egui::Button::new("\u{1F446}").fill(if *mode == InteractionMode::Select { blue } else { grey }), ) .on_hover_text("Select") .on_hover_cursor(egui::CursorIcon::PointingHand) .clicked() { // select *mode = InteractionMode::Select; } if ui .add_enabled( stack.redo.len() > 0, egui::Button::new("\u{2BAB}") ) .on_hover_text("Redo last action") .on_hover_cursor(egui::CursorIcon::PointingHand) .clicked() { ev_undo.send(UndoEvent::Redo); } if ui .add_enabled( stack.undo.len() > 0, egui::Button::new("\u{2BAA}") ) .on_hover_text("Undo last action") .on_hover_cursor(egui::CursorIcon::PointingHand) .clicked() { ev_undo.send(UndoEvent::Undo); } }); }); }); } pub fn ui_node_info_system( egui_context: ResMut<EguiContext>, mut q_gate: Query<(Entity, &Name, &mut Transform, Option<&Gate>, Option<&mut Clk>), With<Selected>>, mut ev_change: EventWriter<ChangeInput>, ) { if let Ok((entity, name, mut trans, gate, mut clk)) = q_gate.get_single_mut() { egui::Window::new(&name.0) .title_bar(false) .anchor(egui::Align2::RIGHT_BOTTOM, egui::Vec2::new(-5., -5.)) .resizable(false) .show(egui_context.ctx(), |ui| { ui.label(&name.0); if let Some(gate) = gate { if gate.in_range.min != gate.in_range.max { ui.horizontal(|ui| { ui.label("Input Count: "); if ui.button("➖").clicked() { if gate.inputs > gate.in_range.min { ev_change.send(ChangeInput { gate: entity, to: gate.inputs - 1, }); } } ui.label(format!("{}", gate.inputs)); if ui.button("➕").clicked() { if gate.inputs < gate.in_range.max { ev_change.send(ChangeInput { gate: entity, to: gate.inputs + 1, }); } } }); } } if let Some(ref mut clk) = clk { let mut clk_f32 = clk.0 * 1000.; ui.horizontal(|ui| { ui.label("Signal Duration: "); ui.add( egui::DragValue::new(&mut clk_f32) .speed(1.0) .clamp_range(std::ops::RangeInclusive::new(250.0, 600000.0)), ); }); clk.0 = clk_f32 / 1000.; } ui.horizontal(|ui| { ui.label("Rotate: "); if ui.button("\u{27f2}").clicked() { trans.rotate(Quat::from_rotation_z(std::f32::consts::PI / 2.0)); } if ui.button("\u{27f3}").clicked() { trans.rotate(Quat::from_rotation_z(-std::f32::consts::PI / 2.0)); } }); }); } }
rust
MIT
853a0f42a05913674b30e2a3b0a79317887422ba
2026-01-04T20:19:46.997032Z
false
r4gus/nodus
https://github.com/r4gus/nodus/blob/853a0f42a05913674b30e2a3b0a79317887422ba/src/gate/graphics/connection_line.rs
src/gate/graphics/connection_line.rs
use crate::gate::core::{State, *}; use bevy::prelude::*; use bevy_prototype_lyon::{entity::ShapeBundle, prelude::*}; use lyon_tessellation::path::path::Builder; use nodus::world2d::camera2d::MouseWorldPos; use nodus::world2d::interaction2d::Selected; /// Sameple the cubic bezier curve, defined by s` (start), /// `c1` (control point 1), `c2` (control point 2) and `e` (end), /// at `t` (t e [0, 1]); #[allow(dead_code)] fn qubic_bezier_point(t: f32, s: Vec2, c1: Vec2, c2: Vec2, e: Vec2) -> Vec2 { let u = 1. - t; let tt = t * t; let uu = u * u; let uuu = uu * u; let ttt = tt * t; let mut p = s * uuu; p += c1 * 3. * uu * t; p += c2 * 3. * u * tt; p += e * ttt; p } /// Solve t for a point `xy` on a qubic bezier curve defined by `s` (start), /// `c1` (control point 1), `c2` (control point 2) and `e` (end). /// /// This is just a approximation and can be used to check if a user clicked /// on a qubic bezier curve. fn t_for_point(xy: Vec2, s: Vec2, c1: Vec2, c2: Vec2, e: Vec2) -> Option<f32> { use lyon_geom::*; const EPSILON: f32 = 16.; let c = CubicBezierSegment { from: Point::new(s.x, s.y), ctrl1: Point::new(c1.x, c1.y), ctrl2: Point::new(c2.x, c2.y), to: Point::new(e.x, e.y), }; let possible_t_values_x = c.solve_t_for_x(xy.x); let _possible_t_values_y = c.solve_t_for_y(xy.y); for t in possible_t_values_x { if t >= -0.001 && t <= 1.001 { let p = c.sample(t); let offset = p - Point::new(xy.x, xy.y); let dot = offset.x * offset.x + offset.y * offset.y; if dot <= EPSILON * EPSILON { return Some(t); } } } None } struct ConnectionLineShape<'a> { pub via: &'a [Vec2], } impl<'a> Geometry for ConnectionLineShape<'a> { fn add_geometry(&self, b: &mut Builder) { let mut path = PathBuilder::new(); path.move_to(self.via[0]); path.cubic_bezier_to(self.via[1], self.via[2], self.via[3]); b.concatenate(&[path.build().0.as_slice()]); } } pub struct LineResource { pub count: f32, pub timestep: f32, pub update: bool, } #[derive(Component)] pub struct DataPoint { stepsize: f32, steps: f32, } #[derive(Component)] pub struct LineHighLight; pub fn draw_line_system( mut commands: Commands, mut q_line: Query< ( Entity, &mut ConnectionLine, Option<&Children>, Option<&Selected>, ), (), >, q_transform: Query<(&Parent, &Connector, &GlobalTransform), ()>, q_outputs: Query<&Outputs, ()>, q_highlight: Query<Entity, With<LineHighLight>>, mut lr: ResMut<LineResource>, time: Res<Time>, ) { lr.count += time.delta_seconds(); for (entity, mut conn_line, _children, selected) in q_line.iter_mut() { if let Ok((t_parent, t_conn, t_from)) = q_transform.get(conn_line.output.entity) { // Set connection line color based on the value of the output. let color = if let Ok(outputs) = q_outputs.get(t_parent.0) { match outputs[t_conn.index] { State::None => Color::RED, State::High => Color::BLUE, State::Low => Color::BLACK, } } else { Color::BLACK }; if let Ok((_, _, t_to)) = q_transform.get(conn_line.input.entity) { let via = ConnectionLine::calculate_nodes( t_from.translation.x, t_from.translation.y, t_to.translation.x, t_to.translation.y, ); let _l = ((via[3].x - via[0].x).powi(2) + (via[3].y - via[0].y).powi(2)).sqrt(); // Remove current line path. commands.entity(entity).remove_bundle::<ShapeBundle>(); // Create new path. let mut path = PathBuilder::new(); path.move_to(via[0]); path.cubic_bezier_to(via[1], via[2], via[3]); let new_ent = commands .entity(entity) .insert_bundle(GeometryBuilder::build_as( &ConnectionLineShape { via: &via }, DrawMode::Stroke(StrokeMode::new(color, 8.0)), Transform::from_xyz(0., 0., 1.), )) .id(); for e in q_highlight.iter() { commands.entity(e).despawn_recursive(); } // Highlight if selected. if let Some(_) = selected { let child = commands .spawn_bundle(GeometryBuilder::build_as( &ConnectionLineShape { via: &via }, DrawMode::Stroke(StrokeMode::new( Color::rgba(0.62, 0.79, 0.94, 0.5), 18.0, )), Transform::from_xyz(0., 0., 0.), )) .insert(LineHighLight) .id(); commands.entity(new_ent).add_child(child); } conn_line.via = via; /* * TODO: nice visual effect but probably distracting as well. * if color == Color::BLUE && lr.count >= lr.timestep { let id = commands .spawn_bundle( GeometryBuilder::build_as( &shapes::Circle { radius: 3., center: Vec2::new(0., 0.), }, DrawMode::Outlined { fill_mode: FillMode::color(Color::WHITE), outline_mode: StrokeMode::new(Color::WHITE, 1.0), }, Transform::from_xyz(t_from.translation.x, t_from.translation.y, 3.), ) ) .insert(DataPoint { stepsize: 1. / (l / 250.), steps: 0., }).id(); commands.entity(entity).push_children(&[id]); } */ } } } if lr.count >= lr.timestep { lr.count = 0.; } } pub fn line_selection_system( mut commands: Commands, mw: Res<MouseWorldPos>, mb: Res<Input<MouseButton>>, q_line: Query<(Entity, &ConnectionLine)>, _q_selected: Query<Entity, With<Selected>>, ) { if mb.just_pressed(MouseButton::Left) { for (entity, line) in q_line.iter() { if let Some(_) = t_for_point( Vec2::new(mw.x, mw.y), line.via[0].clone(), line.via[1].clone(), line.via[2].clone(), line.via[3].clone(), ) { commands.entity(entity).insert(Selected); break; } } } } pub fn delete_line_system( input_keyboard: Res<Input<KeyCode>>, mut ev_disconnect: EventWriter<DisconnectEvent>, q_line: Query<Entity, (With<Selected>, With<ConnectionLine>)>, ) { if input_keyboard.just_pressed(KeyCode::Delete) { for entity in q_line.iter() { ev_disconnect.send(DisconnectEvent { connection: entity, in_parent: None, }); } } } // TODO: Deactivated for now pub fn draw_data_flow( mut commands: Commands, time: Res<Time>, mut q_point: Query<(Entity, &Parent, &mut Transform, &mut DataPoint)>, q_line: Query<&ConnectionLine>, ) { for (entity, parent, mut transform, mut data) in q_point.iter_mut() { if let Ok(line) = q_line.get(parent.0) { let l = ((line.via[3].x - line.via[0].x).powi(2) + (line.via[3].y - line.via[0].y).powi(2)) .sqrt(); data.steps += (1. / (l / 300.)) * time.delta_seconds(); if data.steps >= 1.0 { commands.entity(entity).despawn_recursive(); } else { let p = qubic_bezier_point( data.steps, line.via[0].clone(), line.via[1].clone(), line.via[2].clone(), line.via[3].clone(), ); transform.translation.x = p.x; transform.translation.y = p.y; } } } }
rust
MIT
853a0f42a05913674b30e2a3b0a79317887422ba
2026-01-04T20:19:46.997032Z
false
r4gus/nodus
https://github.com/r4gus/nodus/blob/853a0f42a05913674b30e2a3b0a79317887422ba/src/gate/graphics/toggle_switch.rs
src/gate/graphics/toggle_switch.rs
use super::*; use crate::gate::core::{State, *}; use crate::gate::serialize::*; use bevy::prelude::*; use bevy_prototype_lyon::prelude::*; use lyon_tessellation::path::path::Builder; use nodus::world2d::interaction2d::{Draggable, Hover, Interactable, Selectable}; use std::collections::HashMap; use std::sync::atomic::Ordering; /// A toggle switch that can be either on or off. /// /// If on, it will propagate a State::High signal to all connected /// logical components, else State::Low; #[derive(Debug, Clone, PartialEq, Hash, Component)] pub struct ToggleSwitch; impl ToggleSwitch { /// Crate a new toggle switch at the specified position. pub fn new(commands: &mut Commands, position: Vec2, rotation: Quat, state: State) -> Entity { let z = Z_INDEX.fetch_add(1, Ordering::Relaxed) as f32; let switch = GeometryBuilder::build_as( &ToggleSwitchShape { size: GATE_SIZE / 4., }, DrawMode::Outlined { fill_mode: FillMode::color(Color::WHITE), outline_mode: StrokeMode::new(Color::BLACK, 8.0), }, Transform::from_xyz(position.x, position.y, z) .with_rotation(rotation), ); let parent = commands .spawn_bundle(switch) .insert(ToggleSwitch) .insert(Name("Toggle Switch".to_string())) .insert(Inputs(vec![state])) .insert(Outputs(vec![state])) .insert(Transitions(trans![|inputs| inputs[0]])) .insert(Targets(vec![TargetMap::from(HashMap::new())])) .insert(NodeType::ToggleSwitch) .insert(Interactable::new( Vec2::new(0., 0.), Vec2::new(GATE_SIZE, GATE_SIZE), 1, )) .insert(Selectable) .insert(Draggable { update: true }) .id(); let child = Connector::with_line( commands, Vec3::new(GATE_SIZE * 0.75, 0., 0.), GATE_SIZE * 0.1, ConnectorType::Out, 0, "y1".to_string(), ); let factor = if state == State::High { 1. } else { -1. }; let nod = GeometryBuilder::build_as( &shapes::Circle { radius: GATE_SIZE / 4., center: Vec2::new(0., 0.), }, DrawMode::Outlined { fill_mode: FillMode::color(Color::WHITE), outline_mode: StrokeMode::new(Color::BLACK, 8.0), }, Transform::from_xyz(factor * GATE_SIZE / 4., 0., 1.), ); let nod_child = commands .spawn_bundle(nod) .insert(Switch) .insert(Interactable::new( Vec2::new(0., 0.), Vec2::new(GATE_SIZE / 2., GATE_SIZE / 2.), 1, )) .id(); commands .entity(parent) .push_children(&vec![child, nod_child]); parent } } /// Switch represents the part of the toggle switch the user can click on. #[derive(Debug, Clone, PartialEq, Hash, Component)] pub struct Switch; /// Defines the basic shape of the toggle switch by implementing Geometry. #[derive(Debug, Clone, PartialEq)] struct ToggleSwitchShape { size: f32, } impl Geometry for ToggleSwitchShape { fn add_geometry(&self, b: &mut Builder) { let mut path = PathBuilder::new(); path.move_to(Vec2::new(-self.size, -self.size)); path.arc( Vec2::new(-self.size, 0.), Vec2::new(self.size, self.size), -std::f32::consts::PI, 0., ); path.line_to(Vec2::new(self.size, self.size)); path.arc( Vec2::new(self.size, 0.), Vec2::new(self.size, self.size), -std::f32::consts::PI, 0., ); path.close(); b.concatenate(&[path.build().0.as_slice()]); } } /// Register clicks on a switch and change its state accordingly. pub fn toggle_switch_system( _commands: Commands, mut q_outputs: Query<&mut Inputs>, mut q_switch: Query<(&Parent, &mut Transform), (With<Hover>, With<Switch>)>, mb: Res<Input<MouseButton>>, ) { if mb.just_pressed(MouseButton::Left) { for (parent, mut transform) in q_switch.iter_mut() { if let Ok(mut inputs) = q_outputs.get_mut(parent.0) { let next = match inputs[0] { State::High => { transform.translation.x -= GATE_SIZE / 2.; State::Low } _ => { transform.translation.x += GATE_SIZE / 2.; State::High } }; inputs[0] = next; } } } }
rust
MIT
853a0f42a05913674b30e2a3b0a79317887422ba
2026-01-04T20:19:46.997032Z
false
r4gus/nodus
https://github.com/r4gus/nodus/blob/853a0f42a05913674b30e2a3b0a79317887422ba/src/gate/graphics/highlight.rs
src/gate/graphics/highlight.rs
use crate::gate::core::{ConnectionLine, Connector}; use bevy::prelude::*; use bevy_prototype_lyon::prelude::*; use nodus::world2d::interaction2d::Selected; /// Marker component for entities that act as highlighters. #[derive(Debug, Clone, PartialEq, Component)] pub struct Highlighter; /// Marker component for entities that are highlighted. #[derive(Debug, Clone, PartialEq, Component)] pub struct Highlighted; const RUST_COLOR: Color = Color::rgba(0.72, 0.277, 0.0, 0.5); impl Highlighter { /// Spawn a new highlight entity that uses the given path for its shape. pub fn spawn(commands: &mut Commands, path: &Path) -> Entity { commands .spawn_bundle(GeometryBuilder::build_as( &path.0, DrawMode::Fill(FillMode::color(RUST_COLOR)), Transform::from_xyz(0.0, 0.0, 0.1), )) .insert(Highlighter) .id() } } /// Hightlight a entity (gate, input control, ...) the user has clicked on. pub fn highlight_system( mut commands: Commands, query: Query< (Entity, &Path), ( Added<Selected>, Without<Highlighted>, Without<Connector>, Without<ConnectionLine>, ), >, ) { for (entity, path) in query.iter() { let h = Highlighter::spawn(&mut commands, &path); commands.entity(entity).add_child(h); commands.entity(entity).insert(Highlighted); } } /// Remove highlighting as soon as the entity isn't selected anymore. pub fn remove_highlight_system( mut commands: Commands, query: Query<(Entity, &Children), (With<Highlighted>, Without<Selected>)>, q_child: Query<Entity, With<Highlighter>>, ) { for (parent, children) in query.iter() { commands.entity(parent).remove::<Highlighted>(); for &child in children.iter() { if let Ok(entity) = q_child.get(child) { commands.entity(entity).despawn_recursive(); } } } } /// Redraw the highlight of a highlighted entity if the path of its main shape has changed. pub fn change_highlight_system( mut commands: Commands, query: Query<(Entity, &Children, &Path), (Changed<Path>, With<Highlighted>)>, q_child: Query<Entity, With<Highlighter>>, ) { for (parent, children, path) in query.iter() { for &child in children.iter() { if let Ok(entity) = q_child.get(child) { commands.entity(entity).despawn_recursive(); } } let h = Highlighter::spawn(&mut commands, &path); commands.entity(parent).add_child(h); } }
rust
MIT
853a0f42a05913674b30e2a3b0a79317887422ba
2026-01-04T20:19:46.997032Z
false
r4gus/nodus
https://github.com/r4gus/nodus/blob/853a0f42a05913674b30e2a3b0a79317887422ba/src/gate/graphics/connector.rs
src/gate/graphics/connector.rs
use crate::gate::core::*; use bevy::prelude::*; use bevy_prototype_lyon::{entity::ShapeBundle, prelude::*}; use nodus::world2d::camera2d::MouseWorldPos; use nodus::world2d::interaction2d::{Drag, Draggable, Hover, Interactable, Selectable}; impl Connector { /// Create a new connector for a logic node. pub fn with_shape( commands: &mut Commands, position: Vec3, radius: f32, ctype: ConnectorType, index: usize, name: String, ) -> Entity { let circle = shapes::Circle { radius: radius, center: Vec2::new(0., 0.), }; let connector = GeometryBuilder::build_as( &circle, DrawMode::Outlined { fill_mode: FillMode::color(Color::WHITE), outline_mode: StrokeMode::new(Color::BLACK, 5.0), }, Transform::from_xyz(position.x, position.y, 0.), ); commands .spawn_bundle(connector) .insert(Connector { ctype, index, name }) .insert(Connections(Vec::new())) .insert(Free) .insert(Interactable::new( Vec2::new(0., 0.), Vec2::new(radius * 2., radius * 2.), 2, )) .insert(Selectable) .insert(Draggable { update: false }) .id() } pub fn with_line( commands: &mut Commands, position: Vec3, radius: f32, ctype: ConnectorType, index: usize, name: String, ) -> Entity { let id = Connector::with_shape(commands, position, radius, ctype, index, name); let line = shapes::Line(Vec2::new(-position.x, 0.), Vec2::new(0., 0.)); let line_conn = GeometryBuilder::build_as( &line, DrawMode::Stroke(StrokeMode::new(Color::BLACK, 6.0)), Transform::from_xyz(0., 0., -1.), ); let line_id = commands.spawn_bundle(line_conn).id(); commands.entity(id).push_children(&[line_id]); id } pub fn with_line_vert( commands: &mut Commands, position: Vec3, radius: f32, ctype: ConnectorType, index: usize, name: String, ) -> Entity { let id = Connector::with_shape(commands, position, radius, ctype, index, name); let line = shapes::Line(Vec2::new(0., -position.y), Vec2::new(0., 0.)); let line_conn = GeometryBuilder::build_as( &line, DrawMode::Stroke(StrokeMode::new(Color::BLACK, 6.0)), Transform::from_xyz(0., 0., -1.), ); let line_id = commands.spawn_bundle(line_conn).id(); commands.entity(id).push_children(&[line_id]); id } } /// Highlight a connector by increasing its radius when the mouse /// hovers over it. pub fn highlight_connector_system( // We need all connectors the mouse hovers over. mut q_hover: Query<&mut Transform, (With<Hover>, With<Connector>)>, mut q2_hover: Query<&mut Transform, (Without<Hover>, With<Connector>)>, ) { for mut transform in q_hover.iter_mut() { transform.scale = Vec3::new(1.2, 1.2, transform.scale.z); } for mut transform in q2_hover.iter_mut() { transform.scale = Vec3::new(1.0, 1.0, transform.scale.z); } } /// A line shown when the user clicks and drags from a connector. /// It's expected that there is atmost one ConnectionLineIndicator /// present. #[derive(Debug, Clone, PartialEq, Component)] pub struct ConnectionLineIndicator; pub fn drag_connector_system( mut commands: Commands, mb: Res<Input<MouseButton>>, mw: Res<MouseWorldPos>, // ID and transform of the connector we drag from. q_dragged: Query<(Entity, &GlobalTransform, &Connector), (With<Drag>, With<Free>)>, // The visual connection line indicator to update. q_conn_line: Query<Entity, With<ConnectionLineIndicator>>, // Posible free connector the mouse currently hovers over. q_drop: Query<(Entity, &Connector), (With<Hover>, With<Free>)>, mut ev_connect: EventWriter<ConnectEvent>, ) { if let Ok((entity, transform, connector)) = q_dragged.get_single() { // If the LMB is released we check if we can connect two connectors. if mb.just_released(MouseButton::Left) { commands.entity(entity).remove::<Drag>(); // We dont need the visual connection line any more. // There will be another system responsible for // drawing the connections between nodes. if let Ok(conn_line) = q_conn_line.get_single() { commands.entity(conn_line).despawn_recursive(); } // Try to connect input and output. if let Ok((drop_target, drop_connector)) = q_drop.get_single() { eprintln!("drop"); // One can only connect an input to an output. if connector.ctype != drop_connector.ctype { // Send connection event. match connector.ctype { ConnectorType::In => { ev_connect.send(ConnectEvent { output: drop_target, output_index: drop_connector.index, input: entity, input_index: connector.index, signal_success: true, }); } ConnectorType::Out => { ev_connect.send(ConnectEvent { output: entity, output_index: connector.index, input: drop_target, input_index: drop_connector.index, signal_success: true, }); } } } } } else { // While LMB is being pressed, draw the line from the node clicked on // to the mouse cursor. let conn_entity = if let Ok(conn_line) = q_conn_line.get_single() { commands.entity(conn_line).remove_bundle::<ShapeBundle>(); conn_line } else { commands.spawn().insert(ConnectionLineIndicator).id() }; let shape = shapes::Line( Vec2::new(transform.translation.x, transform.translation.y), Vec2::new(mw.x, mw.y), ); let line = GeometryBuilder::build_as( &shape, DrawMode::Outlined { fill_mode: FillMode::color(Color::WHITE), outline_mode: StrokeMode::new(Color::BLACK, 10.0), }, Transform::from_xyz(0., 0., 1.), ); commands.entity(conn_entity).insert_bundle(line); } } }
rust
MIT
853a0f42a05913674b30e2a3b0a79317887422ba
2026-01-04T20:19:46.997032Z
false
r4gus/nodus
https://github.com/r4gus/nodus/blob/853a0f42a05913674b30e2a3b0a79317887422ba/src/gate/graphics/light_bulb.rs
src/gate/graphics/light_bulb.rs
use super::*; use crate::gate::core::{State, *}; use crate::gate::serialize::*; use bevy::prelude::*; use bevy_prototype_lyon::{entity::ShapeBundle, prelude::*, shapes::SvgPathShape}; use nodus::world2d::interaction2d::{Draggable, Interactable, Selectable}; use std::sync::atomic::Ordering; /// SVG path of a light bulb. const LIGHT_BULB_PATH: &str = "M290.222,0C180.731,0,91.8,88.931,91.8,198.422c0,54.506,17.69,86.062,33.469,113.315l0,0 c12.909,22.472,22.95,40.163,26.775,74.588c0.478,7.649,2.391,14.821,5.259,21.993c-2.391,6.694-3.825,13.866-3.825,21.038 c0,8.128,1.434,15.778,4.781,22.95c-2.869,7.172-4.781,14.821-4.781,22.949c0,23.429,13.866,44.466,34.425,54.028 c10.041,30.601,38.728,51.638,71.719,51.638H321.3c32.513,0,61.678-21.037,71.719-51.638 c21.037-9.562,34.425-31.078,34.425-54.028c0-8.128-1.435-15.777-4.781-22.949c2.869-7.172,4.781-15.301,4.781-22.95 c0-7.172-1.435-14.344-3.825-21.038c3.348-6.693,5.26-14.344,5.26-21.993c3.825-34.425,13.865-52.116,26.775-74.588 c15.777-27.731,33.469-58.809,33.469-113.793C488.644,88.931,399.712,0,290.222,0z M340.425,515.896 c-3.347,7.172-10.997,12.432-19.604,12.432h-61.2c-8.606,0-16.256-5.26-19.603-12.432H340.425z M207.028,429.834 c0-3.347,2.869-6.215,6.216-6.215H367.2c3.347,0,6.215,2.868,6.215,6.215c0,3.348-2.868,6.216-6.215,6.216H213.244 C209.896,436.05,207.028,433.182,207.028,429.834z M375.328,382.5L375.328,382.5v0.956c0,3.347-2.869,6.216-6.216,6.216H211.331 c-3.347,0-6.216-2.869-6.216-6.216l-0.956-9.084c-5.737-41.119-20.081-66.46-32.513-88.453 c-14.344-24.863-26.297-46.378-26.297-87.019c0-79.847,65.025-144.872,144.872-144.872s144.872,64.547,144.872,144.394 c0,40.641-12.432,62.156-26.297,87.019C395.409,309.347,380.109,336.122,375.328,382.5z M213.244,469.519H367.2 c3.347,0,6.215,2.869,6.215,6.216s-2.868,6.216-6.215,6.216H213.244c-3.347,0-6.216-2.869-6.216-6.216 S209.896,469.519,213.244,469.519z"; /// Light bulb component. /// /// A light bulb is meant as a visual representation of a state. /// It has one input connector to receive a signal from a connected /// gate, input control or other logic component. /// /// It glows if the input is [`State::High`]. #[derive(Component)] pub struct LightBulb { state: State, } impl LightBulb { fn shape_bundle(color: Color) -> ShapeBundle { GeometryBuilder::build_as( &SvgPathShape { svg_doc_size_in_px: Vec2::new(580.922, 580.922), svg_path_string: LIGHT_BULB_PATH.to_string(), }, DrawMode::Outlined { fill_mode: FillMode::color(color), outline_mode: StrokeMode::new(Color::BLACK, 8.0), }, Transform::from_scale(Vec3::new(0.22, 0.22, 0.22)), ) } /// Create a new light bulb at the specified position. pub fn spawn(commands: &mut Commands, position: Vec2, rotation: Quat, state: State) -> Entity { let z = Z_INDEX.fetch_add(1, Ordering::Relaxed) as f32; let parent = commands .spawn() .insert(Transform::from_xyz(position.x, position.y, z).with_rotation(rotation)) .insert(GlobalTransform::from_xyz(position.x, position.y, z).with_rotation(rotation)) .insert(LightBulb { state: state }) .insert(Name("Light Bulb".to_string())) .insert(Inputs(vec![state])) .insert(NodeType::LightBulb) .insert(Interactable::new( Vec2::new(0., 0.), Vec2::new(GATE_SIZE, GATE_SIZE), 1, )) .insert(Selectable) .insert(Draggable { update: true }) .id(); let bulb = commands .spawn_bundle(LightBulb::shape_bundle(if state == State::High { Color::BLUE } else { Color::WHITE })) .id(); let child = Connector::with_line( commands, Vec3::new(0., -GATE_SIZE * 0.7, 0.), GATE_SIZE * 0.1, ConnectorType::In, 0, "x1".to_string(), ); commands.entity(parent).push_children(&vec![bulb, child]); parent } } pub fn light_bulb_system( _commands: Commands, mut q_light: Query<(&Children, &Inputs, &mut LightBulb)>, mut draw: Query<&mut DrawMode, Without<Connector>>, ) { for (children, inputs, mut light) in q_light.iter_mut() { // Update the light bulbs visuals only if the state has changed. if inputs[0] != light.state { // Colorize the light bulb based on its new state. let color = match inputs[0] { State::High => Color::BLUE, _ => Color::WHITE, }; // One of the entities children is the actual svg image. Find // and update its color; for &child in children.iter() { if let Ok(mut mode) = draw.get_mut(child) { if let DrawMode::Outlined { ref mut fill_mode, outline_mode: _, } = *mode { fill_mode.color = color; } } } light.state = inputs[0]; } } }
rust
MIT
853a0f42a05913674b30e2a3b0a79317887422ba
2026-01-04T20:19:46.997032Z
false
r4gus/nodus
https://github.com/r4gus/nodus/blob/853a0f42a05913674b30e2a3b0a79317887422ba/src/gate/graphics/clk.rs
src/gate/graphics/clk.rs
use super::*; use crate::gate::core::{State, *}; use crate::gate::serialize::*; use bevy::prelude::*; use bevy_prototype_lyon::prelude::*; use lyon_tessellation::path::path::Builder; use nodus::world2d::interaction2d::{Draggable, Interactable, Selectable}; use std::collections::HashMap; use std::sync::atomic::Ordering; /// Clock (clk) marker component. #[derive(Debug, Clone, PartialEq, Component)] pub struct Clk(pub f32, pub f32); impl Clk { pub fn spawn( commands: &mut Commands, position: Vec2, rotation: Quat, clk: f32, start: f32, state: State, ) -> Entity { let z = Z_INDEX.fetch_add(1, Ordering::Relaxed) as f32; let shape = shapes::Rectangle { extents: Vec2::new(GATE_SIZE, GATE_SIZE), ..shapes::Rectangle::default() }; let clk = commands .spawn_bundle(GeometryBuilder::build_as( &shape, DrawMode::Outlined { fill_mode: FillMode::color(Color::WHITE), outline_mode: StrokeMode::new(Color::BLACK, 6.0), }, Transform::from_xyz(position.x, position.y, z) .with_rotation(rotation), )) .insert(Clk(clk, start)) .insert(Name("Clock".to_string())) .insert(NodeType::Clock) .insert(Outputs(vec![state])) .insert(Targets(vec![TargetMap::from(HashMap::new())])) .insert(Interactable::new( Vec2::new(0., 0.), Vec2::new(GATE_SIZE, GATE_SIZE), 1, )) .insert(Selectable) .insert(Draggable { update: true }) .with_children(|parent| { parent.spawn_bundle(GeometryBuilder::build_as( &ClkShape { size: GATE_SIZE / 2., }, DrawMode::Stroke(StrokeMode::new( if state == State::High { Color::BLUE } else { Color::BLACK }, 16.0, )), Transform::from_xyz(0., 0., 1.), )); }) .id(); let conn = Connector::with_line( commands, Vec3::new(GATE_SIZE * 0.75, 0., 0.), GATE_SIZE * 0.1, ConnectorType::Out, 0, "y1".to_string() ); commands.entity(clk).add_child(conn); clk } } #[derive(Debug, Clone, PartialEq)] struct ClkShape { size: f32, } impl Geometry for ClkShape { fn add_geometry(&self, b: &mut Builder) { let mut path = PathBuilder::new(); path.move_to(Vec2::new(-self.size * 0.75, self.size / 2.)); path.line_to(Vec2::new(0., self.size / 2.)); path.line_to(Vec2::new(0., -self.size / 2.)); path.line_to(Vec2::new(self.size * 0.75, -self.size / 2.)); b.concatenate(&[path.build().0.as_slice()]); } } pub fn clk_system( _commands: Commands, mut q_clk: Query<(&Children, &mut Clk, &mut Outputs)>, mut draw: Query<&mut DrawMode, Without<Connector>>, time: Res<Time>, ) { let delta = time.delta_seconds(); for (children, mut clk, mut outs) in q_clk.iter_mut() { clk.1 += delta; if clk.1 >= clk.0 { clk.1 = 0.0; outs[0] = match outs[0] { State::High => State::Low, _ => State::High, }; for &child in children.iter() { if let Ok(mut mode) = draw.get_mut(child) { if let DrawMode::Stroke(ref mut stroke_mode) = *mode { stroke_mode.color = match outs[0] { State::High => Color::BLUE, _ => Color::BLACK, }; } } } } } }
rust
MIT
853a0f42a05913674b30e2a3b0a79317887422ba
2026-01-04T20:19:46.997032Z
false
r4gus/nodus
https://github.com/r4gus/nodus/blob/853a0f42a05913674b30e2a3b0a79317887422ba/src/gate/graphics/gate.rs
src/gate/graphics/gate.rs
use super::*; use crate::gate::core::{State, *}; use crate::gate::serialize::*; use bevy::prelude::*; use bevy_prototype_lyon::{entity::ShapeBundle, prelude::*}; use lyon_tessellation::path::path::Builder; use nodus::world2d::interaction2d::{Draggable, Interactable, Selectable}; use std::collections::HashMap; use std::sync::atomic::Ordering; pub struct GateSize { pub width: f32, pub height: f32, pub in_step: f32, pub out_step: f32, pub offset: f32, } pub fn get_distances(cin: f32, cout: f32, width: f32, _height: f32) -> GateSize { let factor = if cin >= cout { cin } else { cout }; let height = _height + if factor > 2. { (factor - 1.) * _height / 2. } else { 0. }; let in_step = -(height / (cin + 1.)); let out_step = -(height / (cout + 1.)); let offset = height / 2.; GateSize { width, height, in_step, out_step, offset, } } pub enum SymbolStandard { ANSI(PathBuilder), // Font | Symbol | inverted? BS(Handle<Font>, String, bool), // British System 3939 } pub struct AnsiGateShape { pub path: Path, } impl Geometry for AnsiGateShape { fn add_geometry(&self, b: &mut Builder) { b.concatenate(&[self.path.0.as_slice()]); } } #[derive(Debug, Copy, Clone, Component)] pub struct BritishStandard; impl Gate { fn body_from_path(position: Vec3, rotation: Quat, path: PathBuilder) -> ShapeBundle { GeometryBuilder::build_as( &AnsiGateShape { path: path.build() }, DrawMode::Outlined { fill_mode: FillMode::color(Color::WHITE), outline_mode: StrokeMode::new(Color::BLACK, 6.0), }, Transform::from_xyz(position.x, position.y, position.z) .with_rotation(rotation), ) } pub fn body(position: Vec3, rotation: Quat, size: Vec2) -> ShapeBundle { let shape = shapes::Rectangle { extents: Vec2::new(size.x, size.y), ..shapes::Rectangle::default() }; GeometryBuilder::build_as( &shape, DrawMode::Outlined { fill_mode: FillMode::color(Color::WHITE), outline_mode: StrokeMode::new(Color::BLACK, 6.0), }, Transform::from_xyz(position.x, position.y, position.z) .with_rotation(rotation), ) } fn invert_bs(position: Vec3, radius: f32) -> ShapeBundle { let shape = shapes::Circle { radius, ..shapes::Circle::default() }; GeometryBuilder::build_as( &shape, DrawMode::Outlined { fill_mode: FillMode::color(Color::WHITE), outline_mode: StrokeMode::new(Color::BLACK, 6.0), }, Transform::from_xyz(position.x, position.y, position.z), ) } /// Spawn a new gate at the specified position in the world. pub fn spawn( commands: &mut Commands, name: &str, position: Vec2, rotation: Quat, size: Vec2, in_range: NodeRange, out_range: NodeRange, ins: usize, outs: usize, functions: Vec<Box<dyn Fn(&[State]) -> State + Send + Sync>>, standard: SymbolStandard, ) -> Entity { let gate = commands .spawn() .insert(Self { inputs: ins as u32, outputs: outs as u32, in_range, out_range, }) .insert(Name(name.to_string())) .insert(Inputs(vec![State::None; ins])) .insert(Outputs(vec![State::None; outs])) .insert(Transitions(functions)) .insert(Targets(vec![TargetMap::from(HashMap::new()); outs])) .id(); let z = Z_INDEX.fetch_add(1, Ordering::Relaxed) as f32; let distances; match standard { SymbolStandard::ANSI(path) => { distances = get_distances(ins as f32, outs as f32, size.x, size.y); commands.entity(gate).insert_bundle(Gate::body_from_path( Vec3::new(position.x, position.y, z), rotation, path, )); } SymbolStandard::BS(font, symbol, inverted) => { distances = get_distances(ins as f32, outs as f32, size.x, size.y); commands .entity(gate) .insert_bundle(Gate::body( Vec3::new(position.x, position.y, z), rotation, Vec2::new(distances.width, distances.height), )) .insert(BritishStandard); let symbol = commands .spawn_bundle(Text2dBundle { text: Text::with_section( &symbol, TextStyle { font: font.clone(), font_size: 30.0, color: Color::BLACK, }, TextAlignment { horizontal: HorizontalAlign::Center, ..Default::default() }, ), transform: Transform::from_xyz(0., 0., z), ..Default::default() }) .id(); commands.entity(gate).push_children(&[symbol]); if inverted { let radius = size.y * 0.08; let id = commands .spawn_bundle(Gate::invert_bs( Vec3::new(size.x / 2. + radius, 0., z), radius, )) .id(); commands.entity(gate).push_children(&[id]); } } } commands .entity(gate) .insert(Interactable::new( Vec2::new(0., 0.), Vec2::new(distances.width, distances.height), 1, )) .insert(Selectable) .insert(Draggable { update: true }); let mut entvec: Vec<Entity> = Vec::new(); for i in 1..=ins { entvec.push(Connector::with_line( commands, Vec3::new( -size.y * 0.6, distances.offset + i as f32 * distances.in_step, z, ), size.y * 0.1, ConnectorType::In, (i - 1) as usize, format!("x{}", i), )); } for i in 1..=outs { entvec.push(Connector::with_line( commands, Vec3::new( size.y * 0.6, distances.offset + i as f32 * distances.out_step, z, ), size.y * 0.1, ConnectorType::Out, (i - 1) as usize, format!("y{}", i), )); } commands.entity(gate).push_children(&entvec); gate } } impl Gate { pub fn not_gate_bs_( commands: &mut Commands, position: Vec2, rotation: Quat, ins: usize, outs: usize, font: Handle<Font>, ) -> Entity { let g = Gate::spawn( commands, "NOT Gate", position, rotation, Vec2::new(GATE_WIDTH, GATE_HEIGHT), NodeRange { min: 1, max: 1 }, NodeRange { min: 1, max: 1 }, ins, outs, trans![|inputs| { match inputs[0] { State::None => State::None, State::Low => State::High, State::High => State::Low, } },], SymbolStandard::BS(font, "1".to_string(), true), ); commands.entity(g).insert(NodeType::Not); g } pub fn not_gate_bs( commands: &mut Commands, position: Vec2, rotation: Quat, font: Handle<Font> ) -> Entity { Self::not_gate_bs_(commands, position, rotation, 1, 1, font) } pub fn and_gate_bs_( commands: &mut Commands, position: Vec2, rotation: Quat, ins: usize, outs: usize, font: Handle<Font>, ) -> Entity { let g = Gate::spawn( commands, "AND Gate", position, rotation, Vec2::new(GATE_WIDTH, GATE_HEIGHT), NodeRange { min: 2, max: 16 }, NodeRange { min: 1, max: 1 }, ins, outs, trans![|inputs| { let mut ret = State::High; for i in inputs { match i { State::None => { ret = State::None; } State::Low => { ret = State::Low; break; } State::High => {} } } ret },], SymbolStandard::BS(font, "&".to_string(), false), ); commands.entity(g).insert(NodeType::And); g } pub fn and_gate_bs( commands: &mut Commands, position: Vec2, rotation: Quat, font: Handle<Font> ) -> Entity { Self::and_gate_bs_(commands, position, rotation, 2, 1, font) } pub fn nand_gate_bs_( commands: &mut Commands, position: Vec2, rotation: Quat, ins: usize, outs: usize, font: Handle<Font>, ) -> Entity { let g = Gate::spawn( commands, "NAND Gate", position, rotation, Vec2::new(GATE_WIDTH, GATE_HEIGHT), NodeRange { min: 2, max: 16 }, NodeRange { min: 1, max: 1 }, ins, outs, trans![|inputs| { let mut ret = State::Low; for i in inputs { match i { State::None => { ret = State::None; } State::Low => { ret = State::High; break; } State::High => {} } } ret },], SymbolStandard::BS(font, "&".to_string(), true), ); commands.entity(g).insert(NodeType::Nand); g } pub fn nand_gate_bs( commands: &mut Commands, position: Vec2, rotation: Quat, font: Handle<Font> ) -> Entity { Self::nand_gate_bs_(commands, position, rotation, 2, 1, font) } pub fn or_gate_bs_( commands: &mut Commands, position: Vec2, rotation: Quat, ins: usize, outs: usize, font: Handle<Font>, ) -> Entity { let g = Gate::spawn( commands, "OR Gate", position, rotation, Vec2::new(GATE_WIDTH, GATE_HEIGHT), NodeRange { min: 2, max: 16 }, NodeRange { min: 1, max: 1 }, ins, outs, trans![|inputs| { let mut ret = State::Low; for i in inputs { match i { State::None => { ret = State::None; } State::Low => {} State::High => { ret = State::High; break; } } } ret },], SymbolStandard::BS(font, "≥1".to_string(), false), ); commands.entity(g).insert(NodeType::Or); g } pub fn or_gate_bs( commands: &mut Commands, position: Vec2, rotation: Quat, font: Handle<Font> ) -> Entity { Self::or_gate_bs_(commands, position, rotation, 2, 1, font) } pub fn nor_gate_bs_( commands: &mut Commands, position: Vec2, rotation: Quat, ins: usize, outs: usize, font: Handle<Font>, ) -> Entity { let g = Gate::spawn( commands, "NOR Gate", position, rotation, Vec2::new(GATE_WIDTH, GATE_HEIGHT), NodeRange { min: 2, max: 16 }, NodeRange { min: 1, max: 1 }, ins, outs, trans![|inputs| { let mut ret = State::High; for i in inputs { match i { State::None => { ret = State::None; } State::Low => {} State::High => { ret = State::Low; break; } } } ret },], SymbolStandard::BS(font, "≥1".to_string(), true), ); commands.entity(g).insert(NodeType::Nor); g } pub fn nor_gate_bs( commands: &mut Commands, position: Vec2, rotation: Quat, font: Handle<Font> ) -> Entity { Self::nor_gate_bs_(commands, position, rotation, 2, 1, font) } pub fn xor_gate_bs_( commands: &mut Commands, position: Vec2, rotation: Quat, ins: usize, outs: usize, font: Handle<Font>, ) -> Entity { let g = Gate::spawn( commands, "XOR Gate", position, rotation, Vec2::new(GATE_WIDTH, GATE_HEIGHT), NodeRange { min: 2, max: 16 }, NodeRange { min: 1, max: 1 }, ins, outs, trans![|inputs| { let mut ret = State::Low; for i in inputs { match i { State::None => {} State::Low => {} State::High => match ret { State::None => { ret = State::High; } State::Low => { ret = State::High; } State::High => { ret = State::Low; } }, } } ret },], SymbolStandard::BS(font, "=1".to_string(), false), ); commands.entity(g).insert(NodeType::Xor); g } pub fn xor_gate_bs( commands: &mut Commands, position: Vec2, rotation: Quat, font: Handle<Font> ) -> Entity { Self::xor_gate_bs_(commands, position, rotation, 2, 1, font) } pub fn high_const( commands: &mut Commands, position: Vec2, rotation: Quat, font: Handle<Font> ) -> Entity { let g = Gate::spawn( commands, "HIGH Constant", position, rotation, Vec2::new(GATE_WIDTH, GATE_WIDTH), NodeRange { min: 0, max: 0 }, NodeRange { min: 1, max: 1 }, 0, 1, trans![|_| { State::High },], SymbolStandard::BS(font, "1".to_string(), false), ); commands.entity(g).insert(NodeType::HighConst); g } pub fn low_const( commands: &mut Commands, position: Vec2, rotation: Quat, font: Handle<Font> ) -> Entity { let g = Gate::spawn( commands, "Low Constant", position, rotation, Vec2::new(GATE_WIDTH, GATE_WIDTH), NodeRange { min: 0, max: 0 }, NodeRange { min: 1, max: 1 }, 0, 1, trans![|_| { State::Low },], SymbolStandard::BS(font, "0".to_string(), false), ); commands.entity(g).insert(NodeType::LowConst); g } } pub struct ChangeInput { pub gate: Entity, pub to: u32, } pub fn change_input_system( mut commands: Commands, mut ev_connect: EventReader<ChangeInput>, mut ev_disconnect: EventWriter<DisconnectEvent>, mut q_gate: Query<( Entity, &mut Gate, &mut Inputs, &mut Interactable, &GlobalTransform, Option<&BritishStandard>, )>, q_connectors: Query<&Children>, mut q_connector: Query<(&mut Connector, &mut Transform, &Connections)>, ) { for ev in ev_connect.iter() { if let Ok((gent, mut gate, mut inputs, mut interact, transform, bs)) = q_gate.get_mut(ev.gate) { // Update input count gate.inputs = ev.to; let translation = transform.translation; // Update input vector inputs.resize(gate.inputs as usize, State::None); // If the logic component is BS it has a box as body. // We are going to resize it in relation to the number // of input connectors. let dists = if let Some(_) = bs { let dists = get_distances( gate.inputs as f32, gate.outputs as f32, GATE_WIDTH, GATE_HEIGHT, ); // Update bounding box interact.update_size(0., 0., dists.width, dists.height); let gate = Gate::body( Vec3::new(translation.x, translation.y, translation.z), transform.rotation, Vec2::new(dists.width, dists.height), ); // Update body commands.entity(ev.gate).remove_bundle::<ShapeBundle>(); commands.entity(ev.gate).insert_bundle(gate); dists } else { get_distances( gate.inputs as f32, gate.outputs as f32, GATE_SIZE, GATE_SIZE, ) }; // Update connectors attached to this gate let mut max = 0; if let Ok(connectors) = q_connectors.get(ev.gate) { for connector in connectors.iter() { if let Ok((conn, mut trans, conns)) = q_connector.get_mut(*connector) { if conn.ctype == ConnectorType::In { if conn.index < ev.to as usize { trans.translation = Vec3::new( -GATE_SIZE * 0.6, dists.offset + (conn.index + 1) as f32 * dists.in_step, 0., ); if max < conn.index { max = conn.index; } } else { // Remove connector if neccessary. This includes logical // links between gates and connection line entities. for &c in conns.iter() { ev_disconnect.send(DisconnectEvent { connection: c, in_parent: Some(gent), }); } // Finally remove entity. commands.entity(*connector).despawn_recursive(); } } } } } // If the expected amount of connectors exceeds the factual // amount, add new connectors to the gate. let mut entvec: Vec<Entity> = Vec::new(); for i in (max + 2)..=ev.to as usize { entvec.push(Connector::with_line( &mut commands, Vec3::new( -GATE_SIZE * 0.6, dists.offset + i as f32 * dists.in_step, translation.z, ), GATE_SIZE * 0.1, ConnectorType::In, i - 1, format!("y{}", i), )); } if !entvec.is_empty() { commands.entity(ev.gate).push_children(&entvec); } } } }
rust
MIT
853a0f42a05913674b30e2a3b0a79317887422ba
2026-01-04T20:19:46.997032Z
false
r4gus/nodus
https://github.com/r4gus/nodus/blob/853a0f42a05913674b30e2a3b0a79317887422ba/src/gate/graphics/segment_display.rs
src/gate/graphics/segment_display.rs
use super::*; use crate::gate::core::{State, *}; use crate::gate::serialize::*; use bevy::prelude::*; use bevy_prototype_lyon::prelude::*; use lyon_tessellation::path::path::Builder; use nodus::world2d::interaction2d::{Draggable, Hover, Interactable, Selectable}; use std::collections::HashMap; use std::sync::atomic::Ordering; #[derive(Debug, Clone, PartialEq, Hash, Component)] pub struct Segment { nr: u8, } #[derive(Debug, Clone, PartialEq)] struct SegmentShape { size: f32, } #[derive(Debug, Clone, PartialEq, Hash, Component)] pub struct SevenSegmentDisplay { segments: Vec<Entity>, } impl Geometry for SegmentShape { fn add_geometry(&self, b: &mut Builder) { let mut path = PathBuilder::new(); let step = self.size / 5.0; path.move_to(Vec2::new(0.0, 0.0)); path.line_to(Vec2::new(step, step)); path.line_to(Vec2::new(path.current_position().x + 3.0 * step, path.current_position().y)); path.line_to(Vec2::new(path.current_position().x + step, path.current_position().y - step)); path.line_to(Vec2::new(path.current_position().x - step, path.current_position().y - step)); path.line_to(Vec2::new(path.current_position().x - 3.0 * step, path.current_position().y)); path.close(); b.concatenate(&[path.build().0.as_slice()]); } } impl SegmentShape { pub fn spawn(commands: &mut Commands, position: Vec3, rotation: Quat, size: f32, nr: u8) -> Entity { let segment = GeometryBuilder::build_as( &SegmentShape { size, }, DrawMode::Outlined { fill_mode: FillMode::color(Color::WHITE), outline_mode: StrokeMode::new(Color::BLACK, 2.0), }, Transform::from_xyz(position.x, position.y, position.z) .with_rotation(rotation), ); commands .spawn_bundle(segment) .insert(Segment { nr }) .id() } } impl SevenSegmentDisplay { pub fn spawn(commands: &mut Commands, position: Vec2, rotation: Quat) -> Entity { let z = Z_INDEX.fetch_add(1, Ordering::Relaxed) as f32; let segment_size = GATE_WIDTH; let x = segment_size * 0.5; let y = segment_size * 1.2; let coords = vec![ (Vec3::new(-x, y, 0.1), Quat::IDENTITY), (Vec3::new(segment_size + 2.0 - x, y - 2.0, 0.1), Quat::from_rotation_z(-std::f32::consts::PI/ 2.0)), (Vec3::new(segment_size + 2.0 - x, y - segment_size - 6.0, 0.1), Quat::from_rotation_z(-std::f32::consts::PI/ 2.0)), (Vec3::new(-x, y - segment_size * 2.0 - 8.0, 0.1), Quat::IDENTITY), (Vec3::new(-2.0 - x, y - segment_size - 6.0, 0.1), Quat::from_rotation_z(-std::f32::consts::PI/ 2.0)), (Vec3::new(-2.0 - x, y - 2.0, 0.1), Quat::from_rotation_z(-std::f32::consts::PI/ 2.0)), (Vec3::new(-x, y - segment_size - 4.0, 0.1), Quat::IDENTITY), ]; let mut segments: Vec<Entity> = Vec::new(); for (nr, (pos, rot)) in coords.iter().enumerate() { segments.push( SegmentShape::spawn( commands, *pos, *rot, segment_size, nr as u8 ) ); } let parent = commands .spawn_bundle( Gate::body( Vec3::new(position.x, position.y, z), rotation, Vec2::new(GATE_WIDTH * 2.0, GATE_HEIGHT * 2.0), ) ) .insert( Transform::from_xyz(position.x, position.y, z) .with_rotation(rotation) ) .insert( GlobalTransform::from_xyz(position.x, position.y, z) .with_rotation(rotation) ) .insert(SevenSegmentDisplay { segments: segments.clone() }) .insert(Name("7-Segment Display".to_string())) .insert(Inputs(vec![State::None; 4])) .insert(NodeType::SevenSegmentDisplay) .insert(Interactable::new( Vec2::new(0., 0.), Vec2::new(GATE_WIDTH * 2.0, GATE_HEIGHT * 2.0), 1, )) .insert(Selectable) .insert(Draggable { update: true }) .id(); for i in 0..4 { segments.push( Connector::with_line_vert( commands, Vec3::new( -GATE_WIDTH * 2.0 * 0.375 + i as f32 * GATE_WIDTH * 2.0 * 0.25, -GATE_HEIGHT * 2.0 * 0.7, 0. ), GATE_SIZE * 0.1, ConnectorType::In, i, format!("x{}", i), ) ); } commands .entity(parent) .push_children(&segments); parent } } const COLOR_OFF: Color = Color::WHITE; const COLOR_ON: Color = Color::RED; const DISPLAY_COLORS: [[Color; 7]; 16] = [ [COLOR_ON, COLOR_ON, COLOR_ON, COLOR_ON, COLOR_ON, COLOR_ON, COLOR_OFF], [COLOR_OFF, COLOR_ON, COLOR_ON, COLOR_OFF, COLOR_OFF, COLOR_OFF, COLOR_OFF], [COLOR_ON, COLOR_ON, COLOR_OFF, COLOR_ON, COLOR_ON, COLOR_OFF, COLOR_ON], [COLOR_ON, COLOR_ON, COLOR_ON, COLOR_ON, COLOR_OFF, COLOR_OFF, COLOR_ON], [COLOR_OFF, COLOR_ON, COLOR_ON, COLOR_OFF, COLOR_OFF, COLOR_ON, COLOR_ON], [COLOR_ON, COLOR_OFF, COLOR_ON, COLOR_ON, COLOR_OFF, COLOR_ON, COLOR_ON], [COLOR_ON, COLOR_OFF, COLOR_ON, COLOR_ON, COLOR_ON, COLOR_ON, COLOR_ON], [COLOR_ON, COLOR_ON, COLOR_ON, COLOR_OFF, COLOR_OFF, COLOR_OFF, COLOR_OFF], [COLOR_ON, COLOR_ON, COLOR_ON, COLOR_ON, COLOR_ON, COLOR_ON, COLOR_ON], [COLOR_ON, COLOR_ON, COLOR_ON, COLOR_ON, COLOR_OFF, COLOR_ON, COLOR_ON], [COLOR_ON, COLOR_ON, COLOR_ON, COLOR_OFF, COLOR_ON, COLOR_ON, COLOR_ON], [COLOR_OFF, COLOR_OFF, COLOR_ON, COLOR_ON, COLOR_ON, COLOR_ON, COLOR_ON], [COLOR_ON, COLOR_OFF, COLOR_OFF, COLOR_ON, COLOR_ON, COLOR_ON, COLOR_OFF], [COLOR_OFF, COLOR_ON, COLOR_ON, COLOR_ON, COLOR_ON, COLOR_OFF, COLOR_ON], [COLOR_ON, COLOR_OFF, COLOR_OFF, COLOR_ON, COLOR_ON, COLOR_ON, COLOR_ON], [COLOR_ON, COLOR_OFF, COLOR_OFF, COLOR_OFF, COLOR_ON, COLOR_ON, COLOR_ON], ]; pub fn segment_system( q_seg: Query<(&Inputs, &SevenSegmentDisplay)>, mut draw: Query<&mut DrawMode>, ) { for (inputs, display) in q_seg.iter() { // Inputs are treated as little endian, i.e. 2^3 + 2^2 + 2^1 + 2^0. let mut i = if inputs[3] == State::High { 1 } else { 0 }; i |= if inputs[2] == State::High { 1 } else { 0 } << 1; i |= if inputs[1] == State::High { 1 } else { 0 } << 2; i |= if inputs[0] == State::High { 1 } else { 0 } << 3; for j in 0..7 { let e = display.segments[j]; if let Ok(mut mode) = draw.get_mut(e) { if let DrawMode::Outlined { ref mut fill_mode, outline_mode: _, } = *mode { fill_mode.color = DISPLAY_COLORS[i][j]; } } } } }
rust
MIT
853a0f42a05913674b30e2a3b0a79317887422ba
2026-01-04T20:19:46.997032Z
false
r4gus/nodus
https://github.com/r4gus/nodus/blob/853a0f42a05913674b30e2a3b0a79317887422ba/src/gate/graphics/selector.rs
src/gate/graphics/selector.rs
use crate::gate::{ core::Gate, graphics::{clk::Clk, light_bulb::LightBulb, toggle_switch::ToggleSwitch, segment_display::*,}, }; use bevy::prelude::*; use bevy_prototype_lyon::prelude::*; use nodus::world2d::camera2d::MouseWorldPos; use nodus::world2d::interaction2d::{Hover, Selected}; use nodus::world2d::{InteractionMode, Lock}; #[derive(Debug, Clone, PartialEq, Component)] pub struct SelectBox { start: Vec2, } pub fn selector_system( mut commands: Commands, mb: Res<Input<MouseButton>>, mw: Res<MouseWorldPos>, lock: Res<Lock>, mode: Res<InteractionMode>, q_gate: Query< (Entity, &Transform), Or<(With<Gate>, With<LightBulb>, With<ToggleSwitch>, With<Clk>, With<SevenSegmentDisplay>)>, >, q_hover: Query<Entity, With<Hover>>, mut q_select: Query<(Entity, &mut Path, &SelectBox), With<SelectBox>>, ) { if lock.0 || *mode != InteractionMode::Select { return; } if q_hover.is_empty() && mb.just_pressed(MouseButton::Left) { let frame = GeometryBuilder::build_as( &shapes::Rectangle { extents: Vec2::new(1.0, 1.0), origin: RectangleOrigin::TopLeft, }, DrawMode::Outlined { fill_mode: FillMode::color(Color::rgba(0.72, 0.277, 0.0, 0.5)), outline_mode: StrokeMode::new(Color::rgba(0.72, 0.277, 0.0, 1.0), 2.0), }, Transform::from_xyz(mw.x, mw.y, 900.0), ); commands.spawn_bundle(frame).insert(SelectBox { start: Vec2::new(mw.x, mw.y), }); } else if !q_select.is_empty() && mb.just_released(MouseButton::Left) { if let Ok((entity, _, sb)) = q_select.get_single() { let (wx, wy) = if sb.start.x < mw.x { (sb.start.x, mw.x) } else { (mw.x, sb.start.x) }; let (hx, hy) = if sb.start.y < mw.y { (sb.start.y, mw.y) } else { (mw.y, sb.start.y) }; for (entity, transform) in q_gate.iter() { let (x, y) = (transform.translation.x, transform.translation.y); if wx <= x && x <= wy && hx <= y && y <= hy { commands.entity(entity).insert(Selected); } } commands.entity(entity).despawn_recursive(); } } else if !q_select.is_empty() && mb.pressed(MouseButton::Left) { if let Ok((_, mut path, sb)) = q_select.get_single_mut() { let w = mw.x - sb.start.x; let h = -(mw.y - sb.start.y); let s = &shapes::Rectangle { extents: Vec2::new(w, h), origin: RectangleOrigin::TopLeft, }; *path = ShapePath::build_as(s); } } else { for (entity, _, _) in q_select.iter() { commands.entity(entity).despawn_recursive(); } } }
rust
MIT
853a0f42a05913674b30e2a3b0a79317887422ba
2026-01-04T20:19:46.997032Z
false
r4gus/nodus
https://github.com/r4gus/nodus/blob/853a0f42a05913674b30e2a3b0a79317887422ba/src/gate/graphics/background.rs
src/gate/graphics/background.rs
use bevy::prelude::*; use bevy_prototype_lyon::prelude::*; use nodus::world2d::camera2d::*; #[derive(Debug, Clone, Copy, PartialEq, Component)] pub struct BackgroundGrid; pub fn draw_background_grid_system( mut commands: Commands, wnds: Res<Windows>, mut q: QuerySet<( QueryState<&mut Transform, (With<MainCamera>, Or<(Added<Transform>, Changed<Transform>)>)>, QueryState<(Entity, &mut Transform), With<BackgroundGrid>>, )>, ) { if let Ok(transform) = q.q0().get_single() { let mut x = transform.translation.x; let mut y = transform.translation.y; let mut x_sign = 1.; let mut y_sign = 1.; if x < 0.0 { x *= -1.; x_sign = -1.; } if y < 0.0 { y *= -1.; y_sign = -1.; } let x_start = (x as u32 & !0xFFF) as f32; let y_start = (y as u32 & !0xFFF) as f32; let _scale = transform.scale.clone(); if let Ok((_entity, mut bgt)) = q.q1().get_single_mut() { bgt.translation.x = x_start * x_sign; bgt.translation.y = y_start * y_sign; } else { let color = Color::rgba(0., 0., 0., 0.25); let window_size = get_primary_window_size(&wnds); let wx = window_size.x * 5.; let wy = window_size.y * 5.; let grid = commands .spawn() .insert(BackgroundGrid) .insert(Transform::from_xyz(x_start, y_start, 1.)) .insert(GlobalTransform::from_xyz(x_start, y_start, 1.)) .id(); let mut evec = Vec::new(); for xc in (0..wx as u32 * 4).step_by(120) { evec.push( commands .spawn_bundle(GeometryBuilder::build_as( &shapes::Line( Vec2::new(-wx * 2. + xc as f32, wy * 2.), Vec2::new(-wx * 2. + xc as f32, -wy * 2.), ), DrawMode::Stroke(StrokeMode::new(color, 7.0)), Transform::from_xyz(0., 0., 1.), )) .id(), ); } for yc in (0..wy as u32 * 4).step_by(120) { evec.push( commands .spawn_bundle(GeometryBuilder::build_as( &shapes::Line( Vec2::new(wx * 2., -wy * 2. + yc as f32), Vec2::new(-wx * 2., -wy * 2. + yc as f32), ), DrawMode::Stroke(StrokeMode::new(color, 7.0)), Transform::from_xyz(0., 0., 1.), )) .id(), ); } commands.entity(grid).push_children(&evec); } } }
rust
MIT
853a0f42a05913674b30e2a3b0a79317887422ba
2026-01-04T20:19:46.997032Z
false
zibo-chen/rust-paddle-ocr
https://github.com/zibo-chen/rust-paddle-ocr/blob/2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e/build.rs
build.rs
use std::path::PathBuf; use std::process::Command; use std::{env, fs}; fn main() { // 在 docs.rs 构建环境中,跳过所有 C++ 编译 if env::var("DOCS_RS").is_ok() || env::var("CARGO_FEATURE_DOCSRS").is_ok() { println!("cargo:warning=Building for docs.rs, skipping C++ compilation"); return; } let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); let arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap(); let os = env::var("CARGO_CFG_TARGET_OS").unwrap(); let debug = env::var("DEBUG").unwrap(); // Feature flags let coreml_enabled = env::var("CARGO_FEATURE_COREML").is_ok(); let metal_enabled = env::var("CARGO_FEATURE_METAL").is_ok(); let cuda_enabled = env::var("CARGO_FEATURE_CUDA").is_ok(); let opencl_enabled = env::var("CARGO_FEATURE_OPENCL").is_ok(); let opengl_enabled = env::var("CARGO_FEATURE_OPENGL").is_ok(); let vulkan_enabled = env::var("CARGO_FEATURE_VULKAN").is_ok(); let manifest_dir_path = PathBuf::from(&manifest_dir); // Get or download MNN source code let mnn_source_dir = get_mnn_source(&manifest_dir_path); // Build MNN using cmake let dst = build_mnn_with_cmake( &mnn_source_dir, &arch, &os, &debug, coreml_enabled, metal_enabled, cuda_enabled, opencl_enabled, opengl_enabled, vulkan_enabled, ); // Build our C++ wrapper using cc build_wrapper(&manifest_dir_path, &mnn_source_dir, &dst, &os); // Link libraries link_libraries( &dst, &os, coreml_enabled, metal_enabled, cuda_enabled, opencl_enabled, opengl_enabled, vulkan_enabled, ); // Generate Rust bindings bind_gen(&manifest_dir_path, &mnn_source_dir, &dst, &os, &arch); } /// Get MNN source code directory /// Priority: /// 1. Environment variable MNN_SOURCE_DIR /// 2. Local 3rd_party/MNN directory /// 3. Clone from GitHub fn get_mnn_source(manifest_dir: &PathBuf) -> PathBuf { // Check environment variable first if let Ok(mnn_dir) = env::var("MNN_SOURCE_DIR") { let mnn_path = PathBuf::from(mnn_dir); if mnn_path.exists() && mnn_path.join("CMakeLists.txt").exists() { println!( "cargo:warning=Using MNN source from MNN_SOURCE_DIR: {}", mnn_path.display() ); return mnn_path; } else { panic!( "MNN_SOURCE_DIR is set but directory is invalid or missing CMakeLists.txt: {}", mnn_path.display() ); } } // Check local 3rd_party/MNN let local_mnn = manifest_dir.join("3rd_party/MNN"); if local_mnn.exists() && local_mnn.join("CMakeLists.txt").exists() { println!( "cargo:warning=Using local MNN source: {}", local_mnn.display() ); return local_mnn; } // Clone from GitHub println!("cargo:warning=MNN source not found, cloning from GitHub..."); let third_party_dir = manifest_dir.join("3rd_party"); fs::create_dir_all(&third_party_dir).expect("Failed to create 3rd_party directory"); let status = Command::new("git") .args(&[ "clone", "--depth=1", "https://github.com/alibaba/MNN.git", local_mnn.to_str().unwrap(), ]) .status() .expect("Failed to execute git clone command. Make sure git is installed."); if !status.success() { panic!("Failed to clone MNN from GitHub"); } if !local_mnn.join("CMakeLists.txt").exists() { panic!("MNN cloned but CMakeLists.txt not found"); } println!( "cargo:warning=Successfully cloned MNN to: {}", local_mnn.display() ); local_mnn } fn build_mnn_with_cmake( mnn_source_dir: &PathBuf, arch: &str, os: &str, debug: &str, coreml_enabled: bool, metal_enabled: bool, cuda_enabled: bool, opencl_enabled: bool, opengl_enabled: bool, vulkan_enabled: bool, ) -> PathBuf { let mut config = cmake::Config::new(mnn_source_dir); config .define("MNN_BUILD_SHARED_LIBS", "OFF") .define("MNN_BUILD_TOOLS", "OFF") .define("MNN_BUILD_DEMO", "OFF") .define("MNN_BUILD_TEST", "OFF") .define("MNN_BUILD_BENCHMARK", "OFF") .define("MNN_BUILD_QUANTOOLS", "OFF") .define("MNN_BUILD_CONVERTER", "OFF") .define("MNN_PORTABLE_BUILD", "ON") .define("MNN_SEP_BUILD", "OFF"); // For Windows, always use Release mode to ensure consistent CRT linking if os == "windows" { config.define("CMAKE_BUILD_TYPE", "Release"); // Check if we're using static CRT if env::var("CARGO_CFG_TARGET_FEATURE").map_or(false, |f| f.contains("crt-static")) { // MNN has a specific option for static CRT on Windows config.define("MNN_WIN_RUNTIME_MT", "ON"); // Also set these for extra safety config.define("CMAKE_MSVC_RUNTIME_LIBRARY", "MultiThreaded"); config.define("CMAKE_C_FLAGS_RELEASE", "/MT /O2 /Ob2 /DNDEBUG"); config.define("CMAKE_CXX_FLAGS_RELEASE", "/MT /O2 /Ob2 /DNDEBUG"); config.define("CMAKE_C_FLAGS", "/MT"); config.define("CMAKE_CXX_FLAGS", "/MT"); } // For 32-bit Windows, ensure proper configuration if arch == "x86" { config.define("CMAKE_GENERATOR_PLATFORM", "Win32"); } } else { // For non-Windows platforms, respect debug flag if debug == "true" { config.define("CMAKE_BUILD_TYPE", "Debug"); } else { config.define("CMAKE_BUILD_TYPE", "Release"); } } // Android cross-compilation if os == "android" { let ndk = env::var("ANDROID_NDK_ROOT") .or_else(|_| env::var("ANDROID_NDK_HOME")) .or_else(|_| env::var("ANDROID_NDK")) .or_else(|_| env::var("NDK_HOME")) .expect( "Android NDK not found. Please set one of: ANDROID_NDK_ROOT, ANDROID_NDK_HOME, ANDROID_NDK, NDK_HOME", ); config .define( "CMAKE_TOOLCHAIN_FILE", PathBuf::from(&ndk).join("build/cmake/android.toolchain.cmake"), ) .define("ANDROID_STL", "c++_static") .define("ANDROID_NATIVE_API_LEVEL", "android-21") .define("ANDROID_TOOLCHAIN", "clang") .define("MNN_BUILD_FOR_ANDROID_COMMAND", "ON") .define("MNN_USE_SSE", "OFF"); match arch { "arm" => { config.define("ANDROID_ABI", "armeabi-v7a"); } "aarch64" => { config.define("ANDROID_ABI", "arm64-v8a"); } "x86" => { config.define("ANDROID_ABI", "x86"); } "x86_64" => { config.define("ANDROID_ABI", "x86_64"); } _ => {} } } // iOS cross-compilation if os == "ios" { config .define("CMAKE_SYSTEM_NAME", "iOS") .define("MNN_BUILD_FOR_IOS", "ON"); if arch == "aarch64" { config.define("CMAKE_OSX_ARCHITECTURES", "arm64"); } else if arch == "x86_64" { // Simulator config.define("CMAKE_OSX_ARCHITECTURES", "x86_64"); } } // SIMD optimizations if matches!(arch, "x86" | "x86_64") && os != "android" { config.define("MNN_USE_SSE", "ON"); } // CoreML (macOS/iOS only) if coreml_enabled && matches!(os, "macos" | "ios") { config.define("MNN_COREML", "ON"); } // Metal GPU (macOS/iOS only) if metal_enabled && matches!(os, "macos" | "ios") { config.define("MNN_METAL", "ON"); } // CUDA GPU (Linux/Windows) if cuda_enabled && matches!(os, "linux" | "windows") { config.define("MNN_CUDA", "ON"); } // OpenCL GPU (cross-platform) if opencl_enabled { config.define("MNN_OPENCL", "ON"); } // OpenGL GPU (Android/Linux) if opengl_enabled && matches!(os, "android" | "linux") { config.define("MNN_OPENGL", "ON"); } // Vulkan GPU (cross-platform) if vulkan_enabled { config.define("MNN_VULKAN", "ON"); } println!("cargo:rerun-if-changed=MNN/CMakeLists.txt"); config.build() } fn build_wrapper(manifest_dir: &PathBuf, mnn_source_dir: &PathBuf, mnn_dst: &PathBuf, os: &str) { let wrapper_file = manifest_dir.join("cpp/src/mnn_wrapper.cpp"); println!("cargo:rerun-if-changed=cpp/src/mnn_wrapper.cpp"); println!("cargo:rerun-if-changed=cpp/include/mnn_wrapper.h"); let mut build = cc::Build::new(); build .cpp(true) .file(&wrapper_file) .include(mnn_dst.join("include")) .include(mnn_source_dir.join("include")) .include(manifest_dir.join("cpp/include")); // Platform-specific C++ flags if os == "windows" { build.flag("/std:c++14").flag("/EHsc").flag("/W3"); } else { build.flag("-std=c++14").flag("-fvisibility=hidden"); } build.compile("mnn_wrapper"); } fn link_libraries( mnn_dst: &PathBuf, os: &str, coreml_enabled: bool, metal_enabled: bool, cuda_enabled: bool, opencl_enabled: bool, opengl_enabled: bool, vulkan_enabled: bool, ) { // Add library search paths println!("cargo:rustc-link-search=native={}", mnn_dst.display()); println!( "cargo:rustc-link-search=native={}", mnn_dst.join("lib").display() ); // Link MNN static library println!("cargo:rustc-link-lib=static=MNN"); // Platform-specific C++ runtime match os { "macos" | "ios" => { println!("cargo:rustc-link-lib=c++"); } "linux" => { println!("cargo:rustc-link-lib=stdc++"); println!("cargo:rustc-link-lib=m"); println!("cargo:rustc-link-lib=pthread"); } "android" => { println!("cargo:rustc-link-lib=c++_static"); println!("cargo:rustc-link-lib=log"); } "windows" => { // MSVC runtime is linked automatically when using matching CRT settings } _ => {} } // CoreML frameworks if coreml_enabled && matches!(os, "macos" | "ios") { println!("cargo:rustc-link-lib=framework=CoreML"); println!("cargo:rustc-link-lib=framework=Foundation"); println!("cargo:rustc-link-lib=framework=Metal"); println!("cargo:rustc-link-lib=framework=MetalPerformanceShaders"); } // Metal frameworks if metal_enabled && matches!(os, "macos" | "ios") { println!("cargo:rustc-link-lib=framework=Foundation"); println!("cargo:rustc-link-lib=framework=Metal"); println!("cargo:rustc-link-lib=framework=MetalPerformanceShaders"); } // CUDA libraries if cuda_enabled && matches!(os, "linux" | "windows") { println!("cargo:rustc-link-lib=cuda"); println!("cargo:rustc-link-lib=cudart"); println!("cargo:rustc-link-lib=cublas"); println!("cargo:rustc-link-lib=cudnn"); } // OpenCL library if opencl_enabled { if os == "macos" { println!("cargo:rustc-link-lib=framework=OpenCL"); } else { println!("cargo:rustc-link-lib=OpenCL"); } } // OpenGL libraries if opengl_enabled && matches!(os, "android" | "linux") { if os == "android" { println!("cargo:rustc-link-lib=GLESv3"); println!("cargo:rustc-link-lib=EGL"); } else { println!("cargo:rustc-link-lib=GL"); } } // Vulkan library if vulkan_enabled { println!("cargo:rustc-link-lib=vulkan"); } } fn bind_gen( manifest_dir: &PathBuf, mnn_source_dir: &PathBuf, mnn_dst: &PathBuf, os: &str, arch: &str, ) { let header_path = manifest_dir.join("cpp/include/mnn_wrapper.h"); let mut builder = bindgen::Builder::default() .header(header_path.to_string_lossy()) .allowlist_function("mnnr_.*") .allowlist_type("MNN.*") .allowlist_type("MNNR.*") .clang_arg(format!("-I{}", mnn_dst.join("include").display())) .clang_arg(format!("-I{}", mnn_source_dir.join("include").display())) .parse_callbacks(Box::new(bindgen::CargoCallbacks::new())) .layout_tests(false); // Android-specific clang target if os == "android" { let target = match arch { "aarch64" => "aarch64-linux-android", "arm" => "armv7-linux-androideabi", "x86_64" => "x86_64-linux-android", "x86" => "i686-linux-android", _ => "aarch64-linux-android", }; builder = builder.clang_arg(format!("--target={}", target)); } let bindings = builder.generate().expect("Unable to generate bindings"); let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); fs::write(out_path.join("mnn_bindings.rs"), bindings.to_string()) .expect("Couldn't write bindings!"); }
rust
Apache-2.0
2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e
2026-01-04T20:19:51.104139Z
false
zibo-chen/rust-paddle-ocr
https://github.com/zibo-chen/rust-paddle-ocr/blob/2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e/src/postprocess.rs
src/postprocess.rs
//! Postprocessing Utilities //! //! Provides post-processing functions for text detection results, including bounding box extraction, NMS, box merging, etc. use image::GrayImage; use imageproc::contours::{find_contours, Contour}; use imageproc::point::Point; use imageproc::rect::Rect; /// Text bounding box #[derive(Debug, Clone)] pub struct TextBox { /// Bounding box rectangle pub rect: Rect, /// Confidence score pub score: f32, /// Four corner points (optional, for rotated boxes) pub points: Option<[Point<f32>; 4]>, } impl TextBox { /// Create new text bounding box pub fn new(rect: Rect, score: f32) -> Self { Self { rect, score, points: None, } } /// Create with corner points pub fn with_points(rect: Rect, score: f32, points: [Point<f32>; 4]) -> Self { Self { rect, score, points: Some(points), } } /// Calculate area pub fn area(&self) -> u32 { self.rect.width() * self.rect.height() } /// Expand bounding box pub fn expand(&self, border: u32, max_width: u32, max_height: u32) -> Self { let x = (self.rect.left() - border as i32).max(0) as u32; let y = (self.rect.top() - border as i32).max(0) as u32; let right = ((self.rect.left() as u32 + self.rect.width()) + border).min(max_width); let bottom = ((self.rect.top() as u32 + self.rect.height()) + border).min(max_height); // 确保 right >= x 和 bottom >= y,避免减法溢出 let width = if right > x { right - x } else { 1 }; let height = if bottom > y { bottom - y } else { 1 }; Self { rect: Rect::at(x as i32, y as i32).of_size(width, height), score: self.score, points: self.points, } } } /// Extract text bounding boxes from segmentation mask /// /// # Parameters /// - `mask`: Binarized mask (0 or 255) /// - `width`: Mask width /// - `height`: Mask height /// - `original_width`: Original image width /// - `original_height`: Original image height /// - `min_area`: Minimum bounding box area /// - `box_threshold`: Bounding box score threshold pub fn extract_boxes_from_mask( mask: &[u8], width: u32, height: u32, original_width: u32, original_height: u32, min_area: u32, _box_threshold: f32, ) -> Vec<TextBox> { extract_boxes_from_mask_with_padding( mask, width, height, width, height, original_width, original_height, min_area, _box_threshold, ) } /// Extract text bounding boxes from segmentation mask with padding /// /// # Parameters /// - `mask`: Binarized mask (0 or 255) /// - `mask_width`: Mask width (including padding) /// - `mask_height`: Mask height (including padding) /// - `valid_width`: Valid region width (excluding padding) /// - `valid_height`: Valid region height (excluding padding) /// - `original_width`: Original image width /// - `original_height`: Original image height /// - `min_area`: Minimum bounding box area /// - `box_threshold`: Bounding box score threshold pub fn extract_boxes_from_mask_with_padding( mask: &[u8], mask_width: u32, mask_height: u32, valid_width: u32, valid_height: u32, original_width: u32, original_height: u32, min_area: u32, _box_threshold: f32, ) -> Vec<TextBox> { extract_boxes_with_unclip( mask, mask_width, mask_height, valid_width, valid_height, original_width, original_height, min_area, 1.5, // 默认 unclip_ratio ) } /// Extract text bounding boxes from segmentation mask (with unclip expansion) /// /// Core of DB algorithm is to perform unclip expansion on detected contours, /// because model output segmentation mask is usually smaller than actual text region. pub fn extract_boxes_with_unclip( mask: &[u8], mask_width: u32, mask_height: u32, valid_width: u32, valid_height: u32, original_width: u32, original_height: u32, min_area: u32, unclip_ratio: f32, ) -> Vec<TextBox> { // Create grayscale image let gray_image = GrayImage::from_raw(mask_width, mask_height, mask.to_vec()) .unwrap_or_else(|| GrayImage::new(mask_width, mask_height)); // Find contours let contours = find_contours::<i32>(&gray_image); // Calculate scale ratio (from valid region to original image) let scale_x = original_width as f32 / valid_width as f32; let scale_y = original_height as f32 / valid_height as f32; let mut boxes = Vec::new(); for contour in contours { // Only keep outer contours (without parent), filter out inner/nested contours // This avoids producing overlapping detection boxes if contour.parent.is_some() { continue; } if contour.points.len() < 4 { continue; } // Calculate bounding box let (min_x, min_y, max_x, max_y) = get_contour_bounds(&contour); // Filter out contours in padding area if min_x >= valid_width as i32 || min_y >= valid_height as i32 { continue; } // Clip to valid region let min_x = min_x.max(0); let min_y = min_y.max(0); let max_x = max_x.min(valid_width as i32); let max_y = max_y.min(valid_height as i32); let box_width = (max_x - min_x) as u32; let box_height = (max_y - min_y) as u32; // Filter boxes that are too small if box_width * box_height < min_area { continue; } // Calculate unclip expansion amount // DB algorithm uses area and perimeter to calculate expansion distance: distance = Area * unclip_ratio / Perimeter let area = box_width as f32 * box_height as f32; let perimeter = 2.0 * (box_width + box_height) as f32; let expand_dist = (area * unclip_ratio / perimeter).max(1.0); // Apply unclip expansion (on coordinates before scaling) let expanded_min_x = (min_x as f32 - expand_dist).max(0.0) as i32; let expanded_min_y = (min_y as f32 - expand_dist).max(0.0) as i32; let expanded_max_x = (max_x as f32 + expand_dist).min(valid_width as f32) as i32; let expanded_max_y = (max_y as f32 + expand_dist).min(valid_height as f32) as i32; let expanded_w = (expanded_max_x - expanded_min_x) as u32; let expanded_h = (expanded_max_y - expanded_min_y) as u32; // Scale to original image size let scaled_x = (expanded_min_x as f32 * scale_x) as i32; let scaled_y = (expanded_min_y as f32 * scale_y) as i32; let scaled_w = (expanded_w as f32 * scale_x) as u32; let scaled_h = (expanded_h as f32 * scale_y) as u32; // Ensure boundaries are within valid range let final_x = scaled_x.max(0) as u32; let final_y = scaled_y.max(0) as u32; let final_w = scaled_w.min(original_width.saturating_sub(final_x)); let final_h = scaled_h.min(original_height.saturating_sub(final_y)); if final_w > 0 && final_h > 0 { let rect = Rect::at(final_x as i32, final_y as i32).of_size(final_w, final_h); boxes.push(TextBox::new(rect, 1.0)); } } boxes } /// Get contour bounds fn get_contour_bounds(contour: &Contour<i32>) -> (i32, i32, i32, i32) { let mut min_x = i32::MAX; let mut min_y = i32::MAX; let mut max_x = i32::MIN; let mut max_y = i32::MIN; for point in &contour.points { min_x = min_x.min(point.x); min_y = min_y.min(point.y); max_x = max_x.max(point.x); max_y = max_y.max(point.y); } (min_x, min_y, max_x, max_y) } /// Calculate containment ratio of one box inside another fn compute_containment_ratio(inner: &Rect, outer: &Rect) -> f32 { let x1 = inner.left().max(outer.left()); let y1 = inner.top().max(outer.top()); let x2 = (inner.left() + inner.width() as i32).min(outer.left() + outer.width() as i32); let y2 = (inner.top() + inner.height() as i32).min(outer.top() + outer.height() as i32); if x2 <= x1 || y2 <= y1 { return 0.0; } let intersection = (x2 - x1) as f32 * (y2 - y1) as f32; let inner_area = inner.width() as f32 * inner.height() as f32; if inner_area <= 0.0 { 0.0 } else { intersection / inner_area } } /// Non-Maximum Suppression (NMS) /// /// Filter overlapping bounding boxes, keep ones with highest scores /// Also filters small boxes that are largely contained within other boxes /// /// # Parameters /// - `boxes`: List of bounding boxes /// - `iou_threshold`: IoU threshold, boxes exceeding this value are considered overlapping pub fn nms(boxes: &[TextBox], iou_threshold: f32) -> Vec<TextBox> { if boxes.is_empty() { return Vec::new(); } // Sort by score descending, area descending (keep boxes with higher score and larger area first) let mut indices: Vec<usize> = (0..boxes.len()).collect(); indices.sort_by(|&a, &b| { // First sort by score descending let score_cmp = boxes[b] .score .partial_cmp(&boxes[a].score) .unwrap_or(std::cmp::Ordering::Equal); if score_cmp != std::cmp::Ordering::Equal { return score_cmp; } // When scores are equal, sort by area descending (prefer larger boxes) boxes[b].area().cmp(&boxes[a].area()) }); let mut keep = Vec::new(); let mut suppressed = vec![false; boxes.len()]; for (pos, &i) in indices.iter().enumerate() { if suppressed[i] { continue; } keep.push(boxes[i].clone()); // Check all subsequent boxes (lower score or smaller area) for &j in indices.iter().skip(pos + 1) { if suppressed[j] { continue; } // Check IoU let iou = compute_iou(&boxes[i].rect, &boxes[j].rect); if iou > iou_threshold { suppressed[j] = true; continue; } // Check containment relationship: if j is largely contained (>50%) by i, suppress j let containment_j_in_i = compute_containment_ratio(&boxes[j].rect, &boxes[i].rect); if containment_j_in_i > 0.5 { suppressed[j] = true; continue; } // Check reverse containment: if i is largely contained (>70%) by j, // since i was selected first (higher score or larger area), suppress j let containment_i_in_j = compute_containment_ratio(&boxes[i].rect, &boxes[j].rect); if containment_i_in_j > 0.7 { suppressed[j] = true; continue; } } } keep } /// Calculate IoU (Intersection over Union) of two rectangles pub fn compute_iou(a: &Rect, b: &Rect) -> f32 { let x1 = a.left().max(b.left()); let y1 = a.top().max(b.top()); let x2 = (a.left() + a.width() as i32).min(b.left() + b.width() as i32); let y2 = (a.top() + a.height() as i32).min(b.top() + b.height() as i32); if x2 <= x1 || y2 <= y1 { return 0.0; } let intersection = (x2 - x1) as f32 * (y2 - y1) as f32; let area_a = a.width() as f32 * a.height() as f32; let area_b = b.width() as f32 * b.height() as f32; let union = area_a + area_b - intersection; if union <= 0.0 { 0.0 } else { intersection / union } } /// Merge adjacent bounding boxes /// /// Merge bounding boxes that are close to each other into one /// /// # Parameters /// - `boxes`: List of bounding boxes /// - `distance_threshold`: Distance threshold, boxes below this value will be merged pub fn merge_adjacent_boxes(boxes: &[TextBox], distance_threshold: i32) -> Vec<TextBox> { if boxes.is_empty() { return Vec::new(); } let mut merged = Vec::new(); let mut used = vec![false; boxes.len()]; for i in 0..boxes.len() { if used[i] { continue; } let mut current = boxes[i].rect; let mut group_score = boxes[i].score; let mut count = 1; used[i] = true; // Find boxes that can be merged loop { let mut found = false; for j in 0..boxes.len() { if used[j] { continue; } if can_merge(&current, &boxes[j].rect, distance_threshold) { current = merge_rects(&current, &boxes[j].rect); group_score += boxes[j].score; count += 1; used[j] = true; found = true; } } if !found { break; } } merged.push(TextBox::new(current, group_score / count as f32)); } merged } /// Check if two boxes can be merged fn can_merge(a: &Rect, b: &Rect, threshold: i32) -> bool { // Calculate vertical distance let a_bottom = a.top() + a.height() as i32; let b_bottom = b.top() + b.height() as i32; let _vertical_dist = if a.top() > b_bottom { a.top() - b_bottom } else if b.top() > a_bottom { b.top() - a_bottom } else { 0 // Vertical overlap }; // Calculate horizontal distance let a_right = a.left() + a.width() as i32; let b_right = b.left() + b.width() as i32; let horizontal_dist = if a.left() > b_right { a.left() - b_right } else if b.left() > a_right { b.left() - a_right } else { 0 // Horizontal overlap }; // Check if on same line (vertical overlap) and horizontal distance is less than threshold let vertical_overlap = !(a.top() > b_bottom || b.top() > a_bottom); vertical_overlap && horizontal_dist <= threshold } /// Merge two rectangles fn merge_rects(a: &Rect, b: &Rect) -> Rect { let x1 = a.left().min(b.left()); let y1 = a.top().min(b.top()); let x2 = (a.left() + a.width() as i32).max(b.left() + b.width() as i32); let y2 = (a.top() + a.height() as i32).max(b.top() + b.height() as i32); Rect::at(x1, y1).of_size((x2 - x1) as u32, (y2 - y1) as u32) } /// Sort bounding boxes by reading order (top to bottom, left to right) pub fn sort_boxes_by_reading_order(boxes: &mut [TextBox]) { boxes.sort_by(|a, b| { // First sort by y coordinate (row) let y_cmp = a.rect.top().cmp(&b.rect.top()); if y_cmp != std::cmp::Ordering::Equal { return y_cmp; } // Same row, sort by x coordinate a.rect.left().cmp(&b.rect.left()) }); } /// Group bounding boxes by line /// /// Group boxes with close y coordinates into the same line pub fn group_boxes_by_line(boxes: &[TextBox], line_threshold: i32) -> Vec<Vec<TextBox>> { if boxes.is_empty() { return Vec::new(); } let mut sorted_boxes = boxes.to_vec(); sorted_boxes.sort_by_key(|b| b.rect.top()); let mut lines: Vec<Vec<TextBox>> = Vec::new(); let mut current_line: Vec<TextBox> = vec![sorted_boxes[0].clone()]; let mut current_y = sorted_boxes[0].rect.top(); for box_item in sorted_boxes.iter().skip(1) { if (box_item.rect.top() - current_y).abs() <= line_threshold { current_line.push(box_item.clone()); } else { // Sort current line by x current_line.sort_by_key(|b| b.rect.left()); lines.push(current_line); current_line = vec![box_item.clone()]; current_y = box_item.rect.top(); } } // Add last line if !current_line.is_empty() { current_line.sort_by_key(|b| b.rect.left()); lines.push(current_line); } lines } /// Merge bounding boxes from multiple detection results (for high precision mode) /// /// # Parameters /// - `results`: Multiple detection results, each element is (boxes, offset_x, offset_y, scale) /// - `iou_threshold`: NMS IoU threshold pub fn merge_multi_scale_results( results: &[(Vec<TextBox>, u32, u32, f32)], iou_threshold: f32, ) -> Vec<TextBox> { let mut all_boxes = Vec::new(); for (boxes, offset_x, offset_y, scale) in results { for box_item in boxes { // Convert box coordinates to original image coordinate system let scaled_x = (box_item.rect.left() as f32 / scale) as i32 + *offset_x as i32; let scaled_y = (box_item.rect.top() as f32 / scale) as i32 + *offset_y as i32; let scaled_w = (box_item.rect.width() as f32 / scale) as u32; let scaled_h = (box_item.rect.height() as f32 / scale) as u32; let rect = Rect::at(scaled_x, scaled_y).of_size(scaled_w, scaled_h); all_boxes.push(TextBox::new(rect, box_item.score)); } } // Apply NMS to remove duplicates nms(&all_boxes, iou_threshold) } // ============== Traditional Algorithm Detection ============== /// Detect text regions using traditional algorithm (suitable for solid background) /// /// Based on OTSU binarization + connected component analysis, suitable for: /// - Document images with solid background /// - High contrast text /// - As supplement to deep learning detection /// /// # Parameters /// - `gray_image`: Grayscale image /// - `min_area`: Minimum text region area /// - `expand_ratio`: Bounding box expansion ratio pub fn detect_text_traditional( gray_image: &GrayImage, min_area: u32, expand_ratio: f32, ) -> Vec<TextBox> { let (width, height) = gray_image.dimensions(); // 1. Calculate OTSU threshold let threshold = otsu_threshold(gray_image); // 2. Binarization let binary: Vec<u8> = gray_image .pixels() .map(|p| if p.0[0] < threshold { 255 } else { 0 }) .collect(); // 3. Create binary image and find contours let binary_image = GrayImage::from_raw(width, height, binary).unwrap_or_else(|| GrayImage::new(width, height)); let contours = find_contours::<i32>(&binary_image); // 4. Extract bounding boxes let mut boxes = Vec::new(); for contour in contours { if contour.points.len() < 4 { continue; } let (min_x, min_y, max_x, max_y) = get_contour_bounds(&contour); let box_width = (max_x - min_x) as u32; let box_height = (max_y - min_y) as u32; if box_width * box_height < min_area { continue; } // Expand bounding box let expand_w = (box_width as f32 * expand_ratio * 0.5) as i32; let expand_h = (box_height as f32 * expand_ratio * 0.5) as i32; let final_x = (min_x - expand_w).max(0) as u32; let final_y = (min_y - expand_h).max(0) as u32; let final_w = ((max_x + expand_w) as u32) .min(width) .saturating_sub(final_x); let final_h = ((max_y + expand_h) as u32) .min(height) .saturating_sub(final_y); if final_w > 0 && final_h > 0 { let rect = Rect::at(final_x as i32, final_y as i32).of_size(final_w, final_h); boxes.push(TextBox::new(rect, 1.0)); } } // 5. Merge adjacent boxes to form text lines merge_into_text_lines(&boxes, 10) } /// OTSU adaptive threshold calculation fn otsu_threshold(image: &GrayImage) -> u8 { // Calculate histogram let mut histogram = [0u32; 256]; for pixel in image.pixels() { histogram[pixel.0[0] as usize] += 1; } let total = image.pixels().count() as f64; let mut sum = 0.0; for (i, &count) in histogram.iter().enumerate() { sum += i as f64 * count as f64; } let mut sum_b = 0.0; let mut w_b = 0.0; let mut max_variance = 0.0; let mut threshold = 0u8; for (t, &count) in histogram.iter().enumerate() { w_b += count as f64; if w_b == 0.0 { continue; } let w_f = total - w_b; if w_f == 0.0 { break; } sum_b += t as f64 * count as f64; let m_b = sum_b / w_b; let m_f = (sum - sum_b) / w_f; let variance = w_b * w_f * (m_b - m_f).powi(2); if variance > max_variance { max_variance = variance; threshold = t as u8; } } threshold } /// Merge independent character boxes into text lines fn merge_into_text_lines(boxes: &[TextBox], gap_threshold: i32) -> Vec<TextBox> { if boxes.is_empty() { return Vec::new(); } // Group by y coordinate let mut sorted_boxes: Vec<_> = boxes.iter().collect(); sorted_boxes.sort_by_key(|b| b.rect.top()); let mut lines: Vec<TextBox> = Vec::new(); for bbox in sorted_boxes { let mut merged = false; // Try to merge into existing lines for line in &mut lines { let line_center_y = line.rect.top() + line.rect.height() as i32 / 2; let box_center_y = bbox.rect.top() + bbox.rect.height() as i32 / 2; // If vertical overlap and horizontal proximity if (line_center_y - box_center_y).abs() < line.rect.height() as i32 / 2 { let line_right = line.rect.left() + line.rect.width() as i32; let box_left = bbox.rect.left(); if (box_left - line_right).abs() < gap_threshold * 3 { // Merge let new_left = line.rect.left().min(bbox.rect.left()); let new_top = line.rect.top().min(bbox.rect.top()); let new_right = (line.rect.left() + line.rect.width() as i32) .max(bbox.rect.left() + bbox.rect.width() as i32); let new_bottom = (line.rect.top() + line.rect.height() as i32) .max(bbox.rect.top() + bbox.rect.height() as i32); line.rect = Rect::at(new_left, new_top) .of_size((new_right - new_left) as u32, (new_bottom - new_top) as u32); merged = true; break; } } } if !merged { lines.push(bbox.clone()); } } lines } #[cfg(test)] mod tests { use super::*; #[test] fn test_textbox_new() { let rect = Rect::at(10, 20).of_size(100, 50); let tb = TextBox::new(rect, 0.95); assert_eq!(tb.rect.left(), 10); assert_eq!(tb.rect.top(), 20); assert_eq!(tb.rect.width(), 100); assert_eq!(tb.rect.height(), 50); assert_eq!(tb.score, 0.95); assert!(tb.points.is_none()); } #[test] fn test_textbox_with_points() { let rect = Rect::at(0, 0).of_size(100, 50); let points = [ Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 50.0), Point::new(0.0, 50.0), ]; let tb = TextBox::with_points(rect, 0.9, points); assert!(tb.points.is_some()); let pts = tb.points.unwrap(); assert_eq!(pts[0].x, 0.0); assert_eq!(pts[1].x, 100.0); } #[test] fn test_textbox_area() { let tb = TextBox::new(Rect::at(0, 0).of_size(100, 50), 0.9); assert_eq!(tb.area(), 5000); } #[test] fn test_textbox_expand() { let tb = TextBox::new(Rect::at(50, 50).of_size(100, 100), 0.9); let expanded = tb.expand(10, 500, 500); assert_eq!(expanded.rect.left(), 40); assert_eq!(expanded.rect.top(), 40); assert_eq!(expanded.rect.width(), 120); assert_eq!(expanded.rect.height(), 120); } #[test] fn test_textbox_expand_clamp() { // 测试边界裁剪 let tb = TextBox::new(Rect::at(5, 5).of_size(100, 100), 0.9); let expanded = tb.expand(10, 200, 200); // 左上角应该被限制在 (0, 0) assert_eq!(expanded.rect.left(), 0); assert_eq!(expanded.rect.top(), 0); } #[test] fn test_compute_iou() { let a = Rect::at(0, 0).of_size(10, 10); let b = Rect::at(5, 5).of_size(10, 10); let iou = compute_iou(&a, &b); assert!(iou > 0.0 && iou < 1.0); // 不相交 let c = Rect::at(100, 100).of_size(10, 10); assert_eq!(compute_iou(&a, &c), 0.0); // 完全重叠 assert_eq!(compute_iou(&a, &a), 1.0); } #[test] fn test_compute_iou_partial_overlap() { // 50% 重叠的情况 let a = Rect::at(0, 0).of_size(10, 10); let b = Rect::at(5, 0).of_size(10, 10); let iou = compute_iou(&a, &b); // 交集面积 = 5 * 10 = 50 // 并集面积 = 100 + 100 - 50 = 150 // IoU = 50 / 150 ≈ 0.333 assert!((iou - 0.333).abs() < 0.01); } #[test] fn test_nms() { // 第一个和第二个框有很大重叠,第三个框独立 let boxes = vec![ TextBox::new(Rect::at(0, 0).of_size(10, 10), 0.9), TextBox::new(Rect::at(1, 1).of_size(10, 10), 0.8), // 与第一个框高度重叠 TextBox::new(Rect::at(100, 100).of_size(10, 10), 0.7), ]; let result = nms(&boxes, 0.3); // 使用较低的阈值确保重叠框被过滤 // 第一个框(最高分数)和第三个框(无重叠)应该保留 assert!( result.len() >= 2, "至少应该保留2个框,实际: {}", result.len() ); } #[test] fn test_nms_empty() { let boxes: Vec<TextBox> = vec![]; let result = nms(&boxes, 0.5); assert!(result.is_empty()); } #[test] fn test_nms_single() { let boxes = vec![TextBox::new(Rect::at(0, 0).of_size(10, 10), 0.9)]; let result = nms(&boxes, 0.5); assert_eq!(result.len(), 1); } #[test] fn test_nms_no_overlap() { let boxes = vec![ TextBox::new(Rect::at(0, 0).of_size(10, 10), 0.9), TextBox::new(Rect::at(50, 50).of_size(10, 10), 0.8), TextBox::new(Rect::at(100, 100).of_size(10, 10), 0.7), ]; let result = nms(&boxes, 0.5); assert_eq!(result.len(), 3); // 所有框都保留 } #[test] fn test_merge_adjacent() { let boxes = vec![ TextBox::new(Rect::at(0, 0).of_size(10, 10), 1.0), TextBox::new(Rect::at(12, 0).of_size(10, 10), 1.0), // 水平距离 2 TextBox::new(Rect::at(100, 100).of_size(10, 10), 1.0), ]; let result = merge_adjacent_boxes(&boxes, 5); assert_eq!(result.len(), 2); // 前两个应该合并 } #[test] fn test_merge_adjacent_empty() { let boxes: Vec<TextBox> = vec![]; let result = merge_adjacent_boxes(&boxes, 5); assert!(result.is_empty()); } #[test] fn test_sort_boxes_by_reading_order() { let mut boxes = vec![ TextBox::new(Rect::at(100, 0).of_size(10, 10), 0.9), // 第一行右边 TextBox::new(Rect::at(0, 0).of_size(10, 10), 0.9), // 第一行左边 TextBox::new(Rect::at(0, 50).of_size(10, 10), 0.9), // 第二行 ]; sort_boxes_by_reading_order(&mut boxes); // 应该先按行排序,然后行内按x坐标排序 assert_eq!(boxes[0].rect.left(), 0); assert_eq!(boxes[0].rect.top(), 0); } #[test] fn test_group_boxes_by_line() { let boxes = vec![ TextBox::new(Rect::at(0, 0).of_size(50, 20), 0.9), TextBox::new(Rect::at(60, 0).of_size(50, 20), 0.9), TextBox::new(Rect::at(0, 50).of_size(50, 20), 0.9), ]; let lines = group_boxes_by_line(&boxes, 10); // 应该分成两行 assert_eq!(lines.len(), 2); } }
rust
Apache-2.0
2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e
2026-01-04T20:19:51.104139Z
false
zibo-chen/rust-paddle-ocr
https://github.com/zibo-chen/rust-paddle-ocr/blob/2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e/src/engine.rs
src/engine.rs
//! OCR Engine //! //! Provides complete OCR pipeline encapsulation, performs detection and recognition in one call use image::DynamicImage; use std::path::Path; use crate::det::{DetModel, DetOptions}; use crate::error::OcrResult; use crate::mnn::{Backend, InferenceConfig, PrecisionMode}; use crate::postprocess::TextBox; use crate::rec::{RecModel, RecOptions, RecognitionResult}; /// OCR result #[derive(Debug, Clone)] pub struct OcrResult_ { /// Recognized text pub text: String, /// Confidence score pub confidence: f32, /// Bounding box pub bbox: TextBox, } impl OcrResult_ { /// Create a new OCR result pub fn new(text: String, confidence: f32, bbox: TextBox) -> Self { Self { text, confidence, bbox, } } } /// OCR engine configuration #[derive(Debug, Clone)] pub struct OcrEngineConfig { /// Inference backend pub backend: Backend, /// Thread count pub thread_count: i32, /// Precision mode pub precision_mode: PrecisionMode, /// Detection options pub det_options: DetOptions, /// Recognition options pub rec_options: RecOptions, /// Whether to enable parallel recognition (use rayon to process multiple text regions in parallel) pub enable_parallel: bool, /// Minimum confidence threshold at result level (recognition results below this value will be filtered) pub min_result_confidence: f32, } impl Default for OcrEngineConfig { fn default() -> Self { Self { backend: Backend::CPU, thread_count: 4, precision_mode: PrecisionMode::Normal, det_options: DetOptions::default(), rec_options: RecOptions::default(), enable_parallel: true, min_result_confidence: 0.5, } } } impl OcrEngineConfig { /// Create new configuration pub fn new() -> Self { Self::default() } /// Set inference backend pub fn with_backend(mut self, backend: Backend) -> Self { self.backend = backend; self } /// Set thread count pub fn with_threads(mut self, threads: i32) -> Self { self.thread_count = threads; self } /// Set precision mode pub fn with_precision(mut self, precision: PrecisionMode) -> Self { self.precision_mode = precision; self } /// Set detection options pub fn with_det_options(mut self, options: DetOptions) -> Self { self.det_options = options; self } /// Set recognition options pub fn with_rec_options(mut self, options: RecOptions) -> Self { self.rec_options = options; self } /// Enable/disable parallel processing /// /// Note: When multiple text regions are detected, use rayon for parallel recognition. /// If MNN is already set to multi-threading, enabling this option may cause thread contention. pub fn with_parallel(mut self, enable: bool) -> Self { self.enable_parallel = enable; self } /// Set minimum confidence threshold at result level /// /// Recognition results below this threshold will be filtered out. /// Recommended values: 0.5 (lenient), 0.7 (balanced), 0.9 (strict) pub fn with_min_result_confidence(mut self, threshold: f32) -> Self { self.min_result_confidence = threshold; self } /// Fast mode preset pub fn fast() -> Self { Self { precision_mode: PrecisionMode::Low, det_options: DetOptions::fast(), ..Default::default() } } /// GPU mode preset (Metal) #[cfg(any(target_os = "macos", target_os = "ios"))] pub fn gpu() -> Self { Self { backend: Backend::Metal, ..Default::default() } } /// GPU mode preset (OpenCL) #[cfg(not(any(target_os = "macos", target_os = "ios")))] pub fn gpu() -> Self { Self { backend: Backend::OpenCL, ..Default::default() } } fn to_inference_config(&self) -> InferenceConfig { InferenceConfig { thread_count: self.thread_count, precision_mode: self.precision_mode, backend: self.backend, ..Default::default() } } } /// OCR engine /// /// Encapsulates complete OCR pipeline, including text detection and recognition /// /// # Example /// /// ```ignore /// use ocr_rs::{OcrEngine, OcrEngineConfig}; /// /// // Create engine /// let engine = OcrEngine::new( /// "det_model.mnn", /// "rec_model.mnn", /// "ppocr_keys.txt", /// None, /// )?; /// /// // Recognize image /// let image = image::open("test.jpg")?; /// let results = engine.recognize(&image)?; /// /// for result in results { /// println!("{}: {:.2}", result.text, result.confidence); /// } /// ``` pub struct OcrEngine { det_model: DetModel, rec_model: RecModel, config: OcrEngineConfig, } impl OcrEngine { /// Create OCR engine from model files /// /// # Parameters /// - `det_model_path`: Detection model file path /// - `rec_model_path`: Recognition model file path /// - `charset_path`: Charset file path /// - `config`: Optional engine configuration pub fn new( det_model_path: impl AsRef<Path>, rec_model_path: impl AsRef<Path>, charset_path: impl AsRef<Path>, config: Option<OcrEngineConfig>, ) -> OcrResult<Self> { let config = config.unwrap_or_default(); let inference_config = config.to_inference_config(); // Optimization: Directly move the configuration to avoid multiple clones let det_options = config.det_options.clone(); let rec_options = config.rec_options.clone(); let det_model = DetModel::from_file(det_model_path, Some(inference_config.clone()))? .with_options(det_options); let rec_model = RecModel::from_file(rec_model_path, charset_path, Some(inference_config))? .with_options(rec_options); Ok(Self { det_model, rec_model, config, }) } /// Create OCR engine from model bytes pub fn from_bytes( det_model_bytes: &[u8], rec_model_bytes: &[u8], charset_bytes: &[u8], config: Option<OcrEngineConfig>, ) -> OcrResult<Self> { let config = config.unwrap_or_default(); let inference_config = config.to_inference_config(); // Optimization: Directly move the configuration to avoid multiple clones let det_options = config.det_options.clone(); let rec_options = config.rec_options.clone(); let det_model = DetModel::from_bytes(det_model_bytes, Some(inference_config.clone()))? .with_options(det_options); let rec_model = RecModel::from_bytes_with_charset( rec_model_bytes, charset_bytes, Some(inference_config), )? .with_options(rec_options); Ok(Self { det_model, rec_model, config, }) } /// Create detection-only engine pub fn det_only( det_model_path: impl AsRef<Path>, config: Option<OcrEngineConfig>, ) -> OcrResult<DetOnlyEngine> { let config = config.unwrap_or_default(); let inference_config = config.to_inference_config(); let det_model = DetModel::from_file(det_model_path, Some(inference_config))? .with_options(config.det_options); Ok(DetOnlyEngine { det_model }) } /// Create recognition-only engine pub fn rec_only( rec_model_path: impl AsRef<Path>, charset_path: impl AsRef<Path>, config: Option<OcrEngineConfig>, ) -> OcrResult<RecOnlyEngine> { let config = config.unwrap_or_default(); let inference_config = config.to_inference_config(); let rec_model = RecModel::from_file(rec_model_path, charset_path, Some(inference_config))? .with_options(config.rec_options); Ok(RecOnlyEngine { rec_model }) } /// Perform complete OCR recognition /// /// # Parameters /// - `image`: Input image /// /// # Returns /// List of OCR results, each result contains text, confidence and bounding box pub fn recognize(&self, image: &DynamicImage) -> OcrResult<Vec<OcrResult_>> { // 1. Detect text regions let detections = self.det_model.detect_and_crop(image)?; if detections.is_empty() { return Ok(Vec::new()); } // 2. Batch recognition (avoid cloning) let (images, boxes): (Vec<&DynamicImage>, Vec<TextBox>) = detections .iter() .map(|(img, bbox)| (img, bbox.clone())) .unzip(); let rec_results = if self.config.enable_parallel && images.len() > 4 { // Parallel recognition: for multiple text regions, use rayon for parallel processing use rayon::prelude::*; images .par_iter() .map(|img| self.rec_model.recognize(img)) .collect::<OcrResult<Vec<_>>>()? } else { // Sequential recognition: use batch inference self.rec_model.recognize_batch_ref(&images)? }; // 3. Combine results and filter low confidence let results: Vec<OcrResult_> = rec_results .into_iter() .zip(boxes) .filter(|(rec, _)| { !rec.text.is_empty() && rec.confidence >= self.config.min_result_confidence }) .map(|(rec, bbox)| OcrResult_::new(rec.text, rec.confidence, bbox)) .collect(); Ok(results) } /// Perform detection only pub fn detect(&self, image: &DynamicImage) -> OcrResult<Vec<TextBox>> { self.det_model.detect(image) } /// Perform recognition only (requires pre-cropped text line images) pub fn recognize_text(&self, image: &DynamicImage) -> OcrResult<RecognitionResult> { self.rec_model.recognize(image) } /// Batch recognize text line images pub fn recognize_batch(&self, images: &[DynamicImage]) -> OcrResult<Vec<RecognitionResult>> { self.rec_model.recognize_batch(images) } /// Get detection model reference pub fn det_model(&self) -> &DetModel { &self.det_model } /// Get recognition model reference pub fn rec_model(&self) -> &RecModel { &self.rec_model } /// Get configuration pub fn config(&self) -> &OcrEngineConfig { &self.config } } /// Detection-only engine pub struct DetOnlyEngine { det_model: DetModel, } impl DetOnlyEngine { /// Detect text regions in image pub fn detect(&self, image: &DynamicImage) -> OcrResult<Vec<TextBox>> { self.det_model.detect(image) } /// Detect and return cropped images pub fn detect_and_crop(&self, image: &DynamicImage) -> OcrResult<Vec<(DynamicImage, TextBox)>> { self.det_model.detect_and_crop(image) } /// Get detection model reference pub fn model(&self) -> &DetModel { &self.det_model } } /// Recognition-only engine pub struct RecOnlyEngine { rec_model: RecModel, } impl RecOnlyEngine { /// Recognize a single image pub fn recognize(&self, image: &DynamicImage) -> OcrResult<RecognitionResult> { self.rec_model.recognize(image) } /// Return text only pub fn recognize_text(&self, image: &DynamicImage) -> OcrResult<String> { self.rec_model.recognize_text(image) } /// Batch recognition pub fn recognize_batch(&self, images: &[DynamicImage]) -> OcrResult<Vec<RecognitionResult>> { self.rec_model.recognize_batch(images) } /// Get recognition model reference pub fn model(&self) -> &RecModel { &self.rec_model } } /// Convenience function: recognize from file /// /// # Example /// /// ```ignore /// let results = ocr_rs::ocr_file( /// "test.jpg", /// "det_model.mnn", /// "rec_model.mnn", /// "ppocr_keys.txt", /// )?; /// ``` pub fn ocr_file( image_path: impl AsRef<Path>, det_model_path: impl AsRef<Path>, rec_model_path: impl AsRef<Path>, charset_path: impl AsRef<Path>, ) -> OcrResult<Vec<OcrResult_>> { let image = image::open(image_path)?; let engine = OcrEngine::new(det_model_path, rec_model_path, charset_path, None)?; engine.recognize(&image) } #[cfg(test)] mod tests { use super::*; #[test] fn test_engine_config() { let config = OcrEngineConfig::default(); assert_eq!(config.thread_count, 4); assert_eq!(config.backend, Backend::CPU); let config = OcrEngineConfig::fast(); assert_eq!(config.precision_mode, PrecisionMode::Low); } #[test] fn test_ocr_result() { let bbox = TextBox::new(imageproc::rect::Rect::at(0, 0).of_size(100, 20), 0.9); let result = OcrResult_::new("Hello".to_string(), 0.95, bbox); assert_eq!(result.text, "Hello"); assert_eq!(result.confidence, 0.95); } }
rust
Apache-2.0
2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e
2026-01-04T20:19:51.104139Z
false
zibo-chen/rust-paddle-ocr
https://github.com/zibo-chen/rust-paddle-ocr/blob/2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e/src/lib.rs
src/lib.rs
//! # Rust PaddleOCR //! //! A high-performance OCR library based on PaddleOCR models, using the MNN inference framework. //! //! ## Version 2.0 New Features //! //! - **New API Design**: Complete layered API from low-level models to high-level pipeline //! - **Flexible Model Loading**: Support loading models from file paths or memory bytes //! - **Configurable Detection Parameters**: Support custom detection thresholds, resolution, etc. //! - **GPU Acceleration**: Support multiple GPU backends including Metal, OpenCL, Vulkan //! - **Batch Processing**: Support batch text recognition for improved throughput //! //! ## Quick Start //! //! ### Simple Usage - Using High-Level API (Recommended) //! //! ```ignore //! use ocr_rs::{OcrEngine, OcrEngineConfig}; //! //! fn main() -> Result<(), Box<dyn std::error::Error>> { //! // Create OCR engine //! let engine = OcrEngine::new( //! "models/det_model.mnn", //! "models/rec_model.mnn", //! "models/ppocr_keys.txt", //! None, // Use default config //! )?; //! //! // Open and recognize image //! let image = image::open("test.jpg")?; //! let results = engine.recognize(&image)?; //! //! for result in results { //! println!("Text: {}, Confidence: {:.2}%", result.text, result.confidence * 100.0); //! println!("Position: ({}, {})", result.bbox.rect.left(), result.bbox.rect.top()); //! } //! //! Ok(()) //! } //! ``` //! //! ### Advanced Usage - Using Low-Level API //! //! ```ignore //! use ocr_rs::{DetModel, RecModel, DetOptions, DetPrecisionMode}; //! //! fn main() -> Result<(), Box<dyn std::error::Error>> { //! // Create detection model //! let det = DetModel::from_file("models/det_model.mnn", None)? //! .with_options(DetOptions::fast()); //! //! // Create recognition model //! let rec = RecModel::from_file("models/rec_model.mnn", "models/ppocr_keys.txt", None)?; //! //! // Load image //! let image = image::open("test.jpg")?; //! //! // Detect and crop text regions //! let detections = det.detect_and_crop(&image)?; //! //! // Recognize each text region //! for (cropped_img, bbox) in detections { //! let result = rec.recognize(&cropped_img)?; //! println!("Position: ({}, {}), Text: {}", //! bbox.rect.left(), bbox.rect.top(), result.text); //! } //! //! Ok(()) //! } //! ``` //! //! ### GPU Acceleration //! //! ```ignore //! use ocr_rs::{OcrEngine, OcrEngineConfig, Backend}; //! //! let config = OcrEngineConfig::new() //! .with_backend(Backend::Metal); // macOS/iOS //! // .with_backend(Backend::OpenCL); // Cross-platform //! //! let engine = OcrEngine::new(det_path, rec_path, charset_path, Some(config))?; //! ``` //! //! ## Module Structure //! //! - [`mnn`]: MNN inference engine wrapper, provides low-level inference capabilities //! - [`det`]: Text detection module ([`DetModel`]), detects text regions in images //! - [`rec`]: Text recognition module ([`RecModel`]), recognizes text content //! - [`engine`]: High-level OCR pipeline ([`OcrEngine`]), all-in-one OCR solution //! - [`preprocess`]: Image preprocessing utilities, including normalization, scaling, etc. //! - [`postprocess`]: Post-processing utilities, including NMS, box merging, sorting, etc. //! - [`error`]: Error types [`OcrError`] //! //! ## API Hierarchy //! //! ```text //! ┌─────────────────────────────────────────┐ //! │ OcrEngine (High-Level API) │ //! │ Complete detection and recognition │ //! ├─────────────────────────────────────────┤ //! │ DetModel │ RecModel │ //! │ Detection Model │ Recognition Model │ //! ├─────────────────────────────────────────┤ //! │ InferenceEngine (MNN) │ //! │ Low-level inference engine │ //! └─────────────────────────────────────────┘ //! ``` //! //! ## Supported Models //! //! - **PP-OCRv4**: Stable version, good compatibility //! - **PP-OCRv5**: Recommended version, supports multiple languages, higher accuracy //! - **PP-OCRv5 FP16**: Efficient version, faster inference, lower memory usage // Core modules pub mod det; pub mod engine; pub mod error; pub mod mnn; pub mod postprocess; pub mod preprocess; pub mod rec; // Re-export commonly used types pub use det::{DetModel, DetOptions, DetPrecisionMode}; pub use engine::{ocr_file, DetOnlyEngine, OcrEngine, OcrEngineConfig, OcrResult_, RecOnlyEngine}; pub use error::{OcrError, OcrResult}; pub use mnn::{Backend, InferenceConfig, InferenceEngine, PrecisionMode}; pub use postprocess::TextBox; pub use rec::{RecModel, RecOptions, RecognitionResult}; /// Get library version pub fn version() -> &'static str { env!("CARGO_PKG_VERSION") } /// Get MNN version pub fn mnn_version() -> String { mnn::get_version() } #[cfg(test)] mod tests { use super::*; #[test] fn test_version() { let v = version(); assert!(!v.is_empty()); } }
rust
Apache-2.0
2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e
2026-01-04T20:19:51.104139Z
false
zibo-chen/rust-paddle-ocr
https://github.com/zibo-chen/rust-paddle-ocr/blob/2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e/src/error.rs
src/error.rs
//! OCR error type definitions use thiserror::Error; use crate::mnn::MnnError; /// OCR error type #[derive(Error, Debug)] pub enum OcrError { /// MNN inference engine error #[error("MNN inference error: {0}")] MnnError(#[from] MnnError), /// Image processing error #[error("Image processing error: {0}")] ImageError(#[from] image::ImageError), /// IO error #[error("IO error: {0}")] IoError(#[from] std::io::Error), /// Invalid parameter error #[error("Invalid parameter: {0}")] InvalidParameter(String), /// Model loading error #[error("Model loading failed: {0}")] ModelLoadError(String), /// Preprocessing error #[error("Preprocessing error: {0}")] PreprocessError(String), /// Postprocessing error #[error("Postprocessing error: {0}")] PostprocessError(String), /// Detection error #[error("Detection error: {0}")] DetectionError(String), /// Recognition error #[error("Recognition error: {0}")] RecognitionError(String), /// Not initialized error #[error("Not initialized: {0}")] NotInitialized(String), /// Charset parsing error #[error("Charset parsing error: {0}")] CharsetError(String), } /// OCR result type alias pub type OcrResult<T> = std::result::Result<T, OcrError>;
rust
Apache-2.0
2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e
2026-01-04T20:19:51.104139Z
false
zibo-chen/rust-paddle-ocr
https://github.com/zibo-chen/rust-paddle-ocr/blob/2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e/src/det.rs
src/det.rs
//! Text Detection Model //! //! Provides text region detection functionality based on PaddleOCR detection models use image::{DynamicImage, GenericImageView}; use ndarray::ArrayD; use std::path::Path; use crate::error::{OcrError, OcrResult}; use crate::mnn::{InferenceConfig, InferenceEngine}; use crate::postprocess::{extract_boxes_with_unclip, TextBox}; use crate::preprocess::{preprocess_for_det, NormalizeParams}; /// Detection precision mode #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum DetPrecisionMode { /// Fast mode - single detection #[default] Fast, } /// Detection options #[derive(Debug, Clone)] pub struct DetOptions { /// Maximum image side length limit (will be scaled if exceeded) pub max_side_len: u32, /// Bounding box binarization threshold (0.0 - 1.0) pub box_threshold: f32, /// Text box expansion ratio pub unclip_ratio: f32, /// Pixel-level segmentation threshold pub score_threshold: f32, /// Minimum bounding box area pub min_area: u32, /// Bounding box border expansion pub box_border: u32, /// Whether to merge adjacent text boxes pub merge_boxes: bool, /// Merge distance threshold pub merge_threshold: i32, /// Precision mode pub precision_mode: DetPrecisionMode, /// Scale ratios for multi-scale detection (high precision mode only) pub multi_scales: Vec<f32>, /// Block size for block detection (high precision mode only) pub block_size: u32, /// Overlap area for block detection pub block_overlap: u32, /// NMS IoU threshold pub nms_threshold: f32, } impl Default for DetOptions { fn default() -> Self { Self { max_side_len: 960, box_threshold: 0.5, unclip_ratio: 1.5, score_threshold: 0.3, min_area: 16, box_border: 5, merge_boxes: false, merge_threshold: 10, precision_mode: DetPrecisionMode::Fast, multi_scales: vec![0.5, 1.0, 1.5], block_size: 640, block_overlap: 100, nms_threshold: 0.3, } } } impl DetOptions { /// Create new detection options pub fn new() -> Self { Self::default() } /// Set maximum side length pub fn with_max_side_len(mut self, len: u32) -> Self { self.max_side_len = len; self } /// Set bounding box threshold pub fn with_box_threshold(mut self, threshold: f32) -> Self { self.box_threshold = threshold; self } /// Set segmentation threshold pub fn with_score_threshold(mut self, threshold: f32) -> Self { self.score_threshold = threshold; self } /// Set minimum area pub fn with_min_area(mut self, area: u32) -> Self { self.min_area = area; self } /// Set box border expansion pub fn with_box_border(mut self, border: u32) -> Self { self.box_border = border; self } /// Enable box merging pub fn with_merge_boxes(mut self, merge: bool) -> Self { self.merge_boxes = merge; self } /// Set merge threshold pub fn with_merge_threshold(mut self, threshold: i32) -> Self { self.merge_threshold = threshold; self } /// Set precision mode pub fn with_precision_mode(mut self, mode: DetPrecisionMode) -> Self { self.precision_mode = mode; self } /// Set multi-scale ratios pub fn with_multi_scales(mut self, scales: Vec<f32>) -> Self { self.multi_scales = scales; self } /// Set block size pub fn with_block_size(mut self, size: u32) -> Self { self.block_size = size; self } /// Fast mode preset pub fn fast() -> Self { Self { max_side_len: 960, precision_mode: DetPrecisionMode::Fast, ..Default::default() } } } /// Text detection model pub struct DetModel { engine: InferenceEngine, options: DetOptions, normalize_params: NormalizeParams, } impl DetModel { /// Create detector from model file /// /// # Parameters /// - `model_path`: Model file path (.mnn format) /// - `config`: Optional inference config pub fn from_file( model_path: impl AsRef<Path>, config: Option<InferenceConfig>, ) -> OcrResult<Self> { let engine = InferenceEngine::from_file(model_path, config)?; Ok(Self { engine, options: DetOptions::default(), normalize_params: NormalizeParams::paddle_det(), }) } /// Create detector from model bytes pub fn from_bytes(model_bytes: &[u8], config: Option<InferenceConfig>) -> OcrResult<Self> { let engine = InferenceEngine::from_buffer(model_bytes, config)?; Ok(Self { engine, options: DetOptions::default(), normalize_params: NormalizeParams::paddle_det(), }) } /// Set detection options pub fn with_options(mut self, options: DetOptions) -> Self { self.options = options; self } /// Get current detection options pub fn options(&self) -> &DetOptions { &self.options } /// Modify detection options pub fn options_mut(&mut self) -> &mut DetOptions { &mut self.options } /// Detect text regions in image /// /// # Parameters /// - `image`: Input image /// /// # Returns /// List of detected text bounding boxes pub fn detect(&self, image: &DynamicImage) -> OcrResult<Vec<TextBox>> { self.detect_fast(image) } /// Detect and return cropped text images /// /// # Parameters /// - `image`: Input image /// /// # Returns /// List of (text image, corresponding bounding box) pub fn detect_and_crop(&self, image: &DynamicImage) -> OcrResult<Vec<(DynamicImage, TextBox)>> { let boxes = self.detect(image)?; let (width, height) = image.dimensions(); let mut results = Vec::with_capacity(boxes.len()); for text_box in boxes { // Expand bounding box let expanded = text_box.expand(self.options.box_border, width, height); // Crop image let cropped = image.crop_imm( expanded.rect.left() as u32, expanded.rect.top() as u32, expanded.rect.width(), expanded.rect.height(), ); results.push((cropped, expanded)); } Ok(results) } /// Fast detection (single inference) fn detect_fast(&self, image: &DynamicImage) -> OcrResult<Vec<TextBox>> { let (original_width, original_height) = image.dimensions(); // Scale image let scaled = self.scale_image(image); let (scaled_width, scaled_height) = scaled.dimensions(); // Preprocess let input = preprocess_for_det(&scaled, &self.normalize_params); // Inference (using dynamic shape) let output = self.engine.run_dynamic(input.view().into_dyn())?; // Post-processing - output shape matches input (including padding) let output_shape = output.shape(); let out_w = output_shape[3] as u32; let out_h = output_shape[2] as u32; let boxes = self.postprocess_output( &output, out_w, out_h, scaled_width, scaled_height, original_width, original_height, )?; Ok(boxes) } /// Balanced mode detection (multi-scale) /// Scale image to maximum side length limit fn scale_image(&self, image: &DynamicImage) -> DynamicImage { let (w, h) = image.dimensions(); let max_dim = w.max(h); if max_dim <= self.options.max_side_len { return image.clone(); } let scale = self.options.max_side_len as f64 / max_dim as f64; let new_w = (w as f64 * scale).round() as u32; let new_h = (h as f64 * scale).round() as u32; image.resize_exact(new_w, new_h, image::imageops::FilterType::Lanczos3) } /// Post-process inference output fn postprocess_output( &self, output: &ArrayD<f32>, out_w: u32, out_h: u32, scaled_width: u32, scaled_height: u32, original_width: u32, original_height: u32, ) -> OcrResult<Vec<TextBox>> { // Retrieve output data let output_shape = output.shape(); if output_shape.len() < 3 { return Err(OcrError::PostprocessError( "Detection model output shape invalid".to_string(), )); } // Extract segmentation mask (only valid region, remove padding) let mask_data: Vec<f32> = output.iter().cloned().collect(); // Binarization let binary_mask: Vec<u8> = mask_data .iter() .map(|&v| { if v > self.options.score_threshold { 255u8 } else { 0u8 } }) .collect(); // Extract bounding boxes (with unclip expansion) // DB algorithm needs to expand detected contours because model output segmentation mask is usually smaller than actual text region let boxes = extract_boxes_with_unclip( &binary_mask, out_w, out_h, scaled_width, scaled_height, original_width, original_height, self.options.min_area, self.options.unclip_ratio, ); Ok(boxes) } } /// Low-level detection API impl DetModel { /// Raw inference interface /// /// Execute model inference directly without preprocessing and postprocessing /// /// # Parameters /// - `input`: Preprocessed input tensor [1, 3, H, W] /// /// # Returns /// Model raw output pub fn run_raw(&self, input: ndarray::ArrayViewD<f32>) -> OcrResult<ArrayD<f32>> { Ok(self.engine.run_dynamic(input)?) } /// Get model input shape pub fn input_shape(&self) -> &[usize] { self.engine.input_shape() } /// Get model output shape pub fn output_shape(&self) -> &[usize] { self.engine.output_shape() } } #[cfg(test)] mod tests { use super::*; #[test] fn test_det_options_default() { let opts = DetOptions::default(); assert_eq!(opts.max_side_len, 960); assert_eq!(opts.box_threshold, 0.5); assert_eq!(opts.unclip_ratio, 1.5); assert_eq!(opts.score_threshold, 0.3); assert_eq!(opts.min_area, 16); assert_eq!(opts.box_border, 5); assert!(!opts.merge_boxes); assert_eq!(opts.merge_threshold, 10); assert_eq!(opts.precision_mode, DetPrecisionMode::Fast); assert_eq!(opts.nms_threshold, 0.3); } #[test] fn test_det_options_fast() { let opts = DetOptions::fast(); assert_eq!(opts.max_side_len, 960); assert_eq!(opts.precision_mode, DetPrecisionMode::Fast); } #[test] fn test_det_options_builder() { let opts = DetOptions::new() .with_max_side_len(1280) .with_box_threshold(0.6) .with_score_threshold(0.4) .with_min_area(32) .with_box_border(10) .with_merge_boxes(true) .with_merge_threshold(20) .with_precision_mode(DetPrecisionMode::Fast) .with_multi_scales(vec![0.5, 1.0, 1.5]) .with_block_size(800); assert_eq!(opts.max_side_len, 1280); assert_eq!(opts.box_threshold, 0.6); assert_eq!(opts.score_threshold, 0.4); assert_eq!(opts.min_area, 32); assert_eq!(opts.box_border, 10); assert!(opts.merge_boxes); assert_eq!(opts.merge_threshold, 20); assert_eq!(opts.precision_mode, DetPrecisionMode::Fast); assert_eq!(opts.multi_scales, vec![0.5, 1.0, 1.5]); assert_eq!(opts.block_size, 800); } #[test] fn test_det_precision_mode_default() { let mode = DetPrecisionMode::default(); assert_eq!(mode, DetPrecisionMode::Fast); } #[test] fn test_det_precision_mode_equality() { assert_eq!(DetPrecisionMode::Fast, DetPrecisionMode::Fast); } #[test] fn test_det_options_chaining() { // Test that chaining calls do not lose previous settings let opts = DetOptions::new() .with_max_side_len(1000) .with_box_threshold(0.7); assert_eq!(opts.max_side_len, 1000); assert_eq!(opts.box_threshold, 0.7); // Other values should be default values assert_eq!(opts.score_threshold, 0.3); } #[test] fn test_det_options_presets_are_valid() { // Ensure preset parameter values are within valid ranges let fast = DetOptions::fast(); assert!(fast.box_threshold >= 0.0 && fast.box_threshold <= 1.0); assert!(fast.score_threshold >= 0.0 && fast.score_threshold <= 1.0); assert!(fast.nms_threshold >= 0.0 && fast.nms_threshold <= 1.0); } }
rust
Apache-2.0
2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e
2026-01-04T20:19:51.104139Z
false
zibo-chen/rust-paddle-ocr
https://github.com/zibo-chen/rust-paddle-ocr/blob/2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e/src/rec.rs
src/rec.rs
//! Text Recognition Model //! //! Provides text recognition functionality based on PaddleOCR recognition models use image::DynamicImage; use ndarray::ArrayD; use std::path::Path; use crate::error::{OcrError, OcrResult}; use crate::mnn::{InferenceConfig, InferenceEngine}; use crate::preprocess::{preprocess_for_rec, NormalizeParams}; /// Recognition result #[derive(Debug, Clone)] pub struct RecognitionResult { /// Recognized text pub text: String, /// Confidence score (0.0 - 1.0) pub confidence: f32, /// Confidence score for each character pub char_scores: Vec<(char, f32)>, } impl RecognitionResult { /// Create a new recognition result pub fn new(text: String, confidence: f32, char_scores: Vec<(char, f32)>) -> Self { Self { text, confidence, char_scores, } } /// Check if the result is valid (confidence above threshold) pub fn is_valid(&self, threshold: f32) -> bool { self.confidence >= threshold } } /// Recognition options #[derive(Debug, Clone)] pub struct RecOptions { /// Target height (recognition model input height) pub target_height: u32, /// Minimum confidence threshold (characters below this value will be filtered) pub min_score: f32, /// Minimum confidence threshold for punctuation pub punct_min_score: f32, /// Batch size pub batch_size: usize, /// Whether to enable batch processing pub enable_batch: bool, } impl Default for RecOptions { fn default() -> Self { Self { target_height: 48, min_score: 0.3, // Lower threshold, model output is raw logit punct_min_score: 0.1, batch_size: 8, enable_batch: true, } } } impl RecOptions { /// Create new recognition options pub fn new() -> Self { Self::default() } /// Set target height pub fn with_target_height(mut self, height: u32) -> Self { self.target_height = height; self } /// Set minimum confidence pub fn with_min_score(mut self, score: f32) -> Self { self.min_score = score; self } /// Set punctuation minimum confidence pub fn with_punct_min_score(mut self, score: f32) -> Self { self.punct_min_score = score; self } /// Set batch size pub fn with_batch_size(mut self, size: usize) -> Self { self.batch_size = size; self } /// Enable/disable batch processing pub fn with_batch(mut self, enable: bool) -> Self { self.enable_batch = enable; self } } /// Text recognition model pub struct RecModel { engine: InferenceEngine, /// Character set (index to character mapping) charset: Vec<char>, options: RecOptions, normalize_params: NormalizeParams, } /// Common punctuation marks const PUNCTUATIONS: [char; 49] = [ ',', '.', '!', '?', ';', ':', '"', '\'', '(', ')', '[', ']', '{', '}', '-', '_', '/', '\\', '|', '@', '#', '$', '%', '&', '*', '+', '=', '~', ',', '。', '!', '?', ';', ':', '、', '「', '」', '『', '』', '(', ')', '【', '】', '《', '》', '—', '…', '·', '~', ]; impl RecModel { /// Create recognizer from model file and charset file /// /// # Parameters /// - `model_path`: Model file path (.mnn format) /// - `charset_path`: Charset file path (one character per line) /// - `config`: Optional inference config pub fn from_file( model_path: impl AsRef<Path>, charset_path: impl AsRef<Path>, config: Option<InferenceConfig>, ) -> OcrResult<Self> { let engine = InferenceEngine::from_file(model_path, config)?; let charset = Self::load_charset_from_file(charset_path)?; Ok(Self { engine, charset, options: RecOptions::default(), normalize_params: NormalizeParams::paddle_rec(), }) } /// Create recognizer from model bytes and charset file pub fn from_bytes( model_bytes: &[u8], charset_path: impl AsRef<Path>, config: Option<InferenceConfig>, ) -> OcrResult<Self> { let engine = InferenceEngine::from_buffer(model_bytes, config)?; let charset = Self::load_charset_from_file(charset_path)?; Ok(Self { engine, charset, options: RecOptions::default(), normalize_params: NormalizeParams::paddle_rec(), }) } /// Create recognizer from model bytes and charset bytes pub fn from_bytes_with_charset( model_bytes: &[u8], charset_bytes: &[u8], config: Option<InferenceConfig>, ) -> OcrResult<Self> { let engine = InferenceEngine::from_buffer(model_bytes, config)?; let charset = Self::parse_charset(charset_bytes)?; Ok(Self { engine, charset, options: RecOptions::default(), normalize_params: NormalizeParams::paddle_rec(), }) } /// Load charset from file fn load_charset_from_file(path: impl AsRef<Path>) -> OcrResult<Vec<char>> { let content = std::fs::read_to_string(path)?; Self::parse_charset(content.as_bytes()) } /// Parse charset data fn parse_charset(data: &[u8]) -> OcrResult<Vec<char>> { let content = std::str::from_utf8(data) .map_err(|e| OcrError::CharsetError(format!("UTF-8 decode error: {}", e)))?; // Charset format: one character per line // Add space at beginning and end as blank and padding let mut charset: Vec<char> = vec![' ']; // blank token at start for ch in content.chars() { if ch != '\n' && ch != '\r' { charset.push(ch); } } charset.push(' '); // padding token at end if charset.len() < 3 { return Err(OcrError::CharsetError("Charset too small".to_string())); } Ok(charset) } /// Set recognition options pub fn with_options(mut self, options: RecOptions) -> Self { self.options = options; self } /// Get current recognition options pub fn options(&self) -> &RecOptions { &self.options } /// Modify recognition options pub fn options_mut(&mut self) -> &mut RecOptions { &mut self.options } /// Get charset size pub fn charset_size(&self) -> usize { self.charset.len() } /// Recognize a single image /// /// # Parameters /// - `image`: Input image (text line image) /// /// # Returns /// Recognition result pub fn recognize(&self, image: &DynamicImage) -> OcrResult<RecognitionResult> { // Preprocess let input = preprocess_for_rec(image, self.options.target_height, &self.normalize_params); // Inference (using dynamic shape) let output = self.engine.run_dynamic(input.view().into_dyn())?; // Decode self.decode_output(&output) } /// Recognize a single image, return text only pub fn recognize_text(&self, image: &DynamicImage) -> OcrResult<String> { let result = self.recognize(image)?; Ok(result.text) } /// Batch recognize images /// /// # Parameters /// - `images`: List of input images /// /// # Returns /// List of recognition results pub fn recognize_batch(&self, images: &[DynamicImage]) -> OcrResult<Vec<RecognitionResult>> { if images.is_empty() { return Ok(Vec::new()); } // For small number of images, process individually if images.len() <= 2 || !self.options.enable_batch { return images.iter().map(|img| self.recognize(img)).collect(); } // Batch processing let mut results = Vec::with_capacity(images.len()); for chunk in images.chunks(self.options.batch_size) { let batch_results = self.recognize_batch_internal(chunk)?; results.extend(batch_results); } Ok(results) } /// Batch recognize images (borrowed version, avoid cloning) /// /// # Parameters /// - `images`: List of input image references /// /// # Returns /// List of recognition results pub fn recognize_batch_ref( &self, images: &[&DynamicImage], ) -> OcrResult<Vec<RecognitionResult>> { if images.is_empty() { return Ok(Vec::new()); } // For small number of images, process individually if images.len() <= 2 || !self.options.enable_batch { return images.iter().map(|img| self.recognize(img)).collect(); } // Batch processing let mut results = Vec::with_capacity(images.len()); for chunk in images.chunks(self.options.batch_size) { // Dereference and convert to Vec<DynamicImage> let chunk_owned: Vec<DynamicImage> = chunk.iter().map(|img| (*img).clone()).collect(); let batch_results = self.recognize_batch_internal(&chunk_owned)?; results.extend(batch_results); } Ok(results) } /// Internal batch recognition fn recognize_batch_internal( &self, images: &[DynamicImage], ) -> OcrResult<Vec<RecognitionResult>> { if images.is_empty() { return Ok(Vec::new()); } // If only one image, process individually if images.len() == 1 { return Ok(vec![self.recognize(&images[0])?]); } // Batch preprocessing let batch_input = crate::preprocess::preprocess_batch_for_rec( images, self.options.target_height, &self.normalize_params, ); // Batch inference let batch_output = self.engine.run_dynamic(batch_input.view().into_dyn())?; // Decode output for each sample let shape = batch_output.shape(); if shape.len() != 3 { return Err(OcrError::PostprocessError(format!( "Batch inference output shape error: {:?}", shape ))); } let batch_size = shape[0]; let mut results = Vec::with_capacity(batch_size); for i in 0..batch_size { // Extract output for single sample let sample_output = batch_output.slice(ndarray::s![i, .., ..]).to_owned(); let sample_output_dyn = sample_output.into_dyn(); let result = self.decode_output(&sample_output_dyn)?; results.push(result); } Ok(results) } /// Decode model output fn decode_output(&self, output: &ArrayD<f32>) -> OcrResult<RecognitionResult> { let shape = output.shape(); // Output shape should be [batch, seq_len, num_classes] or [seq_len, num_classes] let (seq_len, num_classes) = if shape.len() == 3 { (shape[1], shape[2]) } else if shape.len() == 2 { (shape[0], shape[1]) } else { return Err(OcrError::PostprocessError(format!( "Invalid output shape: {:?}", shape ))); }; let output_data: Vec<f32> = output.iter().cloned().collect(); // CTC decoding let mut char_scores = Vec::new(); let mut prev_idx = 0usize; for t in 0..seq_len { // Find character with maximum probability at current time step let start = t * num_classes; let end = start + num_classes; let probs = &output_data[start..end]; let (max_idx, &max_prob) = probs .iter() .enumerate() .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap()) .unwrap(); // CTC decoding rule: skip blank (index 0) and duplicate characters if max_idx != 0 && max_idx != prev_idx { if max_idx < self.charset.len() { let ch = self.charset[max_idx]; // Use raw logit value as confidence (model output is already softmax probability) // For large character sets, softmax scores can be very small, so use max_prob directly let score = max_prob; // Only filter out very low confidence characters let threshold = if Self::is_punctuation(ch) { self.options.punct_min_score } else { self.options.min_score }; if score >= threshold { char_scores.push((ch, score)); } } } prev_idx = max_idx; } // Calculate average confidence let confidence = if char_scores.is_empty() { 0.0 } else { char_scores.iter().map(|(_, s)| s).sum::<f32>() / char_scores.len() as f32 }; // Extract text let text: String = char_scores.iter().map(|(ch, _)| ch).collect(); Ok(RecognitionResult::new(text, confidence, char_scores)) } /// Check if character is punctuation fn is_punctuation(ch: char) -> bool { PUNCTUATIONS.contains(&ch) } } /// Low-level recognition API impl RecModel { /// Raw inference interface /// /// Execute model inference directly without preprocessing and postprocessing /// /// # Parameters /// - `input`: Preprocessed input tensor [1, 3, H, W] /// /// # Returns /// Model raw output pub fn run_raw(&self, input: ndarray::ArrayViewD<f32>) -> OcrResult<ArrayD<f32>> { Ok(self.engine.run_dynamic(input)?) } /// Get model input shape pub fn input_shape(&self) -> &[usize] { self.engine.input_shape() } /// Get model output shape pub fn output_shape(&self) -> &[usize] { self.engine.output_shape() } /// Get charset pub fn charset(&self) -> &[char] { &self.charset } /// Get character by index pub fn get_char(&self, index: usize) -> Option<char> { self.charset.get(index).copied() } } #[cfg(test)] mod tests { use super::*; #[test] fn test_rec_options_default() { let opts = RecOptions::default(); assert_eq!(opts.target_height, 48); assert_eq!(opts.min_score, 0.3); assert_eq!(opts.punct_min_score, 0.1); assert_eq!(opts.batch_size, 8); assert!(opts.enable_batch); } #[test] fn test_rec_options_builder() { let opts = RecOptions::new() .with_target_height(32) .with_min_score(0.6) .with_punct_min_score(0.2) .with_batch_size(16) .with_batch(false); assert_eq!(opts.target_height, 32); assert_eq!(opts.min_score, 0.6); assert_eq!(opts.punct_min_score, 0.2); assert_eq!(opts.batch_size, 16); assert!(!opts.enable_batch); } #[test] fn test_recognition_result_new() { let char_scores = vec![ ('H', 0.99), ('e', 0.94), ('l', 0.93), ('l', 0.95), ('o', 0.94), ]; let result = RecognitionResult::new("Hello".to_string(), 0.95, char_scores.clone()); assert_eq!(result.text, "Hello"); assert_eq!(result.confidence, 0.95); assert_eq!(result.char_scores.len(), 5); assert_eq!(result.char_scores[0].0, 'H'); assert_eq!(result.char_scores[0].1, 0.99); } #[test] fn test_recognition_result_is_valid() { let result = RecognitionResult::new( "Hello".to_string(), 0.95, vec![ ('H', 0.99), ('e', 0.94), ('l', 0.93), ('l', 0.95), ('o', 0.94), ], ); assert!(result.is_valid(0.9)); assert!(result.is_valid(0.95)); assert!(!result.is_valid(0.96)); assert!(!result.is_valid(0.99)); } #[test] fn test_recognition_result_empty() { let result = RecognitionResult::new(String::new(), 0.0, vec![]); assert!(result.text.is_empty()); assert_eq!(result.confidence, 0.0); assert!(!result.is_valid(0.1)); } #[test] fn test_is_punctuation_common() { // English punctuation assert!(RecModel::is_punctuation(',')); assert!(RecModel::is_punctuation('.')); assert!(RecModel::is_punctuation('!')); assert!(RecModel::is_punctuation('?')); assert!(RecModel::is_punctuation(';')); assert!(RecModel::is_punctuation(':')); assert!(RecModel::is_punctuation('"')); assert!(RecModel::is_punctuation('\'')); } #[test] fn test_is_punctuation_chinese() { // Chinese punctuation assert!(RecModel::is_punctuation(',')); assert!(RecModel::is_punctuation('。')); assert!(RecModel::is_punctuation('!')); assert!(RecModel::is_punctuation('?')); assert!(RecModel::is_punctuation(';')); assert!(RecModel::is_punctuation(':')); assert!(RecModel::is_punctuation('、')); assert!(RecModel::is_punctuation('—')); assert!(RecModel::is_punctuation('…')); } #[test] fn test_is_punctuation_brackets() { assert!(RecModel::is_punctuation('(')); assert!(RecModel::is_punctuation(')')); assert!(RecModel::is_punctuation('[')); assert!(RecModel::is_punctuation(']')); assert!(RecModel::is_punctuation('{')); assert!(RecModel::is_punctuation('}')); assert!(RecModel::is_punctuation('「')); assert!(RecModel::is_punctuation('」')); assert!(RecModel::is_punctuation('《')); assert!(RecModel::is_punctuation('》')); } #[test] fn test_is_punctuation_false() { // Non-punctuation characters assert!(!RecModel::is_punctuation('A')); assert!(!RecModel::is_punctuation('z')); assert!(!RecModel::is_punctuation('0')); assert!(!RecModel::is_punctuation('中')); assert!(!RecModel::is_punctuation('文')); assert!(!RecModel::is_punctuation(' ')); } }
rust
Apache-2.0
2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e
2026-01-04T20:19:51.104139Z
false
zibo-chen/rust-paddle-ocr
https://github.com/zibo-chen/rust-paddle-ocr/blob/2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e/src/preprocess.rs
src/preprocess.rs
//! Image Preprocessing Utilities //! //! Provides various image preprocessing functions required for OCR use image::{DynamicImage, GenericImageView, RgbImage}; use ndarray::{Array4, ArrayBase, Dim, OwnedRepr}; /// Image normalization parameters #[derive(Debug, Clone)] pub struct NormalizeParams { /// RGB channel means pub mean: [f32; 3], /// RGB channel standard deviations pub std: [f32; 3], } impl Default for NormalizeParams { fn default() -> Self { // ImageNet normalization parameters Self { mean: [0.485, 0.456, 0.406], std: [0.229, 0.224, 0.225], } } } impl NormalizeParams { /// Normalization parameters for PaddleOCR detection model pub fn paddle_det() -> Self { Self { mean: [0.485, 0.456, 0.406], std: [0.229, 0.224, 0.225], } } /// Normalization parameters for PaddleOCR recognition model pub fn paddle_rec() -> Self { Self { mean: [0.5, 0.5, 0.5], std: [0.5, 0.5, 0.5], } } } /// Calculate size to pad to (multiple of 32) #[inline] pub fn get_padded_size(size: u32) -> u32 { ((size + 31) / 32) * 32 } /// Scale image to specified maximum side length /// /// Maintains aspect ratio, scales longest side to max_side_len pub fn resize_to_max_side(img: &DynamicImage, max_side_len: u32) -> DynamicImage { let (w, h) = img.dimensions(); let max_dim = w.max(h); if max_dim <= max_side_len { return img.clone(); } let scale = max_side_len as f64 / max_dim as f64; let new_w = (w as f64 * scale).round() as u32; let new_h = (h as f64 * scale).round() as u32; fast_resize(img, new_w, new_h) } /// Scale image to specified height (for recognition model) /// /// Scales maintaining aspect ratio pub fn resize_to_height(img: &DynamicImage, target_height: u32) -> DynamicImage { let (w, h) = img.dimensions(); if h == target_height { return img.clone(); } let scale = target_height as f64 / h as f64; let new_w = (w as f64 * scale).round() as u32; fast_resize(img, new_w, target_height) } /// Fast image resizing using fast_image_resize /// Can pass DynamicImage directly when "image" feature is enabled fn fast_resize(img: &DynamicImage, new_w: u32, new_h: u32) -> DynamicImage { use fast_image_resize::{images::Image, IntoImageView, PixelType, Resizer}; // Get source image pixel type let pixel_type = img.pixel_type().unwrap_or(PixelType::U8x3); // Create destination image container let mut dst_image = Image::new(new_w, new_h, pixel_type); // Resize using Resizer (pass DynamicImage directly, no manual conversion needed) let mut resizer = Resizer::new(); resizer.resize(img, &mut dst_image, None).unwrap(); // Convert result back to DynamicImage match pixel_type { PixelType::U8x3 => { DynamicImage::ImageRgb8(RgbImage::from_raw(new_w, new_h, dst_image.into_vec()).unwrap()) } PixelType::U8x4 => DynamicImage::ImageRgba8( image::RgbaImage::from_raw(new_w, new_h, dst_image.into_vec()).unwrap(), ), _ => { // Convert other types to RGB DynamicImage::ImageRgb8(RgbImage::from_raw(new_w, new_h, dst_image.into_vec()).unwrap()) } } } /// Convert image to detection model input tensor /// /// Output format: [1, 3, H, W] (NCHW) pub fn preprocess_for_det( img: &DynamicImage, params: &NormalizeParams, ) -> ArrayBase<OwnedRepr<f32>, Dim<[usize; 4]>> { let (w, h) = img.dimensions(); let pad_w = get_padded_size(w) as usize; let pad_h = get_padded_size(h) as usize; let mut input = Array4::<f32>::zeros((1, 3, pad_h, pad_w)); let rgb_img = img.to_rgb8(); // Normalize and pad for y in 0..h as usize { for x in 0..w as usize { let pixel = rgb_img.get_pixel(x as u32, y as u32); let [r, g, b] = pixel.0; input[[0, 0, y, x]] = (r as f32 / 255.0 - params.mean[0]) / params.std[0]; input[[0, 1, y, x]] = (g as f32 / 255.0 - params.mean[1]) / params.std[1]; input[[0, 2, y, x]] = (b as f32 / 255.0 - params.mean[2]) / params.std[2]; } } input } /// Convert image to recognition model input tensor /// /// Output format: [1, 3, H, W] (NCHW) /// Height is fixed at 48 (or specified value), width scaled proportionally pub fn preprocess_for_rec( img: &DynamicImage, target_height: u32, params: &NormalizeParams, ) -> ArrayBase<OwnedRepr<f32>, Dim<[usize; 4]>> { let (w, h) = img.dimensions(); // Calculate scaled width let scale = target_height as f64 / h as f64; let target_width = (w as f64 * scale).round() as u32; // Scale image let resized = if h != target_height { img.resize_exact( target_width, target_height, image::imageops::FilterType::Lanczos3, ) } else { img.clone() }; let rgb_img = resized.to_rgb8(); let (w, h) = (target_width as usize, target_height as usize); let mut input = Array4::<f32>::zeros((1, 3, h, w)); for y in 0..h { for x in 0..w { let pixel = rgb_img.get_pixel(x as u32, y as u32); let [r, g, b] = pixel.0; input[[0, 0, y, x]] = (r as f32 / 255.0 - params.mean[0]) / params.std[0]; input[[0, 1, y, x]] = (g as f32 / 255.0 - params.mean[1]) / params.std[1]; input[[0, 2, y, x]] = (b as f32 / 255.0 - params.mean[2]) / params.std[2]; } } input } /// Batch preprocess recognition images /// /// Process multiple images into batch tensor, all images padded to same width pub fn preprocess_batch_for_rec( images: &[DynamicImage], target_height: u32, params: &NormalizeParams, ) -> ArrayBase<OwnedRepr<f32>, Dim<[usize; 4]>> { if images.is_empty() { return Array4::<f32>::zeros((0, 3, target_height as usize, 0)); } // Calculate scaled width for all images let widths: Vec<u32> = images .iter() .map(|img| { let (w, h) = img.dimensions(); let scale = target_height as f64 / h as f64; (w as f64 * scale).round() as u32 }) .collect(); let max_width = *widths.iter().max().unwrap() as usize; let batch_size = images.len(); let mut batch = Array4::<f32>::zeros((batch_size, 3, target_height as usize, max_width)); for (i, (img, &w)) in images.iter().zip(widths.iter()).enumerate() { let resized = resize_to_height(img, target_height); let rgb_img = resized.to_rgb8(); for y in 0..target_height as usize { for x in 0..w as usize { let pixel = rgb_img.get_pixel(x as u32, y as u32); let [r, g, b] = pixel.0; batch[[i, 0, y, x]] = (r as f32 / 255.0 - params.mean[0]) / params.std[0]; batch[[i, 1, y, x]] = (g as f32 / 255.0 - params.mean[1]) / params.std[1]; batch[[i, 2, y, x]] = (b as f32 / 255.0 - params.mean[2]) / params.std[2]; } } } batch } /// Crop image region pub fn crop_image(img: &DynamicImage, x: u32, y: u32, width: u32, height: u32) -> DynamicImage { img.crop_imm(x, y, width, height) } /// Split image into blocks (for high precision mode) /// /// # Parameters /// - `img`: Input image /// - `block_size`: Block size /// - `overlap`: Overlap region size /// /// # Returns /// List of block images and their positions in original image (x, y) pub fn split_into_blocks( img: &DynamicImage, block_size: u32, overlap: u32, ) -> Vec<(DynamicImage, u32, u32)> { let (width, height) = img.dimensions(); let mut blocks = Vec::new(); let step = block_size - overlap; let mut y = 0u32; while y < height { let mut x = 0u32; while x < width { let block_w = (block_size).min(width - x); let block_h = (block_size).min(height - y); let block = img.crop_imm(x, y, block_w, block_h); blocks.push((block, x, y)); x += step; if x + overlap >= width && x < width { break; } } y += step; if y + overlap >= height && y < height { break; } } blocks } /// Convert grayscale mask to binary mask pub fn threshold_mask(mask: &[f32], threshold: f32) -> Vec<u8> { mask.iter() .map(|&v| if v > threshold { 255u8 } else { 0u8 }) .collect() } /// Create grayscale image pub fn create_gray_image(data: &[u8], width: u32, height: u32) -> image::GrayImage { image::GrayImage::from_raw(width, height, data.to_vec()) .unwrap_or_else(|| image::GrayImage::new(width, height)) } /// Convert image to RGB pub fn to_rgb(img: &DynamicImage) -> RgbImage { img.to_rgb8() } /// Create image from RGB data pub fn rgb_to_image(data: &[u8], width: u32, height: u32) -> DynamicImage { let rgb = RgbImage::from_raw(width, height, data.to_vec()) .unwrap_or_else(|| RgbImage::new(width, height)); DynamicImage::ImageRgb8(rgb) } #[cfg(test)] mod tests { use super::*; #[test] fn test_padded_size() { assert_eq!(get_padded_size(100), 128); assert_eq!(get_padded_size(32), 32); assert_eq!(get_padded_size(33), 64); assert_eq!(get_padded_size(0), 0); assert_eq!(get_padded_size(1), 32); assert_eq!(get_padded_size(31), 32); assert_eq!(get_padded_size(64), 64); assert_eq!(get_padded_size(65), 96); } #[test] fn test_normalize_params() { let params = NormalizeParams::default(); assert_eq!(params.mean[0], 0.485); let paddle = NormalizeParams::paddle_det(); assert_eq!(paddle.mean[0], 0.485); assert_eq!(paddle.std[0], 0.229); } #[test] fn test_normalize_params_paddle_rec() { let params = NormalizeParams::paddle_rec(); assert_eq!(params.mean[0], 0.5); assert_eq!(params.mean[1], 0.5); assert_eq!(params.mean[2], 0.5); assert_eq!(params.std[0], 0.5); assert_eq!(params.std[1], 0.5); assert_eq!(params.std[2], 0.5); } #[test] fn test_resize_to_max_side_no_resize() { let img = DynamicImage::new_rgb8(100, 50); let resized = resize_to_max_side(&img, 200); // 图像已经小于最大边,不应该缩放 assert_eq!(resized.width(), 100); assert_eq!(resized.height(), 50); } #[test] fn test_resize_to_max_side_width_limited() { let img = DynamicImage::new_rgb8(1000, 500); let resized = resize_to_max_side(&img, 500); // 宽度是最大边,应该缩放到 500 assert_eq!(resized.width(), 500); assert_eq!(resized.height(), 250); } #[test] fn test_resize_to_max_side_height_limited() { let img = DynamicImage::new_rgb8(500, 1000); let resized = resize_to_max_side(&img, 500); // 高度是最大边,应该缩放到 500 assert_eq!(resized.width(), 250); assert_eq!(resized.height(), 500); } #[test] fn test_resize_to_height() { let img = DynamicImage::new_rgb8(200, 100); let resized = resize_to_height(&img, 48); assert_eq!(resized.height(), 48); // 宽度应该按比例缩放: 200 * 48/100 = 96 assert_eq!(resized.width(), 96); } #[test] fn test_resize_to_height_no_resize() { let img = DynamicImage::new_rgb8(200, 48); let resized = resize_to_height(&img, 48); // 高度已经是目标高度,不应该缩放 assert_eq!(resized.height(), 48); assert_eq!(resized.width(), 200); } #[test] fn test_preprocess_for_det_shape() { let img = DynamicImage::new_rgb8(100, 50); let params = NormalizeParams::paddle_det(); let tensor = preprocess_for_det(&img, &params); // 输出形状应该是 [1, 3, H, W],H 和 W 是 32 的倍数 assert_eq!(tensor.shape()[0], 1); assert_eq!(tensor.shape()[1], 3); assert_eq!(tensor.shape()[2], 64); // 50 向上取整到 64 assert_eq!(tensor.shape()[3], 128); // 100 向上取整到 128 } #[test] fn test_preprocess_for_rec_shape() { let img = DynamicImage::new_rgb8(200, 100); let params = NormalizeParams::paddle_rec(); let tensor = preprocess_for_rec(&img, 48, &params); // 输出高度应该是 48 assert_eq!(tensor.shape()[0], 1); assert_eq!(tensor.shape()[1], 3); assert_eq!(tensor.shape()[2], 48); // 宽度应该按比例缩放: 200 * 48/100 = 96 assert_eq!(tensor.shape()[3], 96); } #[test] fn test_preprocess_batch_for_rec_empty() { let images: Vec<DynamicImage> = vec![]; let params = NormalizeParams::paddle_rec(); let tensor = preprocess_batch_for_rec(&images, 48, &params); assert_eq!(tensor.shape()[0], 0); } #[test] fn test_preprocess_batch_for_rec_single() { let images = vec![DynamicImage::new_rgb8(200, 100)]; let params = NormalizeParams::paddle_rec(); let tensor = preprocess_batch_for_rec(&images, 48, &params); assert_eq!(tensor.shape()[0], 1); assert_eq!(tensor.shape()[1], 3); assert_eq!(tensor.shape()[2], 48); } #[test] fn test_preprocess_batch_for_rec_multiple() { let images = vec![ DynamicImage::new_rgb8(200, 100), DynamicImage::new_rgb8(300, 100), ]; let params = NormalizeParams::paddle_rec(); let tensor = preprocess_batch_for_rec(&images, 48, &params); assert_eq!(tensor.shape()[0], 2); assert_eq!(tensor.shape()[1], 3); assert_eq!(tensor.shape()[2], 48); // 宽度应该是最大宽度: max(96, 144) = 144 assert_eq!(tensor.shape()[3], 144); } #[test] fn test_crop_image() { let img = DynamicImage::new_rgb8(200, 100); let cropped = crop_image(&img, 50, 25, 100, 50); assert_eq!(cropped.width(), 100); assert_eq!(cropped.height(), 50); } #[test] fn test_split_into_blocks() { let img = DynamicImage::new_rgb8(500, 500); let blocks = split_into_blocks(&img, 200, 50); // 应该有多个块 assert!(!blocks.is_empty()); // 每个块的位置应该记录正确 for (block, x, y) in &blocks { assert!(block.width() <= 200); assert!(block.height() <= 200); assert!(*x < 500); assert!(*y < 500); } } #[test] fn test_split_into_blocks_small_image() { let img = DynamicImage::new_rgb8(100, 100); let blocks = split_into_blocks(&img, 200, 50); // 图像小于块大小,应该只有一个块 assert_eq!(blocks.len(), 1); assert_eq!(blocks[0].1, 0); // x offset assert_eq!(blocks[0].2, 0); // y offset } #[test] fn test_threshold_mask() { let mask = vec![0.1, 0.3, 0.5, 0.7, 0.9]; let binary = threshold_mask(&mask, 0.5); assert_eq!(binary, vec![0, 0, 0, 255, 255]); } #[test] fn test_threshold_mask_all_below() { let mask = vec![0.1, 0.2, 0.3, 0.4]; let binary = threshold_mask(&mask, 0.5); assert_eq!(binary, vec![0, 0, 0, 0]); } #[test] fn test_threshold_mask_all_above() { let mask = vec![0.6, 0.7, 0.8, 0.9]; let binary = threshold_mask(&mask, 0.5); assert_eq!(binary, vec![255, 255, 255, 255]); } #[test] fn test_create_gray_image() { let data = vec![128u8; 100]; let gray = create_gray_image(&data, 10, 10); assert_eq!(gray.width(), 10); assert_eq!(gray.height(), 10); } #[test] fn test_to_rgb() { let img = DynamicImage::new_rgb8(100, 50); let rgb = to_rgb(&img); assert_eq!(rgb.width(), 100); assert_eq!(rgb.height(), 50); } #[test] fn test_rgb_to_image() { let data = vec![128u8; 300]; // 10x10 RGB let img = rgb_to_image(&data, 10, 10); assert_eq!(img.width(), 10); assert_eq!(img.height(), 10); } }
rust
Apache-2.0
2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e
2026-01-04T20:19:51.104139Z
false
zibo-chen/rust-paddle-ocr
https://github.com/zibo-chen/rust-paddle-ocr/blob/2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e/src/mnn/docsrs_stub.rs
src/mnn/docsrs_stub.rs
//! docsrs stub module - for documentation generation //! //! This module is used during docs.rs build, providing type definitions without actual implementations use ndarray::{ArrayD, ArrayViewD}; use std::path::Path; // ============== Error Types ============== /// MNN-related errors #[derive(Debug, Clone, PartialEq, Eq)] pub enum MnnError { /// Invalid parameter InvalidParameter(String), /// Out of memory OutOfMemory, /// Runtime error RuntimeError(String), /// Unsupported operation Unsupported, /// Model loading failed ModelLoadFailed(String), /// Null pointer error NullPointer, /// Shape mismatch ShapeMismatch { expected: Vec<usize>, got: Vec<usize>, }, } impl std::fmt::Display for MnnError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{:?}", self) } } impl std::error::Error for MnnError {} /// MNN Result type pub type Result<T> = std::result::Result<T, MnnError>; // ============== Backend Types ============== /// Computation backend #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum Backend { /// CPU backend (default) #[default] CPU, /// Metal GPU (macOS/iOS) Metal, /// OpenCL GPU OpenCL, /// OpenGL GPU OpenGL, /// Vulkan GPU Vulkan, /// CUDA GPU CUDA, /// CoreML (macOS/iOS) CoreML, } /// Precision mode #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum PrecisionMode { /// Normal precision #[default] Normal, /// Low precision Low, /// High precision High, /// Low memory usage LowMemory, } /// Data format #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum DataFormat { /// NCHW format #[default] NCHW, /// NHWC format NHWC, } // ============== Configuration Types ============== /// Inference configuration #[derive(Debug, Clone)] pub struct InferenceConfig { pub thread_count: i32, pub precision_mode: PrecisionMode, pub backend: Backend, pub use_cache: bool, pub data_format: DataFormat, } impl Default for InferenceConfig { fn default() -> Self { Self { thread_count: 4, precision_mode: PrecisionMode::Normal, backend: Backend::CPU, use_cache: true, data_format: DataFormat::NCHW, } } } impl InferenceConfig { /// Create a new inference configuration pub fn new() -> Self { Self::default() } /// Set the number of threads pub fn with_threads(mut self, threads: i32) -> Self { self.thread_count = threads; self } /// Set the precision mode pub fn with_precision(mut self, precision: PrecisionMode) -> Self { self.precision_mode = precision; self } /// Set the backend pub fn with_backend(mut self, backend: Backend) -> Self { self.backend = backend; self } /// Set the data format pub fn with_data_format(mut self, format: DataFormat) -> Self { self.data_format = format; self } } // ============== Shared Runtime ============== /// Shared runtime for sharing resources between multiple engines pub struct SharedRuntime { _private: (), } impl SharedRuntime { /// Create a new shared runtime pub fn new(_config: &InferenceConfig) -> Result<Self> { unimplemented!( "This feature is only available at runtime, not available during documentation build" ) } } // ============== Inference Engine ============== /// MNN inference engine pub struct InferenceEngine { _input_shape: Vec<usize>, _output_shape: Vec<usize>, } impl InferenceEngine { /// Create inference engine from file pub fn from_file( _model_path: impl AsRef<Path>, _config: Option<InferenceConfig>, ) -> Result<Self> { unimplemented!( "This feature is only available at runtime, not available during documentation build" ) } /// Create inference engine from memory pub fn from_buffer(_data: &[u8], _config: Option<InferenceConfig>) -> Result<Self> { unimplemented!( "This feature is only available at runtime, not available during documentation build" ) } /// Create inference engine from model bytes using shared runtime pub fn from_buffer_with_runtime( _model_buffer: &[u8], _runtime: &SharedRuntime, ) -> Result<Self> { unimplemented!( "This feature is only available at runtime, not available during documentation build" ) } /// Get input shape pub fn input_shape(&self) -> &[usize] { &self._input_shape } /// Get output shape pub fn output_shape(&self) -> &[usize] { &self._output_shape } /// Perform inference pub fn infer(&self, _input: ArrayViewD<f32>) -> Result<ArrayD<f32>> { unimplemented!() } /// Perform inference (variable input shape) pub fn infer_dynamic(&self, _input: ArrayViewD<f32>) -> Result<ArrayD<f32>> { unimplemented!() } /// Perform inference (variable input shape) - alias pub fn run_dynamic(&self, _input: ArrayViewD<f32>) -> Result<ArrayD<f32>> { unimplemented!() } /// Perform inference (raw interface) pub fn run_dynamic_raw( &self, _input_data: &[f32], _input_shape: &[usize], _output_data: &mut [f32], ) -> Result<Vec<usize>> { unimplemented!() } } // ============== Helper Functions ============== /// Get MNN version pub fn get_version() -> String { "unknown (docs.rs build)".to_string() }
rust
Apache-2.0
2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e
2026-01-04T20:19:51.104139Z
false
zibo-chen/rust-paddle-ocr
https://github.com/zibo-chen/rust-paddle-ocr/blob/2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e/src/mnn/mod.rs
src/mnn/mod.rs
//! MNN Inference Engine FFI Binding Layer //! //! This module encapsulates the low-level interfaces of the MNN C++ inference framework, providing safe Rust APIs. // Use stub implementation when building on docs.rs #[cfg(feature = "docsrs")] mod docsrs_stub; #[cfg(feature = "docsrs")] pub use docsrs_stub::*; // Use complete implementation for normal builds #[cfg(not(feature = "docsrs"))] mod normal_impl { use ndarray::{ArrayD, ArrayViewD, IxDyn}; use std::ffi::CStr; use std::ptr::NonNull; #[allow(non_camel_case_types)] #[allow(non_upper_case_globals)] #[allow(non_snake_case)] #[allow(dead_code)] mod ffi { include!(concat!(env!("OUT_DIR"), "/mnn_bindings.rs")); } // ============== Error Types ============== /// MNN related errors #[derive(Debug, Clone, PartialEq, Eq)] pub enum MnnError { /// Invalid parameter InvalidParameter(String), /// Out of memory OutOfMemory, /// Runtime error RuntimeError(String), /// Unsupported operation Unsupported, /// Model loading failed ModelLoadFailed(String), /// Null pointer error NullPointer, /// Shape mismatch ShapeMismatch { expected: Vec<usize>, got: Vec<usize>, }, } impl std::fmt::Display for MnnError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { MnnError::InvalidParameter(msg) => write!(f, "Invalid parameter: {}", msg), MnnError::OutOfMemory => write!(f, "Out of memory"), MnnError::RuntimeError(msg) => write!(f, "Runtime error: {}", msg), MnnError::Unsupported => write!(f, "Unsupported operation"), MnnError::ModelLoadFailed(msg) => write!(f, "Model loading failed: {}", msg), MnnError::NullPointer => write!(f, "Null pointer"), MnnError::ShapeMismatch { expected, got } => { write!(f, "Shape mismatch: expected {:?}, got {:?}", expected, got) } } } } impl std::error::Error for MnnError {} pub type Result<T> = std::result::Result<T, MnnError>; // ============== Configuration Types ============== /// Precision mode #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] #[repr(i32)] pub enum PrecisionMode { /// Normal precision #[default] Normal = 0, /// Low precision (faster) Low = 1, /// High precision (more accurate) High = 2, } /// Data format #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] #[repr(i32)] pub enum DataFormat { /// NCHW format (Caffe/PyTorch/ONNX) #[default] NCHW = 0, /// NHWC format (TensorFlow) NHWC = 1, /// Auto detect Auto = 2, } /// Inference backend type #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum Backend { /// CPU backend #[default] CPU, /// Metal GPU (macOS/iOS) Metal, /// OpenCL GPU OpenCL, /// OpenGL GPU OpenGL, /// Vulkan GPU Vulkan, /// CUDA GPU (NVIDIA) CUDA, /// CoreML (macOS/iOS) CoreML, } /// Inference configuration #[derive(Debug, Clone)] pub struct InferenceConfig { /// Thread count (0 means auto, default is 4) pub thread_count: i32, /// Precision mode pub precision_mode: PrecisionMode, /// Whether to use cache pub use_cache: bool, /// Data format pub data_format: DataFormat, /// Inference backend pub backend: Backend, } impl Default for InferenceConfig { fn default() -> Self { InferenceConfig { thread_count: 4, precision_mode: PrecisionMode::Normal, use_cache: false, data_format: DataFormat::NCHW, backend: Backend::CPU, } } } impl InferenceConfig { /// Create new inference configuration pub fn new() -> Self { Self::default() } /// Set thread count pub fn with_threads(mut self, threads: i32) -> Self { self.thread_count = threads; self } /// Set precision mode pub fn with_precision(mut self, precision: PrecisionMode) -> Self { self.precision_mode = precision; self } /// Set backend pub fn with_backend(mut self, backend: Backend) -> Self { self.backend = backend; self } /// Set data format pub fn with_data_format(mut self, format: DataFormat) -> Self { self.data_format = format; self } fn to_ffi(&self) -> ffi::MNNR_Config { ffi::MNNR_Config { thread_count: self.thread_count, precision_mode: self.precision_mode as i32, use_cache: self.use_cache, data_format: self.data_format as i32, } } } // ============== Shared Runtime ============== /// Shared runtime for sharing resources among multiple engines pub struct SharedRuntime { ptr: NonNull<ffi::MNN_SharedRuntime>, } impl SharedRuntime { /// Create new shared runtime pub fn new(config: &InferenceConfig) -> Result<Self> { let c_config = config.to_ffi(); let runtime_ptr = unsafe { ffi::mnnr_create_runtime(&c_config) }; let ptr = NonNull::new(runtime_ptr).ok_or_else(|| { MnnError::RuntimeError("Create shared runtime failed".to_string()) })?; Ok(SharedRuntime { ptr }) } pub(crate) fn as_ptr(&self) -> *mut ffi::MNN_SharedRuntime { self.ptr.as_ptr() } } impl Drop for SharedRuntime { fn drop(&mut self) { unsafe { ffi::mnnr_destroy_runtime(self.ptr.as_ptr()); } } } unsafe impl Send for SharedRuntime {} unsafe impl Sync for SharedRuntime {} // ============== Helper Functions ============== fn get_last_error_message(engine: Option<*const ffi::MNN_InferenceEngine>) -> String { match engine { Some(ptr) => unsafe { let c_str = ffi::mnnr_get_last_error(ptr); if c_str.is_null() { "Unknown error".to_string() } else { CStr::from_ptr(c_str).to_string_lossy().into_owned() } }, None => "Engine creation failed".to_string(), } } // ============== Inference Engine ============== /// MNN inference engine /// /// Encapsulates MNN model loading and inference functionality pub struct InferenceEngine { ptr: NonNull<ffi::MNN_InferenceEngine>, input_shape: Vec<usize>, output_shape: Vec<usize>, } impl InferenceEngine { /// Create inference engine from model byte data /// /// # Parameters /// - `model_buffer`: Model file byte data /// - `config`: Optional inference configuration /// /// # Example /// ```ignore /// let model_data = std::fs::read("model.mnn")?; /// let engine = InferenceEngine::from_buffer(&model_data, None)?; /// ``` pub fn from_buffer(model_buffer: &[u8], config: Option<InferenceConfig>) -> Result<Self> { if model_buffer.is_empty() { return Err(MnnError::InvalidParameter( "Model data is empty".to_string(), )); } let cfg = config.unwrap_or_default(); let c_config = cfg.to_ffi(); let engine_ptr = unsafe { ffi::mnnr_create_engine( model_buffer.as_ptr() as *const _, model_buffer.len(), &c_config, ) }; let ptr = NonNull::new(engine_ptr) .ok_or_else(|| MnnError::ModelLoadFailed(get_last_error_message(None)))?; let (input_shape, output_shape) = unsafe { Self::get_shapes(ptr.as_ptr())? }; Ok(InferenceEngine { ptr, input_shape, output_shape, }) } /// Create inference engine from model file pub fn from_file( model_path: impl AsRef<std::path::Path>, config: Option<InferenceConfig>, ) -> Result<Self> { let model_buffer = std::fs::read(model_path.as_ref()).map_err(|e| { MnnError::ModelLoadFailed(format!("Failed to read model file: {}", e)) })?; Self::from_buffer(&model_buffer, config) } /// Create inference engine from model byte data using shared runtime pub fn from_buffer_with_runtime( model_buffer: &[u8], runtime: &SharedRuntime, ) -> Result<Self> { if model_buffer.is_empty() { return Err(MnnError::InvalidParameter( "Model data is empty".to_string(), )); } let engine_ptr = unsafe { ffi::mnnr_create_engine_with_runtime( model_buffer.as_ptr() as *const _, model_buffer.len(), runtime.as_ptr(), ) }; let ptr = NonNull::new(engine_ptr) .ok_or_else(|| MnnError::ModelLoadFailed(get_last_error_message(None)))?; let (input_shape, output_shape) = unsafe { Self::get_shapes(ptr.as_ptr())? }; Ok(InferenceEngine { ptr, input_shape, output_shape, }) } unsafe fn get_shapes( ptr: *mut ffi::MNN_InferenceEngine, ) -> Result<(Vec<usize>, Vec<usize>)> { let mut input_shape_vec = vec![0usize; 8]; let mut input_ndims = 0; let mut output_shape_vec = vec![0usize; 8]; let mut output_ndims = 0; if ffi::mnnr_get_input_shape(ptr, input_shape_vec.as_mut_ptr(), &mut input_ndims) != ffi::MNNR_ErrorCode_MNNR_SUCCESS { return Err(MnnError::RuntimeError( "Failed to get input shape".to_string(), )); } input_shape_vec.truncate(input_ndims); if ffi::mnnr_get_output_shape(ptr, output_shape_vec.as_mut_ptr(), &mut output_ndims) != ffi::MNNR_ErrorCode_MNNR_SUCCESS { return Err(MnnError::RuntimeError( "Failed to get output shape".to_string(), )); } output_shape_vec.truncate(output_ndims); Ok((input_shape_vec, output_shape_vec)) } /// Get input tensor shape pub fn input_shape(&self) -> &[usize] { &self.input_shape } /// Get output tensor shape pub fn output_shape(&self) -> &[usize] { &self.output_shape } /// Execute inference /// /// # Parameters /// - `input_data`: Input data, shape must match model input shape /// /// # Returns /// Inference result array pub fn run(&self, input_data: ArrayViewD<f32>) -> Result<ArrayD<f32>> { if input_data.shape() != self.input_shape.as_slice() { return Err(MnnError::ShapeMismatch { expected: self.input_shape.clone(), got: input_data.shape().to_vec(), }); } let input_slice = input_data.as_slice().ok_or_else(|| { MnnError::InvalidParameter("Input data must be contiguous".to_string()) })?; let output_size: usize = self.output_shape.iter().product(); let mut output_buffer = vec![0.0f32; output_size]; let error_code = unsafe { ffi::mnnr_run_inference( self.ptr.as_ptr(), input_slice.as_ptr(), input_slice.len(), output_buffer.as_mut_ptr(), output_buffer.len(), ) }; match error_code { ffi::MNNR_ErrorCode_MNNR_SUCCESS => { ArrayD::from_shape_vec(IxDyn(&self.output_shape), output_buffer).map_err(|e| { MnnError::RuntimeError(format!("Failed to create output array: {}", e)) }) } ffi::MNNR_ErrorCode_MNNR_ERROR_INVALID_PARAMETER => Err( MnnError::InvalidParameter(get_last_error_message(Some(self.ptr.as_ptr()))), ), ffi::MNNR_ErrorCode_MNNR_ERROR_OUT_OF_MEMORY => Err(MnnError::OutOfMemory), ffi::MNNR_ErrorCode_MNNR_ERROR_UNSUPPORTED => Err(MnnError::Unsupported), _ => Err(MnnError::RuntimeError(get_last_error_message(Some( self.ptr.as_ptr(), )))), } } /// Execute inference (using raw slices) /// /// This is a low-level API, suitable for scenarios requiring maximum performance pub fn run_raw(&self, input: &[f32], output: &mut [f32]) -> Result<()> { let expected_input: usize = self.input_shape.iter().product(); let expected_output: usize = self.output_shape.iter().product(); if input.len() != expected_input { return Err(MnnError::ShapeMismatch { expected: vec![expected_input], got: vec![input.len()], }); } if output.len() != expected_output { return Err(MnnError::ShapeMismatch { expected: vec![expected_output], got: vec![output.len()], }); } let error_code = unsafe { ffi::mnnr_run_inference( self.ptr.as_ptr(), input.as_ptr(), input.len(), output.as_mut_ptr(), output.len(), ) }; match error_code { ffi::MNNR_ErrorCode_MNNR_SUCCESS => Ok(()), ffi::MNNR_ErrorCode_MNNR_ERROR_INVALID_PARAMETER => Err( MnnError::InvalidParameter(get_last_error_message(Some(self.ptr.as_ptr()))), ), ffi::MNNR_ErrorCode_MNNR_ERROR_OUT_OF_MEMORY => Err(MnnError::OutOfMemory), _ => Err(MnnError::RuntimeError(get_last_error_message(Some( self.ptr.as_ptr(), )))), } } pub(crate) fn as_ptr(&self) -> NonNull<ffi::MNN_InferenceEngine> { self.ptr } /// Check if model has dynamic shape (contains -1 dimension) pub fn has_dynamic_shape(&self) -> bool { // When shape contains very large values, it indicates dynamic shape (-1 converted to usize becomes very large) self.input_shape.iter().any(|&d| d > 100000) || self.output_shape.iter().any(|&d| d > 100000) } /// Execute dynamic shape inference /// /// Suitable for models where input shape changes at runtime (such as detection models). /// This function adjusts model input tensor shape before running. /// /// # Parameters /// - `input_data`: Input data array /// /// # Returns /// Inference result array, shape dynamically determined by model pub fn run_dynamic(&self, input_data: ArrayViewD<f32>) -> Result<ArrayD<f32>> { let input_shape: Vec<usize> = input_data.shape().to_vec(); let input_slice = input_data.as_slice().ok_or_else(|| { MnnError::InvalidParameter("Input data must be contiguous".to_string()) })?; let mut output_data: *mut f32 = std::ptr::null_mut(); let mut output_size: usize = 0; let mut output_dims = [0usize; 8]; let mut output_ndims: usize = 0; let error_code = unsafe { ffi::mnnr_run_inference_dynamic( self.ptr.as_ptr(), input_slice.as_ptr(), input_shape.as_ptr(), input_shape.len(), &mut output_data, &mut output_size, output_dims.as_mut_ptr(), &mut output_ndims, ) }; if error_code != ffi::MNNR_ErrorCode_MNNR_SUCCESS { return match error_code { ffi::MNNR_ErrorCode_MNNR_ERROR_INVALID_PARAMETER => Err( MnnError::InvalidParameter(get_last_error_message(Some(self.ptr.as_ptr()))), ), ffi::MNNR_ErrorCode_MNNR_ERROR_OUT_OF_MEMORY => Err(MnnError::OutOfMemory), ffi::MNNR_ErrorCode_MNNR_ERROR_UNSUPPORTED => Err(MnnError::Unsupported), _ => Err(MnnError::RuntimeError(get_last_error_message(Some( self.ptr.as_ptr(), )))), }; } // Copy output data and free C buffer let output_shape: Vec<usize> = output_dims[..output_ndims].to_vec(); let output_buffer = unsafe { let slice = std::slice::from_raw_parts(output_data, output_size); let buffer = slice.to_vec(); ffi::mnnr_free_output(output_data); buffer }; ArrayD::from_shape_vec(IxDyn(&output_shape), output_buffer).map_err(|e| { MnnError::RuntimeError(format!("Failed to create output array: {}", e)) }) } /// Execute dynamic shape inference (using raw slices) /// /// Low-level API, caller is responsible for managing output buffer pub fn run_dynamic_raw( &self, input: &[f32], input_shape: &[usize], ) -> Result<(Vec<f32>, Vec<usize>)> { let mut output_data: *mut f32 = std::ptr::null_mut(); let mut output_size: usize = 0; let mut output_dims = [0usize; 8]; let mut output_ndims: usize = 0; let error_code = unsafe { ffi::mnnr_run_inference_dynamic( self.ptr.as_ptr(), input.as_ptr(), input_shape.as_ptr(), input_shape.len(), &mut output_data, &mut output_size, output_dims.as_mut_ptr(), &mut output_ndims, ) }; if error_code != ffi::MNNR_ErrorCode_MNNR_SUCCESS { return match error_code { ffi::MNNR_ErrorCode_MNNR_ERROR_INVALID_PARAMETER => Err( MnnError::InvalidParameter(get_last_error_message(Some(self.ptr.as_ptr()))), ), ffi::MNNR_ErrorCode_MNNR_ERROR_OUT_OF_MEMORY => Err(MnnError::OutOfMemory), _ => Err(MnnError::RuntimeError(get_last_error_message(Some( self.ptr.as_ptr(), )))), }; } // Copy output and free C buffer let output_shape = output_dims[..output_ndims].to_vec(); let output_buffer = unsafe { let slice = std::slice::from_raw_parts(output_data, output_size); let buffer = slice.to_vec(); ffi::mnnr_free_output(output_data); buffer }; Ok((output_buffer, output_shape)) } } impl Drop for InferenceEngine { fn drop(&mut self) { unsafe { ffi::mnnr_destroy_engine(self.ptr.as_ptr()); } } } unsafe impl Send for InferenceEngine {} unsafe impl Sync for InferenceEngine {} // ============== Session Pool ============== /// Session pool for high-concurrency inference scenarios pub struct SessionPool { ptr: NonNull<ffi::MNN_SessionPool>, input_shape: Vec<usize>, output_shape: Vec<usize>, } impl SessionPool { /// Create session pool /// /// # Parameters /// - `engine`: Inference engine /// - `pool_size`: Number of sessions in pool /// - `config`: Optional inference configuration pub fn new( engine: &InferenceEngine, pool_size: usize, config: Option<InferenceConfig>, ) -> Result<Self> { if pool_size == 0 { return Err(MnnError::InvalidParameter( "Pool size cannot be 0".to_string(), )); } let cfg = config.unwrap_or_default(); let c_config = cfg.to_ffi(); let pool_ptr = unsafe { ffi::mnnr_create_session_pool(engine.as_ptr().as_ptr(), pool_size, &c_config) }; let ptr = NonNull::new(pool_ptr) .ok_or_else(|| MnnError::RuntimeError("Create session pool failed".to_string()))?; Ok(SessionPool { ptr, input_shape: engine.input_shape.clone(), output_shape: engine.output_shape.clone(), }) } /// Execute inference (thread-safe) pub fn run(&self, input_data: ArrayViewD<f32>) -> Result<ArrayD<f32>> { if input_data.shape() != self.input_shape.as_slice() { return Err(MnnError::ShapeMismatch { expected: self.input_shape.clone(), got: input_data.shape().to_vec(), }); } let input_slice = input_data.as_slice().ok_or_else(|| { MnnError::InvalidParameter("Input data must be contiguous".to_string()) })?; let output_size: usize = self.output_shape.iter().product(); let mut output_buffer = vec![0.0f32; output_size]; let error_code = unsafe { ffi::mnnr_session_pool_run( self.ptr.as_ptr(), input_slice.as_ptr(), input_slice.len(), output_buffer.as_mut_ptr(), output_buffer.len(), ) }; match error_code { ffi::MNNR_ErrorCode_MNNR_SUCCESS => { ArrayD::from_shape_vec(IxDyn(&self.output_shape), output_buffer).map_err(|e| { MnnError::RuntimeError(format!("Failed to create output array: {}", e)) }) } _ => Err(MnnError::RuntimeError( "Session pool inference failed".to_string(), )), } } /// Get available session count pub fn available(&self) -> usize { unsafe { ffi::mnnr_session_pool_available(self.ptr.as_ptr()) } } } impl Drop for SessionPool { fn drop(&mut self) { unsafe { ffi::mnnr_destroy_session_pool(self.ptr.as_ptr()); } } } unsafe impl Send for SessionPool {} unsafe impl Sync for SessionPool {} // ============== Utility Functions ============== /// Get MNN version number pub fn get_version() -> String { unsafe { let c_str = ffi::mnnr_get_version(); if c_str.is_null() { "unknown".to_string() } else { CStr::from_ptr(c_str).to_string_lossy().into_owned() } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_config_default() { let config = InferenceConfig::default(); assert_eq!(config.thread_count, 4); assert_eq!(config.precision_mode, PrecisionMode::Normal); } #[test] fn test_config_builder() { let config = InferenceConfig::new() .with_threads(8) .with_precision(PrecisionMode::High) .with_backend(Backend::Metal); assert_eq!(config.thread_count, 8); assert_eq!(config.precision_mode, PrecisionMode::High); assert_eq!(config.backend, Backend::Metal); } } } // end of normal_impl module // Re-export types from normal implementation #[cfg(not(feature = "docsrs"))] pub use normal_impl::*;
rust
Apache-2.0
2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e
2026-01-04T20:19:51.104139Z
false
zibo-chen/rust-paddle-ocr
https://github.com/zibo-chen/rust-paddle-ocr/blob/2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e/tests/integration_tests.rs
tests/integration_tests.rs
//! 集成测试 //! //! Integration Tests //! //! 这些测试需要模型文件才能运行 use ocr_rs::{ DetModel, DetOptions, DetPrecisionMode, OcrEngine, OcrEngineConfig, RecModel, RecOptions, }; /// 测试模型文件路径 const DET_MODEL_PATH: &str = "models/PP-OCRv5_mobile_det.mnn"; const REC_MODEL_PATH: &str = "models/PP-OCRv5_mobile_rec.mnn"; const CHARSET_PATH: &str = "models/ppocr_keys_v5.txt"; const TEST_IMAGE_PATH: &str = "res/test1.png"; /// 检查模型文件是否存在 fn models_exist() -> bool { std::path::Path::new(DET_MODEL_PATH).exists() && std::path::Path::new(REC_MODEL_PATH).exists() && std::path::Path::new(CHARSET_PATH).exists() } /// 检查测试图像是否存在 fn test_image_exists() -> bool { std::path::Path::new(TEST_IMAGE_PATH).exists() } #[test] fn test_det_model_creation() { if !models_exist() { eprintln!("跳过测试:模型文件不存在"); return; } let det = DetModel::from_file(DET_MODEL_PATH, None); assert!(det.is_ok(), "检测模型创建失败: {:?}", det.err()); } #[test] fn test_det_model_with_options() { if !models_exist() { eprintln!("跳过测试:模型文件不存在"); return; } let det = DetModel::from_file(DET_MODEL_PATH, None).map(|d| { d.with_options( DetOptions::new() .with_max_side_len(1280) .with_precision_mode(DetPrecisionMode::Fast), ) }); assert!(det.is_ok(), "配置检测模型失败: {:?}", det.err()); } #[test] fn test_rec_model_creation() { if !models_exist() { eprintln!("跳过测试:模型文件不存在"); return; } let rec = RecModel::from_file(REC_MODEL_PATH, CHARSET_PATH, None); assert!(rec.is_ok(), "识别模型创建失败: {:?}", rec.err()); } #[test] fn test_rec_model_charset_size() { if !models_exist() { eprintln!("跳过测试:模型文件不存在"); return; } let rec = RecModel::from_file(REC_MODEL_PATH, CHARSET_PATH, None).unwrap(); let charset_size = rec.charset_size(); // PP-OCRv5 字符集应该有很多字符 assert!( charset_size > 1000, "字符集大小应该大于 1000,实际: {}", charset_size ); } #[test] fn test_rec_model_with_options() { if !models_exist() { eprintln!("跳过测试:模型文件不存在"); return; } let rec = RecModel::from_file(REC_MODEL_PATH, CHARSET_PATH, None) .map(|r| r.with_options(RecOptions::new().with_min_score(0.5).with_batch_size(4))); assert!(rec.is_ok(), "配置识别模型失败: {:?}", rec.err()); } #[test] fn test_ocr_engine_creation() { if !models_exist() { eprintln!("跳过测试:模型文件不存在"); return; } let engine = OcrEngine::new(DET_MODEL_PATH, REC_MODEL_PATH, CHARSET_PATH, None); assert!(engine.is_ok(), "OCR 引擎创建失败: {:?}", engine.err()); } #[test] fn test_ocr_engine_with_config() { if !models_exist() { eprintln!("跳过测试:模型文件不存在"); return; } let config = OcrEngineConfig::new() .with_threads(2) .with_det_options(DetOptions::fast()) .with_rec_options(RecOptions::new().with_min_score(0.3)); let engine = OcrEngine::new(DET_MODEL_PATH, REC_MODEL_PATH, CHARSET_PATH, Some(config)); assert!(engine.is_ok(), "配置 OCR 引擎失败: {:?}", engine.err()); } #[test] fn test_ocr_engine_presets() { if !models_exist() { eprintln!("跳过测试:模型文件不存在"); return; } // 测试快速模式 let fast_config = OcrEngineConfig::fast(); let engine = OcrEngine::new( DET_MODEL_PATH, REC_MODEL_PATH, CHARSET_PATH, Some(fast_config), ); assert!(engine.is_ok(), "快速模式创建失败"); } #[test] fn test_detection_on_image() { if !models_exist() || !test_image_exists() { eprintln!("跳过测试:模型或测试图像不存在"); return; } let det = DetModel::from_file(DET_MODEL_PATH, None).unwrap(); let image = image::open(TEST_IMAGE_PATH).unwrap(); let boxes = det.detect(&image); assert!(boxes.is_ok(), "检测失败: {:?}", boxes.err()); let boxes = boxes.unwrap(); // 测试图像应该有文本 assert!(!boxes.is_empty(), "测试图像应该检测到文本"); } #[test] fn test_detection_and_crop() { if !models_exist() || !test_image_exists() { eprintln!("跳过测试:模型或测试图像不存在"); return; } let det = DetModel::from_file(DET_MODEL_PATH, None).unwrap(); let image = image::open(TEST_IMAGE_PATH).unwrap(); let detections = det.detect_and_crop(&image); assert!(detections.is_ok(), "检测裁剪失败: {:?}", detections.err()); let detections = detections.unwrap(); for (cropped, text_box) in &detections { // 裁剪的图像应该有效 assert!(cropped.width() > 0); assert!(cropped.height() > 0); // 边界框应该有有效的分数 assert!(text_box.score >= 0.0 && text_box.score <= 1.0); } } #[test] fn test_recognition_on_cropped_image() { if !models_exist() || !test_image_exists() { eprintln!("跳过测试:模型或测试图像不存在"); return; } let det = DetModel::from_file(DET_MODEL_PATH, None).unwrap(); let rec = RecModel::from_file(REC_MODEL_PATH, CHARSET_PATH, None).unwrap(); let image = image::open(TEST_IMAGE_PATH).unwrap(); let detections = det.detect_and_crop(&image).unwrap(); if detections.is_empty() { eprintln!("未检测到文本区域,跳过识别测试"); return; } let (cropped, _) = &detections[0]; let result = rec.recognize(cropped); assert!(result.is_ok(), "识别失败: {:?}", result.err()); let result = result.unwrap(); // 置信度应该在有效范围内 assert!(result.confidence >= 0.0 && result.confidence <= 1.0); } #[test] fn test_full_ocr_pipeline() { if !models_exist() || !test_image_exists() { eprintln!("跳过测试:模型或测试图像不存在"); return; } let engine = OcrEngine::new(DET_MODEL_PATH, REC_MODEL_PATH, CHARSET_PATH, None).unwrap(); let image = image::open(TEST_IMAGE_PATH).unwrap(); let results = engine.recognize(&image); assert!(results.is_ok(), "OCR 识别失败: {:?}", results.err()); let results = results.unwrap(); // 测试图像应该有文本 assert!(!results.is_empty(), "测试图像应该识别到文本"); for result in &results { // 每个结果应该有有效的数据 assert!(result.confidence >= 0.0 && result.confidence <= 1.0); assert!(result.bbox.area() > 0); } } #[test] fn test_batch_recognition() { if !models_exist() || !test_image_exists() { eprintln!("跳过测试:模型或测试图像不存在"); return; } let det = DetModel::from_file(DET_MODEL_PATH, None).unwrap(); let rec = RecModel::from_file(REC_MODEL_PATH, CHARSET_PATH, None).unwrap(); let image = image::open(TEST_IMAGE_PATH).unwrap(); let detections = det.detect_and_crop(&image).unwrap(); if detections.len() < 2 { eprintln!("检测到的文本区域不足,跳过批量测试"); return; } let images: Vec<_> = detections.iter().map(|(img, _)| img.clone()).collect(); let results = rec.recognize_batch(&images); assert!(results.is_ok(), "批量识别失败: {:?}", results.err()); let results = results.unwrap(); assert_eq!(results.len(), images.len()); } #[test] fn test_det_only_engine() { if !models_exist() { eprintln!("跳过测试:模型文件不存在"); return; } let det_engine = OcrEngine::det_only(DET_MODEL_PATH, None); assert!( det_engine.is_ok(), "仅检测引擎创建失败: {:?}", det_engine.err() ); } #[test] fn test_rec_only_engine() { if !models_exist() { eprintln!("跳过测试:模型文件不存在"); return; } let rec_engine = OcrEngine::rec_only(REC_MODEL_PATH, CHARSET_PATH, None); assert!( rec_engine.is_ok(), "仅识别引擎创建失败: {:?}", rec_engine.err() ); }
rust
Apache-2.0
2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e
2026-01-04T20:19:51.104139Z
false
zibo-chen/rust-paddle-ocr
https://github.com/zibo-chen/rust-paddle-ocr/blob/2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e/benches/bench_metrics.rs
benches/bench_metrics.rs
use criterion::{criterion_group, criterion_main, Criterion}; use image::DynamicImage; use ocr_rs::{DetModel, DetOptions, DetPrecisionMode, RecModel, RecOptions}; use std::time::Duration; fn setup() -> (DetModel, RecModel, DynamicImage) { // Load models - Complete before performance testing let det = DetModel::from_file("./models/ch_PP-OCRv4_det_infer.mnn", None) .expect("Failed to load detection model") .with_options( DetOptions::new() .with_box_border(12) .with_merge_boxes(false) .with_merge_threshold(1) .with_precision_mode(DetPrecisionMode::Fast), ); let rec = RecModel::from_file( "./models/ch_PP-OCRv4_rec_infer.mnn", "./models/ppocr_keys_v4.txt", None, ) .expect("Failed to load recognition model") .with_options(RecOptions::new()); // Load test image - Complete before performance testing let img = image::open("./res/1.png").expect("Failed to load test image"); (det, rec, img) } fn bench_detection(c: &mut Criterion) { let (det, _, img) = setup(); let mut group = c.benchmark_group("text_detection"); group.measurement_time(Duration::from_secs(10)); group.bench_function("det_model", |b| { b.iter(|| { det.detect(&img).expect("Detection failed"); }); }); group.finish(); } fn bench_recognition(c: &mut Criterion) { let (det, rec, img) = setup(); // First detect text areas and crop let detections = det .detect_and_crop(&img) .expect("Failed to detect and crop text images"); let mut group = c.benchmark_group("text_recognition"); group.measurement_time(Duration::from_secs(10)); group.bench_function("rec_model", |b| { b.iter(|| { // Only test the recognition of the first text area, skip if there is no text area if let Some((text_img, _)) = detections.first() { rec.recognize(text_img).expect("Recognition failed"); } }); }); group.finish(); } criterion_group!(benches, bench_detection, bench_recognition,); criterion_main!(benches);
rust
Apache-2.0
2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e
2026-01-04T20:19:51.104139Z
false
zibo-chen/rust-paddle-ocr
https://github.com/zibo-chen/rust-paddle-ocr/blob/2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e/examples/advanced.rs
examples/advanced.rs
//! 高级使用示例 //! //! Advanced Usage Example //! //! 展示如何使用底层 API 进行更精细的控制 use ocr_rs::{ DetModel, DetOptions, DetPrecisionMode, InferenceConfig, PrecisionMode, RecModel, RecOptions, }; use std::env; use std::error::Error; use std::time::Instant; fn main() -> Result<(), Box<dyn Error>> { // 初始化日志 env_logger::init(); // 获取命令行参数 let args: Vec<String> = env::args().collect(); if args.len() < 5 { eprintln!( "用法: {} <图像路径> <检测模型> <识别模型> <字符集>", args[0] ); std::process::exit(1); } let image_path = &args[1]; let det_model_path = &args[2]; let rec_model_path = &args[3]; let charset_path = &args[4]; // 配置推理引擎 let inference_config = InferenceConfig::new() .with_threads(4) .with_precision(PrecisionMode::Normal); println!("=== 高级 OCR 示例 ===\n"); // 1. 创建检测模型 (使用高精度模式) println!("加载检测模型..."); let det_options = DetOptions::new() .with_max_side_len(1280) .with_precision_mode(DetPrecisionMode::Fast) .with_box_threshold(0.5) .with_score_threshold(0.3) .with_merge_boxes(true) .with_merge_threshold(10); let det_model = DetModel::from_file(det_model_path, Some(inference_config.clone()))? .with_options(det_options); // 2. 创建识别模型 println!("加载识别模型..."); let rec_options = RecOptions::new().with_min_score(0.5).with_batch_size(8); let rec_model = RecModel::from_file(rec_model_path, charset_path, Some(inference_config))? .with_options(rec_options); println!("字符集大小: {}\n", rec_model.charset_size()); // 3. 加载图像 println!("加载图像: {}", image_path); let image = image::open(image_path)?; println!("图像大小: {}x{}\n", image.width(), image.height()); // 4. 执行检测 println!("执行文本检测..."); let det_start = Instant::now(); let detections = det_model.detect_and_crop(&image)?; let det_time = det_start.elapsed(); println!("检测耗时: {:?}", det_time); println!("检测到 {} 个文本区域\n", detections.len()); if detections.is_empty() { println!("未检测到文本区域"); return Ok(()); } // 5. 执行识别 println!("执行文本识别..."); let rec_start = Instant::now(); let images: Vec<_> = detections.iter().map(|(img, _)| img.clone()).collect(); let boxes: Vec<_> = detections.iter().map(|(_, bbox)| bbox.clone()).collect(); let rec_results = rec_model.recognize_batch(&images)?; let rec_time = rec_start.elapsed(); println!("识别耗时: {:?}\n", rec_time); // 6. 输出详细结果 println!("{:=<60}", ""); println!("识别结果:"); println!("{:=<60}\n", ""); for (i, (result, bbox)) in rec_results.iter().zip(boxes.iter()).enumerate() { if result.text.is_empty() { continue; } println!("[区域 {}]", i + 1); println!(" 位置: ({}, {})", bbox.rect.left(), bbox.rect.top()); println!(" 大小: {}x{}", bbox.rect.width(), bbox.rect.height()); println!(" 文本: {}", result.text); println!(" 置信度: {:.1}%", result.confidence * 100.0); // 显示字符级置信度 if !result.char_scores.is_empty() { print!(" 字符分数: "); for (ch, score) in &result.char_scores { print!("{}({:.0}%) ", ch, score * 100.0); } println!(); } println!(); } // 7. 统计信息 println!("{:=<60}", ""); println!("统计信息:"); println!(" 检测耗时: {:?}", det_time); println!(" 识别耗时: {:?}", rec_time); println!(" 总耗时: {:?}", det_time + rec_time); println!( " 平均每区域: {:?}", (det_time + rec_time) / (rec_results.len() as u32).max(1) ); Ok(()) }
rust
Apache-2.0
2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e
2026-01-04T20:19:51.104139Z
false
zibo-chen/rust-paddle-ocr
https://github.com/zibo-chen/rust-paddle-ocr/blob/2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e/examples/optimized_batch.rs
examples/optimized_batch.rs
//! 优化的批量识别示例 //! //! 展示新的优化功能: //! 1. 真正的批量推理 //! 2. 减少内存克隆 //! 3. 并行处理支持 use ocr_rs::{OcrEngine, OcrEngineConfig}; use std::time::Instant; fn main() -> Result<(), Box<dyn std::error::Error>> { // 初始化日志 env_logger::init(); println!("=== OCR 批量识别性能优化示例 ===\n"); // 模型路径 let det_model = "models/PP-OCRv5_mobile_det_fp16.mnn"; let rec_model = "models/PP-OCRv5_mobile_rec_fp16.mnn"; let charset = "models/ppocr_keys_v5.txt"; // 测试图像 let test_image = "res/Paste_1221144147238.png"; if !std::path::Path::new(test_image).exists() { eprintln!("测试图像不存在: {}", test_image); return Ok(()); } // ============ 1. 默认配置(序列批量推理)============ println!("1️⃣ 默认配置 - 序列批量推理"); let config_default = OcrEngineConfig::fast(); let engine_default = OcrEngine::new(det_model, rec_model, charset, Some(config_default))?; let image = image::open(test_image)?; let start = Instant::now(); let results_default = engine_default.recognize(&image)?; let duration_default = start.elapsed(); println!(" 检测到 {} 个文本区域", results_default.len()); println!(" 耗时: {:.2}ms", duration_default.as_secs_f64() * 1000.0); println!(); // ============ 2. 启用并行处理 ============ println!("2️⃣ 启用并行处理 - Rayon 并行识别"); let config_parallel = OcrEngineConfig::fast().with_parallel(true); let engine_parallel = OcrEngine::new(det_model, rec_model, charset, Some(config_parallel))?; let start = Instant::now(); let results_parallel = engine_parallel.recognize(&image)?; let duration_parallel = start.elapsed(); println!(" 检测到 {} 个文本区域", results_parallel.len()); println!(" 耗时: {:.2}ms", duration_parallel.as_secs_f64() * 1000.0); let speedup = duration_default.as_secs_f64() / duration_parallel.as_secs_f64(); println!(" 加速比: {:.2}x", speedup); println!(); // ============ 3. 显示识别结果 ============ println!("3️⃣ 识别结果:"); for (i, result) in results_parallel.iter().enumerate().take(5) { println!( " [{}] 文本: {}, 置信度: {:.2}%", i + 1, result.text, result.confidence * 100.0 ); } if results_parallel.len() > 5 { println!(" ... 还有 {} 个结果", results_parallel.len() - 5); } println!(); // ============ 4. 性能对比总结 ============ println!("📊 性能对比总结:"); println!( " 序列批量推理: {:.2}ms", duration_default.as_secs_f64() * 1000.0 ); println!( " 并行处理: {:.2}ms ({})", duration_parallel.as_secs_f64() * 1000.0, if duration_parallel < duration_default { "✅ 更快" } else { "⚠️ 更慢" } ); Ok(()) }
rust
Apache-2.0
2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e
2026-01-04T20:19:51.104139Z
false
zibo-chen/rust-paddle-ocr
https://github.com/zibo-chen/rust-paddle-ocr/blob/2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e/examples/visualize_det.rs
examples/visualize_det.rs
//! 可视化检测结果 use image::{GenericImageView, Rgb}; use imageproc::drawing::draw_hollow_rect_mut; use imageproc::rect::Rect; use std::env; use ocr_rs::{DetOptions, OcrEngine, OcrEngineConfig}; fn main() { let args: Vec<String> = env::args().collect(); if args.len() < 5 { eprintln!("用法: visualize_det <det_model> <rec_model> <keys> <image> [output]"); return; } let det_model = &args[1]; let rec_model = &args[2]; let keys_path = &args[3]; let image_path = &args[4]; let output_path = args.get(5).map(|s| s.as_str()).unwrap_or("det_result.png"); println!("加载模型..."); let config = OcrEngineConfig::new().with_det_options(DetOptions::fast()); let engine = OcrEngine::new(det_model, rec_model, keys_path, Some(config)).expect("创建引擎失败"); println!("加载图像: {}", image_path); let image = image::open(image_path).expect("加载图像失败"); let (width, height) = image.dimensions(); println!("图像尺寸: {}x{}", width, height); println!("执行检测..."); let boxes = engine.detect(&image).expect("检测失败"); println!("检测到 {} 个边界框", boxes.len()); // 创建可绘制的图像 let mut output_image = image.to_rgb8(); // 颜色列表 let colors = [ Rgb([255u8, 0, 0]), // 红 Rgb([0, 255, 0]), // 绿 Rgb([0, 0, 255]), // 蓝 Rgb([255, 255, 0]), // 黄 Rgb([255, 0, 255]), // 品红 Rgb([0, 255, 255]), // 青 Rgb([255, 128, 0]), // 橙 Rgb([128, 0, 255]), // 紫 ]; // 绘制每个边界框 for (i, text_box) in boxes.iter().enumerate() { let color = colors[i % colors.len()]; let rect = Rect::at(text_box.rect.left(), text_box.rect.top()) .of_size(text_box.rect.width(), text_box.rect.height()); // 绘制矩形边框(绘制多次使线条更粗) draw_hollow_rect_mut(&mut output_image, rect, color); // 稍微偏移再画一次,让边框更明显 if text_box.rect.left() > 0 && text_box.rect.top() > 0 { let rect2 = Rect::at(text_box.rect.left() - 1, text_box.rect.top() - 1) .of_size(text_box.rect.width() + 2, text_box.rect.height() + 2); draw_hollow_rect_mut(&mut output_image, rect2, color); } // 打印框信息 println!( "[{:2}] ({:4}, {:4}) {:4}x{:3}", i, text_box.rect.left(), text_box.rect.top(), text_box.rect.width(), text_box.rect.height() ); } // 保存结果 output_image.save(output_path).expect("保存图像失败"); println!("\n结果已保存到: {}", output_path); }
rust
Apache-2.0
2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e
2026-01-04T20:19:51.104139Z
false
zibo-chen/rust-paddle-ocr
https://github.com/zibo-chen/rust-paddle-ocr/blob/2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e/examples/benchmark_backends.rs
examples/benchmark_backends.rs
//! GPU 后端性能测试 //! //! GPU Backend Performance Benchmark //! //! 测试不同后端的推理速度,包括 CPU、Metal、OpenCL、Vulkan 等 use ocr_rs::{Backend, DetOptions, OcrEngine, OcrEngineConfig}; use std::error::Error; use std::time::{Duration, Instant}; /// 执行多次推理并统计性能 fn benchmark_backend( backend: Backend, image_path: &str, det_model: &str, rec_model: &str, charset: &str, iterations: usize, ) -> Result<(Duration, Duration, Duration, Duration), Box<dyn Error>> { println!("\n{}", "=".repeat(60)); println!("测试后端: {:?}", backend); println!("{}", "=".repeat(60)); // 配置引擎 let config = OcrEngineConfig::new() .with_backend(backend) .with_threads(4) .with_det_options(DetOptions::fast()); // 创建引擎 print!("创建引擎... "); let create_start = Instant::now(); let engine = OcrEngine::new(det_model, rec_model, charset, Some(config))?; let create_time = create_start.elapsed(); println!("完成 ({:?})", create_time); // 加载图像 let image = image::open(image_path)?; println!("图像尺寸: {}x{} 像素", image.width(), image.height()); // 预热 (首次推理通常较慢) print!("预热推理... "); let warmup_start = Instant::now(); let _ = engine.recognize(&image)?; let warmup_time = warmup_start.elapsed(); println!("完成 ({:?})", warmup_time); // 性能测试 println!("\n执行 {} 次推理...", iterations); let mut durations = Vec::with_capacity(iterations); for i in 1..=iterations { let start = Instant::now(); let results = engine.recognize(&image)?; let duration = start.elapsed(); durations.push(duration); print!("\r进度: {}/{} - 本次: {:?}", i, iterations, duration); } println!(); // 换行 // 计算统计数据 let total: Duration = durations.iter().sum(); let avg = total / iterations as u32; let min = *durations.iter().min().unwrap(); let max = *durations.iter().max().unwrap(); // 输出结果 println!("\n{}", "─".repeat(60)); println!("性能统计:"); println!("{}", "─".repeat(60)); println!(" 总耗时: {:?}", total); println!(" 平均耗时: {:?}", avg); println!(" 最短耗时: {:?}", min); println!(" 最长耗时: {:?}", max); println!(" 平均吞吐: {:.2} FPS", 1000.0 / avg.as_millis() as f64); Ok((total, avg, min, max)) } fn main() -> Result<(), Box<dyn Error>> { // 初始化日志 env_logger::init(); println!("\n{}", "#".repeat(60)); println!(" OCR 后端性能基准测试"); println!("{}", "#".repeat(60)); // 固定配置 let image_path = "/Users/chenzibo/git/rust-paddle-ocr/res/1.png"; let det_model = "models/PP-OCRv5_mobile_det_fp16.mnn"; let rec_model = "models/PP-OCRv5_mobile_rec_fp16.mnn"; let charset = "models/ppocr_keys_v5.txt"; let iterations = 10; println!("\n配置信息:"); println!(" 图像: {}", image_path); println!(" 检测模型: {}", det_model); println!(" 识别模型: {}", rec_model); println!(" 字符集: {}", charset); println!(" 测试次数: {}", iterations); // 要测试的后端列表 let backends = vec![ Backend::CPU, Backend::Metal, Backend::OpenCL, Backend::Vulkan, ]; // 存储所有后端的测试结果 let mut results = Vec::new(); // 测试每个后端 for backend in backends { match benchmark_backend( backend, image_path, det_model, rec_model, charset, iterations, ) { Ok((total, avg, min, max)) => { results.push((backend, total, avg, min, max)); } Err(e) => { eprintln!("\n❌ 后端 {:?} 测试失败: {}", backend, e); } } } // 输出汇总对比 if !results.is_empty() { println!("\n\n{}", "#".repeat(60)); println!(" 汇总对比"); println!("{}", "#".repeat(60)); println!( "\n{:<15} {:>12} {:>12} {:>12} {:>10}", "后端", "平均耗时", "最短耗时", "最长耗时", "吞吐(FPS)" ); println!("{}", "─".repeat(60)); for (backend, _total, avg, min, max) in &results { let fps = 1000.0 / avg.as_millis() as f64; println!( "{:<15} {:>12?} {:>12?} {:>12?} {:>10.2}", format!("{:?}", backend), avg, min, max, fps ); } // 找出最快的后端 if let Some((fastest_backend, _, fastest_avg, _, _)) = results.iter().min_by_key(|(_, _, avg, _, _)| avg) { println!( "\n🏆 最快后端: {:?} (平均 {:?})", fastest_backend, fastest_avg ); } } println!("\n{}", "#".repeat(60)); println!(" 测试完成"); println!("{}\n", "#".repeat(60)); Ok(()) }
rust
Apache-2.0
2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e
2026-01-04T20:19:51.104139Z
false
zibo-chen/rust-paddle-ocr
https://github.com/zibo-chen/rust-paddle-ocr/blob/2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e/examples/gpu_inference.rs
examples/gpu_inference.rs
//! GPU 推理示例 //! //! GPU Inference Example //! //! 展示如何配置和使用 GPU 加速 use ocr_rs::{Backend, DetOptions, OcrEngine, OcrEngineConfig}; use std::env; use std::error::Error; use std::time::Instant; fn main() -> Result<(), Box<dyn Error>> { // 初始化日志 env_logger::init(); // 获取命令行参数 let args: Vec<String> = env::args().collect(); if args.len() < 5 { eprintln!( "用法: {} <图像路径> <检测模型> <识别模型> <字符集> [后端]", args[0] ); eprintln!("后端选项: cpu, metal, opencl, vulkan"); std::process::exit(1); } let image_path = &args[1]; let det_model_path = &args[2]; let rec_model_path = &args[3]; let charset_path = &args[4]; let backend_str = args.get(5).map(|s| s.as_str()).unwrap_or("cpu"); // 选择后端 let backend = match backend_str.to_lowercase().as_str() { "cpu" => Backend::CPU, "metal" => Backend::Metal, "opencl" => Backend::OpenCL, "vulkan" => Backend::Vulkan, "opengl" => Backend::OpenGL, "cuda" => Backend::CUDA, _ => { eprintln!("未知后端: {}, 使用 CPU", backend_str); Backend::CPU } }; println!("=== GPU 推理示例 ===\n"); println!("使用后端: {:?}", backend); // 配置引擎 let config = OcrEngineConfig::new() .with_backend(backend) .with_threads(4) .with_det_options(DetOptions::fast()); println!("创建 OCR 引擎..."); let create_start = Instant::now(); let engine = OcrEngine::new(det_model_path, rec_model_path, charset_path, Some(config))?; let create_time = create_start.elapsed(); println!("引擎创建耗时: {:?}\n", create_time); // 加载图像 let image = image::open(image_path)?; println!( "图像: {} ({}x{})\n", image_path, image.width(), image.height() ); // 预热 (首次推理通常较慢) println!("预热推理..."); let _ = engine.recognize(&image)?; // 正式推理 println!("执行 OCR..."); let infer_start = Instant::now(); let results = engine.recognize(&image)?; let infer_time = infer_start.elapsed(); // 输出结果 println!("\n识别结果 ({} 个):", results.len()); println!("{:-<50}", ""); for result in &results { println!( "- {} (置信度: {:.1}%)", result.text, result.confidence * 100.0 ); } println!("\n{:-<50}", ""); println!("推理耗时: {:?}", infer_time); println!( "吞吐量: {:.1} 区域/秒", results.len() as f64 / infer_time.as_secs_f64() ); // 多次推理性能测试 println!("\n性能测试 (10次推理)..."); let bench_start = Instant::now(); for _ in 0..10 { let _ = engine.recognize(&image)?; } let bench_time = bench_start.elapsed(); println!("总耗时: {:?}", bench_time); println!("平均耗时: {:?}", bench_time / 10); Ok(()) }
rust
Apache-2.0
2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e
2026-01-04T20:19:51.104139Z
false
zibo-chen/rust-paddle-ocr
https://github.com/zibo-chen/rust-paddle-ocr/blob/2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e/examples/debug_ocr.rs
examples/debug_ocr.rs
//! OCR 调试示例 //! //! 功能: //! 1. 可视化文本检测框(绘制并保存) //! 2. 输出详细的识别结果(文本、置信度、坐标) //! 3. 适用于调试和验证 OCR 流程 use image::{GenericImageView, Rgb, RgbImage}; use imageproc::drawing::draw_hollow_rect_mut; use imageproc::rect::Rect; use ocr_rs::{OcrEngine, OcrEngineConfig}; use std::env; fn main() -> Result<(), Box<dyn std::error::Error>> { // 初始化日志 env_logger::init(); // 解析命令行参数 let args: Vec<String> = env::args().collect(); if args.len() < 5 { eprintln!("用法: debug_ocr <det_model> <rec_model> <keys> <image> [output]"); eprintln!("\n示例:"); eprintln!(" cargo run --example debug_ocr -- \\"); eprintln!(" models/PP-OCRv5_mobile_det.mnn \\"); eprintln!(" models/PP-OCRv5_mobile_rec.mnn \\"); eprintln!(" models/ppocr_keys_v5.txt \\"); eprintln!(" res/test.png \\"); eprintln!(" output_debug.png"); return Ok(()); } let det_model = &args[1]; let rec_model = &args[2]; let keys_path = &args[3]; let image_path = &args[4]; let output_path = args .get(5) .map(|s| s.as_str()) .unwrap_or("debug_ocr_result.png"); println!("╔════════════════════════════════════════════╗"); println!("║ OCR 调试工具 - Debug Tool ║"); println!("╚════════════════════════════════════════════╝\n"); // 1. 加载模型 println!("📦 加载模型..."); println!(" 检测模型: {}", det_model); println!(" 识别模型: {}", rec_model); println!(" 字符集: {}", keys_path); let config = OcrEngineConfig::fast().with_min_result_confidence(0.7); let engine = OcrEngine::new(det_model, rec_model, keys_path, Some(config))?; println!(" ✅ 模型加载成功"); // 2. 加载图像 println!("🖼️ 加载图像: {}", image_path); let image = image::open(image_path)?; let (width, height) = image.dimensions(); println!(" 尺寸: {}x{}\n", width, height); // 3. 执行 OCR 识别 println!("🔍 执行 OCR 识别..."); let results = engine.recognize(&image)?; println!(" ✅ 检测到 {} 个文本区域\n", results.len()); // 4. 输出详细识别结果到命令行 println!("╔════════════════════════════════════════════════════════════════════════╗"); println!("║ 识别结果详情 ║"); println!("╠════════════════════════════════════════════════════════════════════════╣"); for (i, result) in results.iter().enumerate() { let bbox = &result.bbox; println!("📝 [{:2}] 文本: {}", i + 1, result.text); println!( " 置信度: {:.2}% | 位置: ({}, {}) | 尺寸: {}x{}", result.confidence * 100.0, bbox.rect.left(), bbox.rect.top(), bbox.rect.width(), bbox.rect.height() ); // 如果有四个角点,也输出 if let Some(points) = &bbox.points { println!( " 角点: [{:.0},{:.0}] [{:.0},{:.0}] [{:.0},{:.0}] [{:.0},{:.0}]", points[0].x, points[0].y, points[1].x, points[1].y, points[2].x, points[2].y, points[3].x, points[3].y ); } println!(); } println!("╚════════════════════════════════════════════════════════════════════════╝\n"); // 5. 可视化:绘制边界框到图像 println!("🎨 生成可视化结果..."); let mut output_image = image.to_rgb8(); // 预定义颜色方案(8种明亮的颜色) let colors = [ Rgb([255u8, 0, 0]), // 红色 Rgb([0, 255, 0]), // 绿色 Rgb([0, 0, 255]), // 蓝色 Rgb([255, 255, 0]), // 黄色 Rgb([255, 0, 255]), // 品红 Rgb([0, 255, 255]), // 青色 Rgb([255, 128, 0]), // 橙色 Rgb([128, 0, 255]), // 紫色 ]; for (i, result) in results.iter().enumerate() { let color = colors[i % colors.len()]; let bbox = &result.bbox; // 绘制矩形边框(绘制2次让边框更明显) let rect = Rect::at(bbox.rect.left(), bbox.rect.top()) .of_size(bbox.rect.width(), bbox.rect.height()); draw_hollow_rect_mut(&mut output_image, rect, color); // 绘制加粗边框 if bbox.rect.left() > 0 && bbox.rect.top() > 0 { let rect2 = Rect::at(bbox.rect.left() - 1, bbox.rect.top() - 1) .of_size(bbox.rect.width() + 2, bbox.rect.height() + 2); draw_hollow_rect_mut(&mut output_image, rect2, color); } // 可选:绘制索引标签(如果需要在图像上显示序号) draw_index_label( &mut output_image, i + 1, bbox.rect.left(), bbox.rect.top(), color, ); } // 6. 保存可视化结果 output_image.save(output_path)?; println!(" ✅ 可视化结果已保存到: {}\n", output_path); // 7. 统计信息 println!("📊 统计信息:"); if !results.is_empty() { let avg_confidence = results.iter().map(|r| r.confidence).sum::<f32>() / results.len() as f32; let max_confidence = results .iter() .map(|r| r.confidence) .fold(0.0f32, |a, b| a.max(b)); let min_confidence = results .iter() .map(|r| r.confidence) .fold(1.0f32, |a, b| a.min(b)); println!(" 总文本区域数: {}", results.len()); println!(" 平均置信度: {:.2}%", avg_confidence * 100.0); println!(" 最高置信度: {:.2}%", max_confidence * 100.0); println!(" 最低置信度: {:.2}%", min_confidence * 100.0); } else { println!(" 未检测到任何文本"); } println!("\n✨ 调试完成!"); Ok(()) } /// 在图像上绘制索引标签 fn draw_index_label(image: &mut RgbImage, _index: usize, x: i32, y: i32, color: Rgb<u8>) { // 计算标签位置(稍微偏移到框的左上角外侧) let label_x = (x - 20).max(0); let label_y = (y - 20).max(0); // 绘制标签背景(小方块) let label_size = 18; for dy in 0..label_size { for dx in 0..label_size { let px = label_x + dx; let py = label_y + dy; if px >= 0 && py >= 0 && (px as u32) < image.width() && (py as u32) < image.height() { image.put_pixel(px as u32, py as u32, color); } } } }
rust
Apache-2.0
2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e
2026-01-04T20:19:51.104139Z
false
zibo-chen/rust-paddle-ocr
https://github.com/zibo-chen/rust-paddle-ocr/blob/2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e/examples/debug_det.rs
examples/debug_det.rs
//! 调试检测模型输出 use image::GenericImageView; use ocr_rs::mnn::{InferenceConfig, InferenceEngine}; use ocr_rs::postprocess::extract_boxes_from_mask_with_padding; use ocr_rs::preprocess::{preprocess_for_det, NormalizeParams}; use std::env; fn main() { let args: Vec<String> = env::args().collect(); if args.len() < 3 { eprintln!("用法: debug_det <模型路径> <图像路径>"); return; } let model_path = &args[1]; let image_path = &args[2]; println!("加载模型: {}", model_path); let config = InferenceConfig::default(); let engine = InferenceEngine::from_file(model_path, Some(config)).unwrap(); println!("模型输入形状: {:?}", engine.input_shape()); println!("模型输出形状: {:?}", engine.output_shape()); println!("是否动态形状: {}", engine.has_dynamic_shape()); println!("\n加载图像: {}", image_path); let image = image::open(image_path).unwrap(); let (original_w, original_h) = image.dimensions(); println!("图像尺寸: {}x{}", original_w, original_h); // 缩放图像 let max_side_len = 960u32; let max_dim = original_w.max(original_h); let (scaled, scaled_w, scaled_h) = if max_dim > max_side_len { let scale = max_side_len as f64 / max_dim as f64; let new_w = (original_w as f64 * scale).round() as u32; let new_h = (original_h as f64 * scale).round() as u32; println!("缩放到: {}x{}", new_w, new_h); ( image.resize_exact(new_w, new_h, image::imageops::FilterType::Lanczos3), new_w, new_h, ) } else { (image.clone(), original_w, original_h) }; // 预处理 let params = NormalizeParams::paddle_det(); let input = preprocess_for_det(&scaled, &params); println!("输入张量形状: {:?}", input.shape()); // 推理 println!("\n执行推理..."); let output = engine.run_dynamic(input.view().into_dyn()).unwrap(); let output_shape = output.shape(); println!("输出张量形状: {:?}", output_shape); let out_w = output_shape[3] as u32; let out_h = output_shape[2] as u32; println!("输出尺寸: {}x{}", out_w, out_h); println!("有效尺寸: {}x{}", scaled_w, scaled_h); // 分析输出 let output_data: Vec<f32> = output.iter().cloned().collect(); let min_val = output_data.iter().cloned().fold(f32::INFINITY, f32::min); let max_val = output_data .iter() .cloned() .fold(f32::NEG_INFINITY, f32::max); let mean_val: f32 = output_data.iter().sum::<f32>() / output_data.len() as f32; println!("输出值范围: [{:.6}, {:.6}]", min_val, max_val); println!("输出平均值: {:.6}", mean_val); // 使用不同的阈值测试边界框提取 let thresholds = [0.1, 0.2, 0.3, 0.4, 0.5]; println!("\n边界框提取测试:"); for thresh in thresholds { // 二值化 let binary_mask: Vec<u8> = output_data .iter() .map(|&v| if v > thresh { 255u8 } else { 0u8 }) .collect(); let boxes = extract_boxes_from_mask_with_padding( &binary_mask, out_w, out_h, scaled_w, scaled_h, original_w, original_h, 16, // min_area 0.5, // box_threshold ); println!(" 阈值 {:.1}: {} 个边界框", thresh, boxes.len()); for (i, b) in boxes.iter().take(3).enumerate() { println!( " [{i}] ({}, {}) {}x{}", b.rect.left(), b.rect.top(), b.rect.width(), b.rect.height() ); } } }
rust
Apache-2.0
2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e
2026-01-04T20:19:51.104139Z
false
zibo-chen/rust-paddle-ocr
https://github.com/zibo-chen/rust-paddle-ocr/blob/2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e/examples/debug_rec.rs
examples/debug_rec.rs
//! 调试识别模型输出 use image::GenericImageView; use ocr_rs::mnn::{InferenceConfig, InferenceEngine}; use ocr_rs::preprocess::{preprocess_for_rec, NormalizeParams}; use std::env; use std::fs; fn main() { let args: Vec<String> = env::args().collect(); if args.len() < 4 { eprintln!("用法: debug_rec <模型路径> <字符集路径> <图像路径>"); return; } let model_path = &args[1]; let charset_path = &args[2]; let image_path = &args[3]; // 加载字符集 println!("加载字符集: {}", charset_path); let charset_content = fs::read_to_string(charset_path).expect("读取字符集失败"); let mut charset: Vec<char> = vec![' ']; // blank token for ch in charset_content.chars() { if ch != '\n' && ch != '\r' { charset.push(ch); } } charset.push(' '); // padding token println!("字符集大小: {}", charset.len()); println!("前10个字符: {:?}", &charset[..10.min(charset.len())]); // 加载模型 println!("\n加载模型: {}", model_path); let config = InferenceConfig::default(); let engine = InferenceEngine::from_file(model_path, Some(config)).unwrap(); println!("模型输入形状: {:?}", engine.input_shape()); println!("模型输出形状: {:?}", engine.output_shape()); println!("是否动态形状: {}", engine.has_dynamic_shape()); // 加载图像 println!("\n加载图像: {}", image_path); let image = image::open(image_path).expect("加载图像失败"); let (w, h) = image.dimensions(); println!("图像尺寸: {}x{}", w, h); // 预处理 let target_height = 48u32; let params = NormalizeParams::paddle_rec(); let input = preprocess_for_rec(&image, target_height, &params); println!("输入张量形状: {:?}", input.shape()); // 推理 println!("\n执行推理..."); let output = engine.run_dynamic(input.view().into_dyn()).unwrap(); let output_shape = output.shape(); println!("输出张量形状: {:?}", output_shape); // 分析输出 let output_data: Vec<f32> = output.iter().cloned().collect(); let min_val = output_data.iter().cloned().fold(f32::INFINITY, f32::min); let max_val = output_data .iter() .cloned() .fold(f32::NEG_INFINITY, f32::max); println!("输出值范围: [{:.4}, {:.4}]", min_val, max_val); // 解析输出形状 let (seq_len, num_classes) = if output_shape.len() == 3 { (output_shape[1], output_shape[2]) } else if output_shape.len() == 2 { (output_shape[0], output_shape[1]) } else { eprintln!("无效的输出形状!"); return; }; println!("序列长度: {}, 类别数: {}", seq_len, num_classes); println!("字符集大小: {} (应该接近类别数)", charset.len()); // CTC 解码 println!("\n=== CTC 解码 ==="); let mut decoded_text = String::new(); let mut prev_idx = 0usize; let mut char_details = Vec::new(); for t in 0..seq_len { let start = t * num_classes; let end = start + num_classes; let probs = &output_data[start..end]; // 找最大值 let (max_idx, &max_val) = probs .iter() .enumerate() .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap()) .unwrap(); // 计算 softmax 分数 let max_logit = probs.iter().cloned().fold(f32::NEG_INFINITY, f32::max); let sum_exp: f32 = probs.iter().map(|&x| (x - max_logit).exp()).sum(); let score = (max_val - max_logit).exp() / sum_exp; if t < 10 || (max_idx != 0 && max_idx != prev_idx) { let ch = if max_idx < charset.len() { charset[max_idx] } else { '?' }; if t < 10 { println!( " t={:3}: idx={:5}, val={:8.4}, score={:.4}, char='{}'", t, max_idx, max_val, score, ch ); } } // CTC 解码规则 if max_idx != 0 && max_idx != prev_idx { if max_idx < charset.len() { let ch = charset[max_idx]; decoded_text.push(ch); char_details.push((ch, score)); } } prev_idx = max_idx; } println!("\n=== 解码结果 ==="); println!("文本: '{}'", decoded_text); println!("字符数: {}", decoded_text.len()); if !char_details.is_empty() { println!("字符详情 (前20个):"); for (i, (ch, score)) in char_details.iter().take(20).enumerate() { println!(" [{:2}] '{}' ({:.2}%)", i, ch, score * 100.0); } } }
rust
Apache-2.0
2ef84ebbc1d07d8ea6296340e3c05496bd7dfe8e
2026-01-04T20:19:51.104139Z
false
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/imaging/src/lib.rs
wsdl_rs/imaging/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use onvif as tt; use std::str::FromStr; use validate::Validate; use xsd_macro_utils::*; use yaserde_derive::{YaDeserialize, YaSerialize}; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "timg", namespace = "timg: http://www.onvif.org/ver20/imaging/wsdl" )] pub struct GetServiceCapabilities {} impl Validate for GetServiceCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "timg", namespace = "timg: http://www.onvif.org/ver20/imaging/wsdl" )] pub struct GetServiceCapabilitiesResponse { // The capabilities for the imaging service is returned in the Capabilities // element. #[yaserde(prefix = "timg", rename = "Capabilities")] pub capabilities: Capabilities, } impl Validate for GetServiceCapabilitiesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "timg", namespace = "timg: http://www.onvif.org/ver20/imaging/wsdl" )] pub struct Capabilities { // Indicates whether or not Image Stabilization feature is supported. // The use of this capability is deprecated, a client should use GetOption // to find out if image stabilization is supported. #[yaserde(attribute, rename = "ImageStabilization")] pub image_stabilization: Option<bool>, // Indicates whether or not Imaging Presets feature is supported. #[yaserde(attribute, rename = "Presets")] pub presets: Option<bool>, // Indicates whether or not imaging preset settings can be updated. #[yaserde(attribute, rename = "AdaptablePreset")] pub adaptable_preset: Option<bool>, } impl Validate for Capabilities {} // pub type Capabilities = Capabilities; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "timg", namespace = "timg: http://www.onvif.org/ver20/imaging/wsdl" )] pub struct GetImagingSettings { // Reference token to the VideoSource for which the ImagingSettings. #[yaserde(prefix = "timg", rename = "VideoSourceToken")] pub video_source_token: tt::ReferenceToken, } impl Validate for GetImagingSettings {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "timg", namespace = "timg: http://www.onvif.org/ver20/imaging/wsdl" )] pub struct GetImagingSettingsResponse { // ImagingSettings for the VideoSource that was requested. #[yaserde(prefix = "timg", rename = "ImagingSettings")] pub imaging_settings: tt::ImagingSettings20, } impl Validate for GetImagingSettingsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "timg", namespace = "timg: http://www.onvif.org/ver20/imaging/wsdl" )] pub struct SetImagingSettings { #[yaserde(prefix = "timg", rename = "VideoSourceToken")] pub video_source_token: tt::ReferenceToken, #[yaserde(prefix = "timg", rename = "ImagingSettings")] pub imaging_settings: tt::ImagingSettings20, #[yaserde(prefix = "timg", rename = "ForcePersistence")] pub force_persistence: bool, } impl Validate for SetImagingSettings {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "timg", namespace = "timg: http://www.onvif.org/ver20/imaging/wsdl" )] pub struct SetImagingSettingsResponse {} impl Validate for SetImagingSettingsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "timg", namespace = "timg: http://www.onvif.org/ver20/imaging/wsdl" )] pub struct GetOptions { // Reference token to the VideoSource for which the imaging parameter // options are requested. #[yaserde(prefix = "timg", rename = "VideoSourceToken")] pub video_source_token: tt::ReferenceToken, } impl Validate for GetOptions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "timg", namespace = "timg: http://www.onvif.org/ver20/imaging/wsdl" )] pub struct GetOptionsResponse { // Valid ranges for the imaging parameters that are categorized as device // specific. #[yaserde(prefix = "timg", rename = "ImagingOptions")] pub imaging_options: tt::ImagingOptions20, } impl Validate for GetOptionsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "timg", namespace = "timg: http://www.onvif.org/ver20/imaging/wsdl" )] pub struct Move { // Reference to the VideoSource for the requested move (focus) operation. #[yaserde(prefix = "timg", rename = "VideoSourceToken")] pub video_source_token: tt::ReferenceToken, // Content of the requested move (focus) operation. #[yaserde(prefix = "timg", rename = "Focus")] pub focus: Vec<tt::FocusMove>, } impl Validate for Move {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "timg", namespace = "timg: http://www.onvif.org/ver20/imaging/wsdl" )] pub struct MoveResponse {} impl Validate for MoveResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "timg", namespace = "timg: http://www.onvif.org/ver20/imaging/wsdl" )] pub struct GetMoveOptions { // Reference token to the VideoSource for the requested move options. #[yaserde(prefix = "timg", rename = "VideoSourceToken")] pub video_source_token: tt::ReferenceToken, } impl Validate for GetMoveOptions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "timg", namespace = "timg: http://www.onvif.org/ver20/imaging/wsdl" )] pub struct GetMoveOptionsResponse { // Valid ranges for the focus lens move options. #[yaserde(prefix = "timg", rename = "MoveOptions")] pub move_options: tt::MoveOptions20, } impl Validate for GetMoveOptionsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "timg", namespace = "timg: http://www.onvif.org/ver20/imaging/wsdl" )] pub struct Stop { // Reference token to the VideoSource where the focus movement should be // stopped. #[yaserde(prefix = "timg", rename = "VideoSourceToken")] pub video_source_token: tt::ReferenceToken, } impl Validate for Stop {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "timg", namespace = "timg: http://www.onvif.org/ver20/imaging/wsdl" )] pub struct StopResponse {} impl Validate for StopResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "timg", namespace = "timg: http://www.onvif.org/ver20/imaging/wsdl" )] pub struct GetStatus { // Reference token to the VideoSource where the imaging status should be // requested. #[yaserde(prefix = "timg", rename = "VideoSourceToken")] pub video_source_token: tt::ReferenceToken, } impl Validate for GetStatus {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "timg", namespace = "timg: http://www.onvif.org/ver20/imaging/wsdl" )] pub struct GetStatusResponse { // Requested imaging status. #[yaserde(prefix = "timg", rename = "Status")] pub status: tt::ImagingStatus20, } impl Validate for GetStatusResponse {} // Describes standard Imaging Preset types, used to facilitate Multi-language // support and client display. // "Custom" Type shall be used when Imaging Preset Name does not match any of // the types included in the standard classification. #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct ImagingPresetType(pub String); impl Validate for ImagingPresetType {} // Type describing the Imaging Preset settings. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "timg", namespace = "timg: http://www.onvif.org/ver20/imaging/wsdl" )] pub struct ImagingPreset { // Human readable name of the Imaging Preset. #[yaserde(prefix = "timg", rename = "Name")] pub name: tt::Name, // Unique identifier of this Imaging Preset. #[yaserde(attribute, rename = "token")] pub token: tt::ReferenceToken, // Indicates Imaging Preset Type. Use timg:ImagingPresetType. // Used for multi-language support and display. #[yaserde(attribute, rename = "type")] pub _type: String, } impl Validate for ImagingPreset {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "timg", namespace = "timg: http://www.onvif.org/ver20/imaging/wsdl" )] pub struct GetPresets { // A reference to the VideoSource where the operation should take place. #[yaserde(prefix = "timg", rename = "VideoSourceToken")] pub video_source_token: tt::ReferenceToken, } impl Validate for GetPresets {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "timg", namespace = "timg: http://www.onvif.org/ver20/imaging/wsdl" )] pub struct GetPresetsResponse { // List of Imaging Presets which are available for the requested // VideoSource. #[yaserde(prefix = "timg", rename = "Preset")] pub preset: Vec<ImagingPreset>, } impl Validate for GetPresetsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "timg", namespace = "timg: http://www.onvif.org/ver20/imaging/wsdl" )] pub struct GetCurrentPreset { // Reference token to the VideoSource where the current Imaging Preset // should be requested. #[yaserde(prefix = "timg", rename = "VideoSourceToken")] pub video_source_token: tt::ReferenceToken, } impl Validate for GetCurrentPreset {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "timg", namespace = "timg: http://www.onvif.org/ver20/imaging/wsdl" )] pub struct GetCurrentPresetResponse { // Current Imaging Preset in use for the specified Video Source. #[yaserde(prefix = "timg", rename = "Preset")] pub preset: Option<ImagingPreset>, } impl Validate for GetCurrentPresetResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "timg", namespace = "timg: http://www.onvif.org/ver20/imaging/wsdl" )] pub struct SetCurrentPreset { // Reference token to the VideoSource to which the specified Imaging Preset // should be applied. #[yaserde(prefix = "timg", rename = "VideoSourceToken")] pub video_source_token: tt::ReferenceToken, // Reference token to the Imaging Preset to be applied to the specified // Video Source. #[yaserde(prefix = "timg", rename = "PresetToken")] pub preset_token: tt::ReferenceToken, } impl Validate for SetCurrentPreset {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "timg", namespace = "timg: http://www.onvif.org/ver20/imaging/wsdl" )] pub struct SetCurrentPresetResponse {} impl Validate for SetCurrentPresetResponse {} // Returns the capabilities of the imaging service. The result is returned in a // typed answer. pub async fn get_service_capabilities<T: transport::Transport>( transport: &T, request: &GetServiceCapabilities, ) -> Result<GetServiceCapabilitiesResponse, transport::Error> { transport::request(transport, request).await } // Get the ImagingConfiguration for the requested VideoSource. pub async fn get_imaging_settings<T: transport::Transport>( transport: &T, request: &GetImagingSettings, ) -> Result<GetImagingSettingsResponse, transport::Error> { transport::request(transport, request).await } // Set the ImagingConfiguration for the requested VideoSource. pub async fn set_imaging_settings<T: transport::Transport>( transport: &T, request: &SetImagingSettings, ) -> Result<SetImagingSettingsResponse, transport::Error> { transport::request(transport, request).await } // This operation gets the valid ranges for the imaging parameters that have // device specific ranges. // This command is mandatory for all device implementing the imaging service. // The command returns all supported parameters and their ranges // such that these can be applied to the SetImagingSettings command. pub async fn get_options<T: transport::Transport>( transport: &T, request: &GetOptions, ) -> Result<GetOptionsResponse, transport::Error> { transport::request(transport, request).await } // The Move command moves the focus lens in an absolute, a relative or in a // continuous manner from its current position. // The speed argument is optional for absolute and relative control, but // required for continuous. If no speed argument is used, the default speed is // used. // Focus adjustments through this operation will turn off the autofocus. A // device with support for remote focus control should support absolute, // relative or continuous control through the Move operation. The supported // MoveOpions are signalled via the GetMoveOptions command. // At least one focus control capability is required for this operation to be // functional. pub async fn _move<T: transport::Transport>( transport: &T, request: &Move, ) -> Result<MoveResponse, transport::Error> { transport::request(transport, request).await } // Imaging move operation options supported for the Video source. pub async fn get_move_options<T: transport::Transport>( transport: &T, request: &GetMoveOptions, ) -> Result<GetMoveOptionsResponse, transport::Error> { transport::request(transport, request).await } // The Stop command stops all ongoing focus movements of the lense. A device // with support for remote focus control as signalled via // the GetMoveOptions supports this command. pub async fn stop<T: transport::Transport>( transport: &T, request: &Stop, ) -> Result<StopResponse, transport::Error> { transport::request(transport, request).await } // Via this command the current status of the Move operation can be requested. // Supported for this command is available if the support for the Move operation // is signalled via GetMoveOptions. pub async fn get_status<T: transport::Transport>( transport: &T, request: &GetStatus, ) -> Result<GetStatusResponse, transport::Error> { transport::request(transport, request).await } // Via this command the list of available Imaging Presets can be requested. pub async fn get_presets<T: transport::Transport>( transport: &T, request: &GetPresets, ) -> Result<GetPresetsResponse, transport::Error> { transport::request(transport, request).await } // Via this command the last Imaging Preset applied can be requested. // If the camera configuration does not match any of the existing Imaging // Presets, the output of GetCurrentPreset shall be Empty. // GetCurrentPreset shall return 0 if Imaging Presets are not supported by the // Video Source. pub async fn get_current_preset<T: transport::Transport>( transport: &T, request: &GetCurrentPreset, ) -> Result<GetCurrentPresetResponse, transport::Error> { transport::request(transport, request).await } // The SetCurrentPreset command shall request a given Imaging Preset to be // applied to the specified Video Source. // SetCurrentPreset shall only be available for Video Sources with Imaging // Presets Capability. // Imaging Presets are defined by the Manufacturer, and offered as a tool to // simplify Imaging Settings adjustments for specific scene content. // When the new Imaging Preset is applied by SetCurrentPreset, the Device shall // adjust the Video Source settings to match those defined by the specified // Imaging Preset. pub async fn set_current_preset<T: transport::Transport>( transport: &T, request: &SetCurrentPreset, ) -> Result<SetCurrentPresetResponse, transport::Error> { transport::request(transport, request).await }
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
false
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/ws_addr/src/lib.rs
wsdl_rs/ws_addr/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use std::str::FromStr; use validate::Validate; use xsd_macro_utils::*; use yaserde_derive::{YaDeserialize, YaSerialize}; pub type EndpointReference = EndpointReferenceType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tns", namespace = "tns: http://www.w3.org/2005/08/addressing" )] pub struct EndpointReferenceType { #[yaserde(prefix = "tns", rename = "Address")] pub address: String, #[yaserde(prefix = "tns", rename = "ReferenceParameters")] pub reference_parameters: Option<ReferenceParameters>, #[yaserde(prefix = "tns", rename = "Metadata")] pub metadata: Option<Metadata>, } impl Validate for EndpointReferenceType {} pub type ReferenceParameters = ReferenceParametersType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tns", namespace = "tns: http://www.w3.org/2005/08/addressing" )] pub struct ReferenceParametersType {} impl Validate for ReferenceParametersType {} pub type Metadata = MetadataType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tns", namespace = "tns: http://www.w3.org/2005/08/addressing" )] pub struct MetadataType {} impl Validate for MetadataType {} pub type MessageID = AttributedURIType; pub type RelatesTo = RelatesToType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tns", namespace = "tns: http://www.w3.org/2005/08/addressing" )] pub struct RelatesToType { #[yaserde(attribute, rename = "RelationshipType")] pub relationship_type: Option<RelationshipTypeOpenEnum>, } impl Validate for RelatesToType {} #[derive(PartialEq, Debug, UtilsUnionSerDe)] pub enum RelationshipTypeOpenEnum { RelationshipType(RelationshipType), AnyURI(String), __Unknown__(String), } impl Default for RelationshipTypeOpenEnum { fn default() -> RelationshipTypeOpenEnum { Self::__Unknown__("No valid variants".into()) } } impl Validate for RelationshipTypeOpenEnum {} #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct RelationshipType(pub String); impl Validate for RelationshipType {} pub type ReplyTo = EndpointReferenceType; pub type From = EndpointReferenceType; pub type FaultTo = EndpointReferenceType; pub type To = AttributedURIType; pub type Action = AttributedURIType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tns", namespace = "tns: http://www.w3.org/2005/08/addressing" )] pub struct AttributedURIType {} impl Validate for AttributedURIType {} pub type IsReferenceParameter = bool; #[derive(PartialEq, Debug, UtilsUnionSerDe)] pub enum FaultCodesOpenEnumType { FaultCodesType(FaultCodesType), Qname(String), __Unknown__(String), } impl Default for FaultCodesOpenEnumType { fn default() -> FaultCodesOpenEnumType { Self::__Unknown__("No valid variants".into()) } } impl Validate for FaultCodesOpenEnumType {} #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct FaultCodesType(pub String); impl Validate for FaultCodesType {} pub type RetryAfter = AttributedUnsignedLongType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tns", namespace = "tns: http://www.w3.org/2005/08/addressing" )] pub struct AttributedUnsignedLongType {} impl Validate for AttributedUnsignedLongType {} pub type ProblemHeaderQName = AttributedQNameType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tns", namespace = "tns: http://www.w3.org/2005/08/addressing" )] pub struct AttributedQNameType {} impl Validate for AttributedQNameType {} pub type ProblemIRI = AttributedURIType; pub type ProblemAction = ProblemActionType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tns", namespace = "tns: http://www.w3.org/2005/08/addressing" )] pub struct ProblemActionType { #[yaserde(prefix = "tns", rename = "Action")] pub action: Option<Action>, #[yaserde(prefix = "tns", rename = "SoapAction")] pub soap_action: Option<String>, } impl Validate for ProblemActionType {}
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
false
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/ws_discovery/src/lib.rs
wsdl_rs/ws_discovery/src/lib.rs
pub mod probe { use yaserde_derive::YaSerialize; #[derive(Default, Eq, PartialEq, Debug, YaSerialize)] #[yaserde( prefix = "d", namespace = "d: http://schemas.xmlsoap.org/ws/2005/04/discovery" )] pub struct Probe { #[yaserde(prefix = "d", rename = "Types")] pub types: String, } #[derive(Default, Eq, PartialEq, Debug, YaSerialize)] #[yaserde( prefix = "s", namespace = "s: http://www.w3.org/2003/05/soap-envelope", namespace = "w: http://schemas.xmlsoap.org/ws/2004/08/addressing" )] pub struct Header { #[yaserde(prefix = "w", rename = "MessageID")] pub message_id: String, #[yaserde(prefix = "w", rename = "To")] pub to: String, #[yaserde(prefix = "w", rename = "Action")] pub action: String, } #[derive(Default, Eq, PartialEq, Debug, YaSerialize)] #[yaserde( prefix = "s", namespace = "s: http://www.w3.org/2003/05/soap-envelope", namespace = "d: http://schemas.xmlsoap.org/ws/2005/04/discovery" )] pub struct Body { #[yaserde(prefix = "d", rename = "Probe")] pub probe: Probe, } #[derive(Default, Eq, PartialEq, Debug, YaSerialize)] #[yaserde( prefix = "s", namespace = "s: http://www.w3.org/2003/05/soap-envelope", namespace = "d: http://schemas.xmlsoap.org/ws/2005/04/discovery", namespace = "w: http://schemas.xmlsoap.org/ws/2004/08/addressing" )] pub struct Envelope { #[yaserde(prefix = "s", rename = "Header")] pub header: Header, #[yaserde(prefix = "s", rename = "Body")] pub body: Body, } } pub mod endpoint_reference { use yaserde_derive::YaDeserialize; #[derive(Default, Eq, PartialEq, Debug, YaDeserialize)] #[yaserde( prefix = "wsa", namespace = "wsa: http://schemas.xmlsoap.org/ws/2004/08/addressing" )] pub struct EndpointReference { #[yaserde(prefix = "wsa", rename = "Address")] pub address: String, } } pub mod probe_matches { use crate::endpoint_reference::EndpointReference; use percent_encoding::percent_decode_str; use url::Url; use yaserde_derive::YaDeserialize; #[derive(Default, Eq, PartialEq, Debug, YaDeserialize)] #[yaserde( prefix = "d", namespace = "d: http://schemas.xmlsoap.org/ws/2005/04/discovery", namespace = "wsa: http://schemas.xmlsoap.org/ws/2004/08/addressing" )] pub struct ProbeMatch { #[yaserde(prefix = "wsa", rename = "EndpointReference")] pub endpoint_reference: EndpointReference, #[yaserde(prefix = "d", rename = "Types")] pub types: String, #[yaserde(prefix = "d", rename = "Scopes")] pub scopes: String, #[yaserde(prefix = "d", rename = "XAddrs")] pub x_addrs: String, } #[derive(Default, Eq, PartialEq, Debug, YaDeserialize)] #[yaserde( prefix = "d", namespace = "d: http://schemas.xmlsoap.org/ws/2005/04/discovery" )] pub struct ProbeMatches { #[yaserde(prefix = "d", rename = "ProbeMatch")] pub probe_match: Vec<ProbeMatch>, } #[derive(Default, Eq, PartialEq, Debug, YaDeserialize)] #[yaserde( prefix = "s", namespace = "s: http://www.w3.org/2003/05/soap-envelope", namespace = "w: http://schemas.xmlsoap.org/ws/2004/08/addressing" )] pub struct Header { #[yaserde(prefix = "w", rename = "RelatesTo")] pub relates_to: String, } #[derive(Default, Eq, PartialEq, Debug, YaDeserialize)] #[yaserde( prefix = "s", namespace = "s: http://www.w3.org/2003/05/soap-envelope", namespace = "d: http://schemas.xmlsoap.org/ws/2005/04/discovery" )] pub struct Body { #[yaserde(prefix = "d", rename = "ProbeMatches")] pub probe_matches: ProbeMatches, } #[derive(Default, Eq, PartialEq, Debug, YaDeserialize)] #[yaserde(prefix = "s", namespace = "s: http://www.w3.org/2003/05/soap-envelope")] pub struct Envelope { #[yaserde(prefix = "s", rename = "Header")] pub header: Header, #[yaserde(prefix = "s", rename = "Body")] pub body: Body, } impl ProbeMatch { pub fn types(&self) -> Vec<&str> { self.types .split_whitespace() .map(|t: &str| { // Remove WSDL prefixes match t.find(':') { Some(idx) => t.split_at(idx + 1).1, None => t, } }) .collect() } pub fn scopes(&self) -> Vec<Url> { Self::split_string_to_urls(&self.scopes) } pub fn x_addrs(&self) -> Vec<Url> { Self::split_string_to_urls(&self.x_addrs) } pub fn name(&self) -> Option<String> { self.find_in_scopes("onvif://www.onvif.org/name/") } pub fn hardware(&self) -> Option<String> { self.find_in_scopes("onvif://www.onvif.org/hardware/") } pub fn endpoint_reference_address(&self) -> String { self.endpoint_reference.address.to_string() } pub fn find_in_scopes(&self, prefix: &str) -> Option<String> { self.scopes().iter().find_map(|url| { url.as_str() .strip_prefix(prefix) .map(|s| percent_decode_str(s).decode_utf8_lossy().to_string()) }) } fn split_string_to_urls(s: &str) -> Vec<Url> { s.split_whitespace() .filter_map(|addr| Url::parse(addr).ok()) .collect() } } #[test] fn probe_match() { let ser = r#"<?xml version="1.0" encoding="utf-8"?> <wsd:ProbeMatch xmlns:wsd="http://schemas.xmlsoap.org/ws/2005/04/discovery" xmlns:dn="http://www.onvif.org/ver10/network/wsdl" xmlns:tds="http://www.onvif.org/ver10/device/wsdl"> <wsd:Types> dn:NetworkVideoTransmitter tds:Device </wsd:Types> <wsd:Scopes> onvif://www.onvif.org/name/My%20Camera%202000 onvif://www.onvif.org/hardware/My-HW-2000 onvif://www.onvif.org/type/audio_encoder onvif://www.onvif.org/type/video_encoder onvif://www.onvif.org/type/ptz onvif://www.onvif.org/Profile/G onvif://www.onvif.org/Profile/Streaming </wsd:Scopes> <wsd:XAddrs> http://192.168.0.100:80/onvif/device_service http://10.0.0.200:80/onvif/device_service </wsd:XAddrs> </wsd:ProbeMatch> "#; let de: ProbeMatch = yaserde::de::from_str(ser).unwrap(); assert_eq!(de.name(), Some("My Camera 2000".to_string())); assert_eq!(de.hardware(), Some("My-HW-2000".to_string())); assert!(de .find_in_scopes("onvif://www.onvif.org/type/video_encoder") .is_some()); assert!(de .find_in_scopes("onvif://www.onvif.org/type/video_analytics") .is_none()); assert_eq!( de.x_addrs(), vec![ Url::parse("http://192.168.0.100:80/onvif/device_service").unwrap(), Url::parse("http://10.0.0.200:80/onvif/device_service").unwrap(), ] ); assert_eq!(de.types(), vec!["NetworkVideoTransmitter", "Device"]); } }
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
false
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/bf_2/src/lib.rs
wsdl_rs/bf_2/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use validate::Validate; use ws_addr as wsa; use xml_xsd as xml; use xsd_types::types as xsd; use yaserde_derive::{YaDeserialize, YaSerialize}; // pub type BaseFault = BaseFaultType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsrf-bf", namespace = "wsrf-bf: http://docs.oasis-open.org/wsrf/bf-2" )] pub struct BaseFaultType { #[yaserde(prefix = "wsrf-bf", rename = "Timestamp")] pub timestamp: xsd::DateTime, #[yaserde(prefix = "wsrf-bf", rename = "Originator")] pub originator: wsa::EndpointReferenceType, #[yaserde(prefix = "wsrf-bf", rename = "ErrorCode")] pub error_code: base_fault_type::ErrorCodeType, #[yaserde(prefix = "wsrf-bf", rename = "Description")] pub description: Vec<base_fault_type::DescriptionType>, #[yaserde(prefix = "wsrf-bf", rename = "FaultCause")] pub fault_cause: base_fault_type::FaultCauseType, } impl Validate for BaseFaultType {} pub mod base_fault_type { use super::*; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsrf-bf", namespace = "wsrf-bf: http://docs.oasis-open.org/wsrf/bf-2" )] pub struct ErrorCodeType { #[yaserde(attribute, rename = "dialect")] pub dialect: String, } impl Validate for ErrorCodeType {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsrf-bf", namespace = "wsrf-bf: http://docs.oasis-open.org/wsrf/bf-2" )] pub struct DescriptionType { #[yaserde(attribute, prefix = "xml" rename = "lang")] pub lang: Option<xml::Lang>, } impl Validate for DescriptionType {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsrf-bf", namespace = "wsrf-bf: http://docs.oasis-open.org/wsrf/bf-2" )] pub struct FaultCauseType {} impl Validate for FaultCauseType {} }
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
false
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/replay/src/lib.rs
wsdl_rs/replay/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use onvif as tt; use validate::Validate; use yaserde_derive::{YaDeserialize, YaSerialize}; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trp", namespace = "trp: http://www.onvif.org/ver10/replay/wsdl" )] pub struct GetServiceCapabilities {} impl Validate for GetServiceCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trp", namespace = "trp: http://www.onvif.org/ver10/replay/wsdl" )] pub struct GetServiceCapabilitiesResponse { // The capabilities for the replay service is returned in the Capabilities // element. #[yaserde(prefix = "trp", rename = "Capabilities")] pub capabilities: Capabilities, } impl Validate for GetServiceCapabilitiesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trp", namespace = "trp: http://www.onvif.org/ver10/replay/wsdl" )] pub struct Capabilities { // Indicator that the Device supports reverse playback as defined in the // ONVIF Streaming Specification. #[yaserde(attribute, rename = "ReversePlayback")] pub reverse_playback: Option<bool>, // The list contains two elements defining the minimum and maximum valid // values supported as session timeout in seconds. #[yaserde(attribute, rename = "SessionTimeoutRange")] pub session_timeout_range: Option<tt::FloatAttrList>, // Indicates support for RTP/RTSP/TCP. #[yaserde(attribute, rename = "RTP_RTSP_TCP")] pub rtp_rtsp_tcp: Option<bool>, // If playback streaming over WebSocket is supported, this shall return the // RTSP WebSocket URI as described in Streaming Specification Section // 5.1.1.5. #[yaserde(attribute, rename = "RTSPWebSocketUri")] pub rtsp_web_socket_uri: Option<String>, } impl Validate for Capabilities {} // pub type Capabilities = Capabilities; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trp", namespace = "trp: http://www.onvif.org/ver10/replay/wsdl" )] pub struct GetReplayUri { // Specifies the connection parameters to be used for the stream. The URI // that is returned may depend on these parameters. #[yaserde(prefix = "trp", rename = "StreamSetup")] pub stream_setup: tt::StreamSetup, // The identifier of the recording to be streamed. #[yaserde(prefix = "trp", rename = "RecordingToken")] pub recording_token: tt::ReferenceToken, } impl Validate for GetReplayUri {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trp", namespace = "trp: http://www.onvif.org/ver10/replay/wsdl" )] pub struct GetReplayUriResponse { // The URI to which the client should connect in order to stream the // recording. #[yaserde(prefix = "trp", rename = "Uri")] pub uri: String, } impl Validate for GetReplayUriResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trp", namespace = "trp: http://www.onvif.org/ver10/replay/wsdl" )] pub struct SetReplayConfiguration { // Description of the new replay configuration parameters. #[yaserde(prefix = "trp", rename = "Configuration")] pub configuration: tt::ReplayConfiguration, } impl Validate for SetReplayConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trp", namespace = "trp: http://www.onvif.org/ver10/replay/wsdl" )] pub struct SetReplayConfigurationResponse {} impl Validate for SetReplayConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trp", namespace = "trp: http://www.onvif.org/ver10/replay/wsdl" )] pub struct GetReplayConfiguration {} impl Validate for GetReplayConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trp", namespace = "trp: http://www.onvif.org/ver10/replay/wsdl" )] pub struct GetReplayConfigurationResponse { // The current replay configuration parameters. #[yaserde(prefix = "trp", rename = "Configuration")] pub configuration: tt::ReplayConfiguration, } impl Validate for GetReplayConfigurationResponse {} // Returns the capabilities of the replay service. The result is returned in a // typed answer. pub async fn get_service_capabilities<T: transport::Transport>( transport: &T, request: &GetServiceCapabilities, ) -> Result<GetServiceCapabilitiesResponse, transport::Error> { transport::request(transport, request).await } // Requests a URI that can be used to initiate playback of a recorded stream // using RTSP as the control protocol. The URI is valid only as it is // specified in the response. // This operation is mandatory. pub async fn get_replay_uri<T: transport::Transport>( transport: &T, request: &GetReplayUri, ) -> Result<GetReplayUriResponse, transport::Error> { transport::request(transport, request).await } // Returns the current configuration of the replay service. // This operation is mandatory. pub async fn get_replay_configuration<T: transport::Transport>( transport: &T, request: &GetReplayConfiguration, ) -> Result<GetReplayConfigurationResponse, transport::Error> { transport::request(transport, request).await } // Changes the current configuration of the replay service. // This operation is mandatory. pub async fn set_replay_configuration<T: transport::Transport>( transport: &T, request: &SetReplayConfiguration, ) -> Result<SetReplayConfigurationResponse, transport::Error> { transport::request(transport, request).await }
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
false
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/uplink/src/lib.rs
wsdl_rs/uplink/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use validate::Validate; use yaserde_derive::{YaDeserialize, YaSerialize}; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tup", namespace = "tup: http://www.onvif.org/ver10/uplink/wsdl" )] pub struct GetServiceCapabilities {} impl Validate for GetServiceCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tup", namespace = "tup: http://www.onvif.org/ver10/uplink/wsdl" )] pub struct GetServiceCapabilitiesResponse { // The capabilities for the uplink service is returned in the Capabilities // element. #[yaserde(prefix = "tup", rename = "Capabilities")] pub capabilities: Capabilities, } impl Validate for GetServiceCapabilitiesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tup", namespace = "tup: http://www.onvif.org/ver10/uplink/wsdl" )] pub struct Capabilities { // Maximum number of uplink connections that can be configured. #[yaserde(attribute, rename = "MaxUplinks")] pub max_uplinks: Option<i32>, } impl Validate for Capabilities {} // pub type Capabilities = Capabilities; #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum ConnectionStatus { Offline, Connecting, Connected, __Unknown__(String), } impl Default for ConnectionStatus { fn default() -> ConnectionStatus { Self::__Unknown__("No valid variants".into()) } } impl Validate for ConnectionStatus {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tup", namespace = "tup: http://www.onvif.org/ver10/uplink/wsdl" )] pub struct Configuration { // Uniform resource locator by which the remote client can be reached. #[yaserde(prefix = "tup", rename = "RemoteAddress")] pub remote_address: String, // ID of the certificate to be used for client authentication. #[yaserde(prefix = "tup", rename = "CertificateID")] pub certificate_id: String, // Authorization level that will be assigned to the uplink connection. #[yaserde(prefix = "tup", rename = "UserLevel")] pub user_level: String, // Current connection status (see tup:ConnectionStatus for possible values). #[yaserde(prefix = "tup", rename = "Status")] pub status: Option<String>, } impl Validate for Configuration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tup", namespace = "tup: http://www.onvif.org/ver10/uplink/wsdl" )] pub struct GetUplinks {} impl Validate for GetUplinks {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tup", namespace = "tup: http://www.onvif.org/ver10/uplink/wsdl" )] pub struct GetUplinksResponse { // List of configured uplinks. #[yaserde(prefix = "tup", rename = "Configuration")] pub configuration: Vec<Configuration>, } impl Validate for GetUplinksResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tup", namespace = "tup: http://www.onvif.org/ver10/uplink/wsdl" )] pub struct SetUplink { // SConfiguration to be added or modified. #[yaserde(prefix = "tup", rename = "Configuration")] pub configuration: Configuration, } impl Validate for SetUplink {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tup", namespace = "tup: http://www.onvif.org/ver10/uplink/wsdl" )] pub struct SetUplinkResponse {} impl Validate for SetUplinkResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tup", namespace = "tup: http://www.onvif.org/ver10/uplink/wsdl" )] pub struct DeleteUplink { // Uniform resource locator of the configuration to be deleted. #[yaserde(prefix = "tup", rename = "RemoteAddress")] pub remote_address: String, } impl Validate for DeleteUplink {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tup", namespace = "tup: http://www.onvif.org/ver10/uplink/wsdl" )] pub struct DeleteUplinkResponse {} impl Validate for DeleteUplinkResponse {} // Returns the capabilities of the uplink service. pub async fn get_service_capabilities<T: transport::Transport>( transport: &T, request: &GetServiceCapabilities, ) -> Result<GetServiceCapabilitiesResponse, transport::Error> { transport::request(transport, request).await } // A device supporting uplinks shall support this command to retrieve the // configured uplink configurations. // The Status field shall signal whether a connection is Offline, Connecting or // Online. pub async fn get_uplinks<T: transport::Transport>( transport: &T, request: &GetUplinks, ) -> Result<GetUplinksResponse, transport::Error> { transport::request(transport, request).await } // A device supporting uplinks shall support this command to add or modify an // uplink configuration. // The Status property of the UplinkConfiguration shall be ignored by the // device. A device shall // use the field RemoteAddress to decide whether to update an existing entry or // create a new entry. pub async fn set_uplink<T: transport::Transport>( transport: &T, request: &SetUplink, ) -> Result<SetUplinkResponse, transport::Error> { transport::request(transport, request).await } // A device supporting uplinks shall support this command to remove an uplink // configuration. pub async fn delete_uplink<T: transport::Transport>( transport: &T, request: &DeleteUplink, ) -> Result<DeleteUplinkResponse, transport::Error> { transport::request(transport, request).await }
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
false
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/provisioning/src/lib.rs
wsdl_rs/provisioning/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use onvif as tt; use validate::Validate; use xsd_types::types as xs; use yaserde_derive::{YaDeserialize, YaSerialize}; // The direction for PanMove to move the device. #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum PanDirection { // Move left in relation to the video source image. Left, // Move right in relation to the video source image. Right, __Unknown__(String), } impl Default for PanDirection { fn default() -> PanDirection { Self::__Unknown__("No valid variants".into()) } } impl Validate for PanDirection {} // The direction for TiltMove to move the device. #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum TiltDirection { // Move up in relation to the video source image. Up, // Move down in relation to the video source image. Down, __Unknown__(String), } impl Default for TiltDirection { fn default() -> TiltDirection { Self::__Unknown__("No valid variants".into()) } } impl Validate for TiltDirection {} // The direction for ZoomMove to change the focal length in relation to the // video source. #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum ZoomDirection { // Move video source lens toward a wider field of view. Wide, // Move video source lens toward a narrower field of view. Telephoto, __Unknown__(String), } impl Default for ZoomDirection { fn default() -> ZoomDirection { Self::__Unknown__("No valid variants".into()) } } impl Validate for ZoomDirection {} // The direction for RollMove to move the device. #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum RollDirection { // Move clockwise in relation to the video source image. Clockwise, // Move counterclockwise in relation to the video source image. Counterclockwise, // Automatically level the device in relation to the video source image. Auto, __Unknown__(String), } impl Default for RollDirection { fn default() -> RollDirection { Self::__Unknown__("No valid variants".into()) } } impl Validate for RollDirection {} // The direction for FocusMove to move the focal plane in relation to the video // source. #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum FocusDirection { // Move to focus on close objects. Near, // Move to focus on distant objects. Far, // Automatically focus for the sharpest video source image. Auto, __Unknown__(String), } impl Default for FocusDirection { fn default() -> FocusDirection { Self::__Unknown__("No valid variants".into()) } } impl Validate for FocusDirection {} // The quantity of movement events that have occured over the lifetime of the // device. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tpv", namespace = "tpv: http://www.onvif.org/ver10/provisioning/wsdl" )] pub struct Usage { // The quantity of pan movement events over the life of the device. #[yaserde(prefix = "tpv", rename = "Pan")] pub pan: Option<xs::Integer>, // The quantity of tilt movement events over the life of the device. #[yaserde(prefix = "tpv", rename = "Tilt")] pub tilt: Option<xs::Integer>, // The quantity of zoom movement events over the life of the device. #[yaserde(prefix = "tpv", rename = "Zoom")] pub zoom: Option<xs::Integer>, // The quantity of roll movement events over the life of the device. #[yaserde(prefix = "tpv", rename = "Roll")] pub roll: Option<xs::Integer>, // The quantity of focus movement events over the life of the device. #[yaserde(prefix = "tpv", rename = "Focus")] pub focus: Option<xs::Integer>, } impl Validate for Usage {} // The provisioning capabilities of a video source on the device. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tpv", namespace = "tpv: http://www.onvif.org/ver10/provisioning/wsdl" )] pub struct SourceCapabilities { // Unique identifier of a video source. #[yaserde(attribute, rename = "VideoSourceToken")] pub video_source_token: tt::ReferenceToken, // Lifetime limit of pan moves for this video source. Presence of this // attribute indicates support of pan move. #[yaserde(attribute, rename = "MaximumPanMoves")] pub maximum_pan_moves: Option<xs::Integer>, // Lifetime limit of tilt moves for this video source. Presence of this // attribute indicates support of tilt move. #[yaserde(attribute, rename = "MaximumTiltMoves")] pub maximum_tilt_moves: Option<xs::Integer>, // Lifetime limit of zoom moves for this video source. Presence of this // attribute indicates support of zoom move. #[yaserde(attribute, rename = "MaximumZoomMoves")] pub maximum_zoom_moves: Option<xs::Integer>, // Lifetime limit of roll moves for this video source. Presence of this // attribute indicates support of roll move. #[yaserde(attribute, rename = "MaximumRollMoves")] pub maximum_roll_moves: Option<xs::Integer>, // Indicates "auto" as a valid enum for Direction in RollMove. #[yaserde(attribute, rename = "AutoLevel")] pub auto_level: Option<bool>, // Lifetime limit of focus moves for this video source. Presence of this // attribute indicates support of focus move. #[yaserde(attribute, rename = "MaximumFocusMoves")] pub maximum_focus_moves: Option<xs::Integer>, // Indicates "auto" as a valid enum for Direction in FocusMove. #[yaserde(attribute, rename = "AutoFocus")] pub auto_focus: Option<bool>, } impl Validate for SourceCapabilities {} // The capabilities of Provisioning Service on the device. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tpv", namespace = "tpv: http://www.onvif.org/ver10/provisioning/wsdl" )] pub struct Capabilities { // Maximum time before stopping movement after a move operation. #[yaserde(prefix = "tpv", rename = "DefaultTimeout")] pub default_timeout: xs::Duration, // Capabilities per video source. #[yaserde(prefix = "tpv", rename = "Source")] pub source: Vec<SourceCapabilities>, } impl Validate for Capabilities {} // pub type Capabilities = Capabilities; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tpv", namespace = "tpv: http://www.onvif.org/ver10/provisioning/wsdl" )] pub struct GetServiceCapabilities {} impl Validate for GetServiceCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tpv", namespace = "tpv: http://www.onvif.org/ver10/provisioning/wsdl" )] pub struct GetServiceCapabilitiesResponse { // The capabilities for the provisioning service on this device. #[yaserde(prefix = "tpv", rename = "Capabilities")] pub capabilities: Capabilities, } impl Validate for GetServiceCapabilitiesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tpv", namespace = "tpv: http://www.onvif.org/ver10/provisioning/wsdl" )] pub struct PanMove { // The video source associated with the provisioning. #[yaserde(prefix = "tpv", rename = "VideoSource")] pub video_source: tt::ReferenceToken, // "left" or "right". #[yaserde(prefix = "tpv", rename = "Direction")] pub direction: PanDirection, // "Operation timeout, if less than default timeout. #[yaserde(prefix = "tpv", rename = "Timeout")] pub timeout: Option<xs::Duration>, } impl Validate for PanMove {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tpv", namespace = "tpv: http://www.onvif.org/ver10/provisioning/wsdl" )] pub struct PanMoveResponse {} impl Validate for PanMoveResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tpv", namespace = "tpv: http://www.onvif.org/ver10/provisioning/wsdl" )] pub struct TiltMove { // The video source associated with the provisioning. #[yaserde(prefix = "tpv", rename = "VideoSource")] pub video_source: tt::ReferenceToken, // "up" or "down". #[yaserde(prefix = "tpv", rename = "Direction")] pub direction: TiltDirection, // "Operation timeout, if less than default timeout. #[yaserde(prefix = "tpv", rename = "Timeout")] pub timeout: Option<xs::Duration>, } impl Validate for TiltMove {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tpv", namespace = "tpv: http://www.onvif.org/ver10/provisioning/wsdl" )] pub struct TiltMoveResponse {} impl Validate for TiltMoveResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tpv", namespace = "tpv: http://www.onvif.org/ver10/provisioning/wsdl" )] pub struct ZoomMove { // The video source associated with the provisioning. #[yaserde(prefix = "tpv", rename = "VideoSource")] pub video_source: tt::ReferenceToken, // "wide" or "telephoto". #[yaserde(prefix = "tpv", rename = "Direction")] pub direction: ZoomDirection, // "Operation timeout, if less than default timeout. #[yaserde(prefix = "tpv", rename = "Timeout")] pub timeout: Option<xs::Duration>, } impl Validate for ZoomMove {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tpv", namespace = "tpv: http://www.onvif.org/ver10/provisioning/wsdl" )] pub struct ZoomMoveResponse {} impl Validate for ZoomMoveResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tpv", namespace = "tpv: http://www.onvif.org/ver10/provisioning/wsdl" )] pub struct RollMove { // The video source associated with the provisioning. #[yaserde(prefix = "tpv", rename = "VideoSource")] pub video_source: tt::ReferenceToken, // "clockwise", "counterclockwise", or "auto". #[yaserde(prefix = "tpv", rename = "Direction")] pub direction: RollDirection, // "Operation timeout, if less than default timeout. #[yaserde(prefix = "tpv", rename = "Timeout")] pub timeout: Option<xs::Duration>, } impl Validate for RollMove {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tpv", namespace = "tpv: http://www.onvif.org/ver10/provisioning/wsdl" )] pub struct RollMoveResponse {} impl Validate for RollMoveResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tpv", namespace = "tpv: http://www.onvif.org/ver10/provisioning/wsdl" )] pub struct FocusMove { // The video source associated with the provisioning. #[yaserde(prefix = "tpv", rename = "VideoSource")] pub video_source: tt::ReferenceToken, // "near", "far", or "auto". #[yaserde(prefix = "tpv", rename = "Direction")] pub direction: FocusDirection, // "Operation timeout, if less than default timeout. #[yaserde(prefix = "tpv", rename = "Timeout")] pub timeout: Option<xs::Duration>, } impl Validate for FocusMove {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tpv", namespace = "tpv: http://www.onvif.org/ver10/provisioning/wsdl" )] pub struct FocusMoveResponse {} impl Validate for FocusMoveResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tpv", namespace = "tpv: http://www.onvif.org/ver10/provisioning/wsdl" )] pub struct Stop { // The video source associated with the provisioning. #[yaserde(prefix = "tpv", rename = "VideoSource")] pub video_source: tt::ReferenceToken, } impl Validate for Stop {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tpv", namespace = "tpv: http://www.onvif.org/ver10/provisioning/wsdl" )] pub struct StopResponse {} impl Validate for StopResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tpv", namespace = "tpv: http://www.onvif.org/ver10/provisioning/wsdl" )] pub struct GetUsage { // The video source associated with the provisioning. #[yaserde(prefix = "tpv", rename = "VideoSource")] pub video_source: tt::ReferenceToken, } impl Validate for GetUsage {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tpv", namespace = "tpv: http://www.onvif.org/ver10/provisioning/wsdl" )] pub struct GetUsageResponse { // The set of lifetime usage values for the provisioning associated with the // video source. #[yaserde(prefix = "tpv", rename = "Usage")] pub usage: Usage, } impl Validate for GetUsageResponse {} // Returns the capabilities of the provisioning service. pub async fn get_service_capabilities<T: transport::Transport>( transport: &T, request: &GetServiceCapabilities, ) -> Result<GetServiceCapabilitiesResponse, transport::Error> { transport::request(transport, request).await } // Moves device on the pan axis. pub async fn pan_move<T: transport::Transport>( transport: &T, request: &PanMove, ) -> Result<PanMoveResponse, transport::Error> { transport::request(transport, request).await } // Moves device on the tilt axis. pub async fn tilt_move<T: transport::Transport>( transport: &T, request: &TiltMove, ) -> Result<TiltMoveResponse, transport::Error> { transport::request(transport, request).await } // Moves device on the zoom axis. pub async fn zoom_move<T: transport::Transport>( transport: &T, request: &ZoomMove, ) -> Result<ZoomMoveResponse, transport::Error> { transport::request(transport, request).await } // Moves device on the roll axis. pub async fn roll_move<T: transport::Transport>( transport: &T, request: &RollMove, ) -> Result<RollMoveResponse, transport::Error> { transport::request(transport, request).await } // Moves device on the focus axis. pub async fn focus_move<T: transport::Transport>( transport: &T, request: &FocusMove, ) -> Result<FocusMoveResponse, transport::Error> { transport::request(transport, request).await } // Stops device motion on all axes. pub async fn stop<T: transport::Transport>( transport: &T, request: &Stop, ) -> Result<StopResponse, transport::Error> { transport::request(transport, request).await } // Returns the lifetime move counts. pub async fn get_usage<T: transport::Transport>( transport: &T, request: &GetUsage, ) -> Result<GetUsageResponse, transport::Error> { transport::request(transport, request).await }
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
false
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/display/src/lib.rs
wsdl_rs/display/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use onvif as tt; use validate::Validate; use yaserde_derive::{YaDeserialize, YaSerialize}; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tls", namespace = "tls: http://www.onvif.org/ver10/display/wsdl" )] pub struct GetServiceCapabilities {} impl Validate for GetServiceCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tls", namespace = "tls: http://www.onvif.org/ver10/display/wsdl" )] pub struct GetServiceCapabilitiesResponse { // The capabilities for the display service is returned in the Capabilities // element. #[yaserde(prefix = "tls", rename = "Capabilities")] pub capabilities: Capabilities, } impl Validate for GetServiceCapabilitiesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tls", namespace = "tls: http://www.onvif.org/ver10/display/wsdl" )] pub struct Capabilities { // Indication that the SetLayout command supports only predefined layouts. #[yaserde(attribute, rename = "FixedLayout")] pub fixed_layout: Option<bool>, } impl Validate for Capabilities {} // pub type Capabilities = Capabilities; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tls", namespace = "tls: http://www.onvif.org/ver10/display/wsdl" )] pub struct GetLayout { // Token of the Video Output whose Layout is requested #[yaserde(prefix = "tls", rename = "VideoOutput")] pub video_output: tt::ReferenceToken, } impl Validate for GetLayout {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tls", namespace = "tls: http://www.onvif.org/ver10/display/wsdl" )] pub struct GetLayoutResponse { // Current layout of the video output. #[yaserde(prefix = "tls", rename = "Layout")] pub layout: tt::Layout, } impl Validate for GetLayoutResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tls", namespace = "tls: http://www.onvif.org/ver10/display/wsdl" )] pub struct SetLayout { // Token of the Video Output whose Layout shall be changed. #[yaserde(prefix = "tls", rename = "VideoOutput")] pub video_output: tt::ReferenceToken, // Layout to be set #[yaserde(prefix = "tls", rename = "Layout")] pub layout: tt::Layout, } impl Validate for SetLayout {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tls", namespace = "tls: http://www.onvif.org/ver10/display/wsdl" )] pub struct SetLayoutResponse {} impl Validate for SetLayoutResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tls", namespace = "tls: http://www.onvif.org/ver10/display/wsdl" )] pub struct GetDisplayOptions { // Token of the Video Output whose options are requested #[yaserde(prefix = "tls", rename = "VideoOutput")] pub video_output: tt::ReferenceToken, } impl Validate for GetDisplayOptions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tls", namespace = "tls: http://www.onvif.org/ver10/display/wsdl" )] pub struct GetDisplayOptionsResponse { // The LayoutOptions describe the fixed and predefined layouts of a device. // If the device does // not offer fixed layouts and allows setting the layout free this element // is empty. #[yaserde(prefix = "tls", rename = "LayoutOptions")] pub layout_options: Option<tt::LayoutOptions>, // decoding and encoding capabilities of the device #[yaserde(prefix = "tls", rename = "CodingCapabilities")] pub coding_capabilities: tt::CodingCapabilities, } impl Validate for GetDisplayOptionsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tls", namespace = "tls: http://www.onvif.org/ver10/display/wsdl" )] pub struct GetPaneConfigurations { // Reference Token of the Video Output whose Pane Configurations are // requested #[yaserde(prefix = "tls", rename = "VideoOutput")] pub video_output: tt::ReferenceToken, } impl Validate for GetPaneConfigurations {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tls", namespace = "tls: http://www.onvif.org/ver10/display/wsdl" )] pub struct GetPaneConfigurationsResponse { // Contains a list of defined Panes of the specified VideoOutput. Each // VideoOutput has at least one PaneConfiguration. #[yaserde(prefix = "tls", rename = "PaneConfiguration")] pub pane_configuration: Vec<tt::PaneConfiguration>, } impl Validate for GetPaneConfigurationsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tls", namespace = "tls: http://www.onvif.org/ver10/display/wsdl" )] pub struct GetPaneConfiguration { // Reference Token of the Video Output the requested pane belongs to #[yaserde(prefix = "tls", rename = "VideoOutput")] pub video_output: tt::ReferenceToken, // Reference Token of the Pane whose Configuration is requested #[yaserde(prefix = "tls", rename = "Pane")] pub pane: tt::ReferenceToken, } impl Validate for GetPaneConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tls", namespace = "tls: http://www.onvif.org/ver10/display/wsdl" )] pub struct GetPaneConfigurationResponse { // returns the configuration of the requested pane. #[yaserde(prefix = "tls", rename = "PaneConfiguration")] pub pane_configuration: tt::PaneConfiguration, } impl Validate for GetPaneConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tls", namespace = "tls: http://www.onvif.org/ver10/display/wsdl" )] pub struct SetPaneConfigurations { // Token of the video output whose panes to set. #[yaserde(prefix = "tls", rename = "VideoOutput")] pub video_output: tt::ReferenceToken, // Pane Configuration to be set. #[yaserde(prefix = "tls", rename = "PaneConfiguration")] pub pane_configuration: Vec<tt::PaneConfiguration>, } impl Validate for SetPaneConfigurations {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tls", namespace = "tls: http://www.onvif.org/ver10/display/wsdl" )] pub struct SetPaneConfigurationsResponse {} impl Validate for SetPaneConfigurationsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tls", namespace = "tls: http://www.onvif.org/ver10/display/wsdl" )] pub struct SetPaneConfiguration { // Token of the video output whose panes to set. #[yaserde(prefix = "tls", rename = "VideoOutput")] pub video_output: tt::ReferenceToken, // Pane Configuration to be set. #[yaserde(prefix = "tls", rename = "PaneConfiguration")] pub pane_configuration: tt::PaneConfiguration, } impl Validate for SetPaneConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tls", namespace = "tls: http://www.onvif.org/ver10/display/wsdl" )] pub struct SetPaneConfigurationResponse {} impl Validate for SetPaneConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tls", namespace = "tls: http://www.onvif.org/ver10/display/wsdl" )] pub struct CreatePaneConfiguration { // Token of the video output where the pane shall be created. #[yaserde(prefix = "tls", rename = "VideoOutput")] pub video_output: tt::ReferenceToken, // Configuration of the pane to be created. #[yaserde(prefix = "tls", rename = "PaneConfiguration")] pub pane_configuration: tt::PaneConfiguration, } impl Validate for CreatePaneConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tls", namespace = "tls: http://www.onvif.org/ver10/display/wsdl" )] pub struct CreatePaneConfigurationResponse { // Token of the new pane configuration. #[yaserde(prefix = "tls", rename = "PaneToken")] pub pane_token: tt::ReferenceToken, } impl Validate for CreatePaneConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tls", namespace = "tls: http://www.onvif.org/ver10/display/wsdl" )] pub struct DeletePaneConfiguration { // Token of the video output where the pane shall be deleted. #[yaserde(prefix = "tls", rename = "VideoOutput")] pub video_output: tt::ReferenceToken, // Token of the pane to be deleted. #[yaserde(prefix = "tls", rename = "PaneToken")] pub pane_token: tt::ReferenceToken, } impl Validate for DeletePaneConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tls", namespace = "tls: http://www.onvif.org/ver10/display/wsdl" )] pub struct DeletePaneConfigurationResponse {} impl Validate for DeletePaneConfigurationResponse {} // Returns the capabilities of the display service. The result is returned in a // typed answer. pub async fn get_service_capabilities<T: transport::Transport>( transport: &T, request: &GetServiceCapabilities, ) -> Result<GetServiceCapabilitiesResponse, transport::Error> { transport::request(transport, request).await } // Return the current layout of a video output. The Layout assigns a pane // configuration to a certain area of the display. The layout settings // directly affect a specific video output. The layout consists of a list of // PaneConfigurations and // their associated display areas. pub async fn get_layout<T: transport::Transport>( transport: &T, request: &GetLayout, ) -> Result<GetLayoutResponse, transport::Error> { transport::request(transport, request).await } // Change the layout of a display (e.g. change from // single view to split screen view).The Layout assigns a pane configuration to // a certain area of the display. The layout settings // directly affect a specific video output. The layout consists of a list of // PaneConfigurations and // their associated display areas. pub async fn set_layout<T: transport::Transport>( transport: &T, request: &SetLayout, ) -> Result<SetLayoutResponse, transport::Error> { transport::request(transport, request).await } // The Display Options contain the supported layouts (LayoutOptions) and the // decoding and // encoding capabilities (CodingCapabilities) of the device. The // GetDisplayOptions command // returns both, Layout and Coding Capabilities, of a VideoOutput. pub async fn get_display_options<T: transport::Transport>( transport: &T, request: &GetDisplayOptions, ) -> Result<GetDisplayOptionsResponse, transport::Error> { transport::request(transport, request).await } // List all currently defined panes of a device for a specified video output // (regardless if this pane is visible at a moment). A Pane is a display area on // the monitor that is attached to a video output. A pane has a // PaneConfiguration that describes which entities are associated with the pane. // A client has to configure the pane according to the connection to be // established by setting the // AudioOutput and/or AudioSourceToken. If a Token is not set, the corresponding // session will // not be established. pub async fn get_pane_configurations<T: transport::Transport>( transport: &T, request: &GetPaneConfigurations, ) -> Result<GetPaneConfigurationsResponse, transport::Error> { transport::request(transport, request).await } // Retrieve the pane configuration for a pane token. pub async fn get_pane_configuration<T: transport::Transport>( transport: &T, request: &GetPaneConfiguration, ) -> Result<GetPaneConfigurationResponse, transport::Error> { transport::request(transport, request).await } // Modify one or more configurations of the specified video output. // This method will only modify the provided configurations and leave the others // unchanged. // Use pub async fn set_pane_configurations<T: transport::Transport>( transport: &T, request: &SetPaneConfigurations, ) -> Result<SetPaneConfigurationsResponse, transport::Error> { transport::request(transport, request).await } // This command changes the configuration of the specified pane (tbd) pub async fn set_pane_configuration<T: transport::Transport>( transport: &T, request: &SetPaneConfiguration, ) -> Result<SetPaneConfigurationResponse, transport::Error> { transport::request(transport, request).await } // Create a new pane configuration describing the streaming and coding settings // for a display area. pub async fn create_pane_configuration<T: transport::Transport>( transport: &T, request: &CreatePaneConfiguration, ) -> Result<CreatePaneConfigurationResponse, transport::Error> { transport::request(transport, request).await } // Delete a pane configuration. A service must respond with an error if the pane // configuration // is in use by the current layout. pub async fn delete_pane_configuration<T: transport::Transport>( transport: &T, request: &DeletePaneConfiguration, ) -> Result<DeletePaneConfigurationResponse, transport::Error> { transport::request(transport, request).await }
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
false
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/xml_xsd/src/lib.rs
wsdl_rs/xml_xsd/src/lib.rs
use yaserde_derive::{YaDeserialize, YaSerialize}; // TODO: replace with actual types generated from .xsd #[derive(Default, Eq, PartialEq, Debug, YaSerialize, YaDeserialize)] pub struct Lang {}
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
false
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/thermal/src/lib.rs
wsdl_rs/thermal/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use onvif as tt; use validate::Validate; use yaserde_derive::{YaDeserialize, YaSerialize}; #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum Polarity { WhiteHot, BlackHot, __Unknown__(String), } impl Default for Polarity { fn default() -> Polarity { Self::__Unknown__("No valid variants".into()) } } impl Validate for Polarity {} // Describes standard Color Palette types, used to facilitate Multi-language // support and client display. // "Custom" Type shall be used when Color Palette Name does not match any of the // types included in the standard classification. #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum ColorPaletteType { Custom, Grayscale, BlackHot, WhiteHot, Sepia, Red, Iron, Rain, Rainbow, Isotherm, __Unknown__(String), } impl Default for ColorPaletteType { fn default() -> ColorPaletteType { Self::__Unknown__("No valid variants".into()) } } impl Validate for ColorPaletteType {} // Describes a Color Palette element. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tth", namespace = "tth: http://www.onvif.org/ver10/thermal/wsdl" )] pub struct ColorPalette { // User readable Color Palette name. #[yaserde(prefix = "tth", rename = "Name")] pub name: tt::Name, // Unique identifier of this Color Palette. #[yaserde(attribute, rename = "token")] pub token: tt::ReferenceToken, // Indicates Color Palette Type. Use tth:ColorPaletteType. // Used for multi-language support and display. #[yaserde(attribute, rename = "Type")] pub _type: String, } impl Validate for ColorPalette {} // Type describing a NUC Table element. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tth", namespace = "tth: http://www.onvif.org/ver10/thermal/wsdl" )] pub struct Nuctable { // User reabable name for the Non-Uniformity Correction (NUC) Table. #[yaserde(prefix = "tth", rename = "Name")] pub name: tt::Name, // Unique identifier of this NUC Table. #[yaserde(attribute, rename = "token")] pub token: tt::ReferenceToken, // Low Temperature limit for application of NUC Table, in Kelvin. #[yaserde(attribute, rename = "LowTemperature")] pub low_temperature: Option<f64>, // High Temperature limit for application of NUC Table, in Kelvin. #[yaserde(attribute, rename = "HighTemperature")] pub high_temperature: Option<f64>, } impl Validate for Nuctable {} // Type describing the Cooler settings. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tth", namespace = "tth: http://www.onvif.org/ver10/thermal/wsdl" )] pub struct Cooler { // Indicates whether the Cooler is enabled (running) or not. #[yaserde(prefix = "tth", rename = "Enabled")] pub enabled: bool, // Number of hours the Cooler has been running (unit: hours). Read-only. #[yaserde(prefix = "tth", rename = "RunTime")] pub run_time: Option<f64>, } impl Validate for Cooler {} // Describes valid ranges for the thermal device cooler settings. // Only applicable to cooled thermal devices. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tth", namespace = "tth: http://www.onvif.org/ver10/thermal/wsdl" )] pub struct CoolerOptions { // Indicates the Device allows cooler status to be changed from running // (Enabled) to stopped (Disabled), and viceversa. #[yaserde(prefix = "tth", rename = "Enabled")] pub enabled: Option<bool>, } impl Validate for CoolerOptions {} // Holds default values that will be used in measurement modules when local // parameters are not specified for the module (these are still required for // valid temperature calculations). // Having ReflectedAmbientTemperature, Emissivity and DistanceToObject as // mandatory ensures minimum parameters are available to obtain valid // temperature values. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tth", namespace = "tth: http://www.onvif.org/ver10/thermal/wsdl" )] pub struct RadiometryGlobalParameters { // Reflected Ambient Temperature for the environment in which the thermal // device and the object being measured is located. #[yaserde(prefix = "tth", rename = "ReflectedAmbientTemperature")] pub reflected_ambient_temperature: f64, // Emissivity of the surface of the object on which temperature is being // measured. #[yaserde(prefix = "tth", rename = "Emissivity")] pub emissivity: f64, // Distance from the thermal device to the measured object. #[yaserde(prefix = "tth", rename = "DistanceToObject")] pub distance_to_object: f64, // Relative Humidity in the environment in which the measurement is located. #[yaserde(prefix = "tth", rename = "RelativeHumidity")] pub relative_humidity: Option<f64>, // Temperature of the atmosphere between the thermal device and the object // being measured. #[yaserde(prefix = "tth", rename = "AtmosphericTemperature")] pub atmospheric_temperature: Option<f64>, // Transmittance value for the atmosphere between the thermal device and the // object being measured. #[yaserde(prefix = "tth", rename = "AtmosphericTransmittance")] pub atmospheric_transmittance: Option<f64>, // Temperature of the optics elements between the thermal device and the // object being measured. #[yaserde(prefix = "tth", rename = "ExtOpticsTemperature")] pub ext_optics_temperature: Option<f64>, // Transmittance value for the optics elements between the thermal device // and the object being measured. #[yaserde(prefix = "tth", rename = "ExtOpticsTransmittance")] pub ext_optics_transmittance: Option<f64>, } impl Validate for RadiometryGlobalParameters {} // Describes valid ranges for the different radiometry parameters required for // accurate temperature calculation. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tth", namespace = "tth: http://www.onvif.org/ver10/thermal/wsdl" )] pub struct RadiometryGlobalParameterOptions { // Valid range of temperature values, in Kelvin. #[yaserde(prefix = "tth", rename = "ReflectedAmbientTemperature")] pub reflected_ambient_temperature: tt::FloatRange, // Valid range of emissivity values for the objects to measure. #[yaserde(prefix = "tth", rename = "Emissivity")] pub emissivity: tt::FloatRange, // Valid range of distance between camera and object for a valid temperature // reading, in meters. #[yaserde(prefix = "tth", rename = "DistanceToObject")] pub distance_to_object: tt::FloatRange, // Valid range of relative humidity values, in percentage. #[yaserde(prefix = "tth", rename = "RelativeHumidity")] pub relative_humidity: Option<tt::FloatRange>, // Valid range of temperature values, in Kelvin. #[yaserde(prefix = "tth", rename = "AtmosphericTemperature")] pub atmospheric_temperature: Option<tt::FloatRange>, // Valid range of atmospheric transmittance values. #[yaserde(prefix = "tth", rename = "AtmosphericTransmittance")] pub atmospheric_transmittance: Option<tt::FloatRange>, // Valid range of temperature values, in Kelvin. #[yaserde(prefix = "tth", rename = "ExtOpticsTemperature")] pub ext_optics_temperature: Option<tt::FloatRange>, // Valid range of external optics transmittance. #[yaserde(prefix = "tth", rename = "ExtOpticsTransmittance")] pub ext_optics_transmittance: Option<tt::FloatRange>, } impl Validate for RadiometryGlobalParameterOptions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tth", namespace = "tth: http://www.onvif.org/ver10/thermal/wsdl" )] pub struct Configuration { // Current Color Palette in use by the Thermal Device. #[yaserde(prefix = "tth", rename = "ColorPalette")] pub color_palette: ColorPalette, // Polarity configuration of the Thermal Device. #[yaserde(prefix = "tth", rename = "Polarity")] pub polarity: Polarity, // Current Non-Uniformity Correction (NUC) Table in use by the Thermal // Device. #[yaserde(prefix = "tth", rename = "NUCTable")] pub nuc_table: Option<Nuctable>, // Cooler settings of the Thermal Device. #[yaserde(prefix = "tth", rename = "Cooler")] pub cooler: Option<Cooler>, } impl Validate for Configuration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tth", namespace = "tth: http://www.onvif.org/ver10/thermal/wsdl" )] pub struct Configurations { // Current Thermal Settings for the VideoSource. #[yaserde(prefix = "tth", rename = "Configuration")] pub configuration: Configuration, // Reference token to the thermal VideoSource. #[yaserde(attribute, rename = "token")] pub token: tt::ReferenceToken, } impl Validate for Configurations {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tth", namespace = "tth: http://www.onvif.org/ver10/thermal/wsdl" )] pub struct RadiometryConfiguration { // Global Parameters for Radiometry Measurements. Shall exist if Radiometry // Capability is reported, // and Global Parameters are supported by the device. #[yaserde(prefix = "tth", rename = "RadiometryGlobalParameters")] pub radiometry_global_parameters: Option<RadiometryGlobalParameters>, } impl Validate for RadiometryConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tth", namespace = "tth: http://www.onvif.org/ver10/thermal/wsdl" )] pub struct ConfigurationOptions { // List of Color Palettes available for the requested Thermal VideoSource. #[yaserde(prefix = "tth", rename = "ColorPalette")] pub color_palette: Vec<ColorPalette>, // List of Non-Uniformity Correction (NUC) Tables available for the // requested Thermal VideoSource. #[yaserde(prefix = "tth", rename = "NUCTable")] pub nuc_table: Vec<Nuctable>, // Specifies Cooler Options for cooled thermal devices. #[yaserde(prefix = "tth", rename = "CoolerOptions")] pub cooler_options: Option<CoolerOptions>, } impl Validate for ConfigurationOptions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tth", namespace = "tth: http://www.onvif.org/ver10/thermal/wsdl" )] pub struct RadiometryConfigurationOptions { // Specifies valid ranges and options for the global radiometry parameters // used as default parameter values // for temperature measurement modules (spots and boxes). #[yaserde(prefix = "tth", rename = "RadiometryGlobalParameterOptions")] pub radiometry_global_parameter_options: Option<RadiometryGlobalParameterOptions>, } impl Validate for RadiometryConfigurationOptions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tth", namespace = "tth: http://www.onvif.org/ver10/thermal/wsdl" )] pub struct GetServiceCapabilities {} impl Validate for GetServiceCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tth", namespace = "tth: http://www.onvif.org/ver10/thermal/wsdl" )] pub struct GetServiceCapabilitiesResponse { // The capabilities of the thermal service are returned in the Capabilities // element. #[yaserde(prefix = "tth", rename = "Capabilities")] pub capabilities: Capabilities, } impl Validate for GetServiceCapabilitiesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tth", namespace = "tth: http://www.onvif.org/ver10/thermal/wsdl" )] pub struct Capabilities { // Indicates whether or not radiometric thermal measurements are supported // by the thermal device. #[yaserde(attribute, rename = "Radiometry")] pub radiometry: Option<bool>, } impl Validate for Capabilities {} // pub type Capabilities = Capabilities; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tth", namespace = "tth: http://www.onvif.org/ver10/thermal/wsdl" )] pub struct GetConfigurationOptions { // Reference token to the VideoSource for which the Thermal Configuration // Options are requested. #[yaserde(prefix = "tth", rename = "VideoSourceToken")] pub video_source_token: tt::ReferenceToken, } impl Validate for GetConfigurationOptions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tth", namespace = "tth: http://www.onvif.org/ver10/thermal/wsdl" )] pub struct GetConfigurationOptionsResponse { // Valid ranges for the Thermal configuration parameters that are // categorized as device specific. #[yaserde(prefix = "tth", rename = "ConfigurationOptions")] pub configuration_options: ConfigurationOptions, } impl Validate for GetConfigurationOptionsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tth", namespace = "tth: http://www.onvif.org/ver10/thermal/wsdl" )] pub struct GetConfiguration { // Reference token to the VideoSource for which the Thermal Settings are // requested. #[yaserde(prefix = "tth", rename = "VideoSourceToken")] pub video_source_token: tt::ReferenceToken, } impl Validate for GetConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tth", namespace = "tth: http://www.onvif.org/ver10/thermal/wsdl" )] pub struct GetConfigurationResponse { // Thermal Settings for the VideoSource that was requested. #[yaserde(prefix = "tth", rename = "Configuration")] pub configuration: Configuration, } impl Validate for GetConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tth", namespace = "tth: http://www.onvif.org/ver10/thermal/wsdl" )] pub struct GetConfigurations {} impl Validate for GetConfigurations {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tth", namespace = "tth: http://www.onvif.org/ver10/thermal/wsdl" )] pub struct GetConfigurationsResponse { // This element contains a list of thermal VideoSource configurations. #[yaserde(prefix = "tth", rename = "Configurations")] pub configurations: Vec<Configurations>, } impl Validate for GetConfigurationsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tth", namespace = "tth: http://www.onvif.org/ver10/thermal/wsdl" )] pub struct SetConfiguration { // Reference token to the VideoSource for which the Thermal Settings are // configured. #[yaserde(prefix = "tth", rename = "VideoSourceToken")] pub video_source_token: tt::ReferenceToken, // Thermal Settings to be configured. #[yaserde(prefix = "tth", rename = "Configuration")] pub configuration: Configuration, } impl Validate for SetConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tth", namespace = "tth: http://www.onvif.org/ver10/thermal/wsdl" )] pub struct SetConfigurationResponse {} impl Validate for SetConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tth", namespace = "tth: http://www.onvif.org/ver10/thermal/wsdl" )] pub struct GetRadiometryConfigurationOptions { // Reference token to the VideoSource for which the Thermal Radiometry // Options are requested. #[yaserde(prefix = "tth", rename = "VideoSourceToken")] pub video_source_token: tt::ReferenceToken, } impl Validate for GetRadiometryConfigurationOptions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tth", namespace = "tth: http://www.onvif.org/ver10/thermal/wsdl" )] pub struct GetRadiometryConfigurationOptionsResponse { // Valid ranges for the Thermal Radiometry parameters that are categorized // as device specific. #[yaserde(prefix = "tth", rename = "ConfigurationOptions")] pub configuration_options: RadiometryConfigurationOptions, } impl Validate for GetRadiometryConfigurationOptionsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tth", namespace = "tth: http://www.onvif.org/ver10/thermal/wsdl" )] pub struct GetRadiometryConfiguration { // Reference token to the VideoSource for which the Radiometry Configuration // is requested. #[yaserde(prefix = "tth", rename = "VideoSourceToken")] pub video_source_token: tt::ReferenceToken, } impl Validate for GetRadiometryConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tth", namespace = "tth: http://www.onvif.org/ver10/thermal/wsdl" )] pub struct GetRadiometryConfigurationResponse { // Radiometry Configuration for the VideoSource that was requested. #[yaserde(prefix = "tth", rename = "Configuration")] pub configuration: RadiometryConfiguration, } impl Validate for GetRadiometryConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tth", namespace = "tth: http://www.onvif.org/ver10/thermal/wsdl" )] pub struct SetRadiometryConfiguration { // Reference token to the VideoSource for which the Radiometry settings are // configured. #[yaserde(prefix = "tth", rename = "VideoSourceToken")] pub video_source_token: tt::ReferenceToken, // Radiometry settings to be configured. #[yaserde(prefix = "tth", rename = "Configuration")] pub configuration: RadiometryConfiguration, } impl Validate for SetRadiometryConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tth", namespace = "tth: http://www.onvif.org/ver10/thermal/wsdl" )] pub struct SetRadiometryConfigurationResponse {} impl Validate for SetRadiometryConfigurationResponse {} // Returns the capabilities of the thermal service. The result is returned in a // typed answer. pub async fn get_service_capabilities<T: transport::Transport>( transport: &T, request: &GetServiceCapabilities, ) -> Result<GetServiceCapabilitiesResponse, transport::Error> { transport::request(transport, request).await } // Gets the valid ranges for the Thermal parameters that have device specific // ranges. // This command is mandatory for all devices implementing the Thermal service. // The command shall return all supported parameters // and their ranges, such that these can be applied to the SetConfiguration // command. pub async fn get_configuration_options<T: transport::Transport>( transport: &T, request: &GetConfigurationOptions, ) -> Result<GetConfigurationOptionsResponse, transport::Error> { transport::request(transport, request).await } // Gets the Thermal Configuration for the requested VideoSource. pub async fn get_configuration<T: transport::Transport>( transport: &T, request: &GetConfiguration, ) -> Result<GetConfigurationResponse, transport::Error> { transport::request(transport, request).await } // Gets the Thermal Configuration for all thermal VideoSources of the Device. pub async fn get_configurations<T: transport::Transport>( transport: &T, request: &GetConfigurations, ) -> Result<GetConfigurationsResponse, transport::Error> { transport::request(transport, request).await } // Sets the Thermal Configuration for the requested VideoSource. pub async fn set_configuration<T: transport::Transport>( transport: &T, request: &SetConfiguration, ) -> Result<SetConfigurationResponse, transport::Error> { transport::request(transport, request).await } // Gets the valid ranges for the Radiometry parameters that have device specific // ranges. // The command shall return all supported parameters and their ranges, such that // these can be applied // to the SetRadiometryConfiguration command. pub async fn get_radiometry_configuration_options<T: transport::Transport>( transport: &T, request: &GetRadiometryConfigurationOptions, ) -> Result<GetRadiometryConfigurationOptionsResponse, transport::Error> { transport::request(transport, request).await } // Gets the Radiometry Configuration for the requested VideoSource. pub async fn get_radiometry_configuration<T: transport::Transport>( transport: &T, request: &GetRadiometryConfiguration, ) -> Result<GetRadiometryConfigurationResponse, transport::Error> { transport::request(transport, request).await } // Sets the Radiometry Configuration for the requested VideoSource. pub async fn set_radiometry_configuration<T: transport::Transport>( transport: &T, request: &SetRadiometryConfiguration, ) -> Result<SetRadiometryConfigurationResponse, transport::Error> { transport::request(transport, request).await }
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
false
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/devicemgmt/src/lib.rs
wsdl_rs/devicemgmt/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use onvif as tt; use std::str::FromStr; use validate::Validate; use xsd_macro_utils::*; use xsd_types::types as xs; use yaserde_derive::{YaDeserialize, YaSerialize}; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetServices { // Indicates if the service capabilities (untyped) should be included in the // response. #[yaserde(prefix = "tds", rename = "IncludeCapability")] pub include_capability: bool, } impl Validate for GetServices {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetServicesResponse { // Each Service element contains information about one service. #[yaserde(prefix = "tds", rename = "Service")] pub service: Vec<Service>, } impl Validate for GetServicesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct Service { // Namespace of the service being described. This parameter allows to match // the service capabilities to the service. Note that only one set of // capabilities is supported per namespace. #[yaserde(prefix = "tds", rename = "Namespace")] pub namespace: String, // The transport addresses where the service can be reached. The scheme and // IP part shall match the one used in the request (i.e. the GetServices // request). #[yaserde(prefix = "tds", rename = "XAddr")] pub x_addr: String, #[yaserde(prefix = "tds", rename = "Capabilities")] pub capabilities: Option<service::CapabilitiesType>, // The version of the service (not the ONVIF core spec version). #[yaserde(prefix = "tds", rename = "Version")] pub version: tt::OnvifVersion, } impl Validate for Service {} pub mod service { use super::*; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct CapabilitiesType {} impl Validate for CapabilitiesType {} } #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetServiceCapabilities {} impl Validate for GetServiceCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetServiceCapabilitiesResponse { // The capabilities for the device service is returned in the Capabilities // element. #[yaserde(prefix = "tds", rename = "Capabilities")] pub capabilities: DeviceServiceCapabilities, } impl Validate for GetServiceCapabilitiesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct DeviceServiceCapabilities { // Network capabilities. #[yaserde(prefix = "tds", rename = "Network")] pub network: NetworkCapabilities, // Security capabilities. #[yaserde(prefix = "tds", rename = "Security")] pub security: SecurityCapabilities, // System capabilities. #[yaserde(prefix = "tds", rename = "System")] pub system: SystemCapabilities, // Capabilities that do not fit in any of the other categories. #[yaserde(prefix = "tds", rename = "Misc")] pub misc: Option<MiscCapabilities>, } impl Validate for DeviceServiceCapabilities {} // pub type Capabilities = DeviceServiceCapabilities; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct NetworkCapabilities { // Indicates support for IP filtering. #[yaserde(attribute, rename = "IPFilter")] pub ip_filter: Option<bool>, // Indicates support for zeroconf. #[yaserde(attribute, rename = "ZeroConfiguration")] pub zero_configuration: Option<bool>, // Indicates support for IPv6. #[yaserde(attribute, rename = "IPVersion6")] pub ip_version_6: Option<bool>, // Indicates support for dynamic DNS configuration. #[yaserde(attribute, rename = "DynDNS")] pub dyn_dns: Option<bool>, // Indicates support for IEEE 802.11 configuration. #[yaserde(attribute, rename = "Dot11Configuration")] pub dot_11_configuration: Option<bool>, // Indicates the maximum number of Dot1X configurations supported by the // device #[yaserde(attribute, rename = "Dot1XConfigurations")] pub dot_1x_configurations: Option<i32>, // Indicates support for retrieval of hostname from DHCP. #[yaserde(attribute, rename = "HostnameFromDHCP")] pub hostname_from_dhcp: Option<bool>, // Maximum number of NTP servers supported by the devices SetNTP command. #[yaserde(attribute, rename = "NTP")] pub ntp: Option<i32>, // Indicates support for Stateful IPv6 DHCP. #[yaserde(attribute, rename = "DHCPv6")] pub dhc_pv_6: Option<bool>, } impl Validate for NetworkCapabilities {} #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct EapmethodTypes(pub Vec<i32>); impl Validate for EapmethodTypes {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct SecurityCapabilities { // Indicates support for TLS 1.0. #[yaserde(attribute, rename = "TLS1.0")] pub tls1_0: Option<bool>, // Indicates support for TLS 1.1. #[yaserde(attribute, rename = "TLS1.1")] pub tls1_1: Option<bool>, // Indicates support for TLS 1.2. #[yaserde(attribute, rename = "TLS1.2")] pub tls1_2: Option<bool>, // Indicates support for onboard key generation. #[yaserde(attribute, rename = "OnboardKeyGeneration")] pub onboard_key_generation: Option<bool>, // Indicates support for access policy configuration. #[yaserde(attribute, rename = "AccessPolicyConfig")] pub access_policy_config: Option<bool>, // Indicates support for the ONVIF default access policy. #[yaserde(attribute, rename = "DefaultAccessPolicy")] pub default_access_policy: Option<bool>, // Indicates support for IEEE 802.1X configuration. #[yaserde(attribute, rename = "Dot1X")] pub dot_1x: Option<bool>, // Indicates support for remote user configuration. Used when accessing // another device. #[yaserde(attribute, rename = "RemoteUserHandling")] pub remote_user_handling: Option<bool>, // Indicates support for WS-Security X.509 token. #[yaserde(attribute, rename = "X.509Token")] pub x_509_token: Option<bool>, // Indicates support for WS-Security SAML token. #[yaserde(attribute, rename = "SAMLToken")] pub saml_token: Option<bool>, // Indicates support for WS-Security Kerberos token. #[yaserde(attribute, rename = "KerberosToken")] pub kerberos_token: Option<bool>, // Indicates support for WS-Security Username token. #[yaserde(attribute, rename = "UsernameToken")] pub username_token: Option<bool>, // Indicates support for WS over HTTP digest authenticated communication // layer. #[yaserde(attribute, rename = "HttpDigest")] pub http_digest: Option<bool>, // Indicates support for WS-Security REL token. #[yaserde(attribute, rename = "RELToken")] pub rel_token: Option<bool>, // EAP Methods supported by the device. The int values refer to the #[yaserde(attribute, rename = "SupportedEAPMethods")] pub supported_eap_methods: Option<EapmethodTypes>, // The maximum number of users that the device supports. #[yaserde(attribute, rename = "MaxUsers")] pub max_users: Option<i32>, // Maximum number of characters supported for the username by CreateUsers. #[yaserde(attribute, rename = "MaxUserNameLength")] pub max_user_name_length: Option<i32>, // Maximum number of characters supported for the password by CreateUsers // and SetUser. #[yaserde(attribute, rename = "MaxPasswordLength")] pub max_password_length: Option<i32>, } impl Validate for SecurityCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct SystemCapabilities { // Indicates support for WS Discovery resolve requests. #[yaserde(attribute, rename = "DiscoveryResolve")] pub discovery_resolve: Option<bool>, // Indicates support for WS-Discovery Bye. #[yaserde(attribute, rename = "DiscoveryBye")] pub discovery_bye: Option<bool>, // Indicates support for remote discovery. #[yaserde(attribute, rename = "RemoteDiscovery")] pub remote_discovery: Option<bool>, // Indicates support for system backup through MTOM. #[yaserde(attribute, rename = "SystemBackup")] pub system_backup: Option<bool>, // Indicates support for retrieval of system logging through MTOM. #[yaserde(attribute, rename = "SystemLogging")] pub system_logging: Option<bool>, // Indicates support for firmware upgrade through MTOM. #[yaserde(attribute, rename = "FirmwareUpgrade")] pub firmware_upgrade: Option<bool>, // Indicates support for firmware upgrade through HTTP. #[yaserde(attribute, rename = "HttpFirmwareUpgrade")] pub http_firmware_upgrade: Option<bool>, // Indicates support for system backup through HTTP. #[yaserde(attribute, rename = "HttpSystemBackup")] pub http_system_backup: Option<bool>, // Indicates support for retrieval of system logging through HTTP. #[yaserde(attribute, rename = "HttpSystemLogging")] pub http_system_logging: Option<bool>, // Indicates support for retrieving support information through HTTP. #[yaserde(attribute, rename = "HttpSupportInformation")] pub http_support_information: Option<bool>, // Indicates support for storage configuration interfaces. #[yaserde(attribute, rename = "StorageConfiguration")] pub storage_configuration: Option<bool>, // Indicates maximum number of storage configurations supported. #[yaserde(attribute, rename = "MaxStorageConfigurations")] pub max_storage_configurations: Option<i32>, // If present signals support for geo location. The value signals the // supported number of entries. #[yaserde(attribute, rename = "GeoLocationEntries")] pub geo_location_entries: Option<i32>, // List of supported automatic GeoLocation adjustment supported by the // device. Valid items are defined by tds:AutoGeoMode. #[yaserde(attribute, rename = "AutoGeo")] pub auto_geo: Option<tt::StringAttrList>, // Enumerates the supported StorageTypes, see tds:StorageType. #[yaserde(attribute, rename = "StorageTypesSupported")] pub storage_types_supported: Option<tt::StringAttrList>, } impl Validate for SystemCapabilities {} #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum AutoGeoModes { // Automatic adjustment of the device location. Location, // Automatic adjustment of the device orientation relative to the compass // also called yaw. Heading, // Automatic adjustment of the deviation from the horizon also called pitch // and roll. Leveling, __Unknown__(String), } impl Default for AutoGeoModes { fn default() -> AutoGeoModes { Self::__Unknown__("No valid variants".into()) } } impl Validate for AutoGeoModes {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct MiscCapabilities { // Lists of commands supported by SendAuxiliaryCommand. #[yaserde(attribute, rename = "AuxiliaryCommands")] pub auxiliary_commands: Option<tt::StringAttrList>, } impl Validate for MiscCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetDeviceInformation {} impl Validate for GetDeviceInformation {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetDeviceInformationResponse { // The manufactor of the device. #[yaserde(prefix = "tds", rename = "Manufacturer")] pub manufacturer: String, // The device model. #[yaserde(prefix = "tds", rename = "Model")] pub model: String, // The firmware version in the device. #[yaserde(prefix = "tds", rename = "FirmwareVersion")] pub firmware_version: String, // The serial number of the device. #[yaserde(prefix = "tds", rename = "SerialNumber")] pub serial_number: String, // The hardware ID of the device. #[yaserde(prefix = "tds", rename = "HardwareId")] pub hardware_id: String, } impl Validate for GetDeviceInformationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct SetSystemDateAndTime { // Defines if the date and time is set via NTP or manually. #[yaserde(prefix = "tds", rename = "DateTimeType")] pub date_time_type: tt::SetDateTimeType, // Automatically adjust Daylight savings if defined in TimeZone. #[yaserde(prefix = "tds", rename = "DaylightSavings")] pub daylight_savings: bool, // The time zone in POSIX 1003.1 format #[yaserde(prefix = "tds", rename = "TimeZone")] pub time_zone: Option<tt::TimeZone>, // Date and time in UTC. If time is obtained via NTP, UTCDateTime has no // meaning #[yaserde(prefix = "tds", rename = "UTCDateTime")] pub utc_date_time: Option<tt::DateTime>, } impl Validate for SetSystemDateAndTime {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct SetSystemDateAndTimeResponse {} impl Validate for SetSystemDateAndTimeResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetSystemDateAndTime {} impl Validate for GetSystemDateAndTime {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetSystemDateAndTimeResponse { // Contains information whether system date and time are set manually or by // NTP, daylight savings is on or off, time zone in POSIX 1003.1 format and // system date and time in UTC and also local system date and time. #[yaserde(prefix = "tds", rename = "SystemDateAndTime")] pub system_date_and_time: tt::SystemDateTime, } impl Validate for GetSystemDateAndTimeResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct SetSystemFactoryDefault { // Specifies the factory default action type. #[yaserde(prefix = "tds", rename = "FactoryDefault")] pub factory_default: tt::FactoryDefaultType, } impl Validate for SetSystemFactoryDefault {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct SetSystemFactoryDefaultResponse {} impl Validate for SetSystemFactoryDefaultResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct UpgradeSystemFirmware { #[yaserde(prefix = "tds", rename = "Firmware")] pub firmware: tt::AttachmentData, } impl Validate for UpgradeSystemFirmware {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct UpgradeSystemFirmwareResponse { #[yaserde(prefix = "tds", rename = "Message")] pub message: String, } impl Validate for UpgradeSystemFirmwareResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct SystemReboot {} impl Validate for SystemReboot {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct SystemRebootResponse { // Contains the reboot message sent by the device. #[yaserde(prefix = "tds", rename = "Message")] pub message: String, } impl Validate for SystemRebootResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct RestoreSystem { #[yaserde(prefix = "tds", rename = "BackupFiles")] pub backup_files: Vec<tt::BackupFile>, } impl Validate for RestoreSystem {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct RestoreSystemResponse {} impl Validate for RestoreSystemResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetSystemBackup {} impl Validate for GetSystemBackup {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetSystemBackupResponse { #[yaserde(prefix = "tds", rename = "BackupFiles")] pub backup_files: Vec<tt::BackupFile>, } impl Validate for GetSystemBackupResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetSystemSupportInformation {} impl Validate for GetSystemSupportInformation {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetSystemSupportInformationResponse { // Contains the arbitary device diagnostics information. #[yaserde(prefix = "tds", rename = "SupportInformation")] pub support_information: tt::SupportInformation, } impl Validate for GetSystemSupportInformationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetSystemLog { // Specifies the type of system log to get. #[yaserde(prefix = "tds", rename = "LogType")] pub log_type: tt::SystemLogType, } impl Validate for GetSystemLog {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetSystemLogResponse { // Contains the system log information. #[yaserde(prefix = "tds", rename = "SystemLog")] pub system_log: tt::SystemLog, } impl Validate for GetSystemLogResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetScopes {} impl Validate for GetScopes {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetScopesResponse { // Contains a list of URI definining the device scopes. Scope parameters can // be of two types: fixed and configurable. Fixed parameters can not be // altered. #[yaserde(prefix = "tds", rename = "Scopes")] pub scopes: Vec<tt::Scope>, } impl Validate for GetScopesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct SetScopes { // Contains a list of scope parameters that will replace all existing // configurable scope parameters. #[yaserde(prefix = "tds", rename = "Scopes")] pub scopes: Vec<String>, } impl Validate for SetScopes {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct SetScopesResponse {} impl Validate for SetScopesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct AddScopes { // Contains a list of new configurable scope parameters that will be added // to the existing configurable scope. #[yaserde(prefix = "tds", rename = "ScopeItem")] pub scope_item: Vec<String>, } impl Validate for AddScopes {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct AddScopesResponse {} impl Validate for AddScopesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct RemoveScopes { // Contains a list of URIs that should be removed from the device scope. #[yaserde(prefix = "tds", rename = "ScopeItem")] pub scope_item: Vec<String>, } impl Validate for RemoveScopes {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct RemoveScopesResponse { // Contains a list of URIs that has been removed from the device scope #[yaserde(prefix = "tds", rename = "ScopeItem")] pub scope_item: Vec<String>, } impl Validate for RemoveScopesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetDiscoveryMode {} impl Validate for GetDiscoveryMode {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetDiscoveryModeResponse { // Indicator of discovery mode: Discoverable, NonDiscoverable. #[yaserde(prefix = "tds", rename = "DiscoveryMode")] pub discovery_mode: tt::DiscoveryMode, } impl Validate for GetDiscoveryModeResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct SetDiscoveryMode { // Indicator of discovery mode: Discoverable, NonDiscoverable. #[yaserde(prefix = "tds", rename = "DiscoveryMode")] pub discovery_mode: tt::DiscoveryMode, } impl Validate for SetDiscoveryMode {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct SetDiscoveryModeResponse {} impl Validate for SetDiscoveryModeResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetRemoteDiscoveryMode {} impl Validate for GetRemoteDiscoveryMode {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetRemoteDiscoveryModeResponse { // Indicator of discovery mode: Discoverable, NonDiscoverable. #[yaserde(prefix = "tds", rename = "RemoteDiscoveryMode")] pub remote_discovery_mode: tt::DiscoveryMode, } impl Validate for GetRemoteDiscoveryModeResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct SetRemoteDiscoveryMode { // Indicator of discovery mode: Discoverable, NonDiscoverable. #[yaserde(prefix = "tds", rename = "RemoteDiscoveryMode")] pub remote_discovery_mode: tt::DiscoveryMode, } impl Validate for SetRemoteDiscoveryMode {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct SetRemoteDiscoveryModeResponse {} impl Validate for SetRemoteDiscoveryModeResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetDPAddresses {} impl Validate for GetDPAddresses {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetDPAddressesResponse { #[yaserde(prefix = "tds", rename = "DPAddress")] pub dp_address: Vec<tt::NetworkHost>, } impl Validate for GetDPAddressesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct SetDPAddresses { #[yaserde(prefix = "tds", rename = "DPAddress")] pub dp_address: Vec<tt::NetworkHost>, } impl Validate for SetDPAddresses {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct SetDPAddressesResponse {} impl Validate for SetDPAddressesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetEndpointReference {} impl Validate for GetEndpointReference {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetEndpointReferenceResponse { #[yaserde(prefix = "tds", rename = "GUID")] pub guid: String, } impl Validate for GetEndpointReferenceResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetRemoteUser {} impl Validate for GetRemoteUser {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetRemoteUserResponse { #[yaserde(prefix = "tds", rename = "RemoteUser")] pub remote_user: Option<tt::RemoteUser>, } impl Validate for GetRemoteUserResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct SetRemoteUser { #[yaserde(prefix = "tds", rename = "RemoteUser")] pub remote_user: Option<tt::RemoteUser>, } impl Validate for SetRemoteUser {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct SetRemoteUserResponse {} impl Validate for SetRemoteUserResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetUsers {} impl Validate for GetUsers {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetUsersResponse { // Contains a list of the onvif users and following information is included // in each entry: username and user level. #[yaserde(prefix = "tds", rename = "User")] pub user: Vec<tt::User>, } impl Validate for GetUsersResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct CreateUsers { // Creates new device users and corresponding credentials. Each user entry // includes: username, password and user level. Either all users are created // successfully or a fault message MUST be returned without creating any // user. If trying to create several users with exactly the same username // the request is rejected and no users are created. If password is missing, // then fault message Too weak password is returned. #[yaserde(prefix = "tds", rename = "User")] pub user: Vec<tt::User>, } impl Validate for CreateUsers {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct CreateUsersResponse {} impl Validate for CreateUsersResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct DeleteUsers { // Deletes users on an device and there may exist users that cannot be // deleted to ensure access to the unit. Either all users are deleted // successfully or a fault message MUST be returned and no users be deleted. // If a username exists multiple times in the request, then a fault message // is returned. #[yaserde(prefix = "tds", rename = "Username")] pub username: Vec<String>, } impl Validate for DeleteUsers {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct DeleteUsersResponse {} impl Validate for DeleteUsersResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct SetUser { // Updates the credentials for one or several users on an device. Either all // change requests are processed successfully or a fault message MUST be // returned. If the request contains the same username multiple times, a // fault message is returned. #[yaserde(prefix = "tds", rename = "User")] pub user: Vec<tt::User>, } impl Validate for SetUser {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct SetUserResponse {} impl Validate for SetUserResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetWsdlUrl {} impl Validate for GetWsdlUrl {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetWsdlUrlResponse { #[yaserde(prefix = "tds", rename = "WsdlUrl")] pub wsdl_url: String, } impl Validate for GetWsdlUrlResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetCapabilities { // List of categories to retrieve capability information on. #[yaserde(prefix = "tds", rename = "Category")] pub category: Vec<tt::CapabilityCategory>, } impl Validate for GetCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tds", namespace = "tds: http://www.onvif.org/ver10/device/wsdl" )] pub struct GetCapabilitiesResponse { // Capability information. #[yaserde(prefix = "tds", rename = "Capabilities")] pub capabilities: tt::Capabilities, }
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
true
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/actionengine/src/lib.rs
wsdl_rs/actionengine/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use b_2 as wsnt; use onvif as tt; use validate::Validate; use xsd_types::types as xs; use yaserde_derive::{YaDeserialize, YaSerialize}; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct GetSupportedActions {} impl Validate for GetSupportedActions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct GetSupportedActionsResponse { // Array of supported Action types #[yaserde(prefix = "tae", rename = "SupportedActions")] pub supported_actions: SupportedActions, } impl Validate for GetSupportedActionsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct GetActions {} impl Validate for GetActions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct GetActionsResponse { // Array of current Action configurations #[yaserde(prefix = "tae", rename = "Action")] pub action: Vec<Action>, } impl Validate for GetActionsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct CreateActions { // Array of Actions to be configured on service provider #[yaserde(prefix = "tae", rename = "Action")] pub action: Vec<ActionConfiguration>, } impl Validate for CreateActions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct CreateActionsResponse { // Array of configured Actions with service provider assigned unique // identifiers #[yaserde(prefix = "tae", rename = "Action")] pub action: Vec<Action>, } impl Validate for CreateActionsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct DeleteActions { // Array of tokens referencing existing Action configurations to be removed #[yaserde(prefix = "tae", rename = "Token")] pub token: Vec<tt::ReferenceToken>, } impl Validate for DeleteActions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct DeleteActionsResponse {} impl Validate for DeleteActionsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct ModifyActions { // Array of Action configurations to update the existing action // configurations #[yaserde(prefix = "tae", rename = "Action")] pub action: Vec<Action>, } impl Validate for ModifyActions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct ModifyActionsResponse {} impl Validate for ModifyActionsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct GetServiceCapabilities {} impl Validate for GetServiceCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct GetServiceCapabilitiesResponse { #[yaserde(prefix = "tae", rename = "Capabilities")] pub capabilities: ActionEngineCapabilities, } impl Validate for GetServiceCapabilitiesResponse {} // pub type Capabilities = ActionEngineCapabilities; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct GetActionTriggers {} impl Validate for GetActionTriggers {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct GetActionTriggersResponse { // Array of current Action Trigger configurations #[yaserde(prefix = "tae", rename = "ActionTrigger")] pub action_trigger: Vec<ActionTrigger>, } impl Validate for GetActionTriggersResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct CreateActionTriggers { // Action Triggers to be configured #[yaserde(prefix = "tae", rename = "ActionTrigger")] pub action_trigger: Vec<ActionTriggerConfiguration>, } impl Validate for CreateActionTriggers {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct CreateActionTriggersResponse { // Returns configured Action Triggers with service provider assigned unique // identifers #[yaserde(prefix = "tae", rename = "ActionTrigger")] pub action_trigger: Vec<ActionTrigger>, } impl Validate for CreateActionTriggersResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct ModifyActionTriggers { // Array of Action Trigger configurations to be updated. #[yaserde(prefix = "tae", rename = "ActionTrigger")] pub action_trigger: Vec<ActionTrigger>, } impl Validate for ModifyActionTriggers {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct ModifyActionTriggersResponse {} impl Validate for ModifyActionTriggersResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct DeleteActionTriggers { // Array of tokens referencing existing Action Trigger configurations to be // removed #[yaserde(prefix = "tae", rename = "Token")] pub token: Vec<tt::ReferenceToken>, } impl Validate for DeleteActionTriggers {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct DeleteActionTriggersResponse {} impl Validate for DeleteActionTriggersResponse {} // Describes the configuration parameters of an action. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct ActionConfigDescription { // Action configuration parameter descriptions #[yaserde(prefix = "tae", rename = "ParameterDescription")] pub parameter_description: tt::ItemListDescription, // Action type name #[yaserde(attribute, rename = "Name")] pub name: String, } impl Validate for ActionConfigDescription {} // SupportedActions data structure lists the available action types that service // provider supports. For each action type, data structure contains the action // configuration parameters. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct SupportedActions { // Lists the location of all schemas that are referenced in the supported // actions. If the action descriptions reference data types in the ONVIF // schema file,the ONVIF schema file MUST be explicitly listed. #[yaserde(prefix = "tae", rename = "ActionContentSchemaLocation")] pub action_content_schema_location: Vec<String>, // List of actions supported by Action Engine Service provider. #[yaserde(prefix = "tae", rename = "ActionDescription")] pub action_description: Vec<ActionConfigDescription>, #[yaserde(prefix = "tae", rename = "Extension")] pub extension: Option<SupportedActionsExtension>, } impl Validate for SupportedActions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct SupportedActionsExtension {} impl Validate for SupportedActionsExtension {} // Action Engine Capabilities data structure contains the maximum number of // supported actions and number of actions in use for generic as well as // specific action types #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct ActionEngineCapabilities { // Limits for each action type #[yaserde(prefix = "tae", rename = "ActionCapabilities")] pub action_capabilities: Vec<ActionTypeLimits>, #[yaserde(prefix = "tae", rename = "Extension")] pub extension: Option<ActionEngineCapabilitiesExtension>, // The maximum number of trigger configurations that the service provider // can concurrently support #[yaserde(attribute, rename = "MaximumTriggers")] pub maximum_triggers: Option<xs::Integer>, // The maximum number of actions that the service provider can concurrently // support #[yaserde(attribute, rename = "MaximumActions")] pub maximum_actions: Option<xs::Integer>, } impl Validate for ActionEngineCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct ActionEngineCapabilitiesExtension {} impl Validate for ActionEngineCapabilitiesExtension {} // ActionTypeLimits data structure contains maximum and current usage // information for a specific action type in the service provider #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct ActionTypeLimits { // Action Type #[yaserde(attribute, rename = "Type")] pub _type: String, // For the specific action type, the maximum number of actions that could be // concurrently supported by the service provider #[yaserde(attribute, rename = "Maximum")] pub maximum: xs::Integer, // For the specific action type, the number of actions in use by the service // provider #[yaserde(attribute, rename = "InUse")] pub in_use: Option<xs::Integer>, } impl Validate for ActionTypeLimits {} // Action Configuration data type contains the configuration settings of action // configuration parameters, service requester given action Name, and service // provider supported action type value #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct ActionConfiguration { // Action configuration parameter settings. #[yaserde(prefix = "tae", rename = "Parameters")] pub parameters: tt::ItemList, // User given name. #[yaserde(attribute, rename = "Name")] pub name: String, // Denotes the action type. #[yaserde(attribute, rename = "Type")] pub _type: String, } impl Validate for ActionConfiguration {} // Action data type contains the configuration settings of one action instance // and service provider assigned unique identifier for this action // configuration. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct Action { // Action configuration contains action type, user given action name, and // configuratin parameter settings. #[yaserde(prefix = "tae", rename = "Configuration")] pub configuration: ActionConfiguration, // Unique Action identifier that service provider assigned to the action // configuration. #[yaserde(attribute, rename = "Token")] pub token: tt::ReferenceToken, } impl Validate for Action {} // Action Trigger configuration data type contains mandatory Topic Expression // (Section Topic Filter in [Core Specification]), optional Message content // expression (Section Message Content Filter in [Core Specification]), and set // of actions to be triggered. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct ActionTriggerConfiguration { // Topic expression, for example, to trigger only for relays. Trigger based // on event topic. #[yaserde(prefix = "tae", rename = "TopicExpression")] pub topic_expression: wsnt::TopicExpressionType, // Content expression, for example, to trigger only when the relay value is // on. Trigger based on content data in event. #[yaserde(prefix = "tae", rename = "ContentExpression")] pub content_expression: Option<wsnt::QueryExpressionType>, // Reference to actions to be triggered when the conditions are satisfied. #[yaserde(prefix = "tae", rename = "ActionToken")] pub action_token: Vec<tt::ReferenceToken>, #[yaserde(prefix = "tae", rename = "Extension")] pub extension: Option<ActionTriggerConfigurationExtension>, } impl Validate for ActionTriggerConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct ActionTriggerConfigurationExtension {} impl Validate for ActionTriggerConfigurationExtension {} // Action Trigger data type contains the service provider assigned unique // identifier for the configuration and action trigger configuration data. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct ActionTrigger { // Action Trigger Configuration #[yaserde(prefix = "tae", rename = "Configuration")] pub configuration: ActionTriggerConfiguration, // Unique Action Trigger identifier that service provider assigned to the // action trigger configuration. #[yaserde(attribute, rename = "Token")] pub token: tt::ReferenceToken, } impl Validate for ActionTrigger {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct OnvifAction { #[yaserde(prefix = "tae", rename = "ActionDescription")] pub action_description: Vec<ActionConfigDescription>, } impl Validate for OnvifAction {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct EmailServerConfiguration { // SMTP EMail Server configuration #[yaserde(prefix = "tae", rename = "SMTPConfig")] pub smtp_config: Smtpconfig, // POP EMail Server configuration #[yaserde(prefix = "tae", rename = "POPConfig")] pub pop_config: Popconfig, // Credentials configuration #[yaserde(prefix = "tae", rename = "AuthenticationConfig")] pub authentication_config: AuthenticationConfig, } impl Validate for EmailServerConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct Smtpconfig { // Destination SMTP Address configuration #[yaserde(prefix = "tae", rename = "HostAddress")] pub host_address: HostAddress, #[yaserde(attribute, rename = "portNo")] pub port_no: Option<xs::Integer>, } impl Validate for Smtpconfig {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct Popconfig { // Destination POP Server Address configuration #[yaserde(prefix = "tae", rename = "HostAddress")] pub host_address: HostAddress, } impl Validate for Popconfig {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct HostAddress { // IP Address #[yaserde(prefix = "tae", rename = "Value")] pub value: String, // IP Address format type such as IPv4 or IPv6 #[yaserde(attribute, rename = "formatType")] pub format_type: AddressFormatType, } impl Validate for HostAddress {} #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum AddressFormatType { #[yaserde(rename = "hostname")] Hostname, #[yaserde(rename = "ipv4")] Ipv4, #[yaserde(rename = "ipv6")] Ipv6, Extended, __Unknown__(String), } impl Default for AddressFormatType { fn default() -> AddressFormatType { Self::__Unknown__("No valid variants".into()) } } impl Validate for AddressFormatType {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct UserCredentials { // Username #[yaserde(prefix = "tae", rename = "username")] pub username: String, // Password #[yaserde(prefix = "tae", rename = "password")] pub password: Option<String>, #[yaserde(prefix = "tae", rename = "Extension")] pub extension: Option<UserCredentialsExtension>, } impl Validate for UserCredentials {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct UserCredentialsExtension {} impl Validate for UserCredentialsExtension {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct AuthenticationConfig { // Username-password #[yaserde(prefix = "tae", rename = "User")] pub user: UserCredentials, // Email server authentication mode #[yaserde(attribute, rename = "mode")] pub mode: EmailAuthenticationMode, } impl Validate for AuthenticationConfig {} #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum EmailAuthenticationMode { #[yaserde(rename = "none")] None, #[yaserde(rename = "SMTP")] Smtp, #[yaserde(rename = "POPSMTP")] Popsmtp, Extended, __Unknown__(String), } impl Default for EmailAuthenticationMode { fn default() -> EmailAuthenticationMode { Self::__Unknown__("No valid variants".into()) } } impl Validate for EmailAuthenticationMode {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct EmailReceiverConfiguration { // Configuration for E-mail TO #[yaserde(prefix = "tae", rename = "TO")] pub to: Vec<String>, // Configuration for E-mail CC #[yaserde(prefix = "tae", rename = "CC")] pub cc: Vec<String>, #[yaserde(prefix = "tae", rename = "Extension")] pub extension: Option<EmailReceiverConfigurationExtension>, } impl Validate for EmailReceiverConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct EmailReceiverConfigurationExtension {} impl Validate for EmailReceiverConfigurationExtension {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct EmailAttachmentConfiguration { #[yaserde(prefix = "tae", rename = "FileName")] pub file_name: Option<String>, #[yaserde(prefix = "tae", rename = "doSuffix")] pub do_suffix: Option<FileSuffixType>, #[yaserde(prefix = "tae", rename = "Extension")] pub extension: Option<EmailAttachmentConfigurationExtension>, } impl Validate for EmailAttachmentConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct EmailAttachmentConfigurationExtension {} impl Validate for EmailAttachmentConfigurationExtension {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct EmailBodyTextConfiguration { // Whether content of E-mail message contains event data #[yaserde(attribute, rename = "includeEvent")] pub include_event: Option<bool>, #[yaserde(attribute, rename = "type")] pub _type: Option<String>, } impl Validate for EmailBodyTextConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct MediaSource { // MediaSource profile reference token #[yaserde(prefix = "tae", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, } impl Validate for MediaSource {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct HttpHostConfigurations { // Destination HTTP Server configuration #[yaserde(prefix = "tae", rename = "HttpDestination")] pub http_destination: Vec<HttpDestinationConfiguration>, #[yaserde(prefix = "tae", rename = "Extension")] pub extension: Option<HttpHostConfigurationsExtension>, } impl Validate for HttpHostConfigurations {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct HttpHostConfigurationsExtension {} impl Validate for HttpHostConfigurationsExtension {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct HttpDestinationConfiguration { // Destination HTTP Server address configuration #[yaserde(prefix = "tae", rename = "HostAddress")] pub host_address: HttpHostAddress, // User Credentials configuration for destination HTTP Server #[yaserde(prefix = "tae", rename = "HttpAuthentication")] pub http_authentication: Option<HttpAuthenticationConfiguration>, #[yaserde(prefix = "tae", rename = "Extension")] pub extension: Option<HttpDestinationConfigurationExtension>, // URI for POST Message destination #[yaserde(attribute, rename = "uri")] pub uri: Option<String>, // HTTP/HTTPS protocol selection (default is http) #[yaserde(attribute, rename = "protocol")] pub protocol: Option<HttpProtocolType>, } impl Validate for HttpDestinationConfiguration {} #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum HttpProtocolType { #[yaserde(rename = "http")] Http, #[yaserde(rename = "https")] Https, Extended, __Unknown__(String), } impl Default for HttpProtocolType { fn default() -> HttpProtocolType { Self::__Unknown__("No valid variants".into()) } } impl Validate for HttpProtocolType {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct HttpDestinationConfigurationExtension {} impl Validate for HttpDestinationConfigurationExtension {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct HttpAuthenticationConfiguration { // User credentials #[yaserde(prefix = "tae", rename = "User")] pub user: Option<UserCredentials>, #[yaserde(prefix = "tae", rename = "Extension")] pub extension: Option<HttpAuthenticationConfigurationExtension>, // HTTP Authentication Method #[yaserde(attribute, rename = "method")] pub method: Option<HttpAuthenticationMethodType>, } impl Validate for HttpAuthenticationConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct HttpAuthenticationConfigurationExtension {} impl Validate for HttpAuthenticationConfigurationExtension {} #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum HttpAuthenticationMethodType { #[yaserde(rename = "none")] None, #[yaserde(rename = "MD5Digest")] Md5Digest, Extended, __Unknown__(String), } impl Default for HttpAuthenticationMethodType { fn default() -> HttpAuthenticationMethodType { Self::__Unknown__("No valid variants".into()) } } impl Validate for HttpAuthenticationMethodType {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct HttpHostAddress { // Destination HTTP Server IP Address #[yaserde(prefix = "tae", rename = "Value")] pub value: String, // IPv4 or IPv6 #[yaserde(attribute, rename = "formatType")] pub format_type: AddressFormatType, // Port Number if different from 80 #[yaserde(attribute, rename = "portNo")] pub port_no: Option<xs::Integer>, } impl Validate for HttpHostAddress {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct PostContentConfiguration { // MediaSource reference when the media is attached to POST message #[yaserde(prefix = "tae", rename = "MediaReference")] pub media_reference: Option<MediaSource>, // Configuration for POST Message content #[yaserde(prefix = "tae", rename = "PostBody")] pub post_body: PostBodyConfiguration, } impl Validate for PostContentConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct PostBodyConfiguration { #[yaserde(attribute, rename = "formData")] pub form_data: Option<String>, // Whether include event into POST message #[yaserde(attribute, rename = "includeEvent")] pub include_event: Option<bool>, // Whether attach media into POST message #[yaserde(attribute, rename = "includeMedia")] pub include_media: Option<bool>, } impl Validate for PostBodyConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct FtpHostConfigurations { // FTP Action destination configuration #[yaserde(prefix = "tae", rename = "FtpDestination")] pub ftp_destination: Vec<FtpDestinationConfiguration>, #[yaserde(prefix = "tae", rename = "Extension")] pub extension: Option<FtpHostConfigurationsExtension>, } impl Validate for FtpHostConfigurations {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct FtpHostConfigurationsExtension {} impl Validate for FtpHostConfigurationsExtension {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct FtpDestinationConfiguration { // FTP Server IP Address #[yaserde(prefix = "tae", rename = "HostAddress")] pub host_address: FtpHostAddress, // Upload Directory Path #[yaserde(prefix = "tae", rename = "UploadPath")] pub upload_path: String, // User credentials confguration for target FTP Server #[yaserde(prefix = "tae", rename = "FtpAuthentication")] pub ftp_authentication: FtpAuthenticationConfiguration, #[yaserde(prefix = "tae", rename = "Extension")] pub extension: Option<FtpDestinationConfigurationExtension>, } impl Validate for FtpDestinationConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct FtpDestinationConfigurationExtension {} impl Validate for FtpDestinationConfigurationExtension {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct FtpAuthenticationConfiguration { // User Credentials #[yaserde(prefix = "tae", rename = "User")] pub user: Option<UserCredentials>, #[yaserde(prefix = "tae", rename = "Extension")] pub extension: Option<FtpAuthenticationConfigurationExtension>, } impl Validate for FtpAuthenticationConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct FtpAuthenticationConfigurationExtension {} impl Validate for FtpAuthenticationConfigurationExtension {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct FtpHostAddress { // FTP Server IP Address #[yaserde(prefix = "tae", rename = "Value")] pub value: String, // IPv4 or IPv6 #[yaserde(attribute, rename = "formatType")] pub format_type: AddressFormatType, // Port Number #[yaserde(attribute, rename = "portNo")] pub port_no: Option<xs::Integer>, } impl Validate for FtpHostAddress {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct FtpContent { #[yaserde(prefix = "tae", rename = "FtpContentConfig")] pub ftp_content_config: FtpContentConfiguration, } impl Validate for FtpContent {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct FtpFileNameConfigurations { // Name of file #[yaserde(attribute, rename = "file_name")] pub file_name: Option<String>, // Suffix of file #[yaserde(attribute, rename = "suffix")] pub suffix: Option<FileSuffixType>, } impl Validate for FtpFileNameConfigurations {} #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum FileSuffixType { #[yaserde(rename = "none")] None, #[yaserde(rename = "sequence")] Sequence, #[yaserde(rename = "dateTime")] DateTime, Extended, __Unknown__(String), } impl Default for FileSuffixType { fn default() -> FileSuffixType { Self::__Unknown__("No valid variants".into()) } } impl Validate for FileSuffixType {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tae", namespace = "tae: http://www.onvif.org/ver10/actionengine/wsdl" )] pub struct FtpContentConfiguration { #[yaserde(prefix = "tae", rename = "FtpContentConfigurationChoice")] pub ftp_content_configuration_choice: ftp_content_configuration::FtpContentConfigurationChoice, // Type of FTP Upload action #[yaserde(attribute, rename = "Type")] pub _type: String, } impl Validate for FtpContentConfiguration {} pub mod ftp_content_configuration { use super::*; #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)]
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
true
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/authenticationbehavior/src/lib.rs
wsdl_rs/authenticationbehavior/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use onvif as tt; use types as pt; use validate::Validate; use yaserde_derive::{YaDeserialize, YaSerialize}; // The service capabilities reflect optional functionality of a service. The // information is static // and does not change during device operation. The following capabilities are // available: #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct ServiceCapabilities { // The maximum number of entries returned by a single Get<Entity>List or // Get<Entity> // request. // The device shall never return more than this number of entities in a // single response. #[yaserde(attribute, rename = "MaxLimit")] pub max_limit: pt::PositiveInteger, // Indicates the maximum number of authentication profiles the device // supports. The device // shall // support at least one authentication profile. #[yaserde(attribute, rename = "MaxAuthenticationProfiles")] pub max_authentication_profiles: pt::PositiveInteger, // Indicates the maximum number of authentication policies per // authentication profile supported // by the device. #[yaserde(attribute, rename = "MaxPoliciesPerAuthenticationProfile")] pub max_policies_per_authentication_profile: pt::PositiveInteger, // Indicates the maximum number of security levels the device supports. The // device shall // support at least one // security level. #[yaserde(attribute, rename = "MaxSecurityLevels")] pub max_security_levels: pt::PositiveInteger, // Indicates the maximum number of recognition groups per security level // supported by the // device. #[yaserde(attribute, rename = "MaxRecognitionGroupsPerSecurityLevel")] pub max_recognition_groups_per_security_level: pt::PositiveInteger, // Indicates the maximum number of recognition methods per recognition group // supported by the // device. #[yaserde(attribute, rename = "MaxRecognitionMethodsPerRecognitionGroup")] pub max_recognition_methods_per_recognition_group: pt::PositiveInteger, // Indicates that the client is allowed to supply the token when creating // authentication // profiles and // security levels. To enable the use of the commands // SetAuthenticationProfile and // SetSecurityLevel, the // value must be set to true. #[yaserde(attribute, rename = "ClientSuppliedTokenSupported")] pub client_supplied_token_supported: Option<bool>, // A list of supported authentication modes (including custom modes). // This field is optional, and when omitted, the client shall assume that // the // device supports "pt:SingleCredential" only. #[yaserde(attribute, rename = "SupportedAuthenticationModes")] pub supported_authentication_modes: Option<tt::StringAttrList>, } impl Validate for ServiceCapabilities {} // pub type Capabilities = ServiceCapabilities; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct AuthenticationProfileInfo { // A user readable name. It shall be up to 64 characters. #[yaserde(prefix = "tab", rename = "Name")] pub name: pt::Name, // User readable description for the access profile. It shall be up // to 1024 characters. #[yaserde(prefix = "tab", rename = "Description")] pub description: Option<pt::Description>, pub base: pt::DataEntity, } impl Validate for AuthenticationProfileInfo {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct AuthenticationProfile { // The default security level is used if none of the authentication policies // has a schedule covering the time of access (or if no authentication // policies // are defined). #[yaserde(prefix = "tab", rename = "DefaultSecurityLevelToken")] pub default_security_level_token: pt::ReferenceToken, // Each authentication policy associates a security level with a schedule // (during // which the specified security level will be required at the access point). #[yaserde(prefix = "tab", rename = "AuthenticationPolicy")] pub authentication_policy: Vec<AuthenticationPolicy>, #[yaserde(prefix = "tab", rename = "Extension")] pub extension: Option<AuthenticationProfileExtension>, pub base: AuthenticationProfileInfo, } impl Validate for AuthenticationProfile {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct AuthenticationProfileExtension {} impl Validate for AuthenticationProfileExtension {} // The authentication policy is an association of a security level and a // schedule. It defines when // a certain security level is required to grant access to a credential holder. // Each security // level is given a unique priority. If authentication policies have overlapping // schedules, // the security level with the highest priority is used. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct AuthenticationPolicy { // Reference to the schedule used by the authentication policy. #[yaserde(prefix = "tab", rename = "ScheduleToken")] pub schedule_token: pt::ReferenceToken, // A list of security level constraint structures defining the conditions // for what security level to use. // Minimum one security level constraint must be specified. #[yaserde(prefix = "tab", rename = "SecurityLevelConstraint")] pub security_level_constraint: Vec<SecurityLevelConstraint>, #[yaserde(prefix = "tab", rename = "Extension")] pub extension: Option<AuthenticationPolicyExtension>, } impl Validate for AuthenticationPolicy {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct AuthenticationPolicyExtension {} impl Validate for AuthenticationPolicyExtension {} // This structure defines what security level should be active depending on the // state of the // schedule. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct SecurityLevelConstraint { // Corresponds to the Active field in the ScheduleState structure in // [ONVIF Schedule Service Specification]. #[yaserde(prefix = "tab", rename = "ActiveRegularSchedule")] pub active_regular_schedule: bool, // Corresponds to the SpecialDay field in the ScheduleState structure in // [ONVIF Schedule Service Specification]. // This field will be ignored if the device do not support special days. #[yaserde(prefix = "tab", rename = "ActiveSpecialDaySchedule")] pub active_special_day_schedule: bool, // Defines the mode of authentication. Authentication modes starting with // the prefix // pt: are reserved to define ONVIF-specific authentication modes. For // custom defined // authentication modes, free text can be used. // The following authentication modes are defined by ONVIF: // pt:SingleCredential - Normal mode where only one credential holder is // required to be granted access. // pt:DualCredential - Two credential holders are required to be granted // access #[yaserde(prefix = "tab", rename = "AuthenticationMode")] pub authentication_mode: Option<pt::Name>, // Reference to the security level used by the authentication policy. #[yaserde(prefix = "tab", rename = "SecurityLevelToken")] pub security_level_token: pt::ReferenceToken, #[yaserde(prefix = "tab", rename = "Extension")] pub extension: Option<SecurityLevelConstraintExtension>, } impl Validate for SecurityLevelConstraint {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct SecurityLevelConstraintExtension {} impl Validate for SecurityLevelConstraintExtension {} // Recognition is the action of identifying authorized users requesting access // by the comparison of // presented // credential data with recorded credential data. A recognition method is either // memorized, // biometric or held // within a physical credential. A recognition type is either a recognition // method or a physical // input such as // a request-to-exit button. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct RecognitionMethod { // The requested type of recognition. #[yaserde(prefix = "tab", rename = "RecognitionType")] pub recognition_type: String, // The order value defines when this recognition method will be requested in // relation // to the other recognition methods in the same security level. A lower // number indicates // that the recognition method will be requested before recognition methods // with a higher number. #[yaserde(prefix = "tab", rename = "Order")] pub order: i32, #[yaserde(prefix = "tab", rename = "Extension")] pub extension: Option<RecognitionMethodExtension>, } impl Validate for RecognitionMethod {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct RecognitionMethodExtension {} impl Validate for RecognitionMethodExtension {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct RecognitionGroup { // A list of recognition methods to request for at the access point. #[yaserde(prefix = "tab", rename = "RecognitionMethod")] pub recognition_method: Vec<RecognitionMethod>, #[yaserde(prefix = "tab", rename = "Extension")] pub extension: Option<RecognitionGroupExtension>, } impl Validate for RecognitionGroup {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct RecognitionGroupExtension {} impl Validate for RecognitionGroupExtension {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct SecurityLevelInfo { // A user readable name. It shall be up to 64 characters. #[yaserde(prefix = "tab", rename = "Name")] pub name: pt::Name, // A higher number indicates that the security level is considered more // secure // than security levels with lower priorities. The priority is used when an // authentication profile have overlapping schedules with different security // levels. When an access point is accessed, the authentication policies are // walked through in priority order (highest priority first). When a // schedule is // found covering the time of access, the associated security level is used // and // processing stops. Two security levels cannot have the same priority. #[yaserde(prefix = "tab", rename = "Priority")] pub priority: i32, // User readable description for the access profile. It shall be up // to 1024 characters. #[yaserde(prefix = "tab", rename = "Description")] pub description: Option<pt::Description>, pub base: pt::DataEntity, } impl Validate for SecurityLevelInfo {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct SecurityLevel { // The recognition groups are used to define a logical OR between the // groups. Each // recognition group consists of one or more recognition methods. #[yaserde(prefix = "tab", rename = "RecognitionGroup")] pub recognition_group: Vec<RecognitionGroup>, #[yaserde(prefix = "tab", rename = "Extension")] pub extension: Option<SecurityLevelExtension>, pub base: SecurityLevelInfo, } impl Validate for SecurityLevel {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct SecurityLevelExtension {} impl Validate for SecurityLevelExtension {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct GetServiceCapabilities {} impl Validate for GetServiceCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct GetServiceCapabilitiesResponse { // The capability response message contains the requested access rules // service capabilities using a hierarchical XML capability structure. #[yaserde(prefix = "tab", rename = "Capabilities")] pub capabilities: ServiceCapabilities, } impl Validate for GetServiceCapabilitiesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct GetAuthenticationProfileInfo { // Tokens of AuthenticationProfileInfo items to get. #[yaserde(prefix = "tab", rename = "Token")] pub token: Vec<pt::ReferenceToken>, } impl Validate for GetAuthenticationProfileInfo {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct GetAuthenticationProfileInfoResponse { // List of AuthenticationProfileInfo items. #[yaserde(prefix = "tab", rename = "AuthenticationProfileInfo")] pub authentication_profile_info: Vec<AuthenticationProfileInfo>, } impl Validate for GetAuthenticationProfileInfoResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct GetAuthenticationProfileInfoList { // Maximum number of entries to return. If not specified, less than one // or higher than what the device supports, the number of items is // determined by the // device. #[yaserde(prefix = "tab", rename = "Limit")] pub limit: Option<i32>, // Start returning entries from this start reference. If not specified, // entries shall start from the beginning of the dataset. #[yaserde(prefix = "tab", rename = "StartReference")] pub start_reference: Option<String>, } impl Validate for GetAuthenticationProfileInfoList {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct GetAuthenticationProfileInfoListResponse { // StartReference to use in next call to get the following items. If // absent, no more items to get. #[yaserde(prefix = "tab", rename = "NextStartReference")] pub next_start_reference: Option<String>, // List of AuthenticationProfileInfo items. #[yaserde(prefix = "tab", rename = "AuthenticationProfileInfo")] pub authentication_profile_info: Vec<AuthenticationProfileInfo>, } impl Validate for GetAuthenticationProfileInfoListResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct GetAuthenticationProfiles { // Tokens of AuthenticationProfile items to get. #[yaserde(prefix = "tab", rename = "Token")] pub token: Vec<pt::ReferenceToken>, } impl Validate for GetAuthenticationProfiles {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct GetAuthenticationProfilesResponse { // List of AuthenticationProfile items. #[yaserde(prefix = "tab", rename = "AuthenticationProfile")] pub authentication_profile: Vec<AuthenticationProfile>, } impl Validate for GetAuthenticationProfilesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct GetAuthenticationProfileList { // Maximum number of entries to return. If not specified, less than one // or higher than what the device supports, the number of items is // determined by the // device. #[yaserde(prefix = "tab", rename = "Limit")] pub limit: Option<i32>, // Start returning entries from this start reference. If not specified, // entries shall start from the beginning of the dataset. #[yaserde(prefix = "tab", rename = "StartReference")] pub start_reference: Option<String>, } impl Validate for GetAuthenticationProfileList {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct GetAuthenticationProfileListResponse { // StartReference to use in next call to get the following items. If // absent, no more items to get. #[yaserde(prefix = "tab", rename = "NextStartReference")] pub next_start_reference: Option<String>, // List of AuthenticationProfile items. #[yaserde(prefix = "tab", rename = "AuthenticationProfile")] pub authentication_profile: Vec<AuthenticationProfile>, } impl Validate for GetAuthenticationProfileListResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct CreateAuthenticationProfile { // The AuthenticationProfile to create. #[yaserde(prefix = "tab", rename = "AuthenticationProfile")] pub authentication_profile: AuthenticationProfile, } impl Validate for CreateAuthenticationProfile {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct CreateAuthenticationProfileResponse { // The Token of created AuthenticationProfile. #[yaserde(prefix = "tab", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for CreateAuthenticationProfileResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct SetAuthenticationProfile { // The AuthenticationProfile to create or modify. #[yaserde(prefix = "tab", rename = "AuthenticationProfile")] pub authentication_profile: AuthenticationProfile, } impl Validate for SetAuthenticationProfile {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct SetAuthenticationProfileResponse {} impl Validate for SetAuthenticationProfileResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct ModifyAuthenticationProfile { // The AuthenticationProfile to modify. #[yaserde(prefix = "tab", rename = "AuthenticationProfile")] pub authentication_profile: AuthenticationProfile, } impl Validate for ModifyAuthenticationProfile {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct ModifyAuthenticationProfileResponse {} impl Validate for ModifyAuthenticationProfileResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct DeleteAuthenticationProfile { // The token of the AuthenticationProfile to delete. #[yaserde(prefix = "tab", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for DeleteAuthenticationProfile {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct DeleteAuthenticationProfileResponse {} impl Validate for DeleteAuthenticationProfileResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct GetSecurityLevelInfo { // Tokens of SecurityLevelInfo items to get. #[yaserde(prefix = "tab", rename = "Token")] pub token: Vec<pt::ReferenceToken>, } impl Validate for GetSecurityLevelInfo {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct GetSecurityLevelInfoResponse { // List of SecurityLevelInfo items. #[yaserde(prefix = "tab", rename = "SecurityLevelInfo")] pub security_level_info: Vec<SecurityLevelInfo>, } impl Validate for GetSecurityLevelInfoResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct GetSecurityLevelInfoList { // Maximum number of entries to return. If not specified, less than one // or higher than what the device supports, the number of items is // determined by the // device. #[yaserde(prefix = "tab", rename = "Limit")] pub limit: Option<i32>, // Start returning entries from this start reference. If not specified, // entries shall start from the beginning of the dataset. #[yaserde(prefix = "tab", rename = "StartReference")] pub start_reference: Option<String>, } impl Validate for GetSecurityLevelInfoList {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct GetSecurityLevelInfoListResponse { // StartReference to use in next call to get the following items. If // absent, no more items to get. #[yaserde(prefix = "tab", rename = "NextStartReference")] pub next_start_reference: Option<String>, // List of SecurityLevelInfo items. #[yaserde(prefix = "tab", rename = "SecurityLevelInfo")] pub security_level_info: Vec<SecurityLevelInfo>, } impl Validate for GetSecurityLevelInfoListResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct GetSecurityLevels { // Tokens of SecurityLevel items to get. #[yaserde(prefix = "tab", rename = "Token")] pub token: Vec<pt::ReferenceToken>, } impl Validate for GetSecurityLevels {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct GetSecurityLevelsResponse { // List of SecurityLevel items. #[yaserde(prefix = "tab", rename = "SecurityLevel")] pub security_level: Vec<SecurityLevel>, } impl Validate for GetSecurityLevelsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct GetSecurityLevelList { // Maximum number of entries to return. If not specified, less than one // or higher than what the device supports, the number of items is // determined by the // device. #[yaserde(prefix = "tab", rename = "Limit")] pub limit: Option<i32>, // Start returning entries from this start reference. If not specified, // entries shall start from the beginning of the dataset. #[yaserde(prefix = "tab", rename = "StartReference")] pub start_reference: Option<String>, } impl Validate for GetSecurityLevelList {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct GetSecurityLevelListResponse { // StartReference to use in next call to get the following items. If // absent, no more items to get. #[yaserde(prefix = "tab", rename = "NextStartReference")] pub next_start_reference: Option<String>, // List of SecurityLevel items. #[yaserde(prefix = "tab", rename = "SecurityLevel")] pub security_level: Vec<SecurityLevel>, } impl Validate for GetSecurityLevelListResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct CreateSecurityLevel { // The SecurityLevel to create. #[yaserde(prefix = "tab", rename = "SecurityLevel")] pub security_level: SecurityLevel, } impl Validate for CreateSecurityLevel {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct CreateSecurityLevelResponse { // The Token of created SecurityLevel. #[yaserde(prefix = "tab", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for CreateSecurityLevelResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct SetSecurityLevel { // The SecurityLevel to create or modify. #[yaserde(prefix = "tab", rename = "SecurityLevel")] pub security_level: SecurityLevel, } impl Validate for SetSecurityLevel {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct SetSecurityLevelResponse {} impl Validate for SetSecurityLevelResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct ModifySecurityLevel { // The SecurityLevel to modify. #[yaserde(prefix = "tab", rename = "SecurityLevel")] pub security_level: SecurityLevel, } impl Validate for ModifySecurityLevel {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct ModifySecurityLevelResponse {} impl Validate for ModifySecurityLevelResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct DeleteSecurityLevel { // The token of the SecurityLevel to delete. #[yaserde(prefix = "tab", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for DeleteSecurityLevel {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tab", namespace = "tab: http://www.onvif.org/ver10/authenticationbehavior/wsdl" )] pub struct DeleteSecurityLevelResponse {} impl Validate for DeleteSecurityLevelResponse {} // This operation returns the capabilities of the authentication behavior // service. pub async fn get_service_capabilities<T: transport::Transport>( transport: &T, request: &GetServiceCapabilities, ) -> Result<GetServiceCapabilitiesResponse, transport::Error> { transport::request(transport, request).await } // This operation requests a list of AuthenticationProfileInfo items matching // the given tokens. // The device shall ignore tokens it cannot resolve and shall return an empty // list if there are no items // matching the specified tokens. The device shall not return a fault in this // case. pub async fn get_authentication_profile_info<T: transport::Transport>( transport: &T, request: &GetAuthenticationProfileInfo, ) -> Result<GetAuthenticationProfileInfoResponse, transport::Error> { transport::request(transport, request).await } // This operation requests a list of all of AuthenticationProfileInfo items // provided by the device. // A call to this method shall return a StartReference when not all data is // returned and more data is // available. The reference shall be valid for retrieving the next set of data. // Please refer Access Control // Service Specification for more details. // The number of items returned shall not be greater than Limit parameter. pub async fn get_authentication_profile_info_list<T: transport::Transport>( transport: &T, request: &GetAuthenticationProfileInfoList, ) -> Result<GetAuthenticationProfileInfoListResponse, transport::Error> { transport::request(transport, request).await } // This operation returns the specified AuthenticationProfile item matching the // given tokens. // The device shall ignore tokens it cannot resolve and shall return an empty // list if there are no items // matching specified tokens. The device shall not return a fault in this case. pub async fn get_authentication_profiles<T: transport::Transport>( transport: &T, request: &GetAuthenticationProfiles, ) -> Result<GetAuthenticationProfilesResponse, transport::Error> { transport::request(transport, request).await } // This operation requests a list of all of AuthenticationProfile items provided // by the device. // A call to this method shall return a StartReference when not all data is // returned and more data is // available. The reference shall be valid for retrieving the next set of data. // Please refer Access Control // Service Specification for more details. // The number of items returned shall not be greater the Limit parameter. pub async fn get_authentication_profile_list<T: transport::Transport>( transport: &T, request: &GetAuthenticationProfileList, ) -> Result<GetAuthenticationProfileListResponse, transport::Error> { transport::request(transport, request).await } // This operation creates the specified authentication profile in the device. // The token field of the AuthenticationProfile structure shall be empty and the // device shall allocate a // token for the authentication profile. The allocated token shall be returned // in the response. // If the client sends any value in the token field, the device shall return // InvalidArgVal as a generic // fault code. pub async fn create_authentication_profile<T: transport::Transport>( transport: &T, request: &CreateAuthenticationProfile, ) -> Result<CreateAuthenticationProfileResponse, transport::Error> { transport::request(transport, request).await } // This method is used to synchronize an authentication profile in a client with // the device. // If an authentication profile with the specified token does not exist in the // device, the authentication // profile is // created. If an authentication profile with the specified token exists, then // the authentication profile // is modified. // A call to this method takes an AuthenticationProfile structure as input // parameter. The token field of // the // AuthenticationProfile shall not be empty.
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
true
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/accesscontrol/src/lib.rs
wsdl_rs/accesscontrol/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use types as pt; use validate::Validate; use yaserde_derive::{YaDeserialize, YaSerialize}; // The service capabilities reflect optional functionality of a service. // The information is static and does not change during device operation. // The following capabilities are available: #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct ServiceCapabilities { // The maximum number of entries returned by a single Get<Entity>List or // Get<Entity> request. // The device shall never return more than this number of entities in a // single response. #[yaserde(attribute, rename = "MaxLimit")] pub max_limit: u32, // Indicates the maximum number of access points supported by the device. #[yaserde(attribute, rename = "MaxAccessPoints")] pub max_access_points: Option<u32>, // Indicates the maximum number of areas supported by the device. #[yaserde(attribute, rename = "MaxAreas")] pub max_areas: Option<u32>, // Indicates that the client is allowed to supply the token when creating // access // points and areas. // To enable the use of the commands SetAccessPoint and SetArea, the value // must be set to true. #[yaserde(attribute, rename = "ClientSuppliedTokenSupported")] pub client_supplied_token_supported: Option<bool>, } impl Validate for ServiceCapabilities {} // pub type Capabilities = ServiceCapabilities; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct AccessPointInfoBase { // A user readable name. It shall be up to 64 characters. #[yaserde(prefix = "tac", rename = "Name")] pub name: pt::Name, // Optional user readable description for the AccessPoint. It shall // be up to 1024 characters. #[yaserde(prefix = "tac", rename = "Description")] pub description: Option<pt::Description>, // Optional reference to the Area from which access is requested. #[yaserde(prefix = "tac", rename = "AreaFrom")] pub area_from: Option<pt::ReferenceToken>, // Optional reference to the Area to which access is requested. #[yaserde(prefix = "tac", rename = "AreaTo")] pub area_to: Option<pt::ReferenceToken>, // Optional entity type; if missing, a Door type as defined by [ONVIF Door // Control // Service Specification] should be assumed. This can also be represented by // the // QName value "tdc:Door" – where tdc is the namespace of the door control // service: // "http://www.onvif.org/ver10/doorcontrol/wsdl". This field is provided for // future // extensions; it will allow an access point being extended to cover entity // types // other than doors as well. #[yaserde(prefix = "tac", rename = "EntityType")] pub entity_type: Option<String>, // Reference to the entity used to control access; the entity type // may be specified by the optional EntityType field explained below but is // typically a Door. #[yaserde(prefix = "tac", rename = "Entity")] pub entity: pt::ReferenceToken, pub base: pt::DataEntity, } impl Validate for AccessPointInfoBase {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct AccessPointInfo { // The capabilities for the AccessPoint. #[yaserde(prefix = "tac", rename = "Capabilities")] pub capabilities: AccessPointCapabilities, pub base: AccessPointInfoBase, } impl Validate for AccessPointInfo {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct AccessPoint { // A reference to an authentication profile which defines the authentication // behavior of the access point. #[yaserde(prefix = "tac", rename = "AuthenticationProfileToken")] pub authentication_profile_token: Option<pt::ReferenceToken>, #[yaserde(prefix = "tac", rename = "Extension")] pub extension: Option<AccessPointExtension>, pub base: AccessPointInfo, } impl Validate for AccessPoint {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct AccessPointExtension {} impl Validate for AccessPointExtension {} // The AccessPoint capabilities reflect optional functionality of a particular // physical entity. // Different AccessPoint instances may have different set of capabilities. This // information may // change during device operation, e.g. if hardware settings are changed. // The following capabilities are available: #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct AccessPointCapabilities { // A list of security level tokens that this access point supports. // See [Authentication Behavior Service Specification]. #[yaserde(prefix = "tac", rename = "SupportedSecurityLevels")] pub supported_security_levels: Vec<pt::ReferenceToken>, #[yaserde(prefix = "tac", rename = "Extension")] pub extension: Option<SupportedSecurityLevelsExtension>, // Indicates whether or not this AccessPoint instance supports // EnableAccessPoint // and DisableAccessPoint commands. #[yaserde(attribute, rename = "DisableAccessPoint")] pub disable_access_point: bool, // Indicates whether or not this AccessPoint instance supports generation of // duress events. #[yaserde(attribute, rename = "Duress")] pub duress: Option<bool>, // Indicates whether or not this AccessPoint has a REX switch or other input // that // allows anonymous access. #[yaserde(attribute, rename = "AnonymousAccess")] pub anonymous_access: Option<bool>, // Indicates whether or not this AccessPoint instance supports generation of // AccessTaken and AccessNotTaken events. If AnonymousAccess and AccessTaken // are both true, it // indicates that the Anonymous versions of AccessTaken and AccessNotTaken // are supported. #[yaserde(attribute, rename = "AccessTaken")] pub access_taken: Option<bool>, // Indicates whether or not this AccessPoint instance supports the // ExternalAuthorization operation and the generation of Request events. If // AnonymousAccess and // ExternalAuthorization are both true, it indicates that the Anonymous // version is supported as // well. #[yaserde(attribute, rename = "ExternalAuthorization")] pub external_authorization: Option<bool>, } impl Validate for AccessPointCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct SupportedSecurityLevelsExtension {} impl Validate for SupportedSecurityLevelsExtension {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct AreaInfoBase { // User readable name. It shall be up to 64 characters. #[yaserde(prefix = "tac", rename = "Name")] pub name: pt::Name, // User readable description for the Area. It shall be up to 1024 // characters. #[yaserde(prefix = "tac", rename = "Description")] pub description: Option<pt::Description>, pub base: pt::DataEntity, } impl Validate for AreaInfoBase {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct AreaInfo { pub base: AreaInfoBase, } impl Validate for AreaInfo {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct Area { #[yaserde(prefix = "tac", rename = "Extension")] pub extension: Option<AreaExtension>, pub base: AreaInfo, } impl Validate for Area {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct AreaExtension {} impl Validate for AreaExtension {} // The AccessPointState contains state information for an AccessPoint. // An ONVIF compliant device shall provide the following fields for each // AccessPoint instance: #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct AccessPointState { // Indicates that the AccessPoint is enabled. By default this field value // shall be True, if the DisableAccessPoint capabilities is not supported. #[yaserde(prefix = "tac", rename = "Enabled")] pub enabled: bool, } impl Validate for AccessPointState {} // The Decision enumeration represents a choice of two available options for an // access request: #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum Decision { // The decision is to grant access. Granted, // The decision is to deny access. Denied, __Unknown__(String), } impl Default for Decision { fn default() -> Decision { Self::__Unknown__("No valid variants".into()) } } impl Validate for Decision {} // Non-normative enum that describes the various reasons for denying access. // The following strings shall be used for the reason field: #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum DenyReason { // The device shall provide the following event, whenever a valid credential // is not enabled or has been disabled (e.g., due to credential being lost // etc.) to prevent // unauthorized entry. CredentialNotEnabled, // The device shall provide the following event, whenever a valid credential // is presented though it is not active yet;: e.g, the credential was // presented before the // start date. CredentialNotActive, // The device shall provide the following event, whenever a valid credential // was presented after its expiry date. CredentialExpired, // The device shall provide the following event, whenever an entered PIN // code // does not match the credential. InvalidPIN, // The device shall provide the following event, whenever a valid credential // is denied access to the requested AccessPoint because the credential is // not permitted at // the moment. NotPermittedAtThisTime, // The device shall provide the following event, whenever the presented // credential is not authorized. Unauthorized, // The device shall provide the following event, whenever the request is // denied and no other specific event matches it or is supported by the // service. Other, __Unknown__(String), } impl Default for DenyReason { fn default() -> DenyReason { Self::__Unknown__("No valid variants".into()) } } impl Validate for DenyReason {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct GetServiceCapabilities {} impl Validate for GetServiceCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct GetServiceCapabilitiesResponse { // The capability response message contains the requested Access Control // service capabilities using a hierarchical XML capability structure. #[yaserde(prefix = "tac", rename = "Capabilities")] pub capabilities: ServiceCapabilities, } impl Validate for GetServiceCapabilitiesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct GetAccessPointInfoList { // Maximum number of entries to return. If not specified, less than one // or higher than what the device supports, the number of items is // determined by the // device. #[yaserde(prefix = "tac", rename = "Limit")] pub limit: Option<i32>, // Start returning entries from this start reference. If not specified, // entries shall start from the beginning of the dataset. #[yaserde(prefix = "tac", rename = "StartReference")] pub start_reference: Option<String>, } impl Validate for GetAccessPointInfoList {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct GetAccessPointInfoListResponse { // StartReference to use in next call to get the following items. If // absent, no more items to get. #[yaserde(prefix = "tac", rename = "NextStartReference")] pub next_start_reference: Option<String>, // List of AccessPointInfo items. #[yaserde(prefix = "tac", rename = "AccessPointInfo")] pub access_point_info: Vec<AccessPointInfo>, } impl Validate for GetAccessPointInfoListResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct GetAccessPointInfo { // Tokens of AccessPointInfo items to get. #[yaserde(prefix = "tac", rename = "Token")] pub token: Vec<pt::ReferenceToken>, } impl Validate for GetAccessPointInfo {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct GetAccessPointInfoResponse { // List of AccessPointInfo items. #[yaserde(prefix = "tac", rename = "AccessPointInfo")] pub access_point_info: Vec<AccessPointInfo>, } impl Validate for GetAccessPointInfoResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct GetAccessPointList { // Maximum number of entries to return. If not specified, less than one // or higher than what the device supports, the number of items is // determined by the // device. #[yaserde(prefix = "tac", rename = "Limit")] pub limit: Option<i32>, // Start returning entries from this start reference. If not specified, // entries shall start from the beginning of the dataset. #[yaserde(prefix = "tac", rename = "StartReference")] pub start_reference: Option<String>, } impl Validate for GetAccessPointList {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct GetAccessPointListResponse { // StartReference to use in next call to get the following items. If // absent, no more items to get. #[yaserde(prefix = "tac", rename = "NextStartReference")] pub next_start_reference: Option<String>, // List of AccessPoint items. #[yaserde(prefix = "tac", rename = "AccessPoint")] pub access_point: Vec<AccessPoint>, } impl Validate for GetAccessPointListResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct GetAccessPoints { // Tokens of AccessPoint items to get. #[yaserde(prefix = "tac", rename = "Token")] pub token: Vec<pt::ReferenceToken>, } impl Validate for GetAccessPoints {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct GetAccessPointsResponse { // List of AccessPoint items. #[yaserde(prefix = "tac", rename = "AccessPoint")] pub access_point: Vec<AccessPoint>, } impl Validate for GetAccessPointsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct CreateAccessPoint { // AccessPoint item to create #[yaserde(prefix = "tac", rename = "AccessPoint")] pub access_point: AccessPoint, } impl Validate for CreateAccessPoint {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct CreateAccessPointResponse { // Token of created AccessPoint item #[yaserde(prefix = "tac", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for CreateAccessPointResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct SetAccessPoint { // AccessPoint item to create or modify #[yaserde(prefix = "tac", rename = "AccessPoint")] pub access_point: AccessPoint, } impl Validate for SetAccessPoint {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct SetAccessPointResponse {} impl Validate for SetAccessPointResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct ModifyAccessPoint { // AccessPoint item to modify #[yaserde(prefix = "tac", rename = "AccessPoint")] pub access_point: AccessPoint, } impl Validate for ModifyAccessPoint {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct ModifyAccessPointResponse {} impl Validate for ModifyAccessPointResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct DeleteAccessPoint { // Token of AccessPoint item to delete. #[yaserde(prefix = "tac", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for DeleteAccessPoint {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct DeleteAccessPointResponse {} impl Validate for DeleteAccessPointResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct SetAccessPointAuthenticationProfile { // Token of the AccessPoint. #[yaserde(prefix = "tac", rename = "Token")] pub token: pt::ReferenceToken, // Token of the AuthenticationProfile. #[yaserde(prefix = "tac", rename = "AuthenticationProfileToken")] pub authentication_profile_token: pt::ReferenceToken, } impl Validate for SetAccessPointAuthenticationProfile {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct SetAccessPointAuthenticationProfileResponse {} impl Validate for SetAccessPointAuthenticationProfileResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct DeleteAccessPointAuthenticationProfile { // Token of the AccessPoint. #[yaserde(prefix = "tac", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for DeleteAccessPointAuthenticationProfile {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct DeleteAccessPointAuthenticationProfileResponse {} impl Validate for DeleteAccessPointAuthenticationProfileResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct GetAreaInfoList { // Maximum number of entries to return. If not specified, less than one // or higher than what the device supports, the number of items is // determined by the // device. #[yaserde(prefix = "tac", rename = "Limit")] pub limit: Option<i32>, // Start returning entries from this start reference. If not specified, // entries shall start from the beginning of the dataset. #[yaserde(prefix = "tac", rename = "StartReference")] pub start_reference: Option<String>, } impl Validate for GetAreaInfoList {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct GetAreaInfoListResponse { // StartReference to use in next call to get the following items. If // absent, no more items to get. #[yaserde(prefix = "tac", rename = "NextStartReference")] pub next_start_reference: Option<String>, // List of AreaInfo items. #[yaserde(prefix = "tac", rename = "AreaInfo")] pub area_info: Vec<AreaInfo>, } impl Validate for GetAreaInfoListResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct GetAreaInfo { // Tokens of AreaInfo items to get. #[yaserde(prefix = "tac", rename = "Token")] pub token: Vec<pt::ReferenceToken>, } impl Validate for GetAreaInfo {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct GetAreaInfoResponse { // List of AreaInfo items. #[yaserde(prefix = "tac", rename = "AreaInfo")] pub area_info: Vec<AreaInfo>, } impl Validate for GetAreaInfoResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct GetAreaList { // Maximum number of entries to return. If not specified, less than one // or higher than what the device supports, the number of items is // determined by the // device. #[yaserde(prefix = "tac", rename = "Limit")] pub limit: Option<i32>, // Start returning entries from this start reference. If not specified, // entries shall start from the beginning of the dataset. #[yaserde(prefix = "tac", rename = "StartReference")] pub start_reference: Option<String>, } impl Validate for GetAreaList {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct GetAreaListResponse { // StartReference to use in next call to get the following items. If // absent, no more items to get. #[yaserde(prefix = "tac", rename = "NextStartReference")] pub next_start_reference: Option<String>, // List of Area items. #[yaserde(prefix = "tac", rename = "Area")] pub area: Vec<Area>, } impl Validate for GetAreaListResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct GetAreas { // Tokens of Area items to get. #[yaserde(prefix = "tac", rename = "Token")] pub token: Vec<pt::ReferenceToken>, } impl Validate for GetAreas {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct GetAreasResponse { // List of Area items. #[yaserde(prefix = "tac", rename = "Area")] pub area: Vec<Area>, } impl Validate for GetAreasResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct CreateArea { // Area item to create #[yaserde(prefix = "tac", rename = "Area")] pub area: Area, } impl Validate for CreateArea {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct CreateAreaResponse { // Token of created Area item #[yaserde(prefix = "tac", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for CreateAreaResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct SetArea { // Area item to create or modify #[yaserde(prefix = "tac", rename = "Area")] pub area: Area, } impl Validate for SetArea {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct SetAreaResponse {} impl Validate for SetAreaResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct ModifyArea { // Area item to modify #[yaserde(prefix = "tac", rename = "Area")] pub area: Area, } impl Validate for ModifyArea {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct ModifyAreaResponse {} impl Validate for ModifyAreaResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct DeleteArea { // Token of Area item to delete. #[yaserde(prefix = "tac", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for DeleteArea {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct DeleteAreaResponse {} impl Validate for DeleteAreaResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct GetAccessPointState { // Token of AccessPoint instance to get AccessPointState for. #[yaserde(prefix = "tac", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for GetAccessPointState {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct GetAccessPointStateResponse { // AccessPointState item. #[yaserde(prefix = "tac", rename = "AccessPointState")] pub access_point_state: AccessPointState, } impl Validate for GetAccessPointStateResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct EnableAccessPoint { // Token of the AccessPoint instance to enable. #[yaserde(prefix = "tac", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for EnableAccessPoint {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct EnableAccessPointResponse {} impl Validate for EnableAccessPointResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct DisableAccessPoint { // Token of the AccessPoint instance to disable. #[yaserde(prefix = "tac", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for DisableAccessPoint {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct DisableAccessPointResponse {} impl Validate for DisableAccessPointResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct ExternalAuthorization { // Token of the Access Point instance. #[yaserde(prefix = "tac", rename = "AccessPointToken")] pub access_point_token: pt::ReferenceToken, // Optional token of the Credential involved. #[yaserde(prefix = "tac", rename = "CredentialToken")] pub credential_token: Option<pt::ReferenceToken>, // Optional reason for decision. #[yaserde(prefix = "tac", rename = "Reason")] pub reason: Option<String>, // Decision - Granted or Denied. #[yaserde(prefix = "tac", rename = "Decision")] pub decision: Decision, } impl Validate for ExternalAuthorization {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tac", namespace = "tac: http://www.onvif.org/ver10/accesscontrol/wsdl" )] pub struct ExternalAuthorizationResponse {} impl Validate for ExternalAuthorizationResponse {} // This operation returns the capabilities of the access control service. // A device which provides the access control service shall implement this // method. pub async fn get_service_capabilities<T: transport::Transport>( transport: &T, request: &GetServiceCapabilities, ) -> Result<GetServiceCapabilitiesResponse, transport::Error> { transport::request(transport, request).await } // This operation requests a list of AccessPointInfo items matching the given // tokens. // The device shall ignore tokens it cannot resolve and shall return an empty // list if // there are no items matching the specified tokens. // The device shall not return a fault in this case. // If the number of requested items is greater than MaxLimit, a TooManyItems // fault shall be returned. pub async fn get_access_point_info<T: transport::Transport>( transport: &T, request: &GetAccessPointInfo, ) -> Result<GetAccessPointInfoResponse, transport::Error> { transport::request(transport, request).await } // This operation requests a list of all AccessPointInfo items provided by the // device. // A call to this method shall return a StartReference when not all data is // returned and more // data is available. The reference shall be valid for retrieving the next set // of data. // Please refer to section 4.8.3 in [ONVIF PACS Architecture and Design // Considerations] for more details. // The number of items returned shall not be greater than the Limit parameter. pub async fn get_access_point_info_list<T: transport::Transport>( transport: &T, request: &GetAccessPointInfoList, ) -> Result<GetAccessPointInfoListResponse, transport::Error> { transport::request(transport, request).await } // This operation requests a list of AccessPoint items matching the given // tokens. // The device shall ignore tokens it cannot resolve and shall return an empty // list if there are // no items matching the specified tokens. The device shall not return a fault // in this case. // If the number of requested items is greater than MaxLimit, a TooManyItems // fault shall be returned. pub async fn get_access_points<T: transport::Transport>( transport: &T, request: &GetAccessPoints, ) -> Result<GetAccessPointsResponse, transport::Error> { transport::request(transport, request).await } // This operation requests a list of all AccessPoint items provided by the // device. A call to
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
true
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/schedule/src/lib.rs
wsdl_rs/schedule/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use types as pt; use validate::Validate; use xsd_types::types as xs; use yaserde_derive::{YaDeserialize, YaSerialize}; // The service capabilities reflect optional functionality of a service. // The information is static and does not change during device operation. // The following capabilities are available: #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct ServiceCapabilities { // The maximum number of entries returned by a single Get<Entity>List or // Get<Entity> request. The device shall never return more than this number // of entities in a single response. #[yaserde(attribute, rename = "MaxLimit")] pub max_limit: pt::PositiveInteger, // Indicates the maximum number of schedules the device supports. // The device shall support at least one schedule. #[yaserde(attribute, rename = "MaxSchedules")] pub max_schedules: pt::PositiveInteger, // Indicates the maximum number of time periods per day the device supports // in a schedule including special days schedule. The device shall support // at least one time period per day. #[yaserde(attribute, rename = "MaxTimePeriodsPerDay")] pub max_time_periods_per_day: pt::PositiveInteger, // Indicates the maximum number of special day group entities the device // supports. // The device shall support at least one ‘SpecialDayGroup’ entity. #[yaserde(attribute, rename = "MaxSpecialDayGroups")] pub max_special_day_groups: pt::PositiveInteger, // Indicates the maximum number of days per ‘SpecialDayGroup’ entity the // device // supports. The device shall support at least one day per // ‘SpecialDayGroup’ entity. #[yaserde(attribute, rename = "MaxDaysInSpecialDayGroup")] pub max_days_in_special_day_group: pt::PositiveInteger, // Indicates the maximum number of ‘SpecialDaysSchedule’ entities // referred by a // schedule that the device supports. #[yaserde(attribute, rename = "MaxSpecialDaysSchedules")] pub max_special_days_schedules: pt::PositiveInteger, // For schedules: // If this capability is supported, then all iCalendar recurrence types // shall // be supported by the device. The device shall also support the start and // end dates (or // iCalendar occurrence count) in recurring events (see iCalendar examples // in section 3). // If this capability is not supported, then only the weekly iCalendar // recurrence // type shall be supported. Non-recurring events and other recurring types // are // not supported. The device shall only accept a start date with the year // ‘1970’ // (the month and day is needed to reflect the week day of the recurrence) // and will not accept an occurrence count (or iCalendar until date) in // recurring events. // For special days (only applicable if SpecialDaysSupported is set to // true): // If this capability is supported, then all iCalendar recurrence types // shall // be supported by the device. The device shall also support the start and // end dates (or occurrence count) in recurring events. // If this capability is not supported, then only non-recurring special days // are supported. #[yaserde(attribute, rename = "ExtendedRecurrenceSupported")] pub extended_recurrence_supported: bool, // If this capability is supported, then the device shall support special // days. #[yaserde(attribute, rename = "SpecialDaysSupported")] pub special_days_supported: bool, // If this capability is set to true, the device shall implement the // GetScheduleState command, and shall notify subscribing clients whenever // schedules become active or inactive. #[yaserde(attribute, rename = "StateReportingSupported")] pub state_reporting_supported: bool, // Indicates that the client is allowed to supply the token when creating // schedules and special day groups. // To enable the use of the commands SetSchedule and SetSpecialDayGroup, the // value must be set to true. #[yaserde(attribute, rename = "ClientSuppliedTokenSupported")] pub client_supplied_token_supported: Option<bool>, } impl Validate for ServiceCapabilities {} // pub type Capabilities = ServiceCapabilities; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct ScheduleInfo { // A user readable name. It shall be up to 64 characters. #[yaserde(prefix = "tsc", rename = "Name")] pub name: pt::Name, // User readable description for the schedule. It shall be up to 1024 // characters. #[yaserde(prefix = "tsc", rename = "Description")] pub description: Option<pt::Description>, pub base: pt::DataEntity, } impl Validate for ScheduleInfo {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct Schedule { // An iCalendar structure that defines a number of events. Events // can be recurring or non-recurring. The events can, for instance, // be used to control when a camera should record or when a facility // is accessible. Some devices might not be able to fully support // all the features of iCalendar. Setting the service capability // ExtendedRecurrenceSupported to false will enable more devices // to be ONVIF compliant. Is of type string (but contains an iCalendar // structure). #[yaserde(prefix = "tsc", rename = "Standard")] pub standard: String, // For devices that are not able to support all the features of iCalendar, // supporting special days is essential. Each SpecialDaysSchedule // instance defines an alternate set of time periods that overrides // the regular schedule for a specified list of special days. // Is of type SpecialDaysSchedule. #[yaserde(prefix = "tsc", rename = "SpecialDays")] pub special_days: Vec<SpecialDaysSchedule>, #[yaserde(prefix = "tsc", rename = "Extension")] pub extension: Option<ScheduleExtension>, pub base: ScheduleInfo, } impl Validate for Schedule {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct ScheduleExtension {} impl Validate for ScheduleExtension {} // A override schedule that defines alternate time periods for a group of // special days. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct SpecialDaysSchedule { // Indicates the list of special days in a schedule. #[yaserde(prefix = "tsc", rename = "GroupToken")] pub group_token: pt::ReferenceToken, // Indicates the alternate time periods for the list of special days // (overrides the regular schedule). For example, the regular schedule // indicates // that it is active from 8AM to 5PM on Mondays. However, this particular // Monday is a special day, and the alternate time periods state that the // schedule is active from 9 AM to 11 AM and 1 PM to 4 PM. // If no time periods are defined, then no access is allowed. // Is of type TimePeriod. #[yaserde(prefix = "tsc", rename = "TimeRange")] pub time_range: Vec<TimePeriod>, #[yaserde(prefix = "tsc", rename = "Extension")] pub extension: Option<SpecialDaysScheduleExtension>, } impl Validate for SpecialDaysSchedule {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct SpecialDaysScheduleExtension {} impl Validate for SpecialDaysScheduleExtension {} // The ScheduleState contains state information for a schedule. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct ScheduleState { // Indicates that the current time is within the boundaries of the schedule // or its special days schedules’ time periods. For example, if this // schedule is being used for triggering automatic recording on a video // source, // the Active flag will be true when the schedule-based recording is // supposed to record. #[yaserde(prefix = "tsc", rename = "Active")] pub active: bool, // Indicates that the current time is within the boundaries of its special // days schedules’ time periods. For example, if this schedule is being // used // for recording at a lower frame rate on a video source during special // days, // the SpecialDay flag will be true. If special days are not supported by // the device, // this field may be omitted and interpreted as false by the client. #[yaserde(prefix = "tsc", rename = "SpecialDay")] pub special_day: Option<bool>, #[yaserde(prefix = "tsc", rename = "Extension")] pub extension: Option<ScheduleStateExtension>, } impl Validate for ScheduleState {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct ScheduleStateExtension {} impl Validate for ScheduleStateExtension {} // A time period defines a start and end time. For full day access, the // start time ="00:00:00" with no defined end time. For a time period with no // end time, the schedule runs until midnight. The end time must always be // greater // than the start time, otherwise an InvalidArgVal error messages is generated // by the device. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct TimePeriod { // Indicates the start time. #[yaserde(prefix = "tsc", rename = "From")] pub from: xs::Time, // Indicates the end time. Is optional, if omitted, the period ends at // midnight. // The end time is exclusive, meaning that that exact moment in time is not // part of the period. To determine if a moment in time (t) is part of a // time period, // the formula StartTime ≤ t < EndTime is used. #[yaserde(prefix = "tsc", rename = "Until")] pub until: Option<xs::Time>, #[yaserde(prefix = "tsc", rename = "Extension")] pub extension: Option<TimePeriodExtension>, } impl Validate for TimePeriod {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct TimePeriodExtension {} impl Validate for TimePeriodExtension {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct SpecialDayGroupInfo { // User readable name. It shall be up to 64 characters. #[yaserde(prefix = "tsc", rename = "Name")] pub name: pt::Name, // User readable description for the special days. It shall be up to 1024 // characters. #[yaserde(prefix = "tsc", rename = "Description")] pub description: Option<pt::Description>, pub base: pt::DataEntity, } impl Validate for SpecialDayGroupInfo {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct SpecialDayGroup { // An iCalendar structure that contains a group of special days. // Is of type string (containing an iCalendar structure). #[yaserde(prefix = "tsc", rename = "Days")] pub days: Option<String>, #[yaserde(prefix = "tsc", rename = "Extension")] pub extension: Option<SpecialDayGroupExtension>, pub base: SpecialDayGroupInfo, } impl Validate for SpecialDayGroup {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct SpecialDayGroupExtension {} impl Validate for SpecialDayGroupExtension {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct GetServiceCapabilities {} impl Validate for GetServiceCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct GetServiceCapabilitiesResponse { // The capability response message contains the requested schedule service // capabilities using a hierarchical XML capability structure. #[yaserde(prefix = "tsc", rename = "Capabilities")] pub capabilities: ServiceCapabilities, } impl Validate for GetServiceCapabilitiesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct GetScheduleState { // Token of schedule instance to get ScheduleState. #[yaserde(prefix = "tsc", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for GetScheduleState {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct GetScheduleStateResponse { // ScheduleState item. #[yaserde(prefix = "tsc", rename = "ScheduleState")] pub schedule_state: ScheduleState, } impl Validate for GetScheduleStateResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct GetScheduleInfo { // Tokens of ScheduleInfo items to get. #[yaserde(prefix = "tsc", rename = "Token")] pub token: Vec<pt::ReferenceToken>, } impl Validate for GetScheduleInfo {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct GetScheduleInfoResponse { // List of ScheduleInfo items. #[yaserde(prefix = "tsc", rename = "ScheduleInfo")] pub schedule_info: Vec<ScheduleInfo>, } impl Validate for GetScheduleInfoResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct GetScheduleInfoList { // Maximum number of entries to return. If not specified, less than one // or higher than what the device supports, the number of items is // determined by the device. #[yaserde(prefix = "tsc", rename = "Limit")] pub limit: Option<i32>, // Start returning entries from this start reference. // If not specified, entries shall start from the beginning of the dataset. #[yaserde(prefix = "tsc", rename = "StartReference")] pub start_reference: Option<String>, } impl Validate for GetScheduleInfoList {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct GetScheduleInfoListResponse { // StartReference to use in next call to get the following items. // If absent, no more items to get. #[yaserde(prefix = "tsc", rename = "NextStartReference")] pub next_start_reference: Option<String>, // List of ScheduleInfo items. #[yaserde(prefix = "tsc", rename = "ScheduleInfo")] pub schedule_info: Vec<ScheduleInfo>, } impl Validate for GetScheduleInfoListResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct GetSchedules { // Tokens of Schedule items to get #[yaserde(prefix = "tsc", rename = "Token")] pub token: Vec<pt::ReferenceToken>, } impl Validate for GetSchedules {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct GetSchedulesResponse { // List of schedule items. #[yaserde(prefix = "tsc", rename = "Schedule")] pub schedule: Vec<Schedule>, } impl Validate for GetSchedulesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct GetScheduleList { // Maximum number of entries to return. // If not specified, less than one or higher than what the device supports, // the number of items is determined by the device. #[yaserde(prefix = "tsc", rename = "Limit")] pub limit: Option<i32>, // Start returning entries from this start reference. // If not specified, entries shall start from the beginning of the dataset. #[yaserde(prefix = "tsc", rename = "StartReference")] pub start_reference: Option<String>, } impl Validate for GetScheduleList {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct GetScheduleListResponse { // StartReference to use in next call to get the following items. // If absent, no more items to get. #[yaserde(prefix = "tsc", rename = "NextStartReference")] pub next_start_reference: Option<String>, // List of Schedule items. #[yaserde(prefix = "tsc", rename = "Schedule")] pub schedule: Vec<Schedule>, } impl Validate for GetScheduleListResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct CreateSchedule { // The Schedule to create #[yaserde(prefix = "tsc", rename = "Schedule")] pub schedule: Schedule, } impl Validate for CreateSchedule {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct CreateScheduleResponse { // The token of created Schedule #[yaserde(prefix = "tsc", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for CreateScheduleResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct SetSchedule { // The Schedule to modify/create #[yaserde(prefix = "tsc", rename = "Schedule")] pub schedule: Schedule, } impl Validate for SetSchedule {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct SetScheduleResponse {} impl Validate for SetScheduleResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct ModifySchedule { // The Schedule to modify/update #[yaserde(prefix = "tsc", rename = "Schedule")] pub schedule: Schedule, } impl Validate for ModifySchedule {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct ModifyScheduleResponse {} impl Validate for ModifyScheduleResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct DeleteSchedule { // The token of the schedule to delete. #[yaserde(prefix = "tsc", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for DeleteSchedule {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct DeleteScheduleResponse {} impl Validate for DeleteScheduleResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct GetSpecialDayGroupInfo { // Tokens of SpecialDayGroupInfo items to get. #[yaserde(prefix = "tsc", rename = "Token")] pub token: Vec<pt::ReferenceToken>, } impl Validate for GetSpecialDayGroupInfo {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct GetSpecialDayGroupInfoResponse { // List of SpecialDayGroupInfo items. #[yaserde(prefix = "tsc", rename = "SpecialDayGroupInfo")] pub special_day_group_info: Vec<SpecialDayGroupInfo>, } impl Validate for GetSpecialDayGroupInfoResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct GetSpecialDayGroupInfoList { // Maximum number of entries to return. If not specified, less than // one or higher than what the device supports, the number // of items is determined by the device. #[yaserde(prefix = "tsc", rename = "Limit")] pub limit: Option<i32>, // Start returning entries from this start reference. // If not specified, entries shall start from the beginning of the dataset. #[yaserde(prefix = "tsc", rename = "StartReference")] pub start_reference: Option<String>, } impl Validate for GetSpecialDayGroupInfoList {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct GetSpecialDayGroupInfoListResponse { // StartReference to use in next call to get the following items. // If absent, no more items to get. #[yaserde(prefix = "tsc", rename = "NextStartReference")] pub next_start_reference: Option<String>, // List of SpecialDayGroupInfo items. #[yaserde(prefix = "tsc", rename = "SpecialDayGroupInfo")] pub special_day_group_info: Vec<SpecialDayGroupInfo>, } impl Validate for GetSpecialDayGroupInfoListResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct GetSpecialDayGroups { // Tokens of the SpecialDayGroup items to get #[yaserde(prefix = "tsc", rename = "Token")] pub token: Vec<pt::ReferenceToken>, } impl Validate for GetSpecialDayGroups {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct GetSpecialDayGroupsResponse { // List of SpecialDayGroup items. #[yaserde(prefix = "tsc", rename = "SpecialDayGroup")] pub special_day_group: Vec<SpecialDayGroup>, } impl Validate for GetSpecialDayGroupsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct GetSpecialDayGroupList { // Maximum number of entries to return. If not specified, less than // one or higher than what the device supports, the number of // items is determined by the device. #[yaserde(prefix = "tsc", rename = "Limit")] pub limit: Option<i32>, // Start returning entries from this start reference. // If not specified, entries shall start from the beginning of the dataset. #[yaserde(prefix = "tsc", rename = "StartReference")] pub start_reference: Option<String>, } impl Validate for GetSpecialDayGroupList {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct GetSpecialDayGroupListResponse { // StartReference to use in next call to get the following items. If // absent, no more items to get. #[yaserde(prefix = "tsc", rename = "NextStartReference")] pub next_start_reference: Option<String>, // List of SpecialDayGroup items. #[yaserde(prefix = "tsc", rename = "SpecialDayGroup")] pub special_day_group: Vec<SpecialDayGroup>, } impl Validate for GetSpecialDayGroupListResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct CreateSpecialDayGroup { // The special day group to create. #[yaserde(prefix = "tsc", rename = "SpecialDayGroup")] pub special_day_group: SpecialDayGroup, } impl Validate for CreateSpecialDayGroup {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct CreateSpecialDayGroupResponse { // The token of created special day group. #[yaserde(prefix = "tsc", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for CreateSpecialDayGroupResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct SetSpecialDayGroup { // The SpecialDayGroup to modify/create #[yaserde(prefix = "tsc", rename = "SpecialDayGroup")] pub special_day_group: SpecialDayGroup, } impl Validate for SetSpecialDayGroup {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct SetSpecialDayGroupResponse {} impl Validate for SetSpecialDayGroupResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct ModifySpecialDayGroup { // The special day group to modify/update. #[yaserde(prefix = "tsc", rename = "SpecialDayGroup")] pub special_day_group: SpecialDayGroup, } impl Validate for ModifySpecialDayGroup {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct ModifySpecialDayGroupResponse {} impl Validate for ModifySpecialDayGroupResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct DeleteSpecialDayGroup { // The token of the special day group item to delete. #[yaserde(prefix = "tsc", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for DeleteSpecialDayGroup {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tsc", namespace = "tsc: http://www.onvif.org/ver10/schedule/wsdl" )] pub struct DeleteSpecialDayGroupResponse {} impl Validate for DeleteSpecialDayGroupResponse {} // This operation returns the capabilities of the schedule service. pub async fn get_service_capabilities<T: transport::Transport>( transport: &T, request: &GetServiceCapabilities, ) -> Result<GetServiceCapabilitiesResponse, transport::Error> { transport::request(transport, request).await } // This operation requests the ScheduleState for the schedule instance specified // by the given token. pub async fn get_schedule_state<T: transport::Transport>( transport: &T, request: &GetScheduleState, ) -> Result<GetScheduleStateResponse, transport::Error> { transport::request(transport, request).await } // This method returns a list of schedule info items, specified in the request. // Only found schedules shall be returned, i.e., the returned numbers of // elements can // differ from the requested element. // The device shall ignore tokens it cannot resolve and shall return an empty // list if // there are no items matching the specified tokens. // If the number of requested items is greater than MaxLimit, a TooManyItems // fault shall be returned. pub async fn get_schedule_info<T: transport::Transport>( transport: &T, request: &GetScheduleInfo, ) -> Result<GetScheduleInfoResponse, transport::Error> { transport::request(transport, request).await } // This operation requests a list of all of ScheduleInfo items provided by the // device. // A call to this method shall return a StartReference when not all data is // returned // and more data is available. The reference shall be valid for retrieving the // next set of data. // Please refer Access Control Service Specification for more details. // The number of items returned shall not be greater the Limit parameter. pub async fn get_schedule_info_list<T: transport::Transport>( transport: &T, request: &GetScheduleInfoList, ) -> Result<GetScheduleInfoListResponse, transport::Error> { transport::request(transport, request).await } // This operation returns the specified schedule item matching the given tokens. // The device shall ignore tokens it cannot resolve and shall return an empty // list // if there are no items matching the specified tokens. // If the number of requested items is greater than MaxLimit, a TooManyItems // fault shall be returned pub async fn get_schedules<T: transport::Transport>( transport: &T, request: &GetSchedules, ) -> Result<GetSchedulesResponse, transport::Error> { transport::request(transport, request).await } // This operation requests a list of all of Schedule items provided by the // device. // A call to this method shall return a StartReference when not all data is // returned // and more data is available. The reference shall be valid for retrieving the // next set of data. // Please refer Access Control Service Specification for more details. // The number of items returned shall not be greater the Limit parameter. pub async fn get_schedule_list<T: transport::Transport>( transport: &T, request: &GetScheduleList, ) -> Result<GetScheduleListResponse, transport::Error> { transport::request(transport, request).await } // This operation creates the specified schedule. The token field of the // schedule structure // shall be empty, the device shall allocate a token for the schedule. The // allocated token // shall be returned in the response. If the client sends any value in the token // field, // the device shall return InvalidArgVal as generic fault code. pub async fn create_schedule<T: transport::Transport>( transport: &T, request: &CreateSchedule, ) -> Result<CreateScheduleResponse, transport::Error> { transport::request(transport, request).await } // This operation modifies or creates the specified schedule. pub async fn set_schedule<T: transport::Transport>( transport: &T, request: &SetSchedule, ) -> Result<SetScheduleResponse, transport::Error> { transport::request(transport, request).await } // This operation modifies or updates the specified schedule. pub async fn modify_schedule<T: transport::Transport>( transport: &T, request: &ModifySchedule, ) -> Result<ModifyScheduleResponse, transport::Error> { transport::request(transport, request).await } // This operation will delete the specified schedule. // If it is associated with one or more entities some devices may not be able to // delete the schedule, // and consequently a ReferenceInUse fault shall be generated. pub async fn delete_schedule<T: transport::Transport>( transport: &T, request: &DeleteSchedule, ) -> Result<DeleteScheduleResponse, transport::Error> { transport::request(transport, request).await } // This operation requests a list of SpecialDayGroupInfo items matching the // given tokens. // The device shall ignore tokens it cannot resolve and shall return an empty // list if // there are no items matching specified tokens. The device shall not return a // fault in this case. // If the number of requested items is greater than MaxLimit, a TooManyItems // fault shall be returned.
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
true
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/t_1/src/lib.rs
wsdl_rs/t_1/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use std::str::FromStr; use validate::Validate; use xsd_macro_utils::*; use yaserde_derive::{YaDeserialize, YaSerialize}; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wstop", namespace = "wstop: http://docs.oasis-open.org/wsn/t-1" )] pub struct Documentation {} impl Validate for Documentation {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wstop", namespace = "wstop: http://docs.oasis-open.org/wsn/t-1" )] pub struct ExtensibleDocumented { #[yaserde(prefix = "wstop", rename = "documentation")] pub documentation: Option<Documentation>, } impl Validate for ExtensibleDocumented {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wstop", namespace = "wstop: http://docs.oasis-open.org/wsn/t-1" )] pub struct QueryExpressionType { #[yaserde(attribute, rename = "Dialect")] pub dialect: String, } impl Validate for QueryExpressionType {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wstop", namespace = "wstop: http://docs.oasis-open.org/wsn/t-1" )] pub struct TopicNamespaceType { #[yaserde(prefix = "wstop", rename = "Topic")] pub topic: Vec<topic_namespace_type::TopicType>, #[yaserde(attribute, rename = "name")] pub name: Option<String>, #[yaserde(attribute, rename = "targetNamespace")] pub target_namespace: String, #[yaserde(attribute, rename = "final")] pub _final: Option<bool>, #[yaserde(prefix = "wstop", rename = "documentation")] pub documentation: Option<Documentation>, } impl Validate for TopicNamespaceType {} pub mod topic_namespace_type { use super::*; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wstop", namespace = "wstop: http://docs.oasis-open.org/wsn/t-1" )] pub struct TopicType { #[yaserde(attribute, rename = "parent")] pub parent: Option<ConcreteTopicExpression>, #[yaserde(prefix = "wstop", rename = "MessagePattern")] pub message_pattern: QueryExpressionType, #[yaserde(prefix = "wstop", rename = "Topic")] pub topic: Vec<TopicType>, #[yaserde(attribute, rename = "name")] pub name: String, #[yaserde(attribute, rename = "messageTypes")] pub message_types: Option<String>, #[yaserde(attribute, rename = "final")] pub _final: Option<bool>, } impl Validate for TopicType {} } // pub type TopicNamespace = TopicNamespaceType; // pub type TopicNamespaceLocation = String; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wstop", namespace = "wstop: http://docs.oasis-open.org/wsn/t-1" )] pub struct TopicType { #[yaserde(prefix = "wstop", rename = "MessagePattern")] pub message_pattern: QueryExpressionType, #[yaserde(prefix = "wstop", rename = "Topic")] pub topic: Vec<TopicType>, #[yaserde(attribute, rename = "name")] pub name: String, #[yaserde(attribute, rename = "messageTypes")] pub message_types: Option<String>, #[yaserde(attribute, rename = "final")] pub _final: Option<bool>, #[yaserde(prefix = "wstop", rename = "documentation")] pub documentation: Option<Documentation>, } impl Validate for TopicType {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wstop", namespace = "wstop: http://docs.oasis-open.org/wsn/t-1" )] pub struct TopicSetType { #[yaserde(prefix = "wstop", rename = "documentation")] pub documentation: Option<Documentation>, } impl Validate for TopicSetType {} pub type TopicSet = TopicSetType; // pub type Topic = bool; #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct FullTopicExpression(pub String); impl Validate for FullTopicExpression {} #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct ConcreteTopicExpression(pub String); impl Validate for ConcreteTopicExpression {} #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct SimpleTopicExpression(pub String); impl Validate for SimpleTopicExpression {}
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
false
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/receiver/src/lib.rs
wsdl_rs/receiver/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use onvif as tt; use validate::Validate; use yaserde_derive::{YaDeserialize, YaSerialize}; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trv", namespace = "trv: http://www.onvif.org/ver10/receiver/wsdl" )] pub struct GetServiceCapabilities {} impl Validate for GetServiceCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trv", namespace = "trv: http://www.onvif.org/ver10/receiver/wsdl" )] pub struct GetServiceCapabilitiesResponse { // The capabilities for the receiver service is returned in the Capabilities // element. #[yaserde(prefix = "trv", rename = "Capabilities")] pub capabilities: Capabilities, } impl Validate for GetServiceCapabilitiesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trv", namespace = "trv: http://www.onvif.org/ver10/receiver/wsdl" )] pub struct Capabilities { // Indicates that the device can receive RTP multicast streams. #[yaserde(attribute, rename = "RTP_Multicast")] pub rtp_multicast: Option<bool>, // Indicates that the device can receive RTP/TCP streams #[yaserde(attribute, rename = "RTP_TCP")] pub rtp_tcp: Option<bool>, // Indicates that the device can receive RTP/RTSP/TCP streams. #[yaserde(attribute, rename = "RTP_RTSP_TCP")] pub rtp_rtsp_tcp: Option<bool>, // The maximum number of receivers supported by the device. #[yaserde(attribute, rename = "SupportedReceivers")] pub supported_receivers: i32, // The maximum allowed length for RTSP URIs (Minimum and default value is // 128 octet). #[yaserde(attribute, rename = "MaximumRTSPURILength")] pub maximum_rtspuri_length: Option<i32>, } impl Validate for Capabilities {} // pub type Capabilities = Capabilities; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trv", namespace = "trv: http://www.onvif.org/ver10/receiver/wsdl" )] pub struct GetReceivers {} impl Validate for GetReceivers {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trv", namespace = "trv: http://www.onvif.org/ver10/receiver/wsdl" )] pub struct GetReceiversResponse { // A list of all receivers that currently exist on the device. #[yaserde(prefix = "trv", rename = "Receivers")] pub receivers: Vec<tt::Receiver>, } impl Validate for GetReceiversResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trv", namespace = "trv: http://www.onvif.org/ver10/receiver/wsdl" )] pub struct GetReceiver { // The token of the receiver to be retrieved. #[yaserde(prefix = "trv", rename = "ReceiverToken")] pub receiver_token: tt::ReferenceToken, } impl Validate for GetReceiver {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trv", namespace = "trv: http://www.onvif.org/ver10/receiver/wsdl" )] pub struct GetReceiverResponse { // The details of the receiver. #[yaserde(prefix = "trv", rename = "Receiver")] pub receiver: tt::Receiver, } impl Validate for GetReceiverResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trv", namespace = "trv: http://www.onvif.org/ver10/receiver/wsdl" )] pub struct CreateReceiver { // The initial configuration for the new receiver. #[yaserde(prefix = "trv", rename = "Configuration")] pub configuration: tt::ReceiverConfiguration, } impl Validate for CreateReceiver {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trv", namespace = "trv: http://www.onvif.org/ver10/receiver/wsdl" )] pub struct CreateReceiverResponse { // The details of the receiver that was created. #[yaserde(prefix = "trv", rename = "Receiver")] pub receiver: tt::Receiver, } impl Validate for CreateReceiverResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trv", namespace = "trv: http://www.onvif.org/ver10/receiver/wsdl" )] pub struct DeleteReceiver { // The token of the receiver to be deleted. #[yaserde(prefix = "trv", rename = "ReceiverToken")] pub receiver_token: tt::ReferenceToken, } impl Validate for DeleteReceiver {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trv", namespace = "trv: http://www.onvif.org/ver10/receiver/wsdl" )] pub struct DeleteReceiverResponse {} impl Validate for DeleteReceiverResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trv", namespace = "trv: http://www.onvif.org/ver10/receiver/wsdl" )] pub struct ConfigureReceiver { // The token of the receiver to be configured. #[yaserde(prefix = "trv", rename = "ReceiverToken")] pub receiver_token: tt::ReferenceToken, // The new configuration for the receiver. #[yaserde(prefix = "trv", rename = "Configuration")] pub configuration: tt::ReceiverConfiguration, } impl Validate for ConfigureReceiver {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trv", namespace = "trv: http://www.onvif.org/ver10/receiver/wsdl" )] pub struct ConfigureReceiverResponse {} impl Validate for ConfigureReceiverResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trv", namespace = "trv: http://www.onvif.org/ver10/receiver/wsdl" )] pub struct SetReceiverMode { // The token of the receiver to be changed. #[yaserde(prefix = "trv", rename = "ReceiverToken")] pub receiver_token: tt::ReferenceToken, // The new receiver mode. Options available are: #[yaserde(prefix = "trv", rename = "Mode")] pub mode: tt::ReceiverMode, } impl Validate for SetReceiverMode {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trv", namespace = "trv: http://www.onvif.org/ver10/receiver/wsdl" )] pub struct SetReceiverModeResponse {} impl Validate for SetReceiverModeResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trv", namespace = "trv: http://www.onvif.org/ver10/receiver/wsdl" )] pub struct GetReceiverState { // The token of the receiver to be queried. #[yaserde(prefix = "trv", rename = "ReceiverToken")] pub receiver_token: tt::ReferenceToken, } impl Validate for GetReceiverState {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trv", namespace = "trv: http://www.onvif.org/ver10/receiver/wsdl" )] pub struct GetReceiverStateResponse { // Description of the current receiver state. #[yaserde(prefix = "trv", rename = "ReceiverState")] pub receiver_state: tt::ReceiverStateInformation, } impl Validate for GetReceiverStateResponse {} // Returns the capabilities of the receiver service. The result is returned in a // typed answer. pub async fn get_service_capabilities<T: transport::Transport>( transport: &T, request: &GetServiceCapabilities, ) -> Result<GetServiceCapabilitiesResponse, transport::Error> { transport::request(transport, request).await } // Lists all receivers currently present on a device. This operation is // mandatory. pub async fn get_receivers<T: transport::Transport>( transport: &T, request: &GetReceivers, ) -> Result<GetReceiversResponse, transport::Error> { transport::request(transport, request).await } // Retrieves the details of a specific receiver. This operation is mandatory. pub async fn get_receiver<T: transport::Transport>( transport: &T, request: &GetReceiver, ) -> Result<GetReceiverResponse, transport::Error> { transport::request(transport, request).await } // Creates a new receiver. This operation is mandatory, although the service may // raise a fault if the receiver cannot be created. pub async fn create_receiver<T: transport::Transport>( transport: &T, request: &CreateReceiver, ) -> Result<CreateReceiverResponse, transport::Error> { transport::request(transport, request).await } // Deletes an existing receiver. A receiver may be deleted only if it is not // currently in use; otherwise a fault shall be raised. // This operation is mandatory. pub async fn delete_receiver<T: transport::Transport>( transport: &T, request: &DeleteReceiver, ) -> Result<DeleteReceiverResponse, transport::Error> { transport::request(transport, request).await } // Configures an existing receiver. This operation is mandatory. pub async fn configure_receiver<T: transport::Transport>( transport: &T, request: &ConfigureReceiver, ) -> Result<ConfigureReceiverResponse, transport::Error> { transport::request(transport, request).await } // Sets the mode of the receiver without affecting the rest of its // configuration. // This operation is mandatory. pub async fn set_receiver_mode<T: transport::Transport>( transport: &T, request: &SetReceiverMode, ) -> Result<SetReceiverModeResponse, transport::Error> { transport::request(transport, request).await } // Determines whether the receiver is currently disconnected, connected or // attempting to connect. // This operation is mandatory. pub async fn get_receiver_state<T: transport::Transport>( transport: &T, request: &GetReceiverState, ) -> Result<GetReceiverStateResponse, transport::Error> { transport::request(transport, request).await }
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
false
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/deviceio/src/lib.rs
wsdl_rs/deviceio/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use devicemgmt as tds; use onvif as tt; use std::str::FromStr; use validate::Validate; use xsd_macro_utils::*; use xsd_types::types as xs; use yaserde_derive::{YaDeserialize, YaSerialize}; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetServiceCapabilities {} impl Validate for GetServiceCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetServiceCapabilitiesResponse { // The capabilities for the device IO service is returned in the // Capabilities element. #[yaserde(prefix = "tmd", rename = "Capabilities")] pub capabilities: Capabilities, } impl Validate for GetServiceCapabilitiesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct Capabilities { // Number of video sources (defaults to none). #[yaserde(attribute, rename = "VideoSources")] pub video_sources: Option<i32>, // Number of video outputs (defaults to none). #[yaserde(attribute, rename = "VideoOutputs")] pub video_outputs: Option<i32>, // Number of audio sources (defaults to none). #[yaserde(attribute, rename = "AudioSources")] pub audio_sources: Option<i32>, // Number of audio outputs (defaults to none). #[yaserde(attribute, rename = "AudioOutputs")] pub audio_outputs: Option<i32>, // Number of relay outputs (defaults to none). #[yaserde(attribute, rename = "RelayOutputs")] pub relay_outputs: Option<i32>, // Number of serial ports (defaults to none). #[yaserde(attribute, rename = "SerialPorts")] pub serial_ports: Option<i32>, // Number of digital inputs (defaults to none). #[yaserde(attribute, rename = "DigitalInputs")] pub digital_inputs: Option<i32>, // Indicates support for DigitalInput configuration of the idle state // (defaults to false). #[yaserde(attribute, rename = "DigitalInputOptions")] pub digital_input_options: Option<bool>, } impl Validate for Capabilities {} // pub type Capabilities = Capabilities; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetRelayOutputOptions { // Optional reference token to the relay for which the options are // requested. #[yaserde(prefix = "tmd", rename = "RelayOutputToken")] pub relay_output_token: Option<tt::ReferenceToken>, } impl Validate for GetRelayOutputOptions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetRelayOutputOptionsResponse { // Valid values and ranges for the configuration of a relay output. #[yaserde(prefix = "tmd", rename = "RelayOutputOptions")] pub relay_output_options: Vec<RelayOutputOptions>, } impl Validate for GetRelayOutputOptionsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct RelayOutputOptions { // Supported Modes. #[yaserde(prefix = "tmd", rename = "Mode")] pub mode: Vec<tt::RelayMode>, // Supported delay time range or discrete values in seconds. This element // must be present if MonoStable mode is supported. #[yaserde(prefix = "tmd", rename = "DelayTimes")] pub delay_times: Option<DelayTimes>, // True if the relay only supports the exact values for the DelayTimes // listed. Default is false. #[yaserde(prefix = "tmd", rename = "Discrete")] pub discrete: Option<bool>, #[yaserde(prefix = "tmd", rename = "Extension")] pub extension: Option<RelayOutputOptionsExtension>, // Token of the relay output. #[yaserde(attribute, rename = "token")] pub token: tt::ReferenceToken, } impl Validate for RelayOutputOptions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct RelayOutputOptionsExtension {} impl Validate for RelayOutputOptionsExtension {} #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct DelayTimes(pub Vec<f64>); impl Validate for DelayTimes {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct Get {} impl Validate for Get {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetResponse { // List tokens of a physical IO of a device. #[yaserde(prefix = "tmd", rename = "Token")] pub token: Vec<tt::ReferenceToken>, } impl Validate for GetResponse {} pub type GetVideoSources = Get; pub type GetVideoSourcesResponse = GetResponse; pub type GetAudioSources = Get; pub type GetAudioSourcesResponse = GetResponse; pub type GetAudioOutputs = Get; pub type GetAudioOutputsResponse = GetResponse; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetVideoOutputs {} impl Validate for GetVideoOutputs {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetVideoOutputsResponse { // List containing all physical Video output connections of a device. #[yaserde(prefix = "tmd", rename = "VideoOutputs")] pub video_outputs: Vec<tt::VideoOutput>, } impl Validate for GetVideoOutputsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetAudioSourceConfiguration { // Token of the requested AudioSource. #[yaserde(prefix = "tmd", rename = "AudioSourceToken")] pub audio_source_token: tt::ReferenceToken, } impl Validate for GetAudioSourceConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetAudioSourceConfigurationResponse { // Current configuration of the Audio input. #[yaserde(prefix = "tmd", rename = "AudioSourceConfiguration")] pub audio_source_configuration: tt::AudioSourceConfiguration, } impl Validate for GetAudioSourceConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetAudioOutputConfiguration { // Token of the physical Audio output. #[yaserde(prefix = "tmd", rename = "AudioOutputToken")] pub audio_output_token: tt::ReferenceToken, } impl Validate for GetAudioOutputConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetAudioOutputConfigurationResponse { // Current configuration of the Audio output. #[yaserde(prefix = "tmd", rename = "AudioOutputConfiguration")] pub audio_output_configuration: tt::AudioOutputConfiguration, } impl Validate for GetAudioOutputConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetVideoSourceConfiguration { // Token of the requested VideoSource. #[yaserde(prefix = "tmd", rename = "VideoSourceToken")] pub video_source_token: tt::ReferenceToken, } impl Validate for GetVideoSourceConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetVideoSourceConfigurationResponse { // Current configuration of the Video input. #[yaserde(prefix = "tmd", rename = "VideoSourceConfiguration")] pub video_source_configuration: tt::VideoSourceConfiguration, } impl Validate for GetVideoSourceConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetVideoOutputConfiguration { // Token of the requested VideoOutput. #[yaserde(prefix = "tmd", rename = "VideoOutputToken")] pub video_output_token: tt::ReferenceToken, } impl Validate for GetVideoOutputConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetVideoOutputConfigurationResponse { // Current configuration of the Video output. #[yaserde(prefix = "tmd", rename = "VideoOutputConfiguration")] pub video_output_configuration: tt::VideoOutputConfiguration, } impl Validate for GetVideoOutputConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct SetAudioSourceConfiguration { #[yaserde(prefix = "tmd", rename = "Configuration")] pub configuration: tt::AudioSourceConfiguration, // The ForcePersistence element determines how configuration // changes shall be stored. If true, changes shall be persistent. If false, // changes MAY revert to previous values // after reboot. #[yaserde(prefix = "tmd", rename = "ForcePersistence")] pub force_persistence: bool, } impl Validate for SetAudioSourceConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct SetAudioSourceConfigurationResponse {} impl Validate for SetAudioSourceConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct SetAudioOutputConfiguration { #[yaserde(prefix = "tmd", rename = "Configuration")] pub configuration: tt::AudioOutputConfiguration, // The ForcePersistence element determines how configuration // changes shall be stored. If true, changes shall be persistent. If false, // changes MAY revert to previous values // after reboot. #[yaserde(prefix = "tmd", rename = "ForcePersistence")] pub force_persistence: bool, } impl Validate for SetAudioOutputConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct SetAudioOutputConfigurationResponse {} impl Validate for SetAudioOutputConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct SetVideoSourceConfiguration { #[yaserde(prefix = "tmd", rename = "Configuration")] pub configuration: tt::VideoSourceConfiguration, // The ForcePersistence element determines how configuration // changes shall be stored. If true, changes shall be persistent. If false, // changes MAY revert to previous values // after reboot. #[yaserde(prefix = "tmd", rename = "ForcePersistence")] pub force_persistence: bool, } impl Validate for SetVideoSourceConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct SetVideoSourceConfigurationResponse {} impl Validate for SetVideoSourceConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct SetVideoOutputConfiguration { #[yaserde(prefix = "tmd", rename = "Configuration")] pub configuration: tt::VideoOutputConfiguration, // The ForcePersistence element determines how configuration // changes shall be stored. If true, changes shall be persistent. If false, // changes MAY revert to previous values // after reboot. #[yaserde(prefix = "tmd", rename = "ForcePersistence")] pub force_persistence: bool, } impl Validate for SetVideoOutputConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct SetVideoOutputConfigurationResponse {} impl Validate for SetVideoOutputConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetVideoSourceConfigurationOptions { // Token of the Video input whose options are requested.. #[yaserde(prefix = "tmd", rename = "VideoSourceToken")] pub video_source_token: tt::ReferenceToken, } impl Validate for GetVideoSourceConfigurationOptions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetVideoSourceConfigurationOptionsResponse { #[yaserde(prefix = "tmd", rename = "VideoSourceConfigurationOptions")] pub video_source_configuration_options: tt::VideoSourceConfigurationOptions, } impl Validate for GetVideoSourceConfigurationOptionsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetVideoOutputConfigurationOptions { // Token of the Video Output whose options are requested.. #[yaserde(prefix = "tmd", rename = "VideoOutputToken")] pub video_output_token: tt::ReferenceToken, } impl Validate for GetVideoOutputConfigurationOptions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetVideoOutputConfigurationOptionsResponse { #[yaserde(prefix = "tmd", rename = "VideoOutputConfigurationOptions")] pub video_output_configuration_options: tt::VideoOutputConfigurationOptions, } impl Validate for GetVideoOutputConfigurationOptionsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetAudioSourceConfigurationOptions { // Token of the physical Audio input whose options are requested.. #[yaserde(prefix = "tmd", rename = "AudioSourceToken")] pub audio_source_token: tt::ReferenceToken, } impl Validate for GetAudioSourceConfigurationOptions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetAudioSourceConfigurationOptionsResponse { // Returns the AudioSourceToken available. #[yaserde(prefix = "tmd", rename = "AudioSourceOptions")] pub audio_source_options: tt::AudioSourceConfigurationOptions, } impl Validate for GetAudioSourceConfigurationOptionsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetAudioOutputConfigurationOptions { // Token of the physical Audio Output whose options are requested.. #[yaserde(prefix = "tmd", rename = "AudioOutputToken")] pub audio_output_token: tt::ReferenceToken, } impl Validate for GetAudioOutputConfigurationOptions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetAudioOutputConfigurationOptionsResponse { // Available settings and ranges for the requested Audio output. #[yaserde(prefix = "tmd", rename = "AudioOutputOptions")] pub audio_output_options: tt::AudioOutputConfigurationOptions, } impl Validate for GetAudioOutputConfigurationOptionsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct SetRelayOutputSettings { #[yaserde(prefix = "tmd", rename = "RelayOutput")] pub relay_output: tt::RelayOutput, } impl Validate for SetRelayOutputSettings {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct SetRelayOutputSettingsResponse {} impl Validate for SetRelayOutputSettingsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetDigitalInputs {} impl Validate for GetDigitalInputs {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetDigitalInputsResponse { #[yaserde(prefix = "tmd", rename = "DigitalInputs")] pub digital_inputs: Vec<tt::DigitalInput>, } impl Validate for GetDigitalInputsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct DigitalInputConfigurationOptions { // Configuration Options for a digital input. #[yaserde(prefix = "tmd", rename = "IdleState")] pub idle_state: Vec<tt::DigitalIdleState>, } impl Validate for DigitalInputConfigurationOptions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetDigitalInputConfigurationOptions { #[yaserde(prefix = "tmd", rename = "Token")] pub token: Option<tt::ReferenceToken>, } impl Validate for GetDigitalInputConfigurationOptions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetDigitalInputConfigurationOptionsResponse { #[yaserde(prefix = "tmd", rename = "DigitalInputOptions")] pub digital_input_options: DigitalInputConfigurationOptions, } impl Validate for GetDigitalInputConfigurationOptionsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct SetDigitalInputConfigurations { #[yaserde(prefix = "tmd", rename = "DigitalInputs")] pub digital_inputs: Vec<tt::DigitalInput>, } impl Validate for SetDigitalInputConfigurations {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct SetDigitalInputConfigurationsResponse {} impl Validate for SetDigitalInputConfigurationsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetSerialPorts {} impl Validate for GetSerialPorts {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetSerialPortsResponse { #[yaserde(prefix = "tmd", rename = "SerialPort")] pub serial_port: Vec<SerialPort>, } impl Validate for GetSerialPortsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetSerialPortConfiguration { #[yaserde(prefix = "tmd", rename = "SerialPortToken")] pub serial_port_token: tt::ReferenceToken, } impl Validate for GetSerialPortConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetSerialPortConfigurationResponse { #[yaserde(prefix = "tmd", rename = "SerialPortConfiguration")] pub serial_port_configuration: SerialPortConfiguration, } impl Validate for GetSerialPortConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct SetSerialPortConfiguration { #[yaserde(prefix = "tmd", rename = "SerialPortConfiguration")] pub serial_port_configuration: SerialPortConfiguration, #[yaserde(prefix = "tmd", rename = "ForcePersistance")] pub force_persistance: bool, } impl Validate for SetSerialPortConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct SetSerialPortConfigurationResponse {} impl Validate for SetSerialPortConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetSerialPortConfigurationOptions { #[yaserde(prefix = "tmd", rename = "SerialPortToken")] pub serial_port_token: tt::ReferenceToken, } impl Validate for GetSerialPortConfigurationOptions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct GetSerialPortConfigurationOptionsResponse { #[yaserde(prefix = "tmd", rename = "SerialPortOptions")] pub serial_port_options: SerialPortConfigurationOptions, } impl Validate for GetSerialPortConfigurationOptionsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct SendReceiveSerialCommand { // The physical serial port reference to be used when this request is // invoked. #[yaserde(prefix = "tmd", rename = "Token")] pub token: Option<tt::ReferenceToken>, // The serial port data. #[yaserde(prefix = "tmd", rename = "SerialData")] pub serial_data: Option<SerialData>, // Indicates that the command should be responded back within the specified // period of time. #[yaserde(prefix = "tmd", rename = "TimeOut")] pub time_out: Option<xs::Duration>, // This element may be put in the case that data length returned from the // connected serial device is already determined as some fixed bytes length. // It indicates the length of received data which can be regarded as // available. #[yaserde(prefix = "tmd", rename = "DataLength")] pub data_length: Option<xs::Integer>, // This element may be put in the case that the delimiter codes returned // from the connected serial device is already known. It indicates the // termination data sequence of the responded data. In case the string has // more than one character a device shall interpret the whole string as a // single delimiter. Furthermore a device shall return the delimiter // character(s) to the client. #[yaserde(prefix = "tmd", rename = "Delimiter")] pub delimiter: Option<String>, } impl Validate for SendReceiveSerialCommand {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct SendReceiveSerialCommandResponse { #[yaserde(prefix = "tmd", rename = "SerialData")] pub serial_data: Option<SerialData>, } impl Validate for SendReceiveSerialCommandResponse {} #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum SerialDataChoice { Binary(String), String(String), __Unknown__(String), } impl Default for SerialDataChoice { fn default() -> SerialDataChoice { Self::__Unknown__("No valid variants".into()) } } impl Validate for SerialDataChoice {} // The serial port data. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct SerialData { #[yaserde(flatten)] pub serial_data_choice: SerialDataChoice, } impl Validate for SerialData {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct SerialPort { pub base: tt::DeviceEntity, } impl Validate for SerialPort {} // The type of serial port.Generic can be signaled as a vendor specific serial // port type. #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum SerialPortType { #[yaserde(rename = "RS232")] Rs232, #[yaserde(rename = "RS422HalfDuplex")] Rs422HalfDuplex, #[yaserde(rename = "RS422FullDuplex")] Rs422FullDuplex, #[yaserde(rename = "RS485HalfDuplex")] Rs485HalfDuplex, #[yaserde(rename = "RS485FullDuplex")] Rs485FullDuplex, Generic, __Unknown__(String), } impl Default for SerialPortType { fn default() -> SerialPortType { Self::__Unknown__("No valid variants".into()) } } impl Validate for SerialPortType {} // The parameters for configuring the serial port. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct SerialPortConfiguration { // The transfer bitrate. #[yaserde(prefix = "tmd", rename = "BaudRate")] pub baud_rate: i32, // The parity for the data error detection. #[yaserde(prefix = "tmd", rename = "ParityBit")] pub parity_bit: ParityBit, // The bit length for each character. #[yaserde(prefix = "tmd", rename = "CharacterLength")] pub character_length: i32, // The number of stop bits used to terminate each character. #[yaserde(prefix = "tmd", rename = "StopBit")] pub stop_bit: f64, #[yaserde(attribute, rename = "token")] pub token: tt::ReferenceToken, #[yaserde(attribute, rename = "type")] pub _type: SerialPortType, } impl Validate for SerialPortConfiguration {} // The parity for the data error detection. #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum ParityBit { None, Even, Odd, Mark, Space, Extended, __Unknown__(String), } impl Default for ParityBit { fn default() -> ParityBit { Self::__Unknown__("No valid variants".into()) } } impl Validate for ParityBit {} // The configuration options that relates to serial port. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct SerialPortConfigurationOptions { // The list of configurable transfer bitrate. #[yaserde(prefix = "tmd", rename = "BaudRateList")] pub baud_rate_list: tt::IntList, // The list of configurable parity for the data error detection. #[yaserde(prefix = "tmd", rename = "ParityBitList")] pub parity_bit_list: ParityBitList, // The list of configurable bit length for each character. #[yaserde(prefix = "tmd", rename = "CharacterLengthList")] pub character_length_list: tt::IntList, // The list of configurable number of stop bits used to terminate each // character. #[yaserde(prefix = "tmd", rename = "StopBitList")] pub stop_bit_list: tt::FloatList, #[yaserde(attribute, rename = "token")] pub token: tt::ReferenceToken, } impl Validate for SerialPortConfigurationOptions {} // The list of configurable parity for the data error detection. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tmd", namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl" )] pub struct ParityBitList { #[yaserde(prefix = "tmd", rename = "Items")] pub items: Vec<ParityBit>, } impl Validate for ParityBitList {} // Returns the capabilities of the device IO service. The result is returned in // a typed answer. pub async fn get_service_capabilities<T: transport::Transport>( transport: &T, request: &GetServiceCapabilities, ) -> Result<GetServiceCapabilitiesResponse, transport::Error> { transport::request(transport, request).await } // Request the available settings and ranges for one or all relay outputs. A // device that has one or more RelayOutputs should support this command. pub async fn get_relay_output_options<T: transport::Transport>( transport: &T, request: &GetRelayOutputOptions, ) -> Result<GetRelayOutputOptionsResponse, transport::Error> { transport::request(transport, request).await } // List all available audio sources for the device. The device that has one or // more audio sources shall support the listing of available audio inputs // through the GetAudioSources command. pub async fn get_audio_sources<T: transport::Transport>( transport: &T, request: &GetAudioSources, ) -> Result<GetAudioSourcesResponse, transport::Error> { transport::request(transport, request).await } // List all available audio outputs of a device. A device that has one ore more // physical audio outputs shall support listing of available audio outputs // through the GetAudioOutputs command. pub async fn get_audio_outputs<T: transport::Transport>( transport: &T, request: &GetAudioOutputs, ) -> Result<GetAudioOutputsResponse, transport::Error> { transport::request(transport, request).await } // List all available video sources for the device. The device that has one or // more video inputs shall support the listing of available video sources // through the GetVideoSources command. pub async fn get_video_sources<T: transport::Transport>( transport: &T, request: &GetVideoSources, ) -> Result<GetVideoSourcesResponse, transport::Error> { transport::request(transport, request).await } // List all available video outputs of a device. A device that has one or more // physical video outputs shall support listing of available video outputs // through the GetVideoOutputs command. pub async fn get_video_outputs<T: transport::Transport>( transport: &T, request: &GetVideoOutputs, ) -> Result<GetVideoOutputsResponse, transport::Error> { transport::request(transport, request).await } // Get the video source configurations of a VideoSource. A device with one or // more video sources shall support the GetVideoSourceConfigurations command. pub async fn get_video_source_configuration<T: transport::Transport>( transport: &T, request: &GetVideoSourceConfiguration, ) -> Result<GetVideoSourceConfigurationResponse, transport::Error> { transport::request(transport, request).await } // Get the configuration of a Video Output. A device that has one or more Video // Outputs shall support the retrieval of the VideoOutputConfiguration through // this command. pub async fn get_video_output_configuration<T: transport::Transport>( transport: &T, request: &GetVideoOutputConfiguration, ) -> Result<GetVideoOutputConfigurationResponse, transport::Error> { transport::request(transport, request).await } // List the configuration of an Audio Input. A device with one or more audio // inputs shall support the GetAudioSourceConfiguration command. pub async fn get_audio_source_configuration<T: transport::Transport>( transport: &T, request: &GetAudioSourceConfiguration, ) -> Result<GetAudioSourceConfigurationResponse, transport::Error> {
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
true
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/event/src/lib.rs
wsdl_rs/event/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use b_2 as wsnt; use t_1 as wstop; use validate::Validate; use ws_addr as wsa; use xsd_types::types as xs; use yaserde_derive::{YaDeserialize, YaSerialize}; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tev", namespace = "tev: http://www.onvif.org/ver10/events/wsdl" )] pub struct GetServiceCapabilities {} impl Validate for GetServiceCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tev", namespace = "tev: http://www.onvif.org/ver10/events/wsdl" )] pub struct GetServiceCapabilitiesResponse { // The capabilities for the event service is returned in the Capabilities // element. #[yaserde(prefix = "tev", rename = "Capabilities")] pub capabilities: Capabilities, } impl Validate for GetServiceCapabilitiesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tev", namespace = "tev: http://www.onvif.org/ver10/events/wsdl" )] pub struct Capabilities { // Indicates that the WS Subscription policy is supported. #[yaserde(attribute, rename = "WSSubscriptionPolicySupport")] pub ws_subscription_policy_support: Option<bool>, // Indicates that the WS Pull Point is supported. #[yaserde(attribute, rename = "WSPullPointSupport")] pub ws_pull_point_support: Option<bool>, // Indicates that the WS Pausable Subscription Manager Interface is // supported. #[yaserde(attribute, rename = "WSPausableSubscriptionManagerInterfaceSupport")] pub ws_pausable_subscription_manager_interface_support: Option<bool>, // Maximum number of supported notification producers as defined by // WS-BaseNotification. #[yaserde(attribute, rename = "MaxNotificationProducers")] pub max_notification_producers: Option<i32>, // Maximum supported number of notification pull points. #[yaserde(attribute, rename = "MaxPullPoints")] pub max_pull_points: Option<i32>, // Indication if the device supports persistent notification storage. #[yaserde(attribute, rename = "PersistentNotificationStorage")] pub persistent_notification_storage: Option<bool>, } impl Validate for Capabilities {} // pub type Capabilities = Capabilities; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tev", namespace = "tev: http://www.onvif.org/ver10/events/wsdl" )] pub struct CreatePullPointSubscription { // Optional XPATH expression to select specific topics. #[yaserde(prefix = "tev", rename = "Filter")] pub filter: Option<wsnt::FilterType>, // Initial termination time. #[yaserde(prefix = "tev", rename = "InitialTerminationTime")] pub initial_termination_time: Option<wsnt::AbsoluteOrRelativeTimeType>, // Refer to #[yaserde(prefix = "tev", rename = "SubscriptionPolicy")] pub subscription_policy: Option<create_pull_point_subscription::SubscriptionPolicyType>, } impl Validate for CreatePullPointSubscription {} pub mod create_pull_point_subscription { use super::*; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tev", namespace = "tev: http://www.onvif.org/ver10/events/wsdl" )] pub struct SubscriptionPolicyType {} impl Validate for SubscriptionPolicyType {} } #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tev", namespace = "tev: http://www.onvif.org/ver10/events/wsdl" )] pub struct CreatePullPointSubscriptionResponse { // Endpoint reference of the subscription to be used for pulling the // messages. #[yaserde(prefix = "tev", rename = "SubscriptionReference")] pub subscription_reference: wsa::EndpointReferenceType, // Current time of the server for synchronization purposes. #[yaserde(prefix = "wsnt", rename = "CurrentTime")] pub current_time: wsnt::CurrentTime, // Date time when the PullPoint will be shut down without further pull // requests. #[yaserde(prefix = "wsnt", rename = "TerminationTime")] pub termination_time: wsnt::TerminationTime, } impl Validate for CreatePullPointSubscriptionResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tev", namespace = "tev: http://www.onvif.org/ver10/events/wsdl" )] pub struct PullMessages { // Maximum time to block until this method returns. #[yaserde(prefix = "tev", rename = "Timeout")] pub timeout: xs::Duration, // Upper limit for the number of messages to return at once. A server // implementation may decide to return less messages. #[yaserde(prefix = "tev", rename = "MessageLimit")] pub message_limit: i32, } impl Validate for PullMessages {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tev", namespace = "tev: http://www.onvif.org/ver10/events/wsdl" )] pub struct PullMessagesResponse { // The date and time when the messages have been delivered by the web server // to the client. #[yaserde(prefix = "tev", rename = "CurrentTime")] pub current_time: xs::DateTime, // Date time when the PullPoint will be shut down without further pull // requests. #[yaserde(prefix = "tev", rename = "TerminationTime")] pub termination_time: xs::DateTime, // List of messages. This list shall be empty in case of a timeout. #[yaserde(prefix = "wsnt", rename = "NotificationMessage")] pub notification_message: Vec<wsnt::NotificationMessage>, } impl Validate for PullMessagesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tev", namespace = "tev: http://www.onvif.org/ver10/events/wsdl" )] pub struct PullMessagesFaultResponse { // Maximum timeout supported by the device. #[yaserde(prefix = "tev", rename = "MaxTimeout")] pub max_timeout: xs::Duration, // Maximum message limit supported by the device. #[yaserde(prefix = "tev", rename = "MaxMessageLimit")] pub max_message_limit: i32, } impl Validate for PullMessagesFaultResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tev", namespace = "tev: http://www.onvif.org/ver10/events/wsdl" )] pub struct Seek { // The date and time to match against stored messages. #[yaserde(prefix = "tev", rename = "UtcTime")] pub utc_time: xs::DateTime, // Reverse the pull direction of PullMessages. #[yaserde(prefix = "tev", rename = "Reverse")] pub reverse: bool, } impl Validate for Seek {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tev", namespace = "tev: http://www.onvif.org/ver10/events/wsdl" )] pub struct SeekResponse {} impl Validate for SeekResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tev", namespace = "tev: http://www.onvif.org/ver10/events/wsdl" )] pub struct SetSynchronizationPoint {} impl Validate for SetSynchronizationPoint {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tev", namespace = "tev: http://www.onvif.org/ver10/events/wsdl" )] pub struct SetSynchronizationPointResponse {} impl Validate for SetSynchronizationPointResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tev", namespace = "tev: http://www.onvif.org/ver10/events/wsdl" )] pub struct GetEventProperties {} impl Validate for GetEventProperties {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tev", namespace = "tev: http://www.onvif.org/ver10/events/wsdl" )] pub struct GetEventPropertiesResponse { // List of topic namespaces supported. #[yaserde(prefix = "tev", rename = "TopicNamespaceLocation")] pub topic_namespace_location: Vec<String>, // True when topicset is fixed for all times. #[yaserde(prefix = "wsnt", rename = "FixedTopicSet")] pub fixed_topic_set: wsnt::FixedTopicSet, // Set of topics supported. #[yaserde(prefix = "wstop", rename = "TopicSet")] pub topic_set: wstop::TopicSet, // Defines the XPath expression syntax supported for matching topic // expressions. #[yaserde(prefix = "wsnt", rename = "TopicExpressionDialect")] pub topic_expression_dialect: Vec<wsnt::TopicExpressionDialect>, // Defines the XPath function set supported for message content filtering. #[yaserde(prefix = "tev", rename = "MessageContentFilterDialect")] pub message_content_filter_dialect: Vec<String>, // Optional ProducerPropertiesDialects. Refer to #[yaserde(prefix = "tev", rename = "ProducerPropertiesFilterDialect")] pub producer_properties_filter_dialect: Vec<String>, // The Message Content Description Language allows referencing // of vendor-specific types. In order to ease the integration of such types // into a client application, // the GetEventPropertiesResponse shall list all URI locations to schema // files whose types are // used in the description of notifications, with // MessageContentSchemaLocation elements. #[yaserde(prefix = "tev", rename = "MessageContentSchemaLocation")] pub message_content_schema_location: Vec<String>, } impl Validate for GetEventPropertiesResponse {} // When this element is included in the SubscriptionPolicy, the pullpoint shall // not provide Initialized or Deleted events for Properties. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tev", namespace = "tev: http://www.onvif.org/ver10/events/wsdl" )] pub struct ChangedOnly {} impl Validate for ChangedOnly {} // Returns the capabilities of the event service. The result is returned in a // typed answer. pub async fn get_service_capabilities<T: transport::Transport>( transport: &T, request: &GetServiceCapabilities, ) -> Result<GetServiceCapabilitiesResponse, transport::Error> { transport::request(transport, request).await } // This method returns a PullPointSubscription that can be polled using // PullMessages. // This message contains the same elements as the SubscriptionRequest of the // WS-BaseNotification without the ConsumerReference. pub async fn create_pull_point_subscription<T: transport::Transport>( transport: &T, request: &CreatePullPointSubscription, ) -> Result<CreatePullPointSubscriptionResponse, transport::Error> { transport::request(transport, request).await } // The WS-BaseNotification specification defines a set of OPTIONAL // WS-ResouceProperties. // This specification does not require the implementation of the // WS-ResourceProperty interface. // Instead, the subsequent direct interface shall be implemented by an ONVIF // compliant device // in order to provide information about the FilterDialects, Schema files and // topics supported by // the device. pub async fn get_event_properties<T: transport::Transport>( transport: &T, request: &GetEventProperties, ) -> Result<GetEventPropertiesResponse, transport::Error> { transport::request(transport, request).await } // This method pulls one or more messages from a PullPoint. // The device shall provide the following PullMessages command for all // SubscriptionManager // endpoints returned by the CreatePullPointSubscription command. This method // shall not wait until // the requested number of messages is available but return as soon as at least // one message is available. pub async fn pull_messages<T: transport::Transport>( transport: &T, request: &PullMessages, ) -> Result<PullMessagesResponse, transport::Error> { transport::request(transport, request).await } // This method readjusts the pull pointer into the past. // A device supporting persistent notification storage shall provide the // following Seek command for all SubscriptionManager endpoints returned by // the CreatePullPointSubscription command. The optional Reverse argument can // be used to reverse the pull direction of the PullMessages command. pub async fn seek<T: transport::Transport>( transport: &T, request: &Seek, ) -> Result<SeekResponse, transport::Error> { transport::request(transport, request).await } // Properties inform a client about property creation, changes and // deletion in a uniform way. When a client wants to synchronize its properties // with the // properties of the device, it can request a synchronization point which // repeats the current // status of all properties to which a client has subscribed. The // PropertyOperation of all // produced notifications is set to “Initialized”. The Synchronization Point // is // requested directly from the SubscriptionManager which was returned in either // the // SubscriptionResponse or in the CreatePullPointSubscriptionResponse. The // property update is // transmitted via the notification transportation of the notification // interface. This method is mandatory. pub async fn set_synchronization_point<T: transport::Transport>( transport: &T, request: &SetSynchronizationPoint, ) -> Result<SetSynchronizationPointResponse, transport::Error> { transport::request(transport, request).await } // The device shall provide the following Unsubscribe command for all // SubscriptionManager endpoints returned by the CreatePullPointSubscription // command. // pub async fn unsubscribe<T: transport::Transport>( // transport: &T // ) -> Result<, transport::Error> { // transport::request(transport, request).await // }
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
false
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/media2/src/lib.rs
wsdl_rs/media2/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use onvif as tt; use std::str::FromStr; use validate::Validate; use xsd_macro_utils::*; use yaserde_derive::{YaDeserialize, YaSerialize}; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct GetServiceCapabilities {} impl Validate for GetServiceCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct GetServiceCapabilitiesResponse { // The capabilities for the media service is returned in the Capabilities // element. #[yaserde(prefix = "tr2", rename = "Capabilities")] pub capabilities: Capabilities2, } impl Validate for GetServiceCapabilitiesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct Capabilities2 { // Media profile capabilities. #[yaserde(prefix = "tr2", rename = "ProfileCapabilities")] pub profile_capabilities: ProfileCapabilities, // Streaming capabilities. #[yaserde(prefix = "tr2", rename = "StreamingCapabilities")] pub streaming_capabilities: StreamingCapabilities, // Indicates if GetSnapshotUri is supported. #[yaserde(attribute, rename = "SnapshotUri")] pub snapshot_uri: Option<bool>, // Indicates whether or not Rotation feature is supported. #[yaserde(attribute, rename = "Rotation")] pub rotation: Option<bool>, // Indicates the support for changing video source mode. #[yaserde(attribute, rename = "VideoSourceMode")] pub video_source_mode: Option<bool>, // Indicates if OSD is supported. #[yaserde(attribute, rename = "OSD")] pub osd: Option<bool>, // Indicates the support for temporary osd text configuration. #[yaserde(attribute, rename = "TemporaryOSDText")] pub temporary_osd_text: Option<bool>, // Indicates if Masking is supported. #[yaserde(attribute, rename = "Mask")] pub mask: Option<bool>, // Indicates that privacy masks are only supported at the video source level // and not the video source configuration level. // If this is true any addition, deletion or change of a privacy mask done // for one video source configuration will automatically be // applied by the device to a corresponding privacy mask for all other video // source configuration associated with the same video source. #[yaserde(attribute, rename = "SourceMask")] pub source_mask: Option<bool>, } impl Validate for Capabilities2 {} pub type Capabilities = Capabilities2; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct ProfileCapabilities { // Maximum number of profiles supported. #[yaserde(attribute, rename = "MaximumNumberOfProfiles")] pub maximum_number_of_profiles: Option<i32>, // The configurations supported by the device as defined by // tr2:ConfigurationEnumeration. The enumeration value "All" shall not be // included in this list. #[yaserde(attribute, rename = "ConfigurationsSupported")] pub configurations_supported: Option<tt::StringAttrList>, } impl Validate for ProfileCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct StreamingCapabilities { // Indicates support for live media streaming via RTSP. #[yaserde(attribute, rename = "RTSPStreaming")] pub rtsp_streaming: Option<bool>, // Indicates support for RTP multicast. #[yaserde(attribute, rename = "RTPMulticast")] pub rtp_multicast: Option<bool>, // Indicates support for RTP/RTSP/TCP. #[yaserde(attribute, rename = "RTP_RTSP_TCP")] pub rtp_rtsp_tcp: Option<bool>, // Indicates support for non aggregate RTSP control. #[yaserde(attribute, rename = "NonAggregateControl")] pub non_aggregate_control: Option<bool>, // If streaming over WebSocket is supported, this shall return the RTSP // WebSocket URI as described in Streaming Specification Section 5.1.1.5. #[yaserde(attribute, rename = "RTSPWebSocketUri")] pub rtsp_web_socket_uri: Option<String>, // Indicates support for non-RTSP controlled multicast streaming. #[yaserde(attribute, rename = "AutoStartMulticast")] pub auto_start_multicast: Option<bool>, } impl Validate for StreamingCapabilities {} #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum ConfigurationEnumeration { All, VideoSource, VideoEncoder, AudioSource, AudioEncoder, AudioOutput, AudioDecoder, Metadata, Analytics, #[yaserde(rename = "PTZ")] Ptz, __Unknown__(String), } impl Default for ConfigurationEnumeration { fn default() -> ConfigurationEnumeration { Self::__Unknown__("No valid variants".into()) } } impl Validate for ConfigurationEnumeration {} // pub type ConfigurationEnumeration = ConfigurationEnumeration; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct ConfigurationRef { // Type of the configuration as defined by tr2:ConfigurationEnumeration. #[yaserde(prefix = "tr2", rename = "Type")] pub _type: String, // Reference token of an existing configuration. // Token shall be included in the AddConfiguration request along with the // type. // Token shall be included in the CreateProfile request when Configuration // elements are included and type is selected. // Token is optional for RemoveConfiguration request. If no token is // provided in RemoveConfiguration request, device shall // remove the configuration of the type included in the profile. #[yaserde(prefix = "tr2", rename = "Token")] pub token: Option<tt::ReferenceToken>, } impl Validate for ConfigurationRef {} // A set of media configurations. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct ConfigurationSet { // Optional configuration of the Video input. #[yaserde(prefix = "tr2", rename = "VideoSource")] pub video_source: Option<tt::VideoSourceConfiguration>, // Optional configuration of the Audio input. #[yaserde(prefix = "tr2", rename = "AudioSource")] pub audio_source: Option<tt::AudioSourceConfiguration>, // Optional configuration of the Video encoder. #[yaserde(prefix = "tr2", rename = "VideoEncoder")] pub video_encoder: Option<tt::VideoEncoder2Configuration>, // Optional configuration of the Audio encoder. #[yaserde(prefix = "tr2", rename = "AudioEncoder")] pub audio_encoder: Option<tt::AudioEncoder2Configuration>, // Optional configuration of the analytics module and rule engine. #[yaserde(prefix = "tr2", rename = "Analytics")] pub analytics: Option<tt::VideoAnalyticsConfiguration>, // Optional configuration of the pan tilt zoom unit. #[yaserde(prefix = "tr2", rename = "PTZ")] pub ptz: Option<tt::Ptzconfiguration>, // Optional configuration of the metadata stream. #[yaserde(prefix = "tr2", rename = "Metadata")] pub metadata: Option<tt::MetadataConfiguration>, // Optional configuration of the Audio output. #[yaserde(prefix = "tr2", rename = "AudioOutput")] pub audio_output: Option<tt::AudioOutputConfiguration>, // Optional configuration of the Audio decoder. #[yaserde(prefix = "tr2", rename = "AudioDecoder")] pub audio_decoder: Option<tt::AudioDecoderConfiguration>, } impl Validate for ConfigurationSet {} // A media profile consists of a set of media configurations. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct MediaProfile { // User readable name of the profile. #[yaserde(prefix = "tr2", rename = "Name")] pub name: tt::Name, // The configurations assigned to the profile. #[yaserde(prefix = "tr2", rename = "Configurations")] pub configurations: Option<ConfigurationSet>, // Unique identifier of the profile. #[yaserde(attribute, rename = "token")] pub token: tt::ReferenceToken, // A value of true signals that the profile cannot be deleted. Default is // false. #[yaserde(attribute, rename = "fixed")] pub fixed: Option<bool>, } impl Validate for MediaProfile {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct CreateProfile { // friendly name of the profile to be created #[yaserde(prefix = "tr2", rename = "Name")] pub name: tt::Name, // Optional set of configurations to be assigned to the profile. List // entries with tr2:ConfigurationEnumeration value "All" shall be ignored. #[yaserde(prefix = "tr2", rename = "Configuration")] pub configuration: Vec<ConfigurationRef>, } impl Validate for CreateProfile {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct CreateProfileResponse { // Token assigned by the device for the newly created profile. #[yaserde(prefix = "tr2", rename = "Token")] pub token: tt::ReferenceToken, } impl Validate for CreateProfileResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct GetProfiles { // Optional token of the requested profile. #[yaserde(prefix = "tr2", rename = "Token")] pub token: Option<tt::ReferenceToken>, // The types shall be provided as defined by tr2:ConfigurationEnumeration. #[yaserde(prefix = "tr2", rename = "Type")] pub _type: Vec<String>, } impl Validate for GetProfiles {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct GetProfilesResponse { // Lists all profiles that exist in the media service. The response provides // the requested types of Configurations as far as available. // If a profile doesn't contain a type no error shall be provided. #[yaserde(prefix = "tr2", rename = "Profiles")] pub profiles: Vec<MediaProfile>, } impl Validate for GetProfilesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct AddConfiguration { // Reference to the profile where the configuration should be added #[yaserde(prefix = "tr2", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, // Optional item. If present updates the Name property of the profile. #[yaserde(prefix = "tr2", rename = "Name")] pub name: Option<tt::Name>, // List of configurations to be added. The types shall be provided in the // order defined by tr2:ConfigurationEnumeration. List entries with // tr2:ConfigurationEnumeration value "All" shall be ignored. #[yaserde(prefix = "tr2", rename = "Configuration")] pub configuration: Vec<ConfigurationRef>, } impl Validate for AddConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct AddConfigurationResponse {} impl Validate for AddConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct RemoveConfiguration { // This element contains a reference to the media profile from which the // AudioDecoderConfiguration shall be removed. #[yaserde(prefix = "tr2", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, // List of configurations to be removed. The types shall be provided in the // order defined by tr2:ConfigurationEnumeration. Tokens appearing in the // configuration list shall be ignored. Presence of the "All" type shall // result in an empty profile. #[yaserde(prefix = "tr2", rename = "Configuration")] pub configuration: Vec<ConfigurationRef>, } impl Validate for RemoveConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct RemoveConfigurationResponse {} impl Validate for RemoveConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct DeleteProfile { // This element contains a reference to the profile that should be deleted. #[yaserde(prefix = "tr2", rename = "Token")] pub token: tt::ReferenceToken, } impl Validate for DeleteProfile {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct DeleteProfileResponse {} impl Validate for DeleteProfileResponse {} macro_rules! config { ($name:ident) => { #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct $name { // fields // Token of the requested configuration. #[yaserde(prefix = "tr2", rename = "ConfigurationToken")] pub configuration_token: Option<tt::ReferenceToken>, // Contains the token of an existing media profile the configurations shall // be compatible with. #[yaserde(prefix = "tr2", rename = "ProfileToken")] pub profile_token: Option<tt::ReferenceToken>, } }; } config!(GetConfiguration); impl Validate for GetConfiguration {} config!(GetVideoEncoderConfigurations); #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct GetVideoEncoderConfigurationsResponse { // This element contains a list of video encoder configurations. #[yaserde(prefix = "tr2", rename = "Configurations")] pub configurations: Vec<tt::VideoEncoder2Configuration>, } impl Validate for GetVideoEncoderConfigurationsResponse {} config!(GetVideoSourceConfigurations); #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct GetVideoSourceConfigurationsResponse { // This element contains a list of video source configurations. #[yaserde(prefix = "tr2", rename = "Configurations")] pub configurations: Vec<tt::VideoSourceConfiguration>, } impl Validate for GetVideoSourceConfigurationsResponse {} config!(GetAudioEncoderConfigurations); #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct GetAudioEncoderConfigurationsResponse { // This element contains a list of audio encoder configurations. #[yaserde(prefix = "tr2", rename = "Configurations")] pub configurations: Vec<tt::AudioEncoder2Configuration>, } impl Validate for GetAudioEncoderConfigurationsResponse {} config!(GetAudioSourceConfigurations); #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct GetAudioSourceConfigurationsResponse { // This element contains a list of audio source configurations. #[yaserde(prefix = "tr2", rename = "Configurations")] pub configurations: Vec<tt::AudioSourceConfiguration>, } impl Validate for GetAudioSourceConfigurationsResponse {} config!(GetAnalyticsConfigurations); #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct GetAnalyticsConfigurationsResponse { // This element contains a list of Analytics configurations. #[yaserde(prefix = "tr2", rename = "Configurations")] pub configurations: Vec<tt::VideoAnalyticsConfiguration>, } impl Validate for GetAnalyticsConfigurationsResponse {} config!(GetMetadataConfigurations); #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct GetMetadataConfigurationsResponse { // This element contains a list of metadata configurations #[yaserde(prefix = "tr2", rename = "Configurations")] pub configurations: Vec<tt::MetadataConfiguration>, } impl Validate for GetMetadataConfigurationsResponse {} config!(GetAudioOutputConfigurations); #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct GetAudioOutputConfigurationsResponse { // This element contains a list of audio output configurations #[yaserde(prefix = "tr2", rename = "Configurations")] pub configurations: Vec<tt::AudioOutputConfiguration>, } impl Validate for GetAudioOutputConfigurationsResponse {} config!(GetAudioDecoderConfigurations); #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct GetAudioDecoderConfigurationsResponse { // This element contains a list of audio decoder configurations #[yaserde(prefix = "tr2", rename = "Configurations")] pub configurations: Vec<tt::AudioDecoderConfiguration>, } impl Validate for GetAudioDecoderConfigurationsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct SetVideoEncoderConfiguration { // Contains the modified video encoder configuration. The configuration // shall exist in the device. #[yaserde(prefix = "tr2", rename = "Configuration")] pub configuration: tt::VideoEncoder2Configuration, } impl Validate for SetVideoEncoderConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct SetConfigurationResponse {} impl Validate for SetConfigurationResponse {} pub type SetVideoEncoderConfigurationResponse = SetConfigurationResponse; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct SetVideoSourceConfiguration { // Contains the modified video source configuration. The configuration shall // exist in the device. #[yaserde(prefix = "tr2", rename = "Configuration")] pub configuration: tt::VideoSourceConfiguration, } impl Validate for SetVideoSourceConfiguration {} pub type SetVideoSourceConfigurationResponse = SetConfigurationResponse; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct SetAudioEncoderConfiguration { // Contains the modified audio encoder configuration. The configuration // shall exist in the device. #[yaserde(prefix = "tr2", rename = "Configuration")] pub configuration: tt::AudioEncoder2Configuration, } impl Validate for SetAudioEncoderConfiguration {} pub type SetAudioEncoderConfigurationResponse = SetConfigurationResponse; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct SetAudioSourceConfiguration { // Contains the modified audio source configuration. The configuration shall // exist in the device. #[yaserde(prefix = "tr2", rename = "Configuration")] pub configuration: tt::AudioSourceConfiguration, } impl Validate for SetAudioSourceConfiguration {} pub type SetAudioSourceConfigurationResponse = SetConfigurationResponse; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct SetMetadataConfiguration { // Contains the modified metadata configuration. The configuration shall // exist in the device. #[yaserde(prefix = "tr2", rename = "Configuration")] pub configuration: tt::MetadataConfiguration, } impl Validate for SetMetadataConfiguration {} pub type SetMetadataConfigurationResponse = SetConfigurationResponse; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct SetAudioOutputConfiguration { // Contains the modified audio output configuration. The configuration shall // exist in the device. #[yaserde(prefix = "tr2", rename = "Configuration")] pub configuration: tt::AudioOutputConfiguration, } impl Validate for SetAudioOutputConfiguration {} pub type SetAudioOutputConfigurationResponse = SetConfigurationResponse; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct SetAudioDecoderConfiguration { // Contains the modified audio decoder configuration. The configuration // shall exist in the device. #[yaserde(prefix = "tr2", rename = "Configuration")] pub configuration: tt::AudioDecoderConfiguration, } impl Validate for SetAudioDecoderConfiguration {} pub type SetAudioDecoderConfigurationResponse = SetConfigurationResponse; config!(GetVideoSourceConfigurationOptions); #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct GetVideoSourceConfigurationOptionsResponse { // This message contains the video source configuration options. If a video // source configuration is specified, the options shall concern that // particular configuration. If a media profile is specified, the options // shall be compatible with that media profile. If no tokens are specified, // the options shall be considered generic for the device. #[yaserde(prefix = "tr2", rename = "Options")] pub options: tt::VideoSourceConfigurationOptions, } impl Validate for GetVideoSourceConfigurationOptionsResponse {} config!(GetVideoEncoderConfigurationOptions); #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct GetVideoEncoderConfigurationOptionsResponse { #[yaserde(prefix = "tr2", rename = "Options")] pub options: Vec<tt::VideoEncoder2ConfigurationOptions>, } impl Validate for GetVideoEncoderConfigurationOptionsResponse {} config!(GetAudioSourceConfigurationOptions); #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct GetAudioSourceConfigurationOptionsResponse { // This message contains the audio source configuration options. If a audio // source configuration is specified, the options shall concern that // particular configuration. If a media profile is specified, the options // shall be compatible with that media profile. If no tokens are specified, // the options shall be considered generic for the device. #[yaserde(prefix = "tr2", rename = "Options")] pub options: tt::AudioSourceConfigurationOptions, } impl Validate for GetAudioSourceConfigurationOptionsResponse {} config!(GetAudioEncoderConfigurationOptions); #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct GetAudioEncoderConfigurationOptionsResponse { // This message contains the audio encoder configuration options. If a audio // encoder configuration is specified, the options shall concern that // particular configuration. If a media profile is specified, the options // shall be compatible with that media profile. If no tokens are specified, // the options shall be considered generic for the device. #[yaserde(prefix = "tr2", rename = "Options")] pub options: Vec<tt::AudioEncoder2ConfigurationOptions>, } impl Validate for GetAudioEncoderConfigurationOptionsResponse {} config!(GetMetadataConfigurationOptions); #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct GetMetadataConfigurationOptionsResponse { // This message contains the metadata configuration options. If a metadata // configuration is specified, the options shall concern that particular // configuration. If a media profile is specified, the options shall be // compatible with that media profile. If no tokens are specified, the // options shall be considered generic for the device. #[yaserde(prefix = "tr2", rename = "Options")] pub options: tt::MetadataConfigurationOptions, } impl Validate for GetMetadataConfigurationOptionsResponse {} config!(GetAudioOutputConfigurationOptions); #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct GetAudioOutputConfigurationOptionsResponse { // This message contains the audio output configuration options. If a audio // output configuration is specified, the options shall concern that // particular configuration. If a media profile is specified, the options // shall be compatible with that media profile. If no tokens are specified, // the options shall be considered generic for the device. #[yaserde(prefix = "tr2", rename = "Options")] pub options: tt::AudioOutputConfigurationOptions, } impl Validate for GetAudioOutputConfigurationOptionsResponse {} config!(GetAudioDecoderConfigurationOptions); #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct GetAudioDecoderConfigurationOptionsResponse { // This message contains the audio decoder configuration options. If a audio // decoder configuration is specified, the options shall concern that // particular configuration. If a media profile is specified, the options // shall be compatible with that media profile. If no tokens are specified, // the options shall be considered generic for the device. #[yaserde(prefix = "tr2", rename = "Options")] pub options: Vec<tt::AudioEncoder2ConfigurationOptions>, } impl Validate for GetAudioDecoderConfigurationOptionsResponse {} #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum TransportProtocol { RtspUnicast, RtspMulticast, #[yaserde(rename = "RTSP")] Rtsp, RtspOverHttp, __Unknown__(String), } impl Default for TransportProtocol { fn default() -> TransportProtocol { Self::__Unknown__("No valid variants".into()) } } impl Validate for TransportProtocol {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct GetVideoEncoderInstances { // Token of the video source configuration #[yaserde(prefix = "tr2", rename = "ConfigurationToken")] pub configuration_token: tt::ReferenceToken, } impl Validate for GetVideoEncoderInstances {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct EncoderInstance { // Video Media Subtype for the video format. For definitions see // tt:VideoEncodingMimeNames and #[yaserde(prefix = "tr2", rename = "Encoding")] pub encoding: String, // The minimum guaranteed number of encoder instances (applications) for the // VideoSourceConfiguration. #[yaserde(prefix = "tr2", rename = "Number")] pub number: i32, } impl Validate for EncoderInstance {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct EncoderInstanceInfo { // If a device limits the number of instances for respective Video Codecs // the response contains the information how many streams can be set up at // the same time per VideoSource. #[yaserde(prefix = "tr2", rename = "Codec")] pub codec: Vec<EncoderInstance>, // The minimum guaranteed total number of encoder instances (applications) // per VideoSourceConfiguration. The device is able to deliver the Total // number of streams #[yaserde(prefix = "tr2", rename = "Total")] pub total: i32, } impl Validate for EncoderInstanceInfo {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct GetVideoEncoderInstancesResponse { // The minimum guaranteed total number of encoder instances (applications) // per VideoSourceConfiguration. #[yaserde(prefix = "tr2", rename = "Info")] pub info: EncoderInstanceInfo, } impl Validate for GetVideoEncoderInstancesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct GetStreamUri { // Defines the network protocol for streaming as defined by // tr2:TransportProtocol #[yaserde(prefix = "tr2", rename = "Protocol")] pub protocol: String, // The ProfileToken element indicates the media profile to use and will // define the configuration of the content of the stream. #[yaserde(prefix = "tr2", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, } impl Validate for GetStreamUri {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct GetStreamUriResponse { // Stable Uri to be used for requesting the media stream #[yaserde(prefix = "tr2", rename = "Uri")] pub uri: String, } impl Validate for GetStreamUriResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct SetSynchronizationPoint { // Contains a Profile reference for which a Synchronization Point is // requested. #[yaserde(prefix = "tr2", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, } impl Validate for SetSynchronizationPoint {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct SetSynchronizationPointResponse {} impl Validate for SetSynchronizationPointResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tr2", namespace = "tr2: http://www.onvif.org/ver20/media/wsdl" )] pub struct GetSnapshotUri { // The ProfileToken element indicates the media profile to use and will // define the source and dimensions of the snapshot. #[yaserde(prefix = "tr2", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, } impl Validate for GetSnapshotUri {}
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
true
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/media/src/lib.rs
wsdl_rs/media/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use onvif as tt; use std::str::FromStr; use validate::Validate; use xsd_macro_utils::*; use yaserde_derive::{YaDeserialize, YaSerialize}; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetServiceCapabilities {} impl Validate for GetServiceCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetServiceCapabilitiesResponse { // The capabilities for the media service is returned in the Capabilities // element. #[yaserde(prefix = "trt", rename = "Capabilities")] pub capabilities: Capabilities, } impl Validate for GetServiceCapabilitiesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct Capabilities { // Media profile capabilities. #[yaserde(prefix = "trt", rename = "ProfileCapabilities")] pub profile_capabilities: Vec<ProfileCapabilities>, // Streaming capabilities. #[yaserde(prefix = "trt", rename = "StreamingCapabilities")] pub streaming_capabilities: Vec<StreamingCapabilities>, // Indicates if GetSnapshotUri is supported. #[yaserde(attribute, rename = "SnapshotUri")] pub snapshot_uri: Option<bool>, // Indicates whether or not Rotation feature is supported. #[yaserde(attribute, rename = "Rotation")] pub rotation: Option<bool>, // Indicates the support for changing video source mode. #[yaserde(attribute, rename = "VideoSourceMode")] pub video_source_mode: Option<bool>, // Indicates if OSD is supported. #[yaserde(attribute, rename = "OSD")] pub osd: Option<bool>, // Indicates the support for temporary osd text configuration. #[yaserde(attribute, rename = "TemporaryOSDText")] pub temporary_osd_text: Option<bool>, // Indicates the support for the Efficient XML Interchange (EXI) binary XML // format. #[yaserde(attribute, rename = "EXICompression")] pub exi_compression: Option<bool>, } impl Validate for Capabilities {} // pub type Capabilities = Capabilities; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct ProfileCapabilities { // Maximum number of profiles supported. #[yaserde(attribute, rename = "MaximumNumberOfProfiles")] pub maximum_number_of_profiles: Option<i32>, } impl Validate for ProfileCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct StreamingCapabilities { // Indicates support for RTP multicast. #[yaserde(attribute, rename = "RTPMulticast")] pub rtp_multicast: Option<bool>, // Indicates support for RTP over TCP. #[yaserde(attribute, rename = "RTP_TCP")] pub rtp_tcp: Option<bool>, // Indicates support for RTP/RTSP/TCP. #[yaserde(attribute, rename = "RTP_RTSP_TCP")] pub rtp_rtsp_tcp: Option<bool>, // Indicates support for non aggregate RTSP control. #[yaserde(attribute, rename = "NonAggregateControl")] pub non_aggregate_control: Option<bool>, // Indicates the device does not support live media streaming via RTSP. #[yaserde(attribute, rename = "NoRTSPStreaming")] pub no_rtsp_streaming: Option<bool>, } impl Validate for StreamingCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetVideoSources {} impl Validate for GetVideoSources {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetVideoSourcesResponse { // List of existing Video Sources #[yaserde(prefix = "trt", rename = "VideoSources")] pub video_sources: Vec<tt::VideoSource>, } impl Validate for GetVideoSourcesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetAudioSources {} impl Validate for GetAudioSources {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetAudioSourcesResponse { // List of existing Audio Sources #[yaserde(prefix = "trt", rename = "AudioSources")] pub audio_sources: Vec<tt::AudioSource>, } impl Validate for GetAudioSourcesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetAudioOutputs {} impl Validate for GetAudioOutputs {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetAudioOutputsResponse { // List of existing Audio Outputs #[yaserde(prefix = "trt", rename = "AudioOutputs")] pub audio_outputs: Vec<tt::AudioOutput>, } impl Validate for GetAudioOutputsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct CreateProfile { // friendly name of the profile to be created #[yaserde(prefix = "trt", rename = "Name")] pub name: tt::Name, // Optional token, specifying the unique identifier of the new profile. #[yaserde(prefix = "trt", rename = "Token")] pub token: Option<tt::ReferenceToken>, } impl Validate for CreateProfile {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct CreateProfileResponse { // returns the new created profile #[yaserde(prefix = "trt", rename = "Profile")] pub profile: tt::Profile, } impl Validate for CreateProfileResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetProfile { // this command requests a specific profile #[yaserde(prefix = "trt", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, } impl Validate for GetProfile {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetProfileResponse { // returns the requested media profile #[yaserde(prefix = "trt", rename = "Profile")] pub profile: tt::Profile, } impl Validate for GetProfileResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetProfiles {} impl Validate for GetProfiles {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetProfilesResponse { // lists all profiles that exist in the media service #[yaserde(prefix = "trt", rename = "Profiles")] pub profiles: Vec<tt::Profile>, } impl Validate for GetProfilesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct AddVideoEncoderConfiguration { // Reference to the profile where the configuration should be added #[yaserde(prefix = "trt", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, // Contains a reference to the VideoEncoderConfiguration to add #[yaserde(prefix = "trt", rename = "ConfigurationToken")] pub configuration_token: tt::ReferenceToken, } impl Validate for AddVideoEncoderConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct AddVideoEncoderConfigurationResponse {} impl Validate for AddVideoEncoderConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct RemoveVideoEncoderConfiguration { // Contains a reference to the media profile from which the // VideoEncoderConfiguration shall be removed. #[yaserde(prefix = "trt", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, } impl Validate for RemoveVideoEncoderConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct RemoveVideoEncoderConfigurationResponse {} impl Validate for RemoveVideoEncoderConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct AddVideoSourceConfiguration { // Reference to the profile where the configuration should be added #[yaserde(prefix = "trt", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, // Contains a reference to the VideoSourceConfiguration to add #[yaserde(prefix = "trt", rename = "ConfigurationToken")] pub configuration_token: tt::ReferenceToken, } impl Validate for AddVideoSourceConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct AddVideoSourceConfigurationResponse {} impl Validate for AddVideoSourceConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct RemoveVideoSourceConfiguration { // Contains a reference to the media profile from which the // VideoSourceConfiguration shall be removed. #[yaserde(prefix = "trt", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, } impl Validate for RemoveVideoSourceConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct RemoveVideoSourceConfigurationResponse {} impl Validate for RemoveVideoSourceConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct AddAudioEncoderConfiguration { // Reference to the profile where the configuration should be added #[yaserde(prefix = "trt", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, // Contains a reference to the AudioEncoderConfiguration to add #[yaserde(prefix = "trt", rename = "ConfigurationToken")] pub configuration_token: tt::ReferenceToken, } impl Validate for AddAudioEncoderConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct AddAudioEncoderConfigurationResponse {} impl Validate for AddAudioEncoderConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct RemoveAudioEncoderConfiguration { // Contains a reference to the media profile from which the // AudioEncoderConfiguration shall be removed. #[yaserde(prefix = "trt", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, } impl Validate for RemoveAudioEncoderConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct RemoveAudioEncoderConfigurationResponse {} impl Validate for RemoveAudioEncoderConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct AddAudioSourceConfiguration { // Reference to the profile where the configuration should be added #[yaserde(prefix = "trt", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, // Contains a reference to the AudioSourceConfiguration to add #[yaserde(prefix = "trt", rename = "ConfigurationToken")] pub configuration_token: tt::ReferenceToken, } impl Validate for AddAudioSourceConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct AddAudioSourceConfigurationResponse {} impl Validate for AddAudioSourceConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct RemoveAudioSourceConfiguration { // Contains a reference to the media profile from which the // AudioSourceConfiguration shall be removed. #[yaserde(prefix = "trt", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, } impl Validate for RemoveAudioSourceConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct RemoveAudioSourceConfigurationResponse {} impl Validate for RemoveAudioSourceConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct AddPTZConfiguration { // Reference to the profile where the configuration should be added #[yaserde(prefix = "trt", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, // Contains a reference to the PTZConfiguration to add #[yaserde(prefix = "trt", rename = "ConfigurationToken")] pub configuration_token: tt::ReferenceToken, } impl Validate for AddPTZConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct AddPTZConfigurationResponse {} impl Validate for AddPTZConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct RemovePTZConfiguration { // Contains a reference to the media profile from which the // PTZConfiguration shall be removed. #[yaserde(prefix = "trt", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, } impl Validate for RemovePTZConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct RemovePTZConfigurationResponse {} impl Validate for RemovePTZConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct AddVideoAnalyticsConfiguration { // Reference to the profile where the configuration should be added #[yaserde(prefix = "trt", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, // Contains a reference to the VideoAnalyticsConfiguration to add #[yaserde(prefix = "trt", rename = "ConfigurationToken")] pub configuration_token: tt::ReferenceToken, } impl Validate for AddVideoAnalyticsConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct AddVideoAnalyticsConfigurationResponse {} impl Validate for AddVideoAnalyticsConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct RemoveVideoAnalyticsConfiguration { // Contains a reference to the media profile from which the // VideoAnalyticsConfiguration shall be removed. #[yaserde(prefix = "trt", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, } impl Validate for RemoveVideoAnalyticsConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct RemoveVideoAnalyticsConfigurationResponse {} impl Validate for RemoveVideoAnalyticsConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct AddMetadataConfiguration { // Reference to the profile where the configuration should be added #[yaserde(prefix = "trt", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, // Contains a reference to the MetadataConfiguration to add #[yaserde(prefix = "trt", rename = "ConfigurationToken")] pub configuration_token: tt::ReferenceToken, } impl Validate for AddMetadataConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct AddMetadataConfigurationResponse {} impl Validate for AddMetadataConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct RemoveMetadataConfiguration { // Contains a reference to the media profile from which the // MetadataConfiguration shall be removed. #[yaserde(prefix = "trt", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, } impl Validate for RemoveMetadataConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct RemoveMetadataConfigurationResponse {} impl Validate for RemoveMetadataConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct AddAudioOutputConfiguration { // Reference to the profile where the configuration should be added #[yaserde(prefix = "trt", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, // Contains a reference to the AudioOutputConfiguration to add #[yaserde(prefix = "trt", rename = "ConfigurationToken")] pub configuration_token: tt::ReferenceToken, } impl Validate for AddAudioOutputConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct AddAudioOutputConfigurationResponse {} impl Validate for AddAudioOutputConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct RemoveAudioOutputConfiguration { // Contains a reference to the media profile from which the // AudioOutputConfiguration shall be removed. #[yaserde(prefix = "trt", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, } impl Validate for RemoveAudioOutputConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct RemoveAudioOutputConfigurationResponse {} impl Validate for RemoveAudioOutputConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct AddAudioDecoderConfiguration { // This element contains a reference to the profile where the configuration // should be added. #[yaserde(prefix = "trt", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, // This element contains a reference to the AudioDecoderConfiguration to // add. #[yaserde(prefix = "trt", rename = "ConfigurationToken")] pub configuration_token: tt::ReferenceToken, } impl Validate for AddAudioDecoderConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct AddAudioDecoderConfigurationResponse {} impl Validate for AddAudioDecoderConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct RemoveAudioDecoderConfiguration { // This element contains a reference to the media profile from which the // AudioDecoderConfiguration shall be removed. #[yaserde(prefix = "trt", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, } impl Validate for RemoveAudioDecoderConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct RemoveAudioDecoderConfigurationResponse {} impl Validate for RemoveAudioDecoderConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct DeleteProfile { // This element contains a reference to the profile that should be deleted. #[yaserde(prefix = "trt", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, } impl Validate for DeleteProfile {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct DeleteProfileResponse {} impl Validate for DeleteProfileResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetVideoEncoderConfigurations {} impl Validate for GetVideoEncoderConfigurations {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetVideoEncoderConfigurationsResponse { // This element contains a list of video encoder configurations. #[yaserde(prefix = "trt", rename = "Configurations")] pub configurations: Vec<tt::VideoEncoderConfiguration>, } impl Validate for GetVideoEncoderConfigurationsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetVideoSourceConfigurations {} impl Validate for GetVideoSourceConfigurations {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetVideoSourceConfigurationsResponse { // This element contains a list of video source configurations. #[yaserde(prefix = "trt", rename = "Configurations")] pub configurations: Vec<tt::VideoSourceConfiguration>, } impl Validate for GetVideoSourceConfigurationsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetAudioEncoderConfigurations {} impl Validate for GetAudioEncoderConfigurations {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetAudioEncoderConfigurationsResponse { // This element contains a list of audio encoder configurations. #[yaserde(prefix = "trt", rename = "Configurations")] pub configurations: Vec<tt::AudioEncoderConfiguration>, } impl Validate for GetAudioEncoderConfigurationsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetAudioSourceConfigurations {} impl Validate for GetAudioSourceConfigurations {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetAudioSourceConfigurationsResponse { // This element contains a list of audio source configurations. #[yaserde(prefix = "trt", rename = "Configurations")] pub configurations: Vec<tt::AudioSourceConfiguration>, } impl Validate for GetAudioSourceConfigurationsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetVideoAnalyticsConfigurations {} impl Validate for GetVideoAnalyticsConfigurations {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetVideoAnalyticsConfigurationsResponse { // This element contains a list of VideoAnalytics configurations. #[yaserde(prefix = "trt", rename = "Configurations")] pub configurations: Vec<tt::VideoAnalyticsConfiguration>, } impl Validate for GetVideoAnalyticsConfigurationsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetMetadataConfigurations {} impl Validate for GetMetadataConfigurations {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetMetadataConfigurationsResponse { // This element contains a list of metadata configurations #[yaserde(prefix = "trt", rename = "Configurations")] pub configurations: Vec<tt::MetadataConfiguration>, } impl Validate for GetMetadataConfigurationsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetAudioOutputConfigurations {} impl Validate for GetAudioOutputConfigurations {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetAudioOutputConfigurationsResponse { // This element contains a list of audio output configurations #[yaserde(prefix = "trt", rename = "Configurations")] pub configurations: Vec<tt::AudioOutputConfiguration>, } impl Validate for GetAudioOutputConfigurationsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetAudioDecoderConfigurations {} impl Validate for GetAudioDecoderConfigurations {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetAudioDecoderConfigurationsResponse { // This element contains a list of audio decoder configurations #[yaserde(prefix = "trt", rename = "Configurations")] pub configurations: Vec<tt::AudioDecoderConfiguration>, } impl Validate for GetAudioDecoderConfigurationsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetVideoSourceConfiguration { // Token of the requested video source configuration. #[yaserde(prefix = "trt", rename = "ConfigurationToken")] pub configuration_token: tt::ReferenceToken, } impl Validate for GetVideoSourceConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetVideoSourceConfigurationResponse { // The requested video source configuration. #[yaserde(prefix = "trt", rename = "Configuration")] pub configuration: tt::VideoSourceConfiguration, } impl Validate for GetVideoSourceConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetVideoEncoderConfiguration { // Token of the requested video encoder configuration. #[yaserde(prefix = "trt", rename = "ConfigurationToken")] pub configuration_token: tt::ReferenceToken, } impl Validate for GetVideoEncoderConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetVideoEncoderConfigurationResponse { // The requested video encoder configuration. #[yaserde(prefix = "trt", rename = "Configuration")] pub configuration: tt::VideoEncoderConfiguration, } impl Validate for GetVideoEncoderConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetAudioSourceConfiguration { // Token of the requested audio source configuration. #[yaserde(prefix = "trt", rename = "ConfigurationToken")] pub configuration_token: tt::ReferenceToken, } impl Validate for GetAudioSourceConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetAudioSourceConfigurationResponse { // The requested audio source configuration. #[yaserde(prefix = "trt", rename = "Configuration")] pub configuration: tt::AudioSourceConfiguration, } impl Validate for GetAudioSourceConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetAudioEncoderConfiguration { // Token of the requested audio encoder configuration. #[yaserde(prefix = "trt", rename = "ConfigurationToken")] pub configuration_token: tt::ReferenceToken, } impl Validate for GetAudioEncoderConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetAudioEncoderConfigurationResponse { // The requested audio encoder configuration #[yaserde(prefix = "trt", rename = "Configuration")] pub configuration: tt::AudioEncoderConfiguration, } impl Validate for GetAudioEncoderConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )] pub struct GetVideoAnalyticsConfiguration { // Token of the requested video analytics configuration. #[yaserde(prefix = "trt", rename = "ConfigurationToken")] pub configuration_token: tt::ReferenceToken, } impl Validate for GetVideoAnalyticsConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trt", namespace = "trt: http://www.onvif.org/ver10/media/wsdl" )]
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
true
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/search/src/lib.rs
wsdl_rs/search/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use onvif as tt; use validate::Validate; use xsd_types::types as xs; use yaserde_derive::{YaDeserialize, YaSerialize}; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tse", namespace = "tse: http://www.onvif.org/ver10/search/wsdl" )] pub struct GetServiceCapabilities {} impl Validate for GetServiceCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tse", namespace = "tse: http://www.onvif.org/ver10/search/wsdl" )] pub struct GetServiceCapabilitiesResponse { // The capabilities for the search service is returned in the Capabilities // element. #[yaserde(prefix = "tse", rename = "Capabilities")] pub capabilities: Capabilities, } impl Validate for GetServiceCapabilitiesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tse", namespace = "tse: http://www.onvif.org/ver10/search/wsdl" )] pub struct Capabilities { #[yaserde(attribute, rename = "MetadataSearch")] pub metadata_search: Option<bool>, // Indicates support for general virtual property events in the FindEvents // method. #[yaserde(attribute, rename = "GeneralStartEvents")] pub general_start_events: Option<bool>, } impl Validate for Capabilities {} // pub type Capabilities = Capabilities; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tse", namespace = "tse: http://www.onvif.org/ver10/search/wsdl" )] pub struct GetRecordingSummary {} impl Validate for GetRecordingSummary {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tse", namespace = "tse: http://www.onvif.org/ver10/search/wsdl" )] pub struct GetRecordingSummaryResponse { #[yaserde(prefix = "tse", rename = "Summary")] pub summary: tt::RecordingSummary, } impl Validate for GetRecordingSummaryResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tse", namespace = "tse: http://www.onvif.org/ver10/search/wsdl" )] pub struct GetRecordingInformation { #[yaserde(prefix = "tse", rename = "RecordingToken")] pub recording_token: tt::RecordingReference, } impl Validate for GetRecordingInformation {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tse", namespace = "tse: http://www.onvif.org/ver10/search/wsdl" )] pub struct GetRecordingInformationResponse { #[yaserde(prefix = "tse", rename = "RecordingInformation")] pub recording_information: tt::RecordingInformation, } impl Validate for GetRecordingInformationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tse", namespace = "tse: http://www.onvif.org/ver10/search/wsdl" )] pub struct GetMediaAttributes { #[yaserde(prefix = "tse", rename = "RecordingTokens")] pub recording_tokens: Vec<tt::RecordingReference>, #[yaserde(prefix = "tse", rename = "Time")] pub time: xs::DateTime, } impl Validate for GetMediaAttributes {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tse", namespace = "tse: http://www.onvif.org/ver10/search/wsdl" )] pub struct GetMediaAttributesResponse { #[yaserde(prefix = "tse", rename = "MediaAttributes")] pub media_attributes: Vec<tt::MediaAttributes>, } impl Validate for GetMediaAttributesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tse", namespace = "tse: http://www.onvif.org/ver10/search/wsdl" )] pub struct FindRecordings { // Scope defines the dataset to consider for this search. #[yaserde(prefix = "tse", rename = "Scope")] pub scope: tt::SearchScope, // The search will be completed after this many matches. If not specified, // the search will continue until reaching the endpoint or until the session // expires. #[yaserde(prefix = "tse", rename = "MaxMatches")] pub max_matches: Option<i32>, // The time the search session will be kept alive after responding to this // and subsequent requests. A device shall support at least values up to ten // seconds. #[yaserde(prefix = "tse", rename = "KeepAliveTime")] pub keep_alive_time: xs::Duration, } impl Validate for FindRecordings {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tse", namespace = "tse: http://www.onvif.org/ver10/search/wsdl" )] pub struct FindRecordingsResponse { #[yaserde(prefix = "tse", rename = "SearchToken")] pub search_token: tt::JobToken, } impl Validate for FindRecordingsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tse", namespace = "tse: http://www.onvif.org/ver10/search/wsdl" )] pub struct GetRecordingSearchResults { // The search session to get results from. #[yaserde(prefix = "tse", rename = "SearchToken")] pub search_token: tt::JobToken, // The minimum number of results to return in one response. #[yaserde(prefix = "tse", rename = "MinResults")] pub min_results: Option<i32>, // The maximum number of results to return in one response. #[yaserde(prefix = "tse", rename = "MaxResults")] pub max_results: Option<i32>, // The maximum time before responding to the request, even if the MinResults // parameter is not fulfilled. #[yaserde(prefix = "tse", rename = "WaitTime")] pub wait_time: Option<xs::Duration>, } impl Validate for GetRecordingSearchResults {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tse", namespace = "tse: http://www.onvif.org/ver10/search/wsdl" )] pub struct GetRecordingSearchResultsResponse { #[yaserde(prefix = "tse", rename = "ResultList")] pub result_list: tt::FindRecordingResultList, } impl Validate for GetRecordingSearchResultsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tse", namespace = "tse: http://www.onvif.org/ver10/search/wsdl" )] pub struct FindEvents { // The point of time where the search will start. #[yaserde(prefix = "tse", rename = "StartPoint")] pub start_point: xs::DateTime, // The point of time where the search will stop. This can be a time before // the StartPoint, in which case the search is performed backwards in time. #[yaserde(prefix = "tse", rename = "EndPoint")] pub end_point: Option<xs::DateTime>, #[yaserde(prefix = "tse", rename = "Scope")] pub scope: tt::SearchScope, #[yaserde(prefix = "tse", rename = "SearchFilter")] pub search_filter: tt::EventFilter, // Setting IncludeStartState to true means that the server should return // virtual events representing the start state for any recording included in // the scope. Start state events are limited to the topics defined in the // SearchFilter that have the IsProperty flag set to true. #[yaserde(prefix = "tse", rename = "IncludeStartState")] pub include_start_state: bool, // The search will be completed after this many matches. If not specified, // the search will continue until reaching the endpoint or until the session // expires. #[yaserde(prefix = "tse", rename = "MaxMatches")] pub max_matches: Option<i32>, // The time the search session will be kept alive after responding to this // and subsequent requests. A device shall support at least values up to ten // seconds. #[yaserde(prefix = "tse", rename = "KeepAliveTime")] pub keep_alive_time: xs::Duration, } impl Validate for FindEvents {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tse", namespace = "tse: http://www.onvif.org/ver10/search/wsdl" )] pub struct FindEventsResponse { // A unique reference to the search session created by this request. #[yaserde(prefix = "tse", rename = "SearchToken")] pub search_token: tt::JobToken, } impl Validate for FindEventsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tse", namespace = "tse: http://www.onvif.org/ver10/search/wsdl" )] pub struct GetEventSearchResults { // The search session to get results from. #[yaserde(prefix = "tse", rename = "SearchToken")] pub search_token: tt::JobToken, // The minimum number of results to return in one response. #[yaserde(prefix = "tse", rename = "MinResults")] pub min_results: Option<i32>, // The maximum number of results to return in one response. #[yaserde(prefix = "tse", rename = "MaxResults")] pub max_results: Option<i32>, // The maximum time before responding to the request, even if the MinResults // parameter is not fulfilled. #[yaserde(prefix = "tse", rename = "WaitTime")] pub wait_time: Option<xs::Duration>, } impl Validate for GetEventSearchResults {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tse", namespace = "tse: http://www.onvif.org/ver10/search/wsdl" )] pub struct GetEventSearchResultsResponse { #[yaserde(prefix = "tse", rename = "ResultList")] pub result_list: tt::FindEventResultList, } impl Validate for GetEventSearchResultsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tse", namespace = "tse: http://www.onvif.org/ver10/search/wsdl" )] pub struct FindPTZPosition { // The point of time where the search will start. #[yaserde(prefix = "tse", rename = "StartPoint")] pub start_point: xs::DateTime, // The point of time where the search will stop. This can be a time before // the StartPoint, in which case the search is performed backwards in time. #[yaserde(prefix = "tse", rename = "EndPoint")] pub end_point: Option<xs::DateTime>, #[yaserde(prefix = "tse", rename = "Scope")] pub scope: tt::SearchScope, #[yaserde(prefix = "tse", rename = "SearchFilter")] pub search_filter: tt::PtzpositionFilter, // The search will be completed after this many matches. If not specified, // the search will continue until reaching the endpoint or until the session // expires. #[yaserde(prefix = "tse", rename = "MaxMatches")] pub max_matches: Option<i32>, // The time the search session will be kept alive after responding to this // and subsequent requests. A device shall support at least values up to ten // seconds. #[yaserde(prefix = "tse", rename = "KeepAliveTime")] pub keep_alive_time: xs::Duration, } impl Validate for FindPTZPosition {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tse", namespace = "tse: http://www.onvif.org/ver10/search/wsdl" )] pub struct FindPTZPositionResponse { // A unique reference to the search session created by this request. #[yaserde(prefix = "tse", rename = "SearchToken")] pub search_token: tt::JobToken, } impl Validate for FindPTZPositionResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tse", namespace = "tse: http://www.onvif.org/ver10/search/wsdl" )] pub struct GetPTZPositionSearchResults { // The search session to get results from. #[yaserde(prefix = "tse", rename = "SearchToken")] pub search_token: tt::JobToken, // The minimum number of results to return in one response. #[yaserde(prefix = "tse", rename = "MinResults")] pub min_results: Option<i32>, // The maximum number of results to return in one response. #[yaserde(prefix = "tse", rename = "MaxResults")] pub max_results: Option<i32>, // The maximum time before responding to the request, even if the MinResults // parameter is not fulfilled. #[yaserde(prefix = "tse", rename = "WaitTime")] pub wait_time: Option<xs::Duration>, } impl Validate for GetPTZPositionSearchResults {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tse", namespace = "tse: http://www.onvif.org/ver10/search/wsdl" )] pub struct GetPTZPositionSearchResultsResponse { #[yaserde(prefix = "tse", rename = "ResultList")] pub result_list: tt::FindPTZPositionResultList, } impl Validate for GetPTZPositionSearchResultsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tse", namespace = "tse: http://www.onvif.org/ver10/search/wsdl" )] pub struct FindMetadata { // The point of time where the search will start. #[yaserde(prefix = "tse", rename = "StartPoint")] pub start_point: xs::DateTime, // The point of time where the search will stop. This can be a time before // the StartPoint, in which case the search is performed backwards in time. #[yaserde(prefix = "tse", rename = "EndPoint")] pub end_point: Option<xs::DateTime>, #[yaserde(prefix = "tse", rename = "Scope")] pub scope: tt::SearchScope, #[yaserde(prefix = "tse", rename = "MetadataFilter")] pub metadata_filter: tt::MetadataFilter, // The search will be completed after this many matches. If not specified, // the search will continue until reaching the endpoint or until the session // expires. #[yaserde(prefix = "tse", rename = "MaxMatches")] pub max_matches: Option<i32>, // The time the search session will be kept alive after responding to this // and subsequent requests. A device shall support at least values up to ten // seconds. #[yaserde(prefix = "tse", rename = "KeepAliveTime")] pub keep_alive_time: xs::Duration, } impl Validate for FindMetadata {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tse", namespace = "tse: http://www.onvif.org/ver10/search/wsdl" )] pub struct FindMetadataResponse { // A unique reference to the search session created by this request. #[yaserde(prefix = "tse", rename = "SearchToken")] pub search_token: tt::JobToken, } impl Validate for FindMetadataResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tse", namespace = "tse: http://www.onvif.org/ver10/search/wsdl" )] pub struct GetMetadataSearchResults { // The search session to get results from. #[yaserde(prefix = "tse", rename = "SearchToken")] pub search_token: tt::JobToken, // The minimum number of results to return in one response. #[yaserde(prefix = "tse", rename = "MinResults")] pub min_results: Option<i32>, // The maximum number of results to return in one response. #[yaserde(prefix = "tse", rename = "MaxResults")] pub max_results: Option<i32>, // The maximum time before responding to the request, even if the MinResults // parameter is not fulfilled. #[yaserde(prefix = "tse", rename = "WaitTime")] pub wait_time: Option<xs::Duration>, } impl Validate for GetMetadataSearchResults {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tse", namespace = "tse: http://www.onvif.org/ver10/search/wsdl" )] pub struct GetMetadataSearchResultsResponse { #[yaserde(prefix = "tse", rename = "ResultList")] pub result_list: tt::FindMetadataResultList, } impl Validate for GetMetadataSearchResultsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tse", namespace = "tse: http://www.onvif.org/ver10/search/wsdl" )] pub struct GetSearchState { // The search session to get the state from. #[yaserde(prefix = "tse", rename = "SearchToken")] pub search_token: tt::JobToken, } impl Validate for GetSearchState {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tse", namespace = "tse: http://www.onvif.org/ver10/search/wsdl" )] pub struct GetSearchStateResponse { #[yaserde(prefix = "tse", rename = "State")] pub state: tt::SearchState, } impl Validate for GetSearchStateResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tse", namespace = "tse: http://www.onvif.org/ver10/search/wsdl" )] pub struct EndSearch { // The search session to end. #[yaserde(prefix = "tse", rename = "SearchToken")] pub search_token: tt::JobToken, } impl Validate for EndSearch {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tse", namespace = "tse: http://www.onvif.org/ver10/search/wsdl" )] pub struct EndSearchResponse { // The point of time the search had reached when it was ended. It is equal // to the EndPoint specified in Find-operation if the search was completed. #[yaserde(prefix = "tse", rename = "Endpoint")] pub endpoint: xs::DateTime, } impl Validate for EndSearchResponse {} // Returns the capabilities of the search service. The result is returned in a // typed answer. pub async fn get_service_capabilities<T: transport::Transport>( transport: &T, request: &GetServiceCapabilities, ) -> Result<GetServiceCapabilitiesResponse, transport::Error> { transport::request(transport, request).await } // GetRecordingSummary is used to get a summary description of all recorded // data. This // operation is mandatory to support for a device implementing the recording // search service. pub async fn get_recording_summary<T: transport::Transport>( transport: &T, request: &GetRecordingSummary, ) -> Result<GetRecordingSummaryResponse, transport::Error> { transport::request(transport, request).await } // Returns information about a single Recording specified by a RecordingToken. // This operation // is mandatory to support for a device implementing the recording search // service. pub async fn get_recording_information<T: transport::Transport>( transport: &T, request: &GetRecordingInformation, ) -> Result<GetRecordingInformationResponse, transport::Error> { transport::request(transport, request).await } // Returns a set of media attributes for all tracks of the specified recordings // at a specified point // in time. Clients using this operation shall be able to use it as a non // blocking operation. A // device shall set the starttime and endtime of the MediaAttributes structure // to equal values if // calculating this range would causes this operation to block. See // MediaAttributes structure for // more information. This operation is mandatory to support for a device // implementing the // recording search service. pub async fn get_media_attributes<T: transport::Transport>( transport: &T, request: &GetMediaAttributes, ) -> Result<GetMediaAttributesResponse, transport::Error> { transport::request(transport, request).await } // FindRecordings starts a search session, looking for recordings that matches // the scope (See // 20.2.4) defined in the request. Results from the search are acquired using // the // GetRecordingSearchResults request, specifying the search token returned from // this request. // The device shall continue searching until one of the following occurs: pub async fn find_recordings<T: transport::Transport>( transport: &T, request: &FindRecordings, ) -> Result<FindRecordingsResponse, transport::Error> { transport::request(transport, request).await } // GetRecordingSearchResults acquires the results from a recording search // session previously // initiated by a FindRecordings operation. The response shall not include // results already // returned in previous requests for the same session. If MaxResults is // specified, the response // shall not contain more than MaxResults results. The number of results relates // to the number of recordings. // For viewing individual recorded data for a signal track use the FindEvents // method. pub async fn get_recording_search_results<T: transport::Transport>( transport: &T, request: &GetRecordingSearchResults, ) -> Result<GetRecordingSearchResultsResponse, transport::Error> { transport::request(transport, request).await } // FindEvents starts a search session, looking for recording events (in the // scope that // matches the search filter defined in the request. Results from the search are // acquired using the GetEventSearchResults request, specifying the search token // returned from // this request. pub async fn find_events<T: transport::Transport>( transport: &T, request: &FindEvents, ) -> Result<FindEventsResponse, transport::Error> { transport::request(transport, request).await } // GetEventSearchResults acquires the results from a recording event search // session previously // initiated by a FindEvents operation. The response shall not include results // already returned in // previous requests for the same session. If MaxResults is specified, the // response shall not // contain more than MaxResults results. pub async fn get_event_search_results<T: transport::Transport>( transport: &T, request: &GetEventSearchResults, ) -> Result<GetEventSearchResultsResponse, transport::Error> { transport::request(transport, request).await } // FindPTZPosition starts a search session, looking for ptz positions in the // scope (See 20.2.4) // that matches the search filter defined in the request. Results from the // search are acquired // using the GetPTZPositionSearchResults request, specifying the search token // returned from // this request. pub async fn find_ptz_position<T: transport::Transport>( transport: &T, request: &FindPTZPosition, ) -> Result<FindPTZPositionResponse, transport::Error> { transport::request(transport, request).await } // GetPTZPositionSearchResults acquires the results from a ptz position search // session // previously initiated by a FindPTZPosition operation. The response shall not // include results // already returned in previous requests for the same session. If MaxResults is // specified, the // response shall not contain more than MaxResults results. pub async fn get_ptz_position_search_results<T: transport::Transport>( transport: &T, request: &GetPTZPositionSearchResults, ) -> Result<GetPTZPositionSearchResultsResponse, transport::Error> { transport::request(transport, request).await } // GetSearchState returns the current state of the specified search session. // This command is deprecated . pub async fn get_search_state<T: transport::Transport>( transport: &T, request: &GetSearchState, ) -> Result<GetSearchStateResponse, transport::Error> { transport::request(transport, request).await } // EndSearch stops and ongoing search session, causing any blocking result // request to return // and the SearchToken to become invalid. If the search was interrupted before // completion, the // point in time that the search had reached shall be returned. If the search // had not yet begun, // the StartPoint shall be returned. If the search was completed the original // EndPoint supplied // by the Find operation shall be returned. When issuing EndSearch on a // FindRecordings request the // EndPoint is undefined and shall not be used since the FindRecordings request // doesn't have // StartPoint/EndPoint. This operation is mandatory to support for a device // implementing the // recording search service. pub async fn end_search<T: transport::Transport>( transport: &T, request: &EndSearch, ) -> Result<EndSearchResponse, transport::Error> { transport::request(transport, request).await } // FindMetadata starts a search session, looking for metadata in the scope (See // 20.2.4) that // matches the search filter defined in the request. Results from the search are // acquired using // the GetMetadataSearchResults request, specifying the search token returned // from this // request. pub async fn find_metadata<T: transport::Transport>( transport: &T, request: &FindMetadata, ) -> Result<FindMetadataResponse, transport::Error> { transport::request(transport, request).await } // GetMetadataSearchResults acquires the results from a recording search session // previously // initiated by a FindMetadata operation. The response shall not include results // already returned // in previous requests for the same session. If MaxResults is specified, the // response shall not // contain more than MaxResults results. pub async fn get_metadata_search_results<T: transport::Transport>( transport: &T, request: &GetMetadataSearchResults, ) -> Result<GetMetadataSearchResultsResponse, transport::Error> { transport::request(transport, request).await }
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
false
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/ptz/src/lib.rs
wsdl_rs/ptz/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use onvif as tt; use validate::Validate; use xsd_types::types as xs; use yaserde_derive::{YaDeserialize, YaSerialize}; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GetServiceCapabilities {} impl Validate for GetServiceCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GetServiceCapabilitiesResponse { // The capabilities for the PTZ service is returned in the Capabilities // element. #[yaserde(prefix = "tptz", rename = "Capabilities")] pub capabilities: Capabilities, } impl Validate for GetServiceCapabilitiesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct Capabilities { // Indicates whether or not EFlip is supported. #[yaserde(attribute, rename = "EFlip")] pub e_flip: Option<bool>, // Indicates whether or not reversing of PT control direction is supported. #[yaserde(attribute, rename = "Reverse")] pub reverse: Option<bool>, // Indicates support for the GetCompatibleConfigurations command. #[yaserde(attribute, rename = "GetCompatibleConfigurations")] pub get_compatible_configurations: Option<bool>, // Indicates that the PTZStatus includes MoveStatus information. #[yaserde(attribute, rename = "MoveStatus")] pub move_status: Option<bool>, // Indicates that the PTZStatus includes Position information. #[yaserde(attribute, rename = "StatusPosition")] pub status_position: Option<bool>, } impl Validate for Capabilities {} // pub type Capabilities = Capabilities; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GetNodes {} impl Validate for GetNodes {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GetNodesResponse { // A list of the existing PTZ Nodes on the device. #[yaserde(prefix = "tptz", rename = "PTZNode")] pub ptz_node: Vec<tt::Ptznode>, } impl Validate for GetNodesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GetNode { // Token of the requested PTZNode. #[yaserde(prefix = "tptz", rename = "NodeToken")] pub node_token: tt::ReferenceToken, } impl Validate for GetNode {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GetNodeResponse { // A requested PTZNode. #[yaserde(prefix = "tptz", rename = "PTZNode")] pub ptz_node: tt::Ptznode, } impl Validate for GetNodeResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GetConfigurations {} impl Validate for GetConfigurations {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GetConfigurationsResponse { // A list of all existing PTZConfigurations on the device. #[yaserde(prefix = "tptz", rename = "PTZConfiguration")] pub ptz_configuration: Vec<tt::Ptzconfiguration>, } impl Validate for GetConfigurationsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GetConfiguration { // Token of the requested PTZConfiguration. #[yaserde(prefix = "tptz", rename = "PTZConfigurationToken")] pub ptz_configuration_token: tt::ReferenceToken, } impl Validate for GetConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GetConfigurationResponse { // A requested PTZConfiguration. #[yaserde(prefix = "tptz", rename = "PTZConfiguration")] pub ptz_configuration: tt::Ptzconfiguration, } impl Validate for GetConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct SetConfiguration { #[yaserde(prefix = "tptz", rename = "PTZConfiguration")] pub ptz_configuration: tt::Ptzconfiguration, // Flag that makes configuration persistent. Example: User wants the // configuration to exist after reboot. #[yaserde(prefix = "tptz", rename = "ForcePersistence")] pub force_persistence: bool, } impl Validate for SetConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct SetConfigurationResponse {} impl Validate for SetConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GetConfigurationOptions { // Token of an existing configuration that the options are intended for. #[yaserde(prefix = "tptz", rename = "ConfigurationToken")] pub configuration_token: tt::ReferenceToken, } impl Validate for GetConfigurationOptions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GetConfigurationOptionsResponse { // The requested PTZ configuration options. #[yaserde(prefix = "tptz", rename = "PTZConfigurationOptions")] pub ptz_configuration_options: tt::PtzconfigurationOptions, } impl Validate for GetConfigurationOptionsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct SendAuxiliaryCommand { // A reference to the MediaProfile where the operation should take place. #[yaserde(prefix = "tptz", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, // The Auxiliary request data. #[yaserde(prefix = "tptz", rename = "AuxiliaryData")] pub auxiliary_data: tt::AuxiliaryData, } impl Validate for SendAuxiliaryCommand {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct SendAuxiliaryCommandResponse { // The response contains the auxiliary response. #[yaserde(prefix = "tptz", rename = "AuxiliaryResponse")] pub auxiliary_response: tt::AuxiliaryData, } impl Validate for SendAuxiliaryCommandResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GetPresets { // A reference to the MediaProfile where the operation should take place. #[yaserde(prefix = "tptz", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, } impl Validate for GetPresets {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GetPresetsResponse { // A list of presets which are available for the requested MediaProfile. #[yaserde(prefix = "tptz", rename = "Preset")] pub preset: Vec<tt::Ptzpreset>, } impl Validate for GetPresetsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct SetPreset { // A reference to the MediaProfile where the operation should take place. #[yaserde(prefix = "tptz", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, // A requested preset name. #[yaserde(prefix = "tptz", rename = "PresetName")] pub preset_name: Option<String>, // A requested preset token. #[yaserde(prefix = "tptz", rename = "PresetToken")] pub preset_token: Option<tt::ReferenceToken>, } impl Validate for SetPreset {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct SetPresetResponse { // A token to the Preset which has been set. #[yaserde(prefix = "tptz", rename = "PresetToken")] pub preset_token: tt::ReferenceToken, } impl Validate for SetPresetResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct RemovePreset { // A reference to the MediaProfile where the operation should take place. #[yaserde(prefix = "tptz", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, // A requested preset token. #[yaserde(prefix = "tptz", rename = "PresetToken")] pub preset_token: tt::ReferenceToken, } impl Validate for RemovePreset {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct RemovePresetResponse {} impl Validate for RemovePresetResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GotoPreset { // A reference to the MediaProfile where the operation should take place. #[yaserde(prefix = "tptz", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, // A requested preset token. #[yaserde(prefix = "tptz", rename = "PresetToken")] pub preset_token: tt::ReferenceToken, // A requested speed.The speed parameter can only be specified when Speed // Spaces are available for the PTZ Node. #[yaserde(prefix = "tptz", rename = "Speed")] pub speed: Option<tt::Ptzspeed>, } impl Validate for GotoPreset {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GotoPresetResponse {} impl Validate for GotoPresetResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GetStatus { // A reference to the MediaProfile where the PTZStatus should be requested. #[yaserde(prefix = "tptz", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, } impl Validate for GetStatus {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GetStatusResponse { // The PTZStatus for the requested MediaProfile. #[yaserde(prefix = "tptz", rename = "PTZStatus")] pub ptz_status: tt::Ptzstatus, } impl Validate for GetStatusResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GotoHomePosition { // A reference to the MediaProfile where the operation should take place. #[yaserde(prefix = "tptz", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, // A requested speed.The speed parameter can only be specified when Speed // Spaces are available for the PTZ Node. #[yaserde(prefix = "tptz", rename = "Speed")] pub speed: Option<tt::Ptzspeed>, } impl Validate for GotoHomePosition {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GotoHomePositionResponse {} impl Validate for GotoHomePositionResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct SetHomePosition { // A reference to the MediaProfile where the home position should be set. #[yaserde(prefix = "tptz", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, } impl Validate for SetHomePosition {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct SetHomePositionResponse {} impl Validate for SetHomePositionResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct ContinuousMove { // A reference to the MediaProfile. #[yaserde(prefix = "tptz", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, // A Velocity vector specifying the velocity of pan, tilt and zoom. #[yaserde(prefix = "tptz", rename = "Velocity")] pub velocity: tt::Ptzspeed, // An optional Timeout parameter. #[yaserde(prefix = "tptz", rename = "Timeout")] pub timeout: Option<xs::Duration>, } impl Validate for ContinuousMove {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct ContinuousMoveResponse {} impl Validate for ContinuousMoveResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct RelativeMove { // A reference to the MediaProfile. #[yaserde(prefix = "tptz", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, // A positional Translation relative to the current position #[yaserde(prefix = "tptz", rename = "Translation")] pub translation: tt::Ptzvector, // An optional Speed parameter. #[yaserde(prefix = "tptz", rename = "Speed")] pub speed: Option<tt::Ptzspeed>, } impl Validate for RelativeMove {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct RelativeMoveResponse {} impl Validate for RelativeMoveResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct AbsoluteMove { // A reference to the MediaProfile. #[yaserde(prefix = "tptz", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, // A Position vector specifying the absolute target position. #[yaserde(prefix = "tptz", rename = "Position")] pub position: tt::Ptzvector, // An optional Speed. #[yaserde(prefix = "tptz", rename = "Speed")] pub speed: Option<tt::Ptzspeed>, } impl Validate for AbsoluteMove {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct AbsoluteMoveResponse {} impl Validate for AbsoluteMoveResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GeoMove { // A reference to the MediaProfile. #[yaserde(prefix = "tptz", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, // The geolocation of the target position. #[yaserde(prefix = "tptz", rename = "Target")] pub target: tt::GeoLocation, // An optional Speed. #[yaserde(prefix = "tptz", rename = "Speed")] pub speed: Option<tt::Ptzspeed>, // An optional indication of the height of the target/area. #[yaserde(prefix = "tptz", rename = "AreaHeight")] pub area_height: Option<f64>, // An optional indication of the width of the target/area. #[yaserde(prefix = "tptz", rename = "AreaWidth")] pub area_width: Option<f64>, } impl Validate for GeoMove {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GeoMoveResponse {} impl Validate for GeoMoveResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct Stop { // A reference to the MediaProfile that indicate what should be stopped. #[yaserde(prefix = "tptz", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, // Set true when we want to stop ongoing pan and tilt movements.If PanTilt // arguments are not present, this command stops these movements. #[yaserde(prefix = "tptz", rename = "PanTilt")] pub pan_tilt: Option<bool>, // Set true when we want to stop ongoing zoom movement.If Zoom arguments are // not present, this command stops ongoing zoom movement. #[yaserde(prefix = "tptz", rename = "Zoom")] pub zoom: Option<bool>, } impl Validate for Stop {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct StopResponse {} impl Validate for StopResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GetPresetTours { #[yaserde(prefix = "tptz", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, } impl Validate for GetPresetTours {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GetPresetToursResponse { #[yaserde(prefix = "tptz", rename = "PresetTour")] pub preset_tour: Vec<tt::PresetTour>, } impl Validate for GetPresetToursResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GetPresetTour { #[yaserde(prefix = "tptz", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, #[yaserde(prefix = "tptz", rename = "PresetTourToken")] pub preset_tour_token: tt::ReferenceToken, } impl Validate for GetPresetTour {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GetPresetTourResponse { #[yaserde(prefix = "tptz", rename = "PresetTour")] pub preset_tour: tt::PresetTour, } impl Validate for GetPresetTourResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GetPresetTourOptions { #[yaserde(prefix = "tptz", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, #[yaserde(prefix = "tptz", rename = "PresetTourToken")] pub preset_tour_token: Option<tt::ReferenceToken>, } impl Validate for GetPresetTourOptions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GetPresetTourOptionsResponse { #[yaserde(prefix = "tptz", rename = "Options")] pub options: tt::PtzpresetTourOptions, } impl Validate for GetPresetTourOptionsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct CreatePresetTour { #[yaserde(prefix = "tptz", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, } impl Validate for CreatePresetTour {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct CreatePresetTourResponse { #[yaserde(prefix = "tptz", rename = "PresetTourToken")] pub preset_tour_token: tt::ReferenceToken, } impl Validate for CreatePresetTourResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct ModifyPresetTour { #[yaserde(prefix = "tptz", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, #[yaserde(prefix = "tptz", rename = "PresetTour")] pub preset_tour: tt::PresetTour, } impl Validate for ModifyPresetTour {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct ModifyPresetTourResponse {} impl Validate for ModifyPresetTourResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct OperatePresetTour { #[yaserde(prefix = "tptz", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, #[yaserde(prefix = "tptz", rename = "PresetTourToken")] pub preset_tour_token: tt::ReferenceToken, #[yaserde(prefix = "tptz", rename = "Operation")] pub operation: tt::PtzpresetTourOperation, } impl Validate for OperatePresetTour {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct OperatePresetTourResponse {} impl Validate for OperatePresetTourResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct RemovePresetTour { #[yaserde(prefix = "tptz", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, #[yaserde(prefix = "tptz", rename = "PresetTourToken")] pub preset_tour_token: tt::ReferenceToken, } impl Validate for RemovePresetTour {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct RemovePresetTourResponse {} impl Validate for RemovePresetTourResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GetCompatibleConfigurations { // Contains the token of an existing media profile the configurations shall // be compatible with. #[yaserde(prefix = "tptz", rename = "ProfileToken")] pub profile_token: tt::ReferenceToken, } impl Validate for GetCompatibleConfigurations {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tptz", namespace = "tptz: http://www.onvif.org/ver20/ptz/wsdl" )] pub struct GetCompatibleConfigurationsResponse { // A list of all existing PTZConfigurations on the NVT that is suitable to // be added to the addressed media profile. #[yaserde(prefix = "tptz", rename = "PTZConfiguration")] pub ptz_configuration: Vec<tt::Ptzconfiguration>, } impl Validate for GetCompatibleConfigurationsResponse {} // Returns the capabilities of the PTZ service. The result is returned in a // typed answer. pub async fn get_service_capabilities<T: transport::Transport>( transport: &T, request: &GetServiceCapabilities, ) -> Result<GetServiceCapabilitiesResponse, transport::Error> { transport::request(transport, request).await } // Get the descriptions of the available PTZ Nodes. pub async fn get_nodes<T: transport::Transport>( transport: &T, request: &GetNodes, ) -> Result<GetNodesResponse, transport::Error> { transport::request(transport, request).await } // Get a specific PTZ Node identified by a reference // token or a name. pub async fn get_node<T: transport::Transport>( transport: &T, request: &GetNode, ) -> Result<GetNodeResponse, transport::Error> { transport::request(transport, request).await } // Get a specific PTZconfiguration from the device, identified by its reference // token or name. pub async fn get_configuration<T: transport::Transport>( transport: &T, request: &GetConfiguration, ) -> Result<GetConfigurationResponse, transport::Error> { transport::request(transport, request).await } // Get all the existing PTZConfigurations from the device. pub async fn get_configurations<T: transport::Transport>( transport: &T, request: &GetConfigurations, ) -> Result<GetConfigurationsResponse, transport::Error> { transport::request(transport, request).await } // Set/update a existing PTZConfiguration on the device. pub async fn set_configuration<T: transport::Transport>( transport: &T, request: &SetConfiguration, ) -> Result<SetConfigurationResponse, transport::Error> { transport::request(transport, request).await } // List supported coordinate systems including their range limitations. // Therefore, the options // MAY differ depending on whether the PTZ Configuration is assigned to a // Profile containing a // Video Source Configuration. In that case, the options may additionally // contain coordinate // systems referring to the image coordinate system described by the Video // Source // Configuration. If the PTZ Node supports continuous movements, it shall return // a Timeout Range within // which Timeouts are accepted by the PTZ Node. pub async fn get_configuration_options<T: transport::Transport>( transport: &T, request: &GetConfigurationOptions, ) -> Result<GetConfigurationOptionsResponse, transport::Error> { transport::request(transport, request).await } // Operation to send auxiliary commands to the PTZ device // mapped by the PTZNode in the selected profile. The // operation is supported // if the AuxiliarySupported element of the PTZNode is true pub async fn send_auxiliary_command<T: transport::Transport>( transport: &T, request: &SendAuxiliaryCommand, ) -> Result<SendAuxiliaryCommandResponse, transport::Error> { transport::request(transport, request).await } // Operation to request all PTZ presets for the PTZNode // in the selected profile. The operation is supported if there is support // for at least on PTZ preset by the PTZNode. pub async fn get_presets<T: transport::Transport>( transport: &T, request: &GetPresets, ) -> Result<GetPresetsResponse, transport::Error> { transport::request(transport, request).await } // The SetPreset command saves the current device position parameters so that // the device can // move to the saved preset position through the GotoPreset operation. // In order to create a new preset, the SetPresetRequest contains no // PresetToken. If creation is // successful, the Response contains the PresetToken which uniquely identifies // the Preset. An // existing Preset can be overwritten by specifying the PresetToken of the // corresponding Preset. // In both cases (overwriting or creation) an optional PresetName can be // specified. The // operation fails if the PTZ device is moving during the SetPreset operation. // The device MAY internally save additional states such as imaging properties // in the PTZ // Preset which then should be recalled in the GotoPreset operation. pub async fn set_preset<T: transport::Transport>( transport: &T, request: &SetPreset, ) -> Result<SetPresetResponse, transport::Error> { transport::request(transport, request).await } // Operation to remove a PTZ preset for the Node in // the // selected profile. The operation is supported if the // PresetPosition // capability exists for teh Node in the // selected profile. pub async fn remove_preset<T: transport::Transport>( transport: &T, request: &RemovePreset, ) -> Result<RemovePresetResponse, transport::Error> { transport::request(transport, request).await } // Operation to go to a saved preset position for the // PTZNode in the selected profile. The operation is supported if there is // support for at least on PTZ preset by the PTZNode. pub async fn goto_preset<T: transport::Transport>( transport: &T, request: &GotoPreset, ) -> Result<GotoPresetResponse, transport::Error> { transport::request(transport, request).await } // Operation to move the PTZ device to it's "home" position. The operation is // supported if the HomeSupported element in the PTZNode is true. pub async fn goto_home_position<T: transport::Transport>( transport: &T, request: &GotoHomePosition, ) -> Result<GotoHomePositionResponse, transport::Error> { transport::request(transport, request).await } // Operation to save current position as the home position. // The SetHomePosition command returns with a failure if the “home” position // is fixed and // cannot be overwritten. If the SetHomePosition is successful, it is possible // to recall the // Home Position with the GotoHomePosition command. pub async fn set_home_position<T: transport::Transport>( transport: &T, request: &SetHomePosition, ) -> Result<SetHomePositionResponse, transport::Error> { transport::request(transport, request).await } // Operation for continuous Pan/Tilt and Zoom movements. The operation is // supported if the PTZNode supports at least one continuous Pan/Tilt or Zoom // space. If the space argument is omitted, the default space set by the // PTZConfiguration will be used. pub async fn continuous_move<T: transport::Transport>( transport: &T, request: &ContinuousMove, ) -> Result<ContinuousMoveResponse, transport::Error> { transport::request(transport, request).await } // Operation for Relative Pan/Tilt and Zoom Move. The operation is supported if // the PTZNode supports at least one relative Pan/Tilt or Zoom space. pub async fn relative_move<T: transport::Transport>( transport: &T, request: &RelativeMove, ) -> Result<RelativeMoveResponse, transport::Error> { transport::request(transport, request).await } // Operation to request PTZ status for the Node in the // selected profile. pub async fn get_status<T: transport::Transport>( transport: &T, request: &GetStatus, ) -> Result<GetStatusResponse, transport::Error> { transport::request(transport, request).await } // Operation to move pan,tilt or zoom to a absolute destination. pub async fn absolute_move<T: transport::Transport>( transport: &T, request: &AbsoluteMove, ) -> Result<AbsoluteMoveResponse, transport::Error> { transport::request(transport, request).await } // Operation to move pan,tilt or zoom to point to a destination based on the // geolocation of the target. pub async fn geo_move<T: transport::Transport>( transport: &T, request: &GeoMove, ) -> Result<GeoMoveResponse, transport::Error> { transport::request(transport, request).await } // Operation to stop ongoing pan, tilt and zoom movements of absolute relative // and continuous type. // If no stop argument for pan, tilt or zoom is set, the device will stop all // ongoing pan, tilt and zoom movements. pub async fn stop<T: transport::Transport>( transport: &T, request: &Stop, ) -> Result<StopResponse, transport::Error> { transport::request(transport, request).await } // Operation to request PTZ preset tours in the selected media profiles. pub async fn get_preset_tours<T: transport::Transport>( transport: &T, request: &GetPresetTours, ) -> Result<GetPresetToursResponse, transport::Error> { transport::request(transport, request).await } // Operation to request a specific PTZ preset tour in the selected media // profile. pub async fn get_preset_tour<T: transport::Transport>( transport: &T, request: &GetPresetTour, ) -> Result<GetPresetTourResponse, transport::Error> { transport::request(transport, request).await } // Operation to request available options to configure PTZ preset tour.
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
true
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/analytics/src/lib.rs
wsdl_rs/analytics/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use onvif as tt; use validate::Validate; use yaserde_derive::{YaDeserialize, YaSerialize}; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tan", namespace = "tan: http://www.onvif.org/ver20/analytics/wsdl" )] pub struct GetServiceCapabilities {} impl Validate for GetServiceCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tan", namespace = "tan: http://www.onvif.org/ver20/analytics/wsdl" )] pub struct GetServiceCapabilitiesResponse { // The capabilities for the analytics service is returned in the // Capabilities element. #[yaserde(prefix = "tan", rename = "Capabilities")] pub capabilities: Capabilities, } impl Validate for GetServiceCapabilitiesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tan", namespace = "tan: http://www.onvif.org/ver20/analytics/wsdl" )] pub struct Capabilities { // Indication that the device supports the rules interface and the rules // syntax. #[yaserde(attribute, rename = "RuleSupport")] pub rule_support: Option<bool>, // Indication that the device supports the scene analytics module interface. #[yaserde(attribute, rename = "AnalyticsModuleSupport")] pub analytics_module_support: Option<bool>, // Indication that the device produces the cell based scene description #[yaserde(attribute, rename = "CellBasedSceneDescriptionSupported")] pub cell_based_scene_description_supported: Option<bool>, // Indication that the device supports the GetRuleOptions operation on the // rules interface #[yaserde(attribute, rename = "RuleOptionsSupported")] pub rule_options_supported: Option<bool>, // Indication that the device supports the GetAnalyticsModuleOptions // operation on the analytics interface #[yaserde(attribute, rename = "AnalyticsModuleOptionsSupported")] pub analytics_module_options_supported: Option<bool>, } impl Validate for Capabilities {} // pub type Capabilities = Capabilities; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tan", namespace = "tan: http://www.onvif.org/ver20/analytics/wsdl" )] pub struct GetSupportedRules { // References an existing Video Analytics configuration. The list of // available tokens can be obtained // via the Media service GetVideoAnalyticsConfigurations method. #[yaserde(prefix = "tan", rename = "ConfigurationToken")] pub configuration_token: tt::ReferenceToken, } impl Validate for GetSupportedRules {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tan", namespace = "tan: http://www.onvif.org/ver20/analytics/wsdl" )] pub struct GetSupportedRulesResponse { #[yaserde(prefix = "tan", rename = "SupportedRules")] pub supported_rules: tt::SupportedRules, } impl Validate for GetSupportedRulesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tan", namespace = "tan: http://www.onvif.org/ver20/analytics/wsdl" )] pub struct CreateRules { // Reference to an existing VideoAnalyticsConfiguration. #[yaserde(prefix = "tan", rename = "ConfigurationToken")] pub configuration_token: tt::ReferenceToken, #[yaserde(prefix = "tan", rename = "Rule")] pub rule: Vec<tt::Config>, } impl Validate for CreateRules {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tan", namespace = "tan: http://www.onvif.org/ver20/analytics/wsdl" )] pub struct CreateRulesResponse {} impl Validate for CreateRulesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tan", namespace = "tan: http://www.onvif.org/ver20/analytics/wsdl" )] pub struct DeleteRules { // Reference to an existing VideoAnalyticsConfiguration. #[yaserde(prefix = "tan", rename = "ConfigurationToken")] pub configuration_token: tt::ReferenceToken, // References the specific rule to be deleted (e.g. "MyLineDetector"). #[yaserde(prefix = "tan", rename = "RuleName")] pub rule_name: Vec<String>, } impl Validate for DeleteRules {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tan", namespace = "tan: http://www.onvif.org/ver20/analytics/wsdl" )] pub struct DeleteRulesResponse {} impl Validate for DeleteRulesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tan", namespace = "tan: http://www.onvif.org/ver20/analytics/wsdl" )] pub struct ModifyRules { // Reference to an existing VideoAnalyticsConfiguration. #[yaserde(prefix = "tan", rename = "ConfigurationToken")] pub configuration_token: tt::ReferenceToken, #[yaserde(prefix = "tan", rename = "Rule")] pub rule: Vec<tt::Config>, } impl Validate for ModifyRules {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tan", namespace = "tan: http://www.onvif.org/ver20/analytics/wsdl" )] pub struct ModifyRulesResponse {} impl Validate for ModifyRulesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tan", namespace = "tan: http://www.onvif.org/ver20/analytics/wsdl" )] pub struct GetRules { // Reference to an existing VideoAnalyticsConfiguration. #[yaserde(prefix = "tan", rename = "ConfigurationToken")] pub configuration_token: tt::ReferenceToken, } impl Validate for GetRules {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tan", namespace = "tan: http://www.onvif.org/ver20/analytics/wsdl" )] pub struct GetRulesResponse { #[yaserde(prefix = "tan", rename = "Rule")] pub rule: Vec<tt::Config>, } impl Validate for GetRulesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tan", namespace = "tan: http://www.onvif.org/ver20/analytics/wsdl" )] pub struct GetRuleOptions { // Reference to an SupportedRule Type returned from GetSupportedRules. #[yaserde(prefix = "tan", rename = "RuleType")] pub rule_type: Option<String>, // Reference to an existing analytics configuration. #[yaserde(prefix = "tan", rename = "ConfigurationToken")] pub configuration_token: tt::ReferenceToken, } impl Validate for GetRuleOptions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tan", namespace = "tan: http://www.onvif.org/ver20/analytics/wsdl" )] pub struct GetRuleOptionsResponse { // A device shall provide respective ConfigOptions.RuleType for each // RuleOption if the request does not specify RuleType. The response Options // shall not contain any AnalyticsModule attribute. #[yaserde(prefix = "tan", rename = "RuleOptions")] pub rule_options: Vec<ConfigOptions>, } impl Validate for GetRuleOptionsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tan", namespace = "tan: http://www.onvif.org/ver20/analytics/wsdl" )] pub struct ConfigOptions { // The RuleType the ConfigOptions applies to if the Name attribute is // ambiguous. #[yaserde(attribute, rename = "RuleType")] pub rule_type: Option<String>, // The Name of the SimpleItemDescription/ElementItemDescription // the ConfigOptions applies to. #[yaserde(attribute, rename = "Name")] pub name: String, // Type of the Rule Options represented by a unique QName. // The Type defines the element contained in this structure. // This attribute is deprecated since its value must be identical to the // embedded element. #[yaserde(attribute, rename = "Type")] pub _type: Option<String>, // Optional name of the analytics module this constraint applies to. This // option is only necessary in cases where different constraints for // elements with the same Name exist. #[yaserde(attribute, rename = "AnalyticsModule")] pub analytics_module: Option<String>, } impl Validate for ConfigOptions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tan", namespace = "tan: http://www.onvif.org/ver20/analytics/wsdl" )] pub struct GetSupportedAnalyticsModules { // Reference to an existing VideoAnalyticsConfiguration. #[yaserde(prefix = "tan", rename = "ConfigurationToken")] pub configuration_token: tt::ReferenceToken, } impl Validate for GetSupportedAnalyticsModules {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tan", namespace = "tan: http://www.onvif.org/ver20/analytics/wsdl" )] pub struct GetSupportedAnalyticsModulesResponse { #[yaserde(prefix = "tan", rename = "SupportedAnalyticsModules")] pub supported_analytics_modules: tt::SupportedAnalyticsModules, } impl Validate for GetSupportedAnalyticsModulesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tan", namespace = "tan: http://www.onvif.org/ver20/analytics/wsdl" )] pub struct CreateAnalyticsModules { // Reference to an existing VideoAnalyticsConfiguration. #[yaserde(prefix = "tan", rename = "ConfigurationToken")] pub configuration_token: tt::ReferenceToken, #[yaserde(prefix = "tan", rename = "AnalyticsModule")] pub analytics_module: Vec<tt::Config>, } impl Validate for CreateAnalyticsModules {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tan", namespace = "tan: http://www.onvif.org/ver20/analytics/wsdl" )] pub struct CreateAnalyticsModulesResponse {} impl Validate for CreateAnalyticsModulesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tan", namespace = "tan: http://www.onvif.org/ver20/analytics/wsdl" )] pub struct DeleteAnalyticsModules { // Reference to an existing Video Analytics configuration. #[yaserde(prefix = "tan", rename = "ConfigurationToken")] pub configuration_token: tt::ReferenceToken, // Name of the AnalyticsModule to be deleted. #[yaserde(prefix = "tan", rename = "AnalyticsModuleName")] pub analytics_module_name: Vec<String>, } impl Validate for DeleteAnalyticsModules {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tan", namespace = "tan: http://www.onvif.org/ver20/analytics/wsdl" )] pub struct DeleteAnalyticsModulesResponse {} impl Validate for DeleteAnalyticsModulesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tan", namespace = "tan: http://www.onvif.org/ver20/analytics/wsdl" )] pub struct ModifyAnalyticsModules { // Reference to an existing VideoAnalyticsConfiguration. #[yaserde(prefix = "tan", rename = "ConfigurationToken")] pub configuration_token: tt::ReferenceToken, #[yaserde(prefix = "tan", rename = "AnalyticsModule")] pub analytics_module: Vec<tt::Config>, } impl Validate for ModifyAnalyticsModules {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tan", namespace = "tan: http://www.onvif.org/ver20/analytics/wsdl" )] pub struct ModifyAnalyticsModulesResponse {} impl Validate for ModifyAnalyticsModulesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tan", namespace = "tan: http://www.onvif.org/ver20/analytics/wsdl" )] pub struct GetAnalyticsModules { // Reference to an existing VideoAnalyticsConfiguration. #[yaserde(prefix = "tan", rename = "ConfigurationToken")] pub configuration_token: tt::ReferenceToken, } impl Validate for GetAnalyticsModules {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tan", namespace = "tan: http://www.onvif.org/ver20/analytics/wsdl" )] pub struct GetAnalyticsModulesResponse { #[yaserde(prefix = "tan", rename = "AnalyticsModule")] pub analytics_module: Vec<tt::Config>, } impl Validate for GetAnalyticsModulesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tan", namespace = "tan: http://www.onvif.org/ver20/analytics/wsdl" )] pub struct GetAnalyticsModuleOptions { // Reference to an SupportedAnalyticsModule Type returned from // GetSupportedAnalyticsModules. #[yaserde(prefix = "tan", rename = "Type")] pub _type: Option<String>, // Reference to an existing AnalyticsConfiguration. #[yaserde(prefix = "tan", rename = "ConfigurationToken")] pub configuration_token: tt::ReferenceToken, } impl Validate for GetAnalyticsModuleOptions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tan", namespace = "tan: http://www.onvif.org/ver20/analytics/wsdl" )] pub struct GetAnalyticsModuleOptionsResponse { // List of options for the specified analytics module. The response Options // shall not contain any RuleType attribute. #[yaserde(prefix = "tan", rename = "Options")] pub options: Vec<ConfigOptions>, } impl Validate for GetAnalyticsModuleOptionsResponse {} // Returns the capabilities of the analytics service. The result is returned in // a typed answer. pub async fn get_service_capabilities<T: transport::Transport>( transport: &T, request: &GetServiceCapabilities, ) -> Result<GetServiceCapabilitiesResponse, transport::Error> { transport::request(transport, request).await } // List all analytics modules that are supported by the given // VideoAnalyticsConfiguration. pub async fn get_supported_analytics_modules<T: transport::Transport>( transport: &T, request: &GetSupportedAnalyticsModules, ) -> Result<GetSupportedAnalyticsModulesResponse, transport::Error> { transport::request(transport, request).await } // Return the options for the supported analytics modules that specify an Option // attribute. pub async fn get_analytics_module_options<T: transport::Transport>( transport: &T, request: &GetAnalyticsModuleOptions, ) -> Result<GetAnalyticsModuleOptionsResponse, transport::Error> { transport::request(transport, request).await } // Add one or more analytics modules to an existing VideoAnalyticsConfiguration. // The available supported types can be retrieved via pub async fn create_analytics_modules<T: transport::Transport>( transport: &T, request: &CreateAnalyticsModules, ) -> Result<CreateAnalyticsModulesResponse, transport::Error> { transport::request(transport, request).await } // Remove one or more analytics modules from a VideoAnalyticsConfiguration // referenced by their names. pub async fn delete_analytics_modules<T: transport::Transport>( transport: &T, request: &DeleteAnalyticsModules, ) -> Result<DeleteAnalyticsModulesResponse, transport::Error> { transport::request(transport, request).await } // List the currently assigned set of analytics modules of a // VideoAnalyticsConfiguration. pub async fn get_analytics_modules<T: transport::Transport>( transport: &T, request: &GetAnalyticsModules, ) -> Result<GetAnalyticsModulesResponse, transport::Error> { transport::request(transport, request).await } // Modify the settings of one or more analytics modules of a // VideoAnalyticsConfiguration. The modules are referenced by their names. // It is allowed to pass only a subset to be modified. pub async fn modify_analytics_modules<T: transport::Transport>( transport: &T, request: &ModifyAnalyticsModules, ) -> Result<ModifyAnalyticsModulesResponse, transport::Error> { transport::request(transport, request).await } // List all rules that are supported by the given VideoAnalyticsConfiguration. // The result of this method may depend on the overall Video analytics // configuration of the device, // which is available via the current set of profiles. pub async fn get_supported_rules<T: transport::Transport>( transport: &T, request: &GetSupportedRules, ) -> Result<GetSupportedRulesResponse, transport::Error> { transport::request(transport, request).await } // Add one or more rules to an existing VideoAnalyticsConfiguration. // The available supported types can be retrieved via pub async fn create_rules<T: transport::Transport>( transport: &T, request: &CreateRules, ) -> Result<CreateRulesResponse, transport::Error> { transport::request(transport, request).await } // Remove one or more rules from a VideoAnalyticsConfiguration. pub async fn delete_rules<T: transport::Transport>( transport: &T, request: &DeleteRules, ) -> Result<DeleteRulesResponse, transport::Error> { transport::request(transport, request).await } // List the currently assigned set of rules of a VideoAnalyticsConfiguration. pub async fn get_rules<T: transport::Transport>( transport: &T, request: &GetRules, ) -> Result<GetRulesResponse, transport::Error> { transport::request(transport, request).await } // Return the options for the supported rules that specify an Option attribute. pub async fn get_rule_options<T: transport::Transport>( transport: &T, request: &GetRuleOptions, ) -> Result<GetRuleOptionsResponse, transport::Error> { transport::request(transport, request).await } // Modify one or more rules of a VideoAnalyticsConfiguration. The rules are // referenced by their names. pub async fn modify_rules<T: transport::Transport>( transport: &T, request: &ModifyRules, ) -> Result<ModifyRulesResponse, transport::Error> { transport::request(transport, request).await }
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
false
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/accessrules/src/lib.rs
wsdl_rs/accessrules/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use types as pt; use validate::Validate; use yaserde_derive::{YaDeserialize, YaSerialize}; // The service capabilities reflect optional functionality of a service. The // information is static // and does not change during device operation. The following capabilities are // available: #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tar", namespace = "tar: http://www.onvif.org/ver10/accessrules/wsdl" )] pub struct ServiceCapabilities { // The maximum number of entries returned by a single Get<Entity>List or // Get<Entity> // request. The device shall never return more than this number of entities // in a single // response. #[yaserde(attribute, rename = "MaxLimit")] pub max_limit: String, // Indicates the maximum number of access profiles supported by the device. #[yaserde(attribute, rename = "MaxAccessProfiles")] pub max_access_profiles: String, // Indicates the maximum number of access policies per access profile // supported by the device. #[yaserde(attribute, rename = "MaxAccessPoliciesPerAccessProfile")] pub max_access_policies_per_access_profile: String, // Indicates whether or not several access policies can refer to the same // access point in an // access profile. #[yaserde(attribute, rename = "MultipleSchedulesPerAccessPointSupported")] pub multiple_schedules_per_access_point_supported: bool, // Indicates that the client is allowed to supply the token when creating // access profiles. To // enable the use of the command SetAccessProfile, the value must be set to // true. #[yaserde(attribute, rename = "ClientSuppliedTokenSupported")] pub client_supplied_token_supported: Option<bool>, } impl Validate for ServiceCapabilities {} // pub type Capabilities = ServiceCapabilities; // The access policy is an association of an access point and a schedule. It // defines when an access // point can be accessed using an access profile which contains this access // policy. If an access // profile contains several access policies specifying different schedules for // the same access // point will result in a union of the schedules. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tar", namespace = "tar: http://www.onvif.org/ver10/accessrules/wsdl" )] pub struct AccessPolicy { // Reference to the schedule used by the access policy. #[yaserde(prefix = "tar", rename = "ScheduleToken")] pub schedule_token: pt::ReferenceToken, // Reference to the entity used by the rule engine, the entity type may be // specified by the // optional EntityType field explained below but is typically an access // point. #[yaserde(prefix = "tar", rename = "Entity")] pub entity: pt::ReferenceToken, // Optional entity type; if missing, an access point type as defined by the // ONVIF Access // Control Service Specification should be assumed. This can also be // represented by the // QName value “tac:AccessPoint” where tac is the namespace of ONVIF // Access Control // Service Specification. This field is provided for future extensions; it // will allow an // access policy being extended to cover entity types other than access // points as well. #[yaserde(prefix = "tar", rename = "EntityType")] pub entity_type: Option<String>, #[yaserde(prefix = "tar", rename = "Extension")] pub extension: Option<AccessPolicyExtension>, } impl Validate for AccessPolicy {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tar", namespace = "tar: http://www.onvif.org/ver10/accessrules/wsdl" )] pub struct AccessPolicyExtension {} impl Validate for AccessPolicyExtension {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tar", namespace = "tar: http://www.onvif.org/ver10/accessrules/wsdl" )] pub struct AccessProfileInfo { // A user readable name. It shall be up to 64 characters. #[yaserde(prefix = "tar", rename = "Name")] pub name: pt::Name, // User readable description for the access profile. It shall be up // to 1024 characters. #[yaserde(prefix = "tar", rename = "Description")] pub description: Option<pt::Description>, pub base: pt::DataEntity, } impl Validate for AccessProfileInfo {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tar", namespace = "tar: http://www.onvif.org/ver10/accessrules/wsdl" )] pub struct AccessProfile { // A list of access policy structures, where each access policy // defines during which schedule an access point can be accessed. #[yaserde(prefix = "tar", rename = "AccessPolicy")] pub access_policy: Vec<AccessPolicy>, #[yaserde(prefix = "tar", rename = "Extension")] pub extension: Option<AccessProfileExtension>, pub base: AccessProfileInfo, } impl Validate for AccessProfile {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tar", namespace = "tar: http://www.onvif.org/ver10/accessrules/wsdl" )] pub struct AccessProfileExtension {} impl Validate for AccessProfileExtension {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tar", namespace = "tar: http://www.onvif.org/ver10/accessrules/wsdl" )] pub struct GetServiceCapabilities {} impl Validate for GetServiceCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tar", namespace = "tar: http://www.onvif.org/ver10/accessrules/wsdl" )] pub struct GetServiceCapabilitiesResponse { // The capability response message contains the requested access rules // service capabilities using a hierarchical XML capability structure. #[yaserde(prefix = "tar", rename = "Capabilities")] pub capabilities: ServiceCapabilities, } impl Validate for GetServiceCapabilitiesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tar", namespace = "tar: http://www.onvif.org/ver10/accessrules/wsdl" )] pub struct GetAccessProfileInfo { // Tokens of AccessProfileInfo items to get. #[yaserde(prefix = "tar", rename = "Token")] pub token: Vec<pt::ReferenceToken>, } impl Validate for GetAccessProfileInfo {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tar", namespace = "tar: http://www.onvif.org/ver10/accessrules/wsdl" )] pub struct GetAccessProfileInfoResponse { // List of AccessProfileInfo items. #[yaserde(prefix = "tar", rename = "AccessProfileInfo")] pub access_profile_info: Vec<AccessProfileInfo>, } impl Validate for GetAccessProfileInfoResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tar", namespace = "tar: http://www.onvif.org/ver10/accessrules/wsdl" )] pub struct GetAccessProfileInfoList { // Maximum number of entries to return. If not specified, less than one // or higher than what the device supports, the number of items is // determined by the // device. #[yaserde(prefix = "tar", rename = "Limit")] pub limit: Option<i32>, // Start returning entries from this start reference. If not specified, // entries shall start from the beginning of the dataset. #[yaserde(prefix = "tar", rename = "StartReference")] pub start_reference: Option<String>, } impl Validate for GetAccessProfileInfoList {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tar", namespace = "tar: http://www.onvif.org/ver10/accessrules/wsdl" )] pub struct GetAccessProfileInfoListResponse { // StartReference to use in next call to get the following items. If // absent, no more items to get. #[yaserde(prefix = "tar", rename = "NextStartReference")] pub next_start_reference: Option<String>, // List of AccessProfileInfo items. #[yaserde(prefix = "tar", rename = "AccessProfileInfo")] pub access_profile_info: Vec<AccessProfileInfo>, } impl Validate for GetAccessProfileInfoListResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tar", namespace = "tar: http://www.onvif.org/ver10/accessrules/wsdl" )] pub struct GetAccessProfiles { // Tokens of AccessProfile items to get. #[yaserde(prefix = "tar", rename = "Token")] pub token: Vec<pt::ReferenceToken>, } impl Validate for GetAccessProfiles {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tar", namespace = "tar: http://www.onvif.org/ver10/accessrules/wsdl" )] pub struct GetAccessProfilesResponse { // List of Access Profile items. #[yaserde(prefix = "tar", rename = "AccessProfile")] pub access_profile: Vec<AccessProfile>, } impl Validate for GetAccessProfilesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tar", namespace = "tar: http://www.onvif.org/ver10/accessrules/wsdl" )] pub struct GetAccessProfileList { // Maximum number of entries to return. If not specified, less than one // or higher than what the device supports, the number of items is // determined by the // device. #[yaserde(prefix = "tar", rename = "Limit")] pub limit: Option<i32>, // Start returning entries from this start reference. If not specified, // entries shall start from the beginning of the dataset. #[yaserde(prefix = "tar", rename = "StartReference")] pub start_reference: Option<String>, } impl Validate for GetAccessProfileList {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tar", namespace = "tar: http://www.onvif.org/ver10/accessrules/wsdl" )] pub struct GetAccessProfileListResponse { // StartReference to use in next call to get the following items. If // absent, no more items to get. #[yaserde(prefix = "tar", rename = "NextStartReference")] pub next_start_reference: Option<String>, // List of Access Profile items. #[yaserde(prefix = "tar", rename = "AccessProfile")] pub access_profile: Vec<AccessProfile>, } impl Validate for GetAccessProfileListResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tar", namespace = "tar: http://www.onvif.org/ver10/accessrules/wsdl" )] pub struct CreateAccessProfile { // The AccessProfile to create. #[yaserde(prefix = "tar", rename = "AccessProfile")] pub access_profile: AccessProfile, } impl Validate for CreateAccessProfile {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tar", namespace = "tar: http://www.onvif.org/ver10/accessrules/wsdl" )] pub struct CreateAccessProfileResponse { // The Token of created AccessProfile. #[yaserde(prefix = "tar", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for CreateAccessProfileResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tar", namespace = "tar: http://www.onvif.org/ver10/accessrules/wsdl" )] pub struct ModifyAccessProfile { // The details of Access Profile #[yaserde(prefix = "tar", rename = "AccessProfile")] pub access_profile: AccessProfile, } impl Validate for ModifyAccessProfile {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tar", namespace = "tar: http://www.onvif.org/ver10/accessrules/wsdl" )] pub struct ModifyAccessProfileResponse {} impl Validate for ModifyAccessProfileResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tar", namespace = "tar: http://www.onvif.org/ver10/accessrules/wsdl" )] pub struct SetAccessProfile { // The AccessProfile item to create or modify #[yaserde(prefix = "tar", rename = "AccessProfile")] pub access_profile: AccessProfile, } impl Validate for SetAccessProfile {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tar", namespace = "tar: http://www.onvif.org/ver10/accessrules/wsdl" )] pub struct SetAccessProfileResponse {} impl Validate for SetAccessProfileResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tar", namespace = "tar: http://www.onvif.org/ver10/accessrules/wsdl" )] pub struct DeleteAccessProfile { // The token of the access profile to delete. #[yaserde(prefix = "tar", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for DeleteAccessProfile {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tar", namespace = "tar: http://www.onvif.org/ver10/accessrules/wsdl" )] pub struct DeleteAccessProfileResponse {} impl Validate for DeleteAccessProfileResponse {} // This operation returns the capabilities of the access rules service. pub async fn get_service_capabilities<T: transport::Transport>( transport: &T, request: &GetServiceCapabilities, ) -> Result<GetServiceCapabilitiesResponse, transport::Error> { transport::request(transport, request).await } // This operation requests a list of AccessProfileInfo items matching the given // tokens. The device shall // ignore tokens it cannot resolve and shall return an empty list if there are // no items matching the // specified tokens. The device shall not return a fault in this case. // If the number of requested items is greater than MaxLimit, a TooManyItems // fault shall be returned. pub async fn get_access_profile_info<T: transport::Transport>( transport: &T, request: &GetAccessProfileInfo, ) -> Result<GetAccessProfileInfoResponse, transport::Error> { transport::request(transport, request).await } // This operation requests a list of all of AccessProfileInfo items provided by // the device. // A call to this method shall return a StartReference when not all data is // returned and more data is // available. The reference shall be valid for retrieving the next set of data. // The number of items returned shall not be greater than the Limit parameter. pub async fn get_access_profile_info_list<T: transport::Transport>( transport: &T, request: &GetAccessProfileInfoList, ) -> Result<GetAccessProfileInfoListResponse, transport::Error> { transport::request(transport, request).await } // This operation returns the specified access profile item matching the given // tokens. // The device shall ignore tokens it cannot resolve and shall return an empty // list if there are no items // matching specified tokens. The device shall not return a fault in this case. // If the number of requested items is greater than MaxLimit, a TooManyItems // fault shall be returned. pub async fn get_access_profiles<T: transport::Transport>( transport: &T, request: &GetAccessProfiles, ) -> Result<GetAccessProfilesResponse, transport::Error> { transport::request(transport, request).await } // This operation requests a list of all of access profile items provided by the // device. // A call to this method shall return a StartReference when not all data is // returned and more data is // available. The reference shall be valid for retrieving the next set of data. // The number of items returned shall not be greater than the Limit parameter. pub async fn get_access_profile_list<T: transport::Transport>( transport: &T, request: &GetAccessProfileList, ) -> Result<GetAccessProfileListResponse, transport::Error> { transport::request(transport, request).await } // This operation creates the specified access profile in the device. The token // field of the access profile shall be // empty, the service shall allocate a token for the access profile. The // allocated token shall be returned // in the response. If the client sends any value in the token field, the device // shall return InvalidArgVal // as generic fault code. // In an access profile, if several access policies specifying different // schedules for the same access // point will result in a union of the schedules. pub async fn create_access_profile<T: transport::Transport>( transport: &T, request: &CreateAccessProfile, ) -> Result<CreateAccessProfileResponse, transport::Error> { transport::request(transport, request).await } // This operation will modify the access profile for the specified access // profile token. The token of the // access profile to modify is specified in the token field of the AccessProile // structure and shall not // be empty. All other fields in the structure shall overwrite the fields in the // specified access profile. // If several access policies specifying different schedules for the same access // point will result in a // union of the schedules. // If the device could not store the access profile information then a fault // will be generated. pub async fn modify_access_profile<T: transport::Transport>( transport: &T, request: &ModifyAccessProfile, ) -> Result<ModifyAccessProfileResponse, transport::Error> { transport::request(transport, request).await } // This operation will synchronize an access profile in a client with the // device. // If an access profile with the specified token does not exist in the device, // the access profile is // created. If an access profile with the specified token exists, then the // access profile is modified. // A call to this method takes an access profile structure as input parameter. // The token field of the // access profile must not be empty. // A device that signals support for the ClientSuppliedTokenSupported capability // shall implement this command. pub async fn set_access_profile<T: transport::Transport>( transport: &T, request: &SetAccessProfile, ) -> Result<SetAccessProfileResponse, transport::Error> { transport::request(transport, request).await } // This operation will delete the specified access profile. // If the access profile is deleted, all access policies associated to the // access profile will also be // deleted. // If it is associated with one or more entities some devices may not be able to // delete the access profile, // and consequently a ReferenceInUse fault shall be generated. pub async fn delete_access_profile<T: transport::Transport>( transport: &T, request: &DeleteAccessProfile, ) -> Result<DeleteAccessProfileResponse, transport::Error> { transport::request(transport, request).await }
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
false
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/credential/src/lib.rs
wsdl_rs/credential/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use std::str::FromStr; use types as pt; use validate::Validate; use xsd_macro_utils::*; use xsd_types::types as xs; use yaserde_derive::{YaDeserialize, YaSerialize}; // The service capabilities reflect optional functionality of a service. The // information is static // and does not change during device operation. The following capabilities are // available: #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct ServiceCapabilities { // A list of identifier types that the device supports. Identifiers types // starting with // the prefix pt: are reserved to define ONVIF specific types. For custom // defined identifier types // shall all share the "pt:<Name>" syntax. #[yaserde(prefix = "tcr", rename = "SupportedIdentifierType")] pub supported_identifier_type: Vec<pt::Name>, #[yaserde(prefix = "tcr", rename = "Extension")] pub extension: Option<ServiceCapabilitiesExtension>, // The maximum number of entries returned by a single Get<Entity>List or // Get<Entity> // request. The device shall never return more than this number of entities // in a single response. #[yaserde(attribute, rename = "MaxLimit")] pub max_limit: pt::PositiveInteger, // Indicates that the device supports credential validity. #[yaserde(attribute, rename = "CredentialValiditySupported")] pub credential_validity_supported: bool, // Indicates that the device supports validity on the association between a // credential and an // access profile. #[yaserde(attribute, rename = "CredentialAccessProfileValiditySupported")] pub credential_access_profile_validity_supported: bool, // Indicates that the device supports both date and time value for validity. // If set to false, // then the time value is ignored. #[yaserde(attribute, rename = "ValiditySupportsTimeValue")] pub validity_supports_time_value: bool, // The maximum number of credential supported by the device. #[yaserde(attribute, rename = "MaxCredentials")] pub max_credentials: pt::PositiveInteger, // The maximum number of access profiles for a credential. #[yaserde(attribute, rename = "MaxAccessProfilesPerCredential")] pub max_access_profiles_per_credential: pt::PositiveInteger, // Indicates the device supports resetting of anti-passback violations and // notifying on // anti-passback violations. #[yaserde(attribute, rename = "ResetAntipassbackSupported")] pub reset_antipassback_supported: bool, // Indicates that the client is allowed to supply the token when creating // credentials. // To enable the use of the command SetCredential, the value must be set to // true. #[yaserde(attribute, rename = "ClientSuppliedTokenSupported")] pub client_supplied_token_supported: Option<bool>, // The default time period that the credential will temporary be suspended // (e.g. by using // the wrong PIN a predetermined number of times). // The time period is defined as an [ISO 8601] duration string (e.g. // “PT5M”). #[yaserde(attribute, rename = "DefaultCredentialSuspensionDuration")] pub default_credential_suspension_duration: Option<xs::Duration>, } impl Validate for ServiceCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct ServiceCapabilitiesExtension { // A list of exemptions that the device supports. Supported exemptions // starting with the // prefix pt: are reserved to define ONVIF specific exemption types and // these reserved // exemption types shall all share "pt:<Name>" syntax. #[yaserde(prefix = "tcr", rename = "SupportedExemptionType")] pub supported_exemption_type: Vec<pt::Name>, } impl Validate for ServiceCapabilitiesExtension {} // pub type Capabilities = ServiceCapabilities; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct CredentialInfo { // User readable description for the credential. It shall be up to 1024 // characters. #[yaserde(prefix = "tcr", rename = "Description")] pub description: Option<pt::Description>, // An external reference to a person holding this credential. The // reference is a username or used ID in an external system, such as a // directory // service. #[yaserde(prefix = "tcr", rename = "CredentialHolderReference")] pub credential_holder_reference: credential_info::CredentialHolderReferenceType, // The start date/time validity of the credential. If the // ValiditySupportsTimeValue capability is set to false, then only date is // supported (time is ignored). #[yaserde(prefix = "tcr", rename = "ValidFrom")] pub valid_from: Option<xs::DateTime>, // The expiration date/time validity of the credential. If the // ValiditySupportsTimeValue capability is set to false, then only date is // supported (time is ignored). #[yaserde(prefix = "tcr", rename = "ValidTo")] pub valid_to: Option<xs::DateTime>, pub base: pt::DataEntity, } impl Validate for CredentialInfo {} pub mod credential_info { use super::*; #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct CredentialHolderReferenceType(pub String); impl Validate for CredentialHolderReferenceType { fn validate(&self) -> Result<(), String> { if self.0.len() > "64".parse().unwrap() { return Err(format!("MaxLength validation error. \nExpected: 0 length <= 64 \nActual: 0 length == {}", self.0.len())); } if self.0.len() < "0".parse().unwrap() { return Err(format!("MinLength validation error. \nExpected: 0 length >= 0 \nActual: 0 length == {}", self.0.len())); } Ok(()) } } } #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct Credential { // A list of credential identifier structures. At least one // credential identifier is required. Maximum one credential identifier // structure // per type is allowed. #[yaserde(prefix = "tcr", rename = "CredentialIdentifier")] pub credential_identifier: Vec<CredentialIdentifier>, // A list of credential access profile structures. #[yaserde(prefix = "tcr", rename = "CredentialAccessProfile")] pub credential_access_profile: Vec<CredentialAccessProfile>, // A boolean indicating that the credential holder needs extra time to get // through the door. // ExtendedReleaseTime will be added to ReleaseTime, and ExtendedOpenTime // will be added to OpenTime #[yaserde(prefix = "tcr", rename = "ExtendedGrantTime")] pub extended_grant_time: Option<bool>, // A list of credential attributes as name value pairs. Key names // starting with the prefix pt: are reserved to define PACS specific // attributes // following the "pt:<Name>" syntax. #[yaserde(prefix = "tcr", rename = "Attribute")] pub attribute: Vec<pt::Attribute>, #[yaserde(prefix = "tcr", rename = "Extension")] pub extension: Option<CredentialExtension>, pub base: CredentialInfo, } impl Validate for Credential {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct CredentialExtension {} impl Validate for CredentialExtension {} // A credential identifier is a card number, unique card information, PIN or // biometric information such as fingerprint, iris, vein, face recognition, that // can be validated // in an access point. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct CredentialIdentifier { // Contains the details of the credential identifier type. Is of type // CredentialIdentifierType. #[yaserde(prefix = "tcr", rename = "Type")] pub _type: CredentialIdentifierType, // If set to true, this credential identifier is not considered for // authentication. For example if the access point requests Card plus PIN, // and the credential // identifier of type PIN is exempted from authentication, then the access // point will not prompt // for the PIN. #[yaserde(prefix = "tcr", rename = "ExemptedFromAuthentication")] pub exempted_from_authentication: bool, // The value of the identifier in hexadecimal representation. #[yaserde(prefix = "tcr", rename = "Value")] pub value: String, } impl Validate for CredentialIdentifier {} // Specifies the name of credential identifier type and its format for the // credential // value. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct CredentialIdentifierType { // The name of the credential identifier type, such as pt:Card, pt:PIN, // etc. #[yaserde(prefix = "tcr", rename = "Name")] pub name: pt::Name, // Specifies the format of the credential value for the specified identifier // type name. #[yaserde(prefix = "tcr", rename = "FormatType")] pub format_type: String, } impl Validate for CredentialIdentifierType {} // The association between a credential and an access profile. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct CredentialAccessProfile { // The reference token of the associated access profile. #[yaserde(prefix = "tcr", rename = "AccessProfileToken")] pub access_profile_token: pt::ReferenceToken, // The start date/time of the validity for the association between the // credential and the access profile. If the ValiditySupportsTimeValue // capability is set to // false, then only date is supported (time is ignored). #[yaserde(prefix = "tcr", rename = "ValidFrom")] pub valid_from: Option<xs::DateTime>, // The end date/time of the validity for the association between the // credential and the access profile. If the ValiditySupportsTimeValue // capability is set to // false, then only date is supported (time is ignored). #[yaserde(prefix = "tcr", rename = "ValidTo")] pub valid_to: Option<xs::DateTime>, } impl Validate for CredentialAccessProfile {} // The CredentialState structure contains information about the state of the // credential and // optionally the reason of why the credential was disabled. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct CredentialState { // True if the credential is enabled or false if the credential is // disabled. #[yaserde(prefix = "tcr", rename = "Enabled")] pub enabled: bool, // Predefined ONVIF reasons as mentioned in the section 5.4.2.7 // of credential service specification document. For any other reason, free // text can be used. #[yaserde(prefix = "tcr", rename = "Reason")] pub reason: Option<pt::Name>, // A structure indicating the anti-passback state. This field shall be // supported if the ResetAntipassbackSupported capability is set to true. #[yaserde(prefix = "tcr", rename = "AntipassbackState")] pub antipassback_state: Option<AntipassbackState>, #[yaserde(prefix = "tcr", rename = "Extension")] pub extension: Option<CredentialStateExtension>, } impl Validate for CredentialState {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct CredentialStateExtension {} impl Validate for CredentialStateExtension {} // A structure containing anti-passback related state information. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct AntipassbackState { // Indicates if anti-passback is violated for the credential. #[yaserde(prefix = "tcr", rename = "AntipassbackViolated")] pub antipassback_violated: bool, } impl Validate for AntipassbackState {} // Contains information about a format type. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct CredentialIdentifierFormatTypeInfo { // A format type supported by the device. A list of supported format types // is // provided in [ISO 16484-5:2014-09 Annex P]. The BACnet type "CUSTOM" is // not used in this // specification. Instead device manufacturers can define their own format // types. #[yaserde(prefix = "tcr", rename = "FormatType")] pub format_type: String, // User readable description of the credential identifier format type. It // shall be up to 1024 characters. For custom types, it is recommended to // describe how the // octet string is encoded (following the structure in column Authentication // Factor Value // Encoding of [ISO 16484-5:2014-09 Annex P]). #[yaserde(prefix = "tcr", rename = "Description")] pub description: pt::Description, #[yaserde(prefix = "tcr", rename = "Extension")] pub extension: Option<CredentialIdentifierFormatTypeInfoExtension>, } impl Validate for CredentialIdentifierFormatTypeInfo {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct CredentialIdentifierFormatTypeInfoExtension {} impl Validate for CredentialIdentifierFormatTypeInfoExtension {} // Contains information about a format type. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct CredentialData { // A format type supported by the device. A list of supported format types // is // provided in [ISO 16484-5:2014-09 Annex P]. The BACnet type "CUSTOM" is // not used in this // specification. Instead device manufacturers can define their own format // types. #[yaserde(prefix = "tcr", rename = "Credential")] pub credential: Credential, // User readable description of the credential identifier format type. It // shall be up to 1024 characters. For custom types, it is recommended to // describe how the // octet string is encoded (following the structure in column Authentication // Factor Value // Encoding of [ISO 16484-5:2014-09 Annex P]). #[yaserde(prefix = "tcr", rename = "CredentialState")] pub credential_state: CredentialState, #[yaserde(prefix = "tcr", rename = "Extension")] pub extension: Option<CredentialDataExtension>, } impl Validate for CredentialData {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct CredentialDataExtension {} impl Validate for CredentialDataExtension {} // Contains information about a format type. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct FaultResponse { // A format type supported by the device. A list of supported format types // is // provided in [ISO 16484-5:2014-09 Annex P]. The BACnet type "CUSTOM" is // not used in this // specification. Instead device manufacturers can define their own format // types. #[yaserde(prefix = "tcr", rename = "Token")] pub token: pt::ReferenceToken, // User readable description of the credential identifier format type. It // shall be up to 1024 characters. For custom types, it is recommended to // describe how the // octet string is encoded (following the structure in column Authentication // Factor Value // Encoding of [ISO 16484-5:2014-09 Annex P]). #[yaserde(prefix = "tcr", rename = "Fault")] pub fault: String, #[yaserde(prefix = "tcr", rename = "Extension")] pub extension: Option<FaultResponseExtension>, } impl Validate for FaultResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct FaultResponseExtension {} impl Validate for FaultResponseExtension {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct GetServiceCapabilities {} impl Validate for GetServiceCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct GetServiceCapabilitiesResponse { // The capability response message contains the requested credential // service capabilities using a hierarchical XML capability structure. #[yaserde(prefix = "tcr", rename = "Capabilities")] pub capabilities: ServiceCapabilities, } impl Validate for GetServiceCapabilitiesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct GetSupportedFormatTypes { // Name of the credential identifier type #[yaserde(prefix = "tcr", rename = "CredentialIdentifierTypeName")] pub credential_identifier_type_name: String, } impl Validate for GetSupportedFormatTypes {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct GetSupportedFormatTypesResponse { // Identifier format type #[yaserde(prefix = "tcr", rename = "FormatTypeInfo")] pub format_type_info: Vec<CredentialIdentifierFormatTypeInfo>, } impl Validate for GetSupportedFormatTypesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct GetCredentialInfo { // Tokens of CredentialInfo items to get. #[yaserde(prefix = "tcr", rename = "Token")] pub token: Vec<pt::ReferenceToken>, } impl Validate for GetCredentialInfo {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct GetCredentialInfoResponse { // List of CredentialInfo items. #[yaserde(prefix = "tcr", rename = "CredentialInfo")] pub credential_info: Vec<CredentialInfo>, } impl Validate for GetCredentialInfoResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct GetCredentialInfoList { // Maximum number of entries to return. If not specified, less than one // or higher than what the device supports, the number of items is // determined by the // device. #[yaserde(prefix = "tcr", rename = "Limit")] pub limit: Option<i32>, // Start returning entries from this start reference. If not specified, // entries shall start from the beginning of the dataset. #[yaserde(prefix = "tcr", rename = "StartReference")] pub start_reference: Option<String>, } impl Validate for GetCredentialInfoList {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct GetCredentialInfoListResponse { // StartReference to use in next call to get the following items. If // absent, no more items to get. #[yaserde(prefix = "tcr", rename = "NextStartReference")] pub next_start_reference: Option<String>, // List of CredentialInfo items. #[yaserde(prefix = "tcr", rename = "CredentialInfo")] pub credential_info: Vec<CredentialInfo>, } impl Validate for GetCredentialInfoListResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct GetCredentials { // Token of Credentials to get #[yaserde(prefix = "tcr", rename = "Token")] pub token: Vec<pt::ReferenceToken>, } impl Validate for GetCredentials {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct GetCredentialsResponse { // List of Credential items. #[yaserde(prefix = "tcr", rename = "Credential")] pub credential: Vec<Credential>, } impl Validate for GetCredentialsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct GetCredentialList { // Maximum number of entries to return. If not specified, less than one // or higher than what the device supports, the number of items is // determined by the // device. #[yaserde(prefix = "tcr", rename = "Limit")] pub limit: Option<i32>, // Start returning entries from this start reference. If not specified, // entries shall start from the beginning of the dataset. #[yaserde(prefix = "tcr", rename = "StartReference")] pub start_reference: Option<String>, } impl Validate for GetCredentialList {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct GetCredentialListResponse { // StartReference to use in next call to get the following items. If // absent, no more items to get. #[yaserde(prefix = "tcr", rename = "NextStartReference")] pub next_start_reference: Option<String>, // List of Credential items. #[yaserde(prefix = "tcr", rename = "Credential")] pub credential: Vec<Credential>, } impl Validate for GetCredentialListResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct CreateCredential { // The credential to create. #[yaserde(prefix = "tcr", rename = "Credential")] pub credential: Credential, // The state of the credential. #[yaserde(prefix = "tcr", rename = "State")] pub state: CredentialState, } impl Validate for CreateCredential {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct CreateCredentialResponse { // The token of the created credential #[yaserde(prefix = "tcr", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for CreateCredentialResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct ModifyCredential { // Details of the credential. #[yaserde(prefix = "tcr", rename = "Credential")] pub credential: Credential, } impl Validate for ModifyCredential {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct ModifyCredentialResponse {} impl Validate for ModifyCredentialResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct SetCredential { // Details of the credential. #[yaserde(prefix = "tcr", rename = "CredentialData")] pub credential_data: CredentialData, } impl Validate for SetCredential {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct SetCredentialResponse {} impl Validate for SetCredentialResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct DeleteCredential { // The token of the credential to delete. #[yaserde(prefix = "tcr", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for DeleteCredential {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct DeleteCredentialResponse {} impl Validate for DeleteCredentialResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct GetCredentialState { // Token of Credential #[yaserde(prefix = "tcr", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for GetCredentialState {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct GetCredentialStateResponse { // State of the credential. #[yaserde(prefix = "tcr", rename = "State")] pub state: CredentialState, } impl Validate for GetCredentialStateResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct EnableCredential { // The token of the credential #[yaserde(prefix = "tcr", rename = "Token")] pub token: pt::ReferenceToken, // Reason for enabling the credential. #[yaserde(prefix = "tcr", rename = "Reason")] pub reason: Option<pt::Name>, } impl Validate for EnableCredential {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct EnableCredentialResponse {} impl Validate for EnableCredentialResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct DisableCredential { // Token of the Credential #[yaserde(prefix = "tcr", rename = "Token")] pub token: pt::ReferenceToken, // Reason for disabling the credential #[yaserde(prefix = "tcr", rename = "Reason")] pub reason: Option<pt::Name>, } impl Validate for DisableCredential {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct DisableCredentialResponse {} impl Validate for DisableCredentialResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct ResetAntipassbackViolation { // Token of the Credential #[yaserde(prefix = "tcr", rename = "CredentialToken")] pub credential_token: pt::ReferenceToken, } impl Validate for ResetAntipassbackViolation {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct ResetAntipassbackViolationResponse {} impl Validate for ResetAntipassbackViolationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct GetCredentialIdentifiers { // Token of the Credential #[yaserde(prefix = "tcr", rename = "CredentialToken")] pub credential_token: pt::ReferenceToken, } impl Validate for GetCredentialIdentifiers {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct GetCredentialIdentifiersResponse { // Identifier of the credential #[yaserde(prefix = "tcr", rename = "CredentialIdentifier")] pub credential_identifier: Vec<CredentialIdentifier>, } impl Validate for GetCredentialIdentifiersResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct SetCredentialIdentifier { // Token of the Credential #[yaserde(prefix = "tcr", rename = "CredentialToken")] pub credential_token: pt::ReferenceToken, // Identifier of the credential #[yaserde(prefix = "tcr", rename = "CredentialIdentifier")] pub credential_identifier: CredentialIdentifier, } impl Validate for SetCredentialIdentifier {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct SetCredentialIdentifierResponse {} impl Validate for SetCredentialIdentifierResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct DeleteCredentialIdentifier { // Token of the Credential #[yaserde(prefix = "tcr", rename = "CredentialToken")] pub credential_token: pt::ReferenceToken, // Identifier type name of a credential #[yaserde(prefix = "tcr", rename = "CredentialIdentifierTypeName")] pub credential_identifier_type_name: pt::Name, } impl Validate for DeleteCredentialIdentifier {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct DeleteCredentialIdentifierResponse {} impl Validate for DeleteCredentialIdentifierResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct GetCredentialAccessProfiles { // Token of the Credential #[yaserde(prefix = "tcr", rename = "CredentialToken")] pub credential_token: pt::ReferenceToken, } impl Validate for GetCredentialAccessProfiles {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct GetCredentialAccessProfilesResponse { // Access Profiles of the credential #[yaserde(prefix = "tcr", rename = "CredentialAccessProfile")] pub credential_access_profile: Vec<CredentialAccessProfile>, } impl Validate for GetCredentialAccessProfilesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct SetCredentialAccessProfiles { // Token of the Credential #[yaserde(prefix = "tcr", rename = "CredentialToken")] pub credential_token: pt::ReferenceToken, // Access Profiles of the credential #[yaserde(prefix = "tcr", rename = "CredentialAccessProfile")] pub credential_access_profile: Vec<CredentialAccessProfile>, } impl Validate for SetCredentialAccessProfiles {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tcr", namespace = "tcr: http://www.onvif.org/ver10/credential/wsdl" )] pub struct SetCredentialAccessProfilesResponse {} impl Validate for SetCredentialAccessProfilesResponse {}
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
true
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/b_2/src/lib.rs
wsdl_rs/b_2/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use t_1 as wstop; use validate::Validate; use ws_addr as wsa; use xsd_macro_utils::*; use xsd_types::types as xs; use yaserde_derive::{YaDeserialize, YaSerialize}; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct QueryExpressionType { #[yaserde(attribute, rename = "Dialect")] pub dialect: String, } impl Validate for QueryExpressionType {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct TopicExpressionType { #[yaserde(attribute, rename = "Dialect")] pub dialect: String, #[yaserde(text)] pub inner_text: String, } impl Validate for TopicExpressionType {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct FilterType { #[yaserde(prefix = "wsnt", rename = "TopicExpression")] pub topic_expression: Option<TopicExpressionType>, } impl Validate for FilterType {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct SubscriptionPolicyType {} impl Validate for SubscriptionPolicyType {} pub type TopicExpression = TopicExpressionType; // pub type FixedTopicSet = bool; // pub type TopicExpressionDialect = String; // TODO: replace FixedTopicSet and TopicExpressionDialect with actual types generated from .xsd #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] pub struct FixedTopicSet {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] pub struct TopicExpressionDialect {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct NotificationProducerRP { #[yaserde(prefix = "wsnt", rename = "TopicExpression")] pub topic_expression: Vec<TopicExpression>, #[yaserde(prefix = "wsnt", rename = "FixedTopicSet")] pub fixed_topic_set: FixedTopicSet, #[yaserde(prefix = "wsnt", rename = "TopicExpressionDialect")] pub topic_expression_dialect: Vec<TopicExpressionDialect>, #[yaserde(prefix = "wstop", rename = "TopicSet")] pub topic_set: wstop::TopicSet, } impl Validate for NotificationProducerRP {} pub type ConsumerReference = wsa::EndpointReferenceType; pub type Filter = FilterType; pub type SubscriptionPolicy = SubscriptionPolicyType; pub type CreationTime = xs::DateTime; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct SubscriptionManagerRP { #[yaserde(prefix = "wsnt", rename = "ConsumerReference")] pub consumer_reference: ConsumerReference, #[yaserde(prefix = "wsnt", rename = "Filter")] pub filter: Filter, #[yaserde(prefix = "wsnt", rename = "SubscriptionPolicy")] pub subscription_policy: SubscriptionPolicy, #[yaserde(prefix = "wsnt", rename = "CreationTime")] pub creation_time: CreationTime, } impl Validate for SubscriptionManagerRP {} pub type SubscriptionReference = wsa::EndpointReferenceType; pub type Topic = TopicExpressionType; pub type ProducerReference = wsa::EndpointReferenceType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct NotificationMessageHolderType { #[yaserde(prefix = "wsnt", rename = "SubscriptionReference")] pub subscription_reference: SubscriptionReference, #[yaserde(prefix = "wsnt", rename = "Topic")] pub topic: Topic, #[yaserde(prefix = "wsnt", rename = "ProducerReference")] pub producer_reference: ProducerReference, #[yaserde(prefix = "wsnt", rename = "Message")] pub message: notification_message_holder_type::MessageType, } impl Validate for NotificationMessageHolderType {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct SimpleItemType { // Item name. #[yaserde(attribute, rename = "Name")] pub name: String, // Item value. The type is defined in the corresponding description. #[yaserde(attribute, rename = "Value")] pub value: String, } pub mod notification_message_holder_type { use super::*; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct DataType { #[yaserde(prefix = "tt", rename = "SimpleItem")] pub simple_item: Vec<SimpleItemType>, } #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct SourceType { #[yaserde(prefix = "tt", rename = "SimpleItem")] pub simple_item: Vec<SimpleItemType>, } #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct MessageTypeInner { #[yaserde(prefix = "tt", rename = "Source")] pub source: SourceType, #[yaserde(prefix = "tt", rename = "Data")] pub data: DataType, } #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct MessageType { #[yaserde(prefix = "tt", rename = "Message")] pub msg: MessageTypeInner, } impl Validate for MessageType {} } pub type NotificationMessage = NotificationMessageHolderType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct Notify { #[yaserde(prefix = "wsnt", rename = "NotificationMessage")] pub notification_message: Vec<NotificationMessage>, } impl Validate for Notify {} #[derive(PartialEq, Debug, UtilsUnionSerDe)] pub enum AbsoluteOrRelativeTimeType { DateTime(xs::DateTime), Duration(xs::Duration), __Unknown__(String), } impl Default for AbsoluteOrRelativeTimeType { fn default() -> AbsoluteOrRelativeTimeType { Self::__Unknown__("No valid variants".into()) } } impl Validate for AbsoluteOrRelativeTimeType {} pub type CurrentTime = xs::DateTime; pub type TerminationTime = xs::DateTime; pub type ProducerProperties = QueryExpressionType; pub type MessageContent = QueryExpressionType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct UseRaw {} impl Validate for UseRaw {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct Subscribe { #[yaserde(prefix = "wsnt", rename = "ConsumerReference")] pub consumer_reference: wsa::EndpointReferenceType, #[yaserde(prefix = "wsnt", rename = "Filter")] pub filter: FilterType, #[yaserde(prefix = "wsnt", rename = "InitialTerminationTime")] pub initial_termination_time: AbsoluteOrRelativeTimeType, #[yaserde(prefix = "wsnt", rename = "SubscriptionPolicy")] pub subscription_policy: subscribe::SubscriptionPolicyType, } impl Validate for Subscribe {} pub mod subscribe { use super::*; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct SubscriptionPolicyType {} impl Validate for SubscriptionPolicyType {} } #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct SubscribeResponse { #[yaserde(prefix = "wsnt", rename = "SubscriptionReference")] pub subscription_reference: wsa::EndpointReferenceType, #[yaserde(prefix = "wsnt", rename = "CurrentTime")] pub current_time: CurrentTime, #[yaserde(prefix = "wsnt", rename = "TerminationTime")] pub termination_time: TerminationTime, } impl Validate for SubscribeResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct GetCurrentMessage { #[yaserde(prefix = "wsnt", rename = "Topic")] pub topic: TopicExpressionType, } impl Validate for GetCurrentMessage {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct GetCurrentMessageResponse {} impl Validate for GetCurrentMessageResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct SubscribeCreationFailedFaultType {} impl Validate for SubscribeCreationFailedFaultType {} pub type SubscribeCreationFailedFault = SubscribeCreationFailedFaultType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct InvalidFilterFaultType { #[yaserde(prefix = "wsnt", rename = "UnknownFilter")] pub unknown_filter: Vec<String>, } impl Validate for InvalidFilterFaultType {} pub type InvalidFilterFault = InvalidFilterFaultType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct TopicExpressionDialectUnknownFaultType {} impl Validate for TopicExpressionDialectUnknownFaultType {} pub type TopicExpressionDialectUnknownFault = TopicExpressionDialectUnknownFaultType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct InvalidTopicExpressionFaultType {} impl Validate for InvalidTopicExpressionFaultType {} pub type InvalidTopicExpressionFault = InvalidTopicExpressionFaultType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct TopicNotSupportedFaultType {} impl Validate for TopicNotSupportedFaultType {} pub type TopicNotSupportedFault = TopicNotSupportedFaultType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct MultipleTopicsSpecifiedFaultType {} impl Validate for MultipleTopicsSpecifiedFaultType {} pub type MultipleTopicsSpecifiedFault = MultipleTopicsSpecifiedFaultType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct InvalidProducerPropertiesExpressionFaultType {} impl Validate for InvalidProducerPropertiesExpressionFaultType {} pub type InvalidProducerPropertiesExpressionFault = InvalidProducerPropertiesExpressionFaultType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct InvalidMessageContentExpressionFaultType {} impl Validate for InvalidMessageContentExpressionFaultType {} pub type InvalidMessageContentExpressionFault = InvalidMessageContentExpressionFaultType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct UnrecognizedPolicyRequestFaultType { #[yaserde(prefix = "wsnt", rename = "UnrecognizedPolicy")] pub unrecognized_policy: Vec<String>, } impl Validate for UnrecognizedPolicyRequestFaultType {} pub type UnrecognizedPolicyRequestFault = UnrecognizedPolicyRequestFaultType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct UnsupportedPolicyRequestFaultType { #[yaserde(prefix = "wsnt", rename = "UnsupportedPolicy")] pub unsupported_policy: Vec<String>, } impl Validate for UnsupportedPolicyRequestFaultType {} pub type UnsupportedPolicyRequestFault = UnsupportedPolicyRequestFaultType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct NotifyMessageNotSupportedFaultType {} impl Validate for NotifyMessageNotSupportedFaultType {} pub type NotifyMessageNotSupportedFault = NotifyMessageNotSupportedFaultType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct UnacceptableInitialTerminationTimeFaultType { #[yaserde(prefix = "wsnt", rename = "MinimumTime")] pub minimum_time: xs::DateTime, #[yaserde(prefix = "wsnt", rename = "MaximumTime")] pub maximum_time: Option<xs::DateTime>, } impl Validate for UnacceptableInitialTerminationTimeFaultType {} pub type UnacceptableInitialTerminationTimeFault = UnacceptableInitialTerminationTimeFaultType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct NoCurrentMessageOnTopicFaultType {} impl Validate for NoCurrentMessageOnTopicFaultType {} pub type NoCurrentMessageOnTopicFault = NoCurrentMessageOnTopicFaultType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct GetMessages { #[yaserde(prefix = "wsnt", rename = "MaximumNumber")] pub maximum_number: Option<xs::Integer>, } impl Validate for GetMessages {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct GetMessagesResponse { #[yaserde(prefix = "wsnt", rename = "NotificationMessage")] pub notification_message: Vec<NotificationMessage>, } impl Validate for GetMessagesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct DestroyPullPoint {} impl Validate for DestroyPullPoint {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct DestroyPullPointResponse {} impl Validate for DestroyPullPointResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct UnableToGetMessagesFaultType {} impl Validate for UnableToGetMessagesFaultType {} pub type UnableToGetMessagesFault = UnableToGetMessagesFaultType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct UnableToDestroyPullPointFaultType {} impl Validate for UnableToDestroyPullPointFaultType {} pub type UnableToDestroyPullPointFault = UnableToDestroyPullPointFaultType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct CreatePullPoint {} impl Validate for CreatePullPoint {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct CreatePullPointResponse { #[yaserde(prefix = "wsnt", rename = "PullPoint")] pub pull_point: wsa::EndpointReferenceType, } impl Validate for CreatePullPointResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct UnableToCreatePullPointFaultType {} impl Validate for UnableToCreatePullPointFaultType {} pub type UnableToCreatePullPointFault = UnableToCreatePullPointFaultType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct Renew { #[yaserde(prefix = "wsnt", rename = "TerminationTime")] pub termination_time: AbsoluteOrRelativeTimeType, } impl Validate for Renew {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct RenewResponse { #[yaserde(prefix = "wsnt", rename = "TerminationTime")] pub termination_time: TerminationTime, #[yaserde(prefix = "wsnt", rename = "CurrentTime")] pub current_time: CurrentTime, } impl Validate for RenewResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct UnacceptableTerminationTimeFaultType { #[yaserde(prefix = "wsnt", rename = "MinimumTime")] pub minimum_time: xs::DateTime, #[yaserde(prefix = "wsnt", rename = "MaximumTime")] pub maximum_time: Option<xs::DateTime>, } impl Validate for UnacceptableTerminationTimeFaultType {} pub type UnacceptableTerminationTimeFault = UnacceptableTerminationTimeFaultType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct Unsubscribe {} impl Validate for Unsubscribe {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct UnsubscribeResponse {} impl Validate for UnsubscribeResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct UnableToDestroySubscriptionFaultType {} impl Validate for UnableToDestroySubscriptionFaultType {} pub type UnableToDestroySubscriptionFault = UnableToDestroySubscriptionFaultType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct PauseSubscription {} impl Validate for PauseSubscription {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct PauseSubscriptionResponse {} impl Validate for PauseSubscriptionResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct ResumeSubscription {} impl Validate for ResumeSubscription {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct ResumeSubscriptionResponse {} impl Validate for ResumeSubscriptionResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct PauseFailedFaultType {} impl Validate for PauseFailedFaultType {} pub type PauseFailedFault = PauseFailedFaultType; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "wsnt", namespace = "wsnt: http://docs.oasis-open.org/wsn/b-2" )] pub struct ResumeFailedFaultType {} impl Validate for ResumeFailedFaultType {} pub type ResumeFailedFault = ResumeFailedFaultType;
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
false
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/doorcontrol/src/lib.rs
wsdl_rs/doorcontrol/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use types as pt; use validate::Validate; use xsd_types::types as xs; use yaserde_derive::{YaDeserialize, YaSerialize}; // ServiceCapabilities structure reflects optional functionality of a service. // The information is static and does not change during device operation. // The following capabilities are available: #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct ServiceCapabilities { // The maximum number of entries returned by a single Get<Entity>List or // Get<Entity> request. The device shall never return more than this number // of entities // in a single response. #[yaserde(attribute, rename = "MaxLimit")] pub max_limit: u32, // Indicates the maximum number of doors supported by the device. #[yaserde(attribute, rename = "MaxDoors")] pub max_doors: Option<u32>, // Indicates that the client is allowed to supply the token when creating // doors. // To enable the use of the command SetDoor, the value must be set to true. #[yaserde(attribute, rename = "ClientSuppliedTokenSupported")] pub client_supplied_token_supported: Option<bool>, } impl Validate for ServiceCapabilities {} // pub type Capabilities = ServiceCapabilities; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct DoorInfoBase { // A user readable name. It shall be up to 64 characters. #[yaserde(prefix = "tdc", rename = "Name")] pub name: pt::Name, // A user readable description. It shall be up to 1024 characters. #[yaserde(prefix = "tdc", rename = "Description")] pub description: Option<pt::Description>, pub base: pt::DataEntity, } impl Validate for DoorInfoBase {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct DoorInfo { // The capabilities of the Door. #[yaserde(prefix = "tdc", rename = "Capabilities")] pub capabilities: DoorCapabilities, pub base: DoorInfoBase, } impl Validate for DoorInfo {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct Door { // The type of door. Is of type text. Can be either one of the following // reserved // ONVIF types: "pt:Door", "pt:ManTrap", "pt:Turnstile", "pt:RevolvingDoor", // "pt:Barrier", or a custom defined type. #[yaserde(prefix = "tdc", rename = "DoorType")] pub door_type: pt::Name, // A structure defining times such as how long the door is unlocked when // accessed, extended grant time, etc. #[yaserde(prefix = "tdc", rename = "Timings")] pub timings: Timings, #[yaserde(prefix = "tdc", rename = "Extension")] pub extension: Option<DoorExtension>, pub base: DoorInfo, } impl Validate for Door {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct DoorExtension {} impl Validate for DoorExtension {} // A structure defining times such as how long the door is unlocked when // accessed, // extended grant time, etc. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct Timings { // When access is granted (door mode becomes Accessed), the latch is // unlocked. // ReleaseTime is the time from when the latch is unlocked until it is // relocked again (unless the door is physically opened). #[yaserde(prefix = "tdc", rename = "ReleaseTime")] pub release_time: xs::Duration, // The time from when the door is physically opened until the door is set in // the // DoorOpenTooLong alarm state. #[yaserde(prefix = "tdc", rename = "OpenTime")] pub open_time: xs::Duration, // Some individuals need extra time to open the door before the latch // relocks. // If supported, ExtendedReleaseTime shall be added to ReleaseTime if // UseExtendedTime // is set to true in the AccessDoor command. #[yaserde(prefix = "tdc", rename = "ExtendedReleaseTime")] pub extended_release_time: Option<xs::Duration>, // If the door is physically opened after access is granted, // then DelayTimeBeforeRelock is the time from when the door is physically // opened until the latch goes back to locked state. #[yaserde(prefix = "tdc", rename = "DelayTimeBeforeRelock")] pub delay_time_before_relock: Option<xs::Duration>, // Some individuals need extra time to pass through the door. If supported, // ExtendedOpenTime shall be added to OpenTime if UseExtendedTime is set to // true // in the AccessDoor command. #[yaserde(prefix = "tdc", rename = "ExtendedOpenTime")] pub extended_open_time: Option<xs::Duration>, // Before a DoorOpenTooLong alarm state is generated, a signal will sound to // indicate // that the door must be closed. PreAlarmTime defines how long before // DoorOpenTooLong // the warning signal shall sound. #[yaserde(prefix = "tdc", rename = "PreAlarmTime")] pub pre_alarm_time: Option<xs::Duration>, #[yaserde(prefix = "tdc", rename = "Extension")] pub extension: Option<TimingsExtension>, } impl Validate for Timings {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct TimingsExtension {} impl Validate for TimingsExtension {} // DoorCapabilities reflect optional functionality of a particular physical // entity. // Different door instances may have different set of capabilities. // This information may change during device operation, e.g. if hardware // settings are changed. // The following capabilities are available: #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct DoorCapabilities { // Indicates whether or not this Door instance supports AccessDoor command // to // perform momentary access. #[yaserde(attribute, rename = "Access")] pub access: Option<bool>, // Indicates that this Door instance supports overriding configured timing // in the // AccessDoor command. #[yaserde(attribute, rename = "AccessTimingOverride")] pub access_timing_override: Option<bool>, // Indicates that this Door instance supports LockDoor command to lock the // door. #[yaserde(attribute, rename = "Lock")] pub lock: Option<bool>, // Indicates that this Door instance supports UnlockDoor command to unlock // the // door. #[yaserde(attribute, rename = "Unlock")] pub unlock: Option<bool>, // Indicates that this Door instance supports BlockDoor command to block the // door. #[yaserde(attribute, rename = "Block")] pub block: Option<bool>, // Indicates that this Door instance supports DoubleLockDoor command to lock // multiple locks on the door. #[yaserde(attribute, rename = "DoubleLock")] pub double_lock: Option<bool>, // Indicates that this Door instance supports LockDown (and LockDownRelease) // commands to lock the door and put it in LockedDown mode. #[yaserde(attribute, rename = "LockDown")] pub lock_down: Option<bool>, // Indicates that this Door instance supports LockOpen (and LockOpenRelease) // commands to unlock the door and put it in LockedOpen mode. #[yaserde(attribute, rename = "LockOpen")] pub lock_open: Option<bool>, // Indicates that this Door instance has a DoorMonitor and supports the // DoorPhysicalState event. #[yaserde(attribute, rename = "DoorMonitor")] pub door_monitor: Option<bool>, // Indicates that this Door instance has a LockMonitor and supports the // LockPhysicalState event. #[yaserde(attribute, rename = "LockMonitor")] pub lock_monitor: Option<bool>, // Indicates that this Door instance has a DoubleLockMonitor and supports // the // DoubleLockPhysicalState event. #[yaserde(attribute, rename = "DoubleLockMonitor")] pub double_lock_monitor: Option<bool>, // Indicates that this Door instance supports door alarm and the DoorAlarm // event. #[yaserde(attribute, rename = "Alarm")] pub alarm: Option<bool>, // Indicates that this Door instance has a Tamper detector and supports the // DoorTamper event. #[yaserde(attribute, rename = "Tamper")] pub tamper: Option<bool>, // Indicates that this Door instance supports door fault and the DoorFault // event. #[yaserde(attribute, rename = "Fault")] pub fault: Option<bool>, } impl Validate for DoorCapabilities {} // The DoorState structure contains current aggregate runtime status of Door. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct DoorState { // Physical state of the Door; it is of type DoorPhysicalState. A device // that // signals support for DoorMonitor capability for a particular door instance // shall provide // this field. #[yaserde(prefix = "tdc", rename = "DoorPhysicalState")] pub door_physical_state: Option<DoorPhysicalState>, // Physical state of the Lock; it is of type LockPhysicalState. A device // that // signals support for LockMonitor capability for a particular door instance // shall provide // this field. #[yaserde(prefix = "tdc", rename = "LockPhysicalState")] pub lock_physical_state: Option<LockPhysicalState>, // Physical state of the DoubleLock; it is of type LockPhysicalState. A // device that signals support for DoubleLockMonitor capability for a // particular door // instance shall provide this field. #[yaserde(prefix = "tdc", rename = "DoubleLockPhysicalState")] pub double_lock_physical_state: Option<LockPhysicalState>, // Alarm state of the door; it is of type DoorAlarmState. A device that // signals support for Alarm capability for a particular door instance shall // provide this // field. #[yaserde(prefix = "tdc", rename = "Alarm")] pub alarm: Option<DoorAlarmState>, // Tampering state of the door; it is of type DoorTamper. A device that // signals support for Tamper capability for a particular door instance // shall provide this // field. #[yaserde(prefix = "tdc", rename = "Tamper")] pub tamper: Option<DoorTamper>, // Fault information for door; it is of type DoorFault. A device that // signals // support for Fault capability for a particular door instance shall provide // this field. #[yaserde(prefix = "tdc", rename = "Fault")] pub fault: Option<DoorFault>, // The logical operating mode of the door; it is of type DoorMode. An ONVIF // compatible device shall report current operating mode in this field. #[yaserde(prefix = "tdc", rename = "DoorMode")] pub door_mode: DoorMode, } impl Validate for DoorState {} // The physical state of a Door. #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum DoorPhysicalState { // Value is currently unknown (possibly due to initialization or monitors // not // giving a conclusive result). Unknown, // Door is open. Open, // Door is closed. Closed, // Door monitor fault is detected. Fault, __Unknown__(String), } impl Default for DoorPhysicalState { fn default() -> DoorPhysicalState { Self::__Unknown__("No valid variants".into()) } } impl Validate for DoorPhysicalState {} // The physical state of a Lock (including Double Lock). #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum LockPhysicalState { // Value is currently not known. Unknown, // Lock is activated. Locked, // Lock is not activated. Unlocked, // Lock fault is detected. Fault, __Unknown__(String), } impl Default for LockPhysicalState { fn default() -> LockPhysicalState { Self::__Unknown__("No valid variants".into()) } } impl Validate for LockPhysicalState {} // Describes the state of a Door with regard to alarms. #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum DoorAlarmState { // No alarm. Normal, // Door is forced open. DoorForcedOpen, // Door is held open too long. DoorOpenTooLong, __Unknown__(String), } impl Default for DoorAlarmState { fn default() -> DoorAlarmState { Self::__Unknown__("No valid variants".into()) } } impl Validate for DoorAlarmState {} // Tampering information for a Door. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct DoorTamper { // Optional field; Details describing tampering state change (e.g., reason, // place and time). // NOTE: All fields (including this one) which are designed to give // end-user prompts can be localized to the customer's native language. #[yaserde(prefix = "tdc", rename = "Reason")] pub reason: Option<String>, // State of the tamper detector; it is of type DoorTamperState. #[yaserde(prefix = "tdc", rename = "State")] pub state: DoorTamperState, } impl Validate for DoorTamper {} // Describes the state of a Tamper detector. #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum DoorTamperState { // Value is currently not known. Unknown, // No tampering is detected. NotInTamper, // Tampering is detected. TamperDetected, __Unknown__(String), } impl Default for DoorTamperState { fn default() -> DoorTamperState { Self::__Unknown__("No valid variants".into()) } } impl Validate for DoorTamperState {} // Fault information for a Door. // This can be extended with optional attributes in the future. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct DoorFault { // Optional reason for fault. #[yaserde(prefix = "tdc", rename = "Reason")] pub reason: Option<String>, // Overall fault state for the door; it is of type DoorFaultState. If there // are any faults, the value shall be: FaultDetected. Details of the // detected fault shall // be found in the Reason field, and/or the various DoorState fields and/or // in extensions // to this structure. #[yaserde(prefix = "tdc", rename = "State")] pub state: DoorFaultState, } impl Validate for DoorFault {} // Describes the state of a Door fault. #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum DoorFaultState { // Fault state is unknown. Unknown, // No fault is detected. NotInFault, // Fault is detected. FaultDetected, __Unknown__(String), } impl Default for DoorFaultState { fn default() -> DoorFaultState { Self::__Unknown__("No valid variants".into()) } } impl Validate for DoorFaultState {} // The DoorMode describe the mode of operation from a logical perspective. // Setting a door mode reflects the intent to set a door in a physical state. #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum DoorMode { // The mode of operation is unknown. Unknown, // The intention is to set the door to a physical locked state. // In this mode the device shall provide momentary access using the // AccessDoor // method if supported by the door instance. Locked, // The intention is to set the door to a physical unlocked state. // Alarms related to door timing operations such as open too long // or forced open are masked in this mode. Unlocked, // The intention is to momentary set the door to a physical unlocked state. // After a predefined time the device shall revert the door to its previous // mode. // Alarms related to timing operations such as door forced open are masked // in this mode. Accessed, // The intention is to set the door to a physical locked state and the // device shall not allow AccessDoor requests, i.e. it is not possible // for the door to go to the accessed mode. // All other requests to change the door mode are allowed. Blocked, // The intention is to set the door to a physical locked state and the // device // shall only allow the LockDownReleaseDoor request. // All other requests to change the door mode are not allowed. LockedDown, // The intention is to set the door to a physical unlocked state and the // device shall only allow the LockOpenReleaseDoor request. // All other requests to change the door mode are not allowed. LockedOpen, // The intention is to set the door with multiple locks to a physical double // locked state. // If the door does not support double locking the devices shall // treat this as a normal locked mode. // When changing to an unlocked mode from the double locked mode, the // physical state // of the door may first go to locked state before unlocking. DoubleLocked, __Unknown__(String), } impl Default for DoorMode { fn default() -> DoorMode { Self::__Unknown__("No valid variants".into()) } } impl Validate for DoorMode {} // Extension for the AccessDoor command. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct AccessDoorExtension {} impl Validate for AccessDoorExtension {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct GetServiceCapabilities {} impl Validate for GetServiceCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct GetServiceCapabilitiesResponse { // The capability response message contains the requested DoorControl // service capabilities using a hierarchical XML capability structure. #[yaserde(prefix = "tdc", rename = "Capabilities")] pub capabilities: ServiceCapabilities, } impl Validate for GetServiceCapabilitiesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct GetDoorInfoList { // Maximum number of entries to return. If Limit is omitted or if the // value of Limit is higher than what the device supports, then the device // shall // return its maximum amount of entries. #[yaserde(prefix = "tdc", rename = "Limit")] pub limit: Option<i32>, // Start returning entries from this start reference. If not specified, // entries shall start from the beginning of the dataset. #[yaserde(prefix = "tdc", rename = "StartReference")] pub start_reference: Option<String>, } impl Validate for GetDoorInfoList {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct GetDoorInfoListResponse { // StartReference to use in next call to get the following items. If // absent, no more items to get. #[yaserde(prefix = "tdc", rename = "NextStartReference")] pub next_start_reference: Option<String>, // List of DoorInfo items. #[yaserde(prefix = "tdc", rename = "DoorInfo")] pub door_info: Vec<DoorInfo>, } impl Validate for GetDoorInfoListResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct GetDoorInfo { // Tokens of DoorInfo items to get. #[yaserde(prefix = "tdc", rename = "Token")] pub token: Vec<pt::ReferenceToken>, } impl Validate for GetDoorInfo {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct GetDoorInfoResponse { // List of DoorInfo items. #[yaserde(prefix = "tdc", rename = "DoorInfo")] pub door_info: Vec<DoorInfo>, } impl Validate for GetDoorInfoResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct GetDoorList { // Maximum number of entries to return. If not specified, less than one // or higher than what the device supports, the number of items is // determined by the // device. #[yaserde(prefix = "tdc", rename = "Limit")] pub limit: Option<i32>, // Start returning entries from this start reference. If not specified, // entries shall start from the beginning of the dataset. #[yaserde(prefix = "tdc", rename = "StartReference")] pub start_reference: Option<String>, } impl Validate for GetDoorList {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct GetDoorListResponse { // StartReference to use in next call to get the following items. If // absent, no more items to get. #[yaserde(prefix = "tdc", rename = "NextStartReference")] pub next_start_reference: Option<String>, // List of Door items. #[yaserde(prefix = "tdc", rename = "Door")] pub door: Vec<Door>, } impl Validate for GetDoorListResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct GetDoors { // Tokens of Door items to get. #[yaserde(prefix = "tdc", rename = "Token")] pub token: Vec<pt::ReferenceToken>, } impl Validate for GetDoors {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct GetDoorsResponse { // List of Door items. #[yaserde(prefix = "tdc", rename = "Door")] pub door: Vec<Door>, } impl Validate for GetDoorsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct CreateDoor { // Door item to create #[yaserde(prefix = "tdc", rename = "Door")] pub door: Door, } impl Validate for CreateDoor {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct CreateDoorResponse { // Token of created Door item #[yaserde(prefix = "tdc", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for CreateDoorResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct SetDoor { // The Door item to create or modify #[yaserde(prefix = "tdc", rename = "Door")] pub door: Door, } impl Validate for SetDoor {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct SetDoorResponse {} impl Validate for SetDoorResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct ModifyDoor { // The details of the door #[yaserde(prefix = "tdc", rename = "Door")] pub door: Door, } impl Validate for ModifyDoor {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct ModifyDoorResponse {} impl Validate for ModifyDoorResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct DeleteDoor { // The Token of the door to delete. #[yaserde(prefix = "tdc", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for DeleteDoor {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct DeleteDoorResponse {} impl Validate for DeleteDoorResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct GetDoorState { // Token of the Door instance to get the state for. #[yaserde(prefix = "tdc", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for GetDoorState {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct GetDoorStateResponse { // The state of the door. #[yaserde(prefix = "tdc", rename = "DoorState")] pub door_state: DoorState, } impl Validate for GetDoorStateResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct AccessDoor { // Token of the Door instance to control. #[yaserde(prefix = "tdc", rename = "Token")] pub token: pt::ReferenceToken, // Optional - Indicates that the configured extended time should be // used. #[yaserde(prefix = "tdc", rename = "UseExtendedTime")] pub use_extended_time: Option<bool>, // Optional - overrides ReleaseTime if specified. #[yaserde(prefix = "tdc", rename = "AccessTime")] pub access_time: Option<xs::Duration>, // Optional - overrides OpenTime if specified. #[yaserde(prefix = "tdc", rename = "OpenTooLongTime")] pub open_too_long_time: Option<xs::Duration>, // Optional - overrides PreAlarmTime if specified. #[yaserde(prefix = "tdc", rename = "PreAlarmTime")] pub pre_alarm_time: Option<xs::Duration>, // Future extension. #[yaserde(prefix = "tdc", rename = "Extension")] pub extension: Option<AccessDoorExtension>, } impl Validate for AccessDoor {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct AccessDoorResponse {} impl Validate for AccessDoorResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct LockDoor { // Token of the Door instance to control. #[yaserde(prefix = "tdc", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for LockDoor {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct LockDoorResponse {} impl Validate for LockDoorResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct UnlockDoor { // Token of the Door instance to control. #[yaserde(prefix = "tdc", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for UnlockDoor {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct UnlockDoorResponse {} impl Validate for UnlockDoorResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct BlockDoor { // Token of the Door instance to control. #[yaserde(prefix = "tdc", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for BlockDoor {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct BlockDoorResponse {} impl Validate for BlockDoorResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct LockDownDoor { // Token of the Door instance to control. #[yaserde(prefix = "tdc", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for LockDownDoor {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct LockDownDoorResponse {} impl Validate for LockDownDoorResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct LockDownReleaseDoor { // Token of the Door instance to control. #[yaserde(prefix = "tdc", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for LockDownReleaseDoor {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct LockDownReleaseDoorResponse {} impl Validate for LockDownReleaseDoorResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct LockOpenDoor { // Token of the Door instance to control. #[yaserde(prefix = "tdc", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for LockOpenDoor {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct LockOpenDoorResponse {} impl Validate for LockOpenDoorResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct LockOpenReleaseDoor { // Token of the Door instance to control. #[yaserde(prefix = "tdc", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for LockOpenReleaseDoor {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct LockOpenReleaseDoorResponse {} impl Validate for LockOpenReleaseDoorResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct DoubleLockDoor { // Token of the Door instance to control. #[yaserde(prefix = "tdc", rename = "Token")] pub token: pt::ReferenceToken, } impl Validate for DoubleLockDoor {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tdc", namespace = "tdc: http://www.onvif.org/ver10/doorcontrol/wsdl" )] pub struct DoubleLockDoorResponse {} impl Validate for DoubleLockDoorResponse {} // This operation returns the capabilities of the service. // An ONVIF compliant device which provides the Door Control service shall // implement this method. pub async fn get_service_capabilities<T: transport::Transport>( transport: &T, request: &GetServiceCapabilities, ) -> Result<GetServiceCapabilitiesResponse, transport::Error> {
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
true
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/advancedsecurity/src/lib.rs
wsdl_rs/advancedsecurity/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use std::str::FromStr; use validate::Validate; use xsd_macro_utils::*; use xsd_types::types as xs; use yaserde_derive::{YaDeserialize, YaSerialize}; // Unique identifier for keys in the keystore. #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct KeyID(pub String); impl Validate for KeyID { fn validate(&self) -> Result<(), String> { if self.0.len() > "64".parse().unwrap() { return Err(format!( "MaxLength validation error. \nExpected: 0 length <= 64 \nActual: 0 length == {}", self.0.len() )); } Ok(()) } } // Unique identifier for certificates in the keystore. #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct CertificateID(pub String); impl Validate for CertificateID { fn validate(&self) -> Result<(), String> { if self.0.len() > "64".parse().unwrap() { return Err(format!( "MaxLength validation error. \nExpected: 0 length <= 64 \nActual: 0 length == {}", self.0.len() )); } Ok(()) } } // Unique identifier for certification paths in the keystore. #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct CertificationPathID(pub String); impl Validate for CertificationPathID { fn validate(&self) -> Result<(), String> { if self.0.len() > "64".parse().unwrap() { return Err(format!( "MaxLength validation error. \nExpected: 0 length <= 64 \nActual: 0 length == {}", self.0.len() )); } Ok(()) } } // Unique identifier for passphrases in the keystore. #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct PassphraseID(pub String); impl Validate for PassphraseID { fn validate(&self) -> Result<(), String> { if self.0.len() > "64".parse().unwrap() { return Err(format!( "MaxLength validation error. \nExpected: 0 length <= 64 \nActual: 0 length == {}", self.0.len() )); } Ok(()) } } // Unique identifier for 802.1X configurations in the keystore. #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct Dot1XID(pub String); impl Validate for Dot1XID { fn validate(&self) -> Result<(), String> { if self.0.len() > "64".parse().unwrap() { return Err(format!( "MaxLength validation error. \nExpected: 0 length <= 64 \nActual: 0 length == {}", self.0.len() )); } Ok(()) } } // The status of a key in the keystore. #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum KeyStatus { // Key is ready for use #[yaserde(rename = "ok")] Ok, // Key is being generated #[yaserde(rename = "generating")] Generating, // Key has not been successfully generated and cannot be used. #[yaserde(rename = "corrupt")] Corrupt, __Unknown__(String), } impl Default for KeyStatus { fn default() -> KeyStatus { Self::__Unknown__("No valid variants".into()) } } impl Validate for KeyStatus {} // An object identifier (OID) in dot-decimal form as specified in RFC4512. #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct DotDecimalOID(pub String); impl Validate for DotDecimalOID {} // The distinguished name attribute type encoded as specified in RFC 4514. #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct DnattributeType(pub String); impl Validate for DnattributeType {} #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct DnattributeValue(pub String); impl Validate for DnattributeValue {} // The attributes of a key in the keystore. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct KeyAttribute { // The ID of the key. #[yaserde(prefix = "tas", rename = "KeyID")] pub key_id: KeyID, // The client-defined alias of the key. #[yaserde(prefix = "tas", rename = "Alias")] pub alias: Option<String>, // Absent if the key is not a key pair. True if and only if the key is a key // pair and contains a private key. False if and only if the key is a key // pair and does not contain a private key. #[yaserde(prefix = "tas", rename = "hasPrivateKey")] pub has_private_key: Option<bool>, // The status of the key. The value should be one of the values in the // tas:KeyStatus enumeration. #[yaserde(prefix = "tas", rename = "KeyStatus")] pub key_status: String, // True if and only if the key was generated outside the device. #[yaserde(prefix = "tas", rename = "externallyGenerated")] pub externally_generated: Option<bool>, // True if and only if the key is stored in a specially protected hardware // component inside the device. #[yaserde(prefix = "tas", rename = "securelyStored")] pub securely_stored: Option<bool>, #[yaserde(prefix = "tas", rename = "Extension")] pub extension: Option<key_attribute::ExtensionType>, } impl Validate for KeyAttribute {} pub mod key_attribute { use super::*; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct ExtensionType {} impl Validate for ExtensionType {} } // A distinguished name attribute type and value pair. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct DnattributeTypeAndValue { // The attribute type. #[yaserde(prefix = "tas", rename = "Type")] pub _type: DnattributeType, // The value of the attribute. #[yaserde(prefix = "tas", rename = "Value")] pub value: DnattributeValue, } impl Validate for DnattributeTypeAndValue {} // A multi-valued RDN #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct MultiValuedRDN { // A list of types and values defining a multi-valued RDN #[yaserde(prefix = "tas", rename = "Attribute")] pub attribute: Vec<DnattributeTypeAndValue>, } impl Validate for MultiValuedRDN {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct DistinguishedName { // A country name as specified in // X.500. #[yaserde(prefix = "tas", rename = "Country")] pub country: Vec<DnattributeValue>, // An organization name as specified in // X.500. #[yaserde(prefix = "tas", rename = "Organization")] pub organization: Vec<DnattributeValue>, // An organizational unit name as specified in // X.500. #[yaserde(prefix = "tas", rename = "OrganizationalUnit")] pub organizational_unit: Vec<DnattributeValue>, // A distinguished name qualifier as specified in // X.500. #[yaserde(prefix = "tas", rename = "DistinguishedNameQualifier")] pub distinguished_name_qualifier: Vec<DnattributeValue>, // A state or province name as specified in // X.500. #[yaserde(prefix = "tas", rename = "StateOrProvinceName")] pub state_or_province_name: Vec<DnattributeValue>, // A common name as specified in // X.500. #[yaserde(prefix = "tas", rename = "CommonName")] pub common_name: Vec<DnattributeValue>, // A serial number as specified in // X.500. #[yaserde(prefix = "tas", rename = "SerialNumber")] pub serial_number: Vec<DnattributeValue>, // A locality as specified in X.500. #[yaserde(prefix = "tas", rename = "Locality")] pub locality: Vec<DnattributeValue>, // A title as specified in X.500. #[yaserde(prefix = "tas", rename = "Title")] pub title: Vec<DnattributeValue>, // A surname as specified in X.500. #[yaserde(prefix = "tas", rename = "Surname")] pub surname: Vec<DnattributeValue>, // A given name as specified in X.500. #[yaserde(prefix = "tas", rename = "GivenName")] pub given_name: Vec<DnattributeValue>, // Initials as specified in X.500. #[yaserde(prefix = "tas", rename = "Initials")] pub initials: Vec<DnattributeValue>, // A pseudonym as specified in X.500. #[yaserde(prefix = "tas", rename = "Pseudonym")] pub pseudonym: Vec<DnattributeValue>, // A generation qualifier as specified in // X.500. #[yaserde(prefix = "tas", rename = "GenerationQualifier")] pub generation_qualifier: Vec<DnattributeValue>, // A generic type-value pair // attribute. #[yaserde(prefix = "tas", rename = "GenericAttribute")] pub generic_attribute: Vec<DnattributeTypeAndValue>, // A multi-valued RDN #[yaserde(prefix = "tas", rename = "MultiValuedRDN")] pub multi_valued_rdn: Vec<MultiValuedRDN>, // Required extension point. It is recommended to not use this element, and // instead use GenericAttribute and the numeric Distinguished Name Attribute // Type. #[yaserde(prefix = "tas", rename = "anyAttribute")] pub any_attribute: Option<distinguished_name::AnyAttributeType>, } impl Validate for DistinguishedName {} pub mod distinguished_name { use super::*; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct AnyAttributeType { // Domain Component as specified in RFC3739 #[yaserde(prefix = "tas", rename = "DomainComponent")] pub domain_component: Vec<DnattributeValue>, } impl Validate for AnyAttributeType {} } // An identifier of an algorithm. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct AlgorithmIdentifier { // The OID of the algorithm in dot-decimal form. #[yaserde(prefix = "tas", rename = "algorithm")] pub algorithm: DotDecimalOID, // Optional parameters of the algorithm (depending on the algorithm). #[yaserde(prefix = "tas", rename = "parameters")] pub parameters: Option<Base64DERencodedASN1Value>, #[yaserde(prefix = "tas", rename = "anyParameters")] pub any_parameters: Option<algorithm_identifier::AnyParametersType>, } impl Validate for AlgorithmIdentifier {} pub mod algorithm_identifier { use super::*; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct AnyParametersType {} impl Validate for AnyParametersType {} } // A CSR attribute as specified in RFC 2986. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct BasicRequestAttribute { // The OID of the attribute. #[yaserde(prefix = "tas", rename = "OID")] pub oid: DotDecimalOID, // The value of the attribute as a base64-encoded DER representation of an // ASN.1 value. #[yaserde(prefix = "tas", rename = "value")] pub value: Base64DERencodedASN1Value, } impl Validate for BasicRequestAttribute {} #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum CsrattributeChoice { // An X.509v3 extension field. #[yaserde(rename = "X509v3Extension")] X509V3Extension(X509V3Extension), // A basic CSR attribute. BasicRequestAttribute(BasicRequestAttribute), #[yaserde(rename = "anyAttribute")] AnyAttribute, __Unknown__(String), } impl Default for CsrattributeChoice { fn default() -> CsrattributeChoice { Self::__Unknown__("No valid variants".into()) } } impl Validate for CsrattributeChoice {} // A CSR attribute as specified in PKCS#10. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct Csrattribute { #[yaserde(flatten)] pub csr_attribute_choice: CsrattributeChoice, } impl Validate for Csrattribute {} // A base64-encoded ASN.1 value. #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct Base64DERencodedASN1Value(pub String); impl Validate for Base64DERencodedASN1Value {} // An X.509v3 extension field as specified in RFC 5280 #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct X509V3Extension { // The OID of the extension field. #[yaserde(prefix = "tas", rename = "extnOID")] pub extn_oid: DotDecimalOID, // True if and only if the extension is critical. #[yaserde(prefix = "tas", rename = "critical")] pub critical: bool, // The value of the extension field as a base64-encoded DER representation // of an ASN.1 value. #[yaserde(prefix = "tas", rename = "extnValue")] pub extn_value: Base64DERencodedASN1Value, } impl Validate for X509V3Extension {} // An X.509 cerficiate as specified in RFC 5280. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct X509Certificate { // The ID of the certificate. #[yaserde(prefix = "tas", rename = "CertificateID")] pub certificate_id: CertificateID, // The ID of the key that this certificate associates to the certificate // subject. #[yaserde(prefix = "tas", rename = "KeyID")] pub key_id: KeyID, // The client-defined alias of the certificate. #[yaserde(prefix = "tas", rename = "Alias")] pub alias: Option<String>, // The base64-encoded DER representation of the X.509 certificate. #[yaserde(prefix = "tas", rename = "CertificateContent")] pub certificate_content: Base64DERencodedASN1Value, } impl Validate for X509Certificate {} // A sequence of certificate IDs. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct CertificateIDs { // A certificate ID. #[yaserde(prefix = "tas", rename = "CertificateID")] pub certificate_id: Vec<CertificateID>, } impl Validate for CertificateIDs {} // An X.509 certification path as defined in RFC 5280. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct CertificationPath { // A certificate in the certification path. #[yaserde(prefix = "tas", rename = "CertificateID")] pub certificate_id: Vec<CertificateID>, // The client-defined alias of the certification path. #[yaserde(prefix = "tas", rename = "Alias")] pub alias: Option<String>, #[yaserde(prefix = "tas", rename = "anyElement")] pub any_element: Option<certification_path::AnyElementType>, } impl Validate for CertificationPath {} pub mod certification_path { use super::*; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct AnyElementType {} impl Validate for AnyElementType {} } #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct PassphraseAttribute { // The ID of the passphrase. #[yaserde(prefix = "tas", rename = "PassphraseID")] pub passphrase_id: PassphraseID, // The alias of the passphrase. #[yaserde(prefix = "tas", rename = "Alias")] pub alias: Option<String>, } impl Validate for PassphraseAttribute {} // A list of supported 802.1X authentication methods, such as // "EAP-PEAP/MSCHAPv2" and "EAP-MD5". The '/' character is used as a separator // between the outer and inner methods. #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct Dot1XMethods(pub Vec<String>); impl Validate for Dot1XMethods {} // The capabilities of the 802.1X implementation on a device. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct Dot1XCapabilities { // The maximum number of 802.1X configurations that may be defined // simultaneously. #[yaserde(attribute, rename = "MaximumNumberOfDot1XConfigurations")] pub maximum_number_of_dot_1x_configurations: Option<xs::Integer>, // The authentication methods supported by the 802.1X implementation. #[yaserde(attribute, rename = "Dot1XMethods")] pub dot_1x_methods: Option<Dot1XMethods>, } impl Validate for Dot1XCapabilities {} // The configuration parameters required for a particular authentication method. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct Dot1XStage { // The identity used in this authentication method, if required. #[yaserde(prefix = "tas", rename = "Identity")] pub identity: Option<String>, // The unique identifier of the certification path used in this // authentication method, if required. #[yaserde(prefix = "tas", rename = "CertificationPathID")] pub certification_path_id: Option<CertificationPathID>, // The identifier for the password used in this authentication method, if // required. If Identity is used as an anonymous identity for this // authentication method, PassphraseID is ignored. #[yaserde(prefix = "tas", rename = "PassphraseID")] pub passphrase_id: Option<PassphraseID>, // The configuration of the next stage of authentication, if required. #[yaserde(prefix = "tas", rename = "Inner")] pub inner: Vec<Dot1XStage>, #[yaserde(prefix = "tas", rename = "Extension")] pub extension: Option<Dot1XStageExtension>, // The authentication method for this stage (e.g., "EAP-PEAP"). #[yaserde(attribute, rename = "Method")] pub method: String, } impl Validate for Dot1XStage {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct Dot1XStageExtension {} impl Validate for Dot1XStageExtension {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct Dot1XConfiguration { // The unique identifier of the IEEE 802.1X configuration. #[yaserde(prefix = "tas", rename = "Dot1XID")] pub dot_1xid: Option<Dot1XID>, // The client-defined alias of the 802.1X configuration. #[yaserde(prefix = "tas", rename = "Alias")] pub alias: Option<String>, // The outer level authentication method used in this 802.1X configuration. #[yaserde(prefix = "tas", rename = "Outer")] pub outer: Dot1XStage, } impl Validate for Dot1XConfiguration {} #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct Crlid(pub String); impl Validate for Crlid { fn validate(&self) -> Result<(), String> { if self.0.len() > "64".parse().unwrap() { return Err(format!( "MaxLength validation error. \nExpected: 0 length <= 64 \nActual: 0 length == {}", self.0.len() )); } Ok(()) } } #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct CertPathValidationPolicyID(pub String); impl Validate for CertPathValidationPolicyID { fn validate(&self) -> Result<(), String> { if self.0.len() > "64".parse().unwrap() { return Err(format!( "MaxLength validation error. \nExpected: 0 length <= 64 \nActual: 0 length == {}", self.0.len() )); } Ok(()) } } #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct Crl { #[yaserde(prefix = "tas", rename = "CRLID")] pub crlid: Crlid, #[yaserde(prefix = "tas", rename = "Alias")] pub alias: String, #[yaserde(prefix = "tas", rename = "CRLContent")] pub crl_content: Base64DERencodedASN1Value, } impl Validate for Crl {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct CertPathValidationParameters { // True if and only if the TLS server shall not authenticate client // certificates that do not contain the TLS WWW client authentication key // usage extension as specified in RFC 5280, Sect. 4.2.1.12. #[yaserde(prefix = "tas", rename = "RequireTLSWWWClientAuthExtendedKeyUsage")] pub require_tlswww_client_auth_extended_key_usage: Option<bool>, // True if and only if delta CRLs, if available, shall be applied to CRLs. #[yaserde(prefix = "tas", rename = "UseDeltaCRLs")] pub use_delta_cr_ls: Option<bool>, #[yaserde(prefix = "tas", rename = "anyParameters")] pub any_parameters: Option<cert_path_validation_parameters::AnyParametersType>, } impl Validate for CertPathValidationParameters {} pub mod cert_path_validation_parameters { use super::*; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct AnyParametersType {} impl Validate for AnyParametersType {} } #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct TrustAnchor { // The certificate ID of the certificate to be used as trust anchor. #[yaserde(prefix = "tas", rename = "CertificateID")] pub certificate_id: CertificateID, } impl Validate for TrustAnchor {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct CertPathValidationPolicy { #[yaserde(prefix = "tas", rename = "CertPathValidationPolicyID")] pub cert_path_validation_policy_id: CertPathValidationPolicyID, #[yaserde(prefix = "tas", rename = "Alias")] pub alias: Option<String>, #[yaserde(prefix = "tas", rename = "Parameters")] pub parameters: CertPathValidationParameters, #[yaserde(prefix = "tas", rename = "TrustAnchor")] pub trust_anchor: Vec<TrustAnchor>, #[yaserde(prefix = "tas", rename = "anyParameters")] pub any_parameters: Option<cert_path_validation_policy::AnyParametersType>, } impl Validate for CertPathValidationPolicy {} pub mod cert_path_validation_policy { use super::*; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct AnyParametersType {} impl Validate for AnyParametersType {} } // A list of RSA key lenghts in bits. #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct RsakeyLengths(pub Vec<xs::Integer>); impl Validate for RsakeyLengths {} // A list of X.509 versions. #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct X509Versions(pub Vec<i32>); impl Validate for X509Versions {} // A list of TLS versions. #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct Tlsversions(pub Vec<String>); impl Validate for Tlsversions {} // A list of password based encryption algorithms. #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct PasswordBasedEncryptionAlgorithms(pub Vec<String>); impl Validate for PasswordBasedEncryptionAlgorithms {} // A list of password based MAC algorithms. #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct PasswordBasedMACAlgorithms(pub Vec<String>); impl Validate for PasswordBasedMACAlgorithms {} // The capabilities of a keystore implementation on a device. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct KeystoreCapabilities { // The signature algorithms supported by the keystore implementation. #[yaserde(prefix = "tas", rename = "SignatureAlgorithms")] pub signature_algorithms: Vec<AlgorithmIdentifier>, #[yaserde(prefix = "tas", rename = "anyElement")] pub any_element: Option<keystore_capabilities::AnyElementType>, // Indicates the maximum number of keys that the device can store // simultaneously. #[yaserde(attribute, rename = "MaximumNumberOfKeys")] pub maximum_number_of_keys: Option<xs::Integer>, // Indicates the maximum number of certificates that the device can store // simultaneously. #[yaserde(attribute, rename = "MaximumNumberOfCertificates")] pub maximum_number_of_certificates: Option<xs::Integer>, // Indicates the maximum number of certification paths that the device can // store simultaneously. #[yaserde(attribute, rename = "MaximumNumberOfCertificationPaths")] pub maximum_number_of_certification_paths: Option<xs::Integer>, // Indication that the device supports on-board RSA key pair generation. #[yaserde(attribute, rename = "RSAKeyPairGeneration")] pub rsa_key_pair_generation: Option<bool>, // Indicates which RSA key lengths are supported by the device. #[yaserde(attribute, rename = "RSAKeyLengths")] pub rsa_key_lengths: Option<RsakeyLengths>, // Indicates support for creating PKCS#10 requests for RSA keys and // uploading the certificate obtained from a CA.. #[yaserde(attribute, rename = "PKCS10ExternalCertificationWithRSA")] pub pkcs10_external_certification_with_rsa: Option<bool>, // Indicates support for creating self-signed certificates for RSA keys. #[yaserde(attribute, rename = "SelfSignedCertificateCreationWithRSA")] pub self_signed_certificate_creation_with_rsa: Option<bool>, // Indicates which X.509 versions are supported by the device. #[yaserde(attribute, rename = "X509Versions")] pub x509_versions: Option<X509Versions>, // Indicates the maximum number of passphrases that the device is able to // store simultaneously. #[yaserde(attribute, rename = "MaximumNumberOfPassphrases")] pub maximum_number_of_passphrases: Option<xs::Integer>, // Indicates support for uploading an RSA key pair in a PKCS#8 data // structure. #[yaserde(attribute, rename = "PKCS8RSAKeyPairUpload")] pub pkcs8rsa_key_pair_upload: Option<bool>, // Indicates support for uploading a certificate along with an RSA private // key in a PKCS#12 data structure. #[yaserde(attribute, rename = "PKCS12CertificateWithRSAPrivateKeyUpload")] pub pkcs12_certificate_with_rsa_private_key_upload: Option<bool>, // Indicates which password-based encryption algorithms are supported by the // device. #[yaserde(attribute, rename = "PasswordBasedEncryptionAlgorithms")] pub password_based_encryption_algorithms: Option<PasswordBasedEncryptionAlgorithms>, // Indicates which password-based MAC algorithms are supported by the // device. #[yaserde(attribute, rename = "PasswordBasedMACAlgorithms")] pub password_based_mac_algorithms: Option<PasswordBasedMACAlgorithms>, // Indicates the maximum number of CRLs that the device is able to store // simultaneously. #[yaserde(attribute, rename = "MaximumNumberOfCRLs")] pub maximum_number_of_cr_ls: Option<xs::Integer>, // Indicates the maximum number of certification path validation policies // that the device is able to store simultaneously. #[yaserde( attribute, rename = "MaximumNumberOfCertificationPathValidationPolicies" )] pub maximum_number_of_certification_path_validation_policies: Option<xs::Integer>, // Indicates whether a device supports checking for the TLS WWW client auth // extended key usage extension while validating certification paths. #[yaserde(attribute, rename = "EnforceTLSWebClientAuthExtKeyUsage")] pub enforce_tls_web_client_auth_ext_key_usage: Option<bool>, // Indicates the device requires that each certificate with private key has // its own unique key. #[yaserde(attribute, rename = "NoPrivateKeySharing")] pub no_private_key_sharing: Option<bool>, } impl Validate for KeystoreCapabilities {} pub mod keystore_capabilities { use super::*; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct AnyElementType {} impl Validate for AnyElementType {} } // The capabilities of a TLS server implementation on a device. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct TlsserverCapabilities { // Indicates which TLS versions are supported by the device. #[yaserde(attribute, rename = "TLSServerSupported")] pub tls_server_supported: Option<Tlsversions>, // Indicates whether the device supports enabling and disabling specific TLS // versions. #[yaserde(attribute, rename = "EnabledVersionsSupported")] pub enabled_versions_supported: Option<bool>, // Indicates the maximum number of certification paths that may be assigned // to the TLS server simultaneously. #[yaserde(attribute, rename = "MaximumNumberOfTLSCertificationPaths")] pub maximum_number_of_tls_certification_paths: Option<xs::Integer>, // Indicates whether the device supports TLS client authentication. #[yaserde(attribute, rename = "TLSClientAuthSupported")] pub tls_client_auth_supported: Option<bool>, // Indicates the maximum number of certification path validation policies // that may be assigned to the TLS server simultaneously. #[yaserde( attribute, rename = "MaximumNumberOfTLSCertificationPathValidationPolicies" )] pub maximum_number_of_tls_certification_path_validation_policies: Option<xs::Integer>, } impl Validate for TlsserverCapabilities {} // The capabilities of a Security Configuration Service implementation on a // device. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct Capabilities { // The capabilities of the keystore implementation. #[yaserde(prefix = "tas", rename = "KeystoreCapabilities")] pub keystore_capabilities: Vec<KeystoreCapabilities>, // The capabilities of the TLS server implementation. #[yaserde(prefix = "tas", rename = "TLSServerCapabilities")] pub tls_server_capabilities: Vec<TlsserverCapabilities>, // The capabilities of the 802.1X implementation. #[yaserde(prefix = "tas", rename = "Dot1XCapabilities")] pub dot_1x_capabilities: Vec<Dot1XCapabilities>, } impl Validate for Capabilities {} // pub type Capabilities = Capabilities; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )] pub struct GetServiceCapabilities {} impl Validate for GetServiceCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "tas", namespace = "tas: http://www.onvif.org/ver10/advancedsecurity/wsdl" )]
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
true
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/wsdl_rs/recording/src/lib.rs
wsdl_rs/recording/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use onvif as tt; use std::str::FromStr; use validate::Validate; use xsd_macro_utils::*; use xsd_types::types as xs; use yaserde_derive::{YaDeserialize, YaSerialize}; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct GetServiceCapabilities {} impl Validate for GetServiceCapabilities {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct GetServiceCapabilitiesResponse { // The capabilities for the recording service is returned in the // Capabilities element. #[yaserde(prefix = "trc", rename = "Capabilities")] pub capabilities: Capabilities, } impl Validate for GetServiceCapabilitiesResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct Capabilities { // Indication if the device supports dynamic creation and deletion of // recordings #[yaserde(attribute, rename = "DynamicRecordings")] pub dynamic_recordings: Option<bool>, // Indication if the device supports dynamic creation and deletion of tracks #[yaserde(attribute, rename = "DynamicTracks")] pub dynamic_tracks: Option<bool>, // Indication which encodings are supported for recording. The list may // contain one or more enumeration values of tt:VideoEncoding and // tt:AudioEncoding. For encodings that are neither defined in // tt:VideoEncoding nor tt:AudioEncoding the device shall use the #[yaserde(attribute, rename = "Encoding")] pub encoding: Option<EncodingTypes>, // Maximum supported bit rate for all tracks of a recording in kBit/s. #[yaserde(attribute, rename = "MaxRate")] pub max_rate: Option<f64>, // Maximum supported bit rate for all recordings in kBit/s. #[yaserde(attribute, rename = "MaxTotalRate")] pub max_total_rate: Option<f64>, // Maximum number of recordings supported. (Integer values only.) #[yaserde(attribute, rename = "MaxRecordings")] pub max_recordings: Option<f64>, // Maximum total number of supported recording jobs by the device. #[yaserde(attribute, rename = "MaxRecordingJobs")] pub max_recording_jobs: Option<i32>, // Indication if the device supports the GetRecordingOptions command. #[yaserde(attribute, rename = "Options")] pub options: Option<bool>, // Indication if the device supports recording metadata. #[yaserde(attribute, rename = "MetadataRecording")] pub metadata_recording: Option<bool>, // Indication that the device supports ExportRecordedData command for the // listed export file formats. // The list shall return at least one export file format value. The value of // 'ONVIF' refers to // ONVIF Export File Format specification. #[yaserde(attribute, rename = "SupportedExportFileFormats")] pub supported_export_file_formats: Option<tt::StringAttrList>, } impl Validate for Capabilities {} #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct EncodingTypes(pub Vec<String>); impl Validate for EncodingTypes {} // pub type Capabilities = Capabilities; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct CreateRecording { // Initial configuration for the recording. #[yaserde(prefix = "trc", rename = "RecordingConfiguration")] pub recording_configuration: tt::RecordingConfiguration, } impl Validate for CreateRecording {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct CreateRecordingResponse { // The reference to the created recording. #[yaserde(prefix = "trc", rename = "RecordingToken")] pub recording_token: tt::RecordingReference, } impl Validate for CreateRecordingResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct DeleteRecording { // The reference of the recording to be deleted. #[yaserde(prefix = "trc", rename = "RecordingToken")] pub recording_token: tt::RecordingReference, } impl Validate for DeleteRecording {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct DeleteRecordingResponse {} impl Validate for DeleteRecordingResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct GetRecordings {} impl Validate for GetRecordings {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct GetRecordingsResponse { // List of recording items. #[yaserde(prefix = "trc", rename = "RecordingItem")] pub recording_item: Vec<tt::GetRecordingsResponseItem>, } impl Validate for GetRecordingsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct SetRecordingConfiguration { // Token of the recording that shall be changed. #[yaserde(prefix = "trc", rename = "RecordingToken")] pub recording_token: tt::RecordingReference, // The new configuration. #[yaserde(prefix = "trc", rename = "RecordingConfiguration")] pub recording_configuration: tt::RecordingConfiguration, } impl Validate for SetRecordingConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct SetRecordingConfigurationResponse {} impl Validate for SetRecordingConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct GetRecordingConfiguration { // Token of the configuration to be retrieved. #[yaserde(prefix = "trc", rename = "RecordingToken")] pub recording_token: tt::RecordingReference, } impl Validate for GetRecordingConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct GetRecordingConfigurationResponse { // Configuration of the recording. #[yaserde(prefix = "trc", rename = "RecordingConfiguration")] pub recording_configuration: tt::RecordingConfiguration, } impl Validate for GetRecordingConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct CreateTrack { // Identifies the recording to which a track shall be added. #[yaserde(prefix = "trc", rename = "RecordingToken")] pub recording_token: tt::RecordingReference, // The configuration of the new track. #[yaserde(prefix = "trc", rename = "TrackConfiguration")] pub track_configuration: tt::TrackConfiguration, } impl Validate for CreateTrack {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct CreateTrackResponse { // The TrackToken shall identify the newly created track. The // TrackToken shall be unique within the recoding to which // the new track belongs. #[yaserde(prefix = "trc", rename = "TrackToken")] pub track_token: tt::TrackReference, } impl Validate for CreateTrackResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct DeleteTrack { // Token of the recording the track belongs to. #[yaserde(prefix = "trc", rename = "RecordingToken")] pub recording_token: tt::RecordingReference, // Token of the track to be deleted. #[yaserde(prefix = "trc", rename = "TrackToken")] pub track_token: tt::TrackReference, } impl Validate for DeleteTrack {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct DeleteTrackResponse {} impl Validate for DeleteTrackResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct GetTrackConfiguration { // Token of the recording the track belongs to. #[yaserde(prefix = "trc", rename = "RecordingToken")] pub recording_token: tt::RecordingReference, // Token of the track. #[yaserde(prefix = "trc", rename = "TrackToken")] pub track_token: tt::TrackReference, } impl Validate for GetTrackConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct GetTrackConfigurationResponse { // Configuration of the track. #[yaserde(prefix = "trc", rename = "TrackConfiguration")] pub track_configuration: tt::TrackConfiguration, } impl Validate for GetTrackConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct SetTrackConfiguration { // Token of the recording the track belongs to. #[yaserde(prefix = "trc", rename = "RecordingToken")] pub recording_token: tt::RecordingReference, // Token of the track to be modified. #[yaserde(prefix = "trc", rename = "TrackToken")] pub track_token: tt::TrackReference, // New configuration for the track. #[yaserde(prefix = "trc", rename = "TrackConfiguration")] pub track_configuration: tt::TrackConfiguration, } impl Validate for SetTrackConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct SetTrackConfigurationResponse {} impl Validate for SetTrackConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct CreateRecordingJob { // The initial configuration of the new recording job. #[yaserde(prefix = "trc", rename = "JobConfiguration")] pub job_configuration: tt::RecordingJobConfiguration, } impl Validate for CreateRecordingJob {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct CreateRecordingJobResponse { // The JobToken shall identify the created recording job. #[yaserde(prefix = "trc", rename = "JobToken")] pub job_token: tt::RecordingJobReference, // The JobConfiguration structure shall be the configuration as it is used // by the device. This may be different from the // JobConfiguration passed to CreateRecordingJob. #[yaserde(prefix = "trc", rename = "JobConfiguration")] pub job_configuration: tt::RecordingJobConfiguration, } impl Validate for CreateRecordingJobResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct DeleteRecordingJob { // The token of the job to be deleted. #[yaserde(prefix = "trc", rename = "JobToken")] pub job_token: tt::RecordingJobReference, } impl Validate for DeleteRecordingJob {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct DeleteRecordingJobResponse {} impl Validate for DeleteRecordingJobResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct GetRecordingJobs {} impl Validate for GetRecordingJobs {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct GetRecordingJobsResponse { // List of recording jobs. #[yaserde(prefix = "trc", rename = "JobItem")] pub job_item: Vec<tt::GetRecordingJobsResponseItem>, } impl Validate for GetRecordingJobsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct SetRecordingJobConfiguration { // Token of the job to be modified. #[yaserde(prefix = "trc", rename = "JobToken")] pub job_token: tt::RecordingJobReference, // New configuration of the recording job. #[yaserde(prefix = "trc", rename = "JobConfiguration")] pub job_configuration: tt::RecordingJobConfiguration, } impl Validate for SetRecordingJobConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct SetRecordingJobConfigurationResponse { // The JobConfiguration structure shall be the configuration // as it is used by the device. This may be different from the // JobConfiguration passed to SetRecordingJobConfiguration. #[yaserde(prefix = "trc", rename = "JobConfiguration")] pub job_configuration: tt::RecordingJobConfiguration, } impl Validate for SetRecordingJobConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct GetRecordingJobConfiguration { // Token of the recording job. #[yaserde(prefix = "trc", rename = "JobToken")] pub job_token: tt::RecordingJobReference, } impl Validate for GetRecordingJobConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct GetRecordingJobConfigurationResponse { // Current configuration of the recording job. #[yaserde(prefix = "trc", rename = "JobConfiguration")] pub job_configuration: tt::RecordingJobConfiguration, } impl Validate for GetRecordingJobConfigurationResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct SetRecordingJobMode { // Token of the recording job. #[yaserde(prefix = "trc", rename = "JobToken")] pub job_token: tt::RecordingJobReference, // The new mode for the recording job. #[yaserde(prefix = "trc", rename = "Mode")] pub mode: tt::RecordingJobMode, } impl Validate for SetRecordingJobMode {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct SetRecordingJobModeResponse {} impl Validate for SetRecordingJobModeResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct GetRecordingJobState { // Token of the recording job. #[yaserde(prefix = "trc", rename = "JobToken")] pub job_token: tt::RecordingJobReference, } impl Validate for GetRecordingJobState {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct GetRecordingJobStateResponse { // The current state of the recording job. #[yaserde(prefix = "trc", rename = "State")] pub state: tt::RecordingJobStateInformation, } impl Validate for GetRecordingJobStateResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct GetRecordingOptions { // Token of the recording. #[yaserde(prefix = "trc", rename = "RecordingToken")] pub recording_token: tt::RecordingReference, } impl Validate for GetRecordingOptions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct GetRecordingOptionsResponse { // Configuration of the recording. #[yaserde(prefix = "trc", rename = "Options")] pub options: RecordingOptions, } impl Validate for GetRecordingOptionsResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct ExportRecordedData { // Optional parameter that specifies start time for the exporting. #[yaserde(prefix = "trc", rename = "StartPoint")] pub start_point: Option<xs::DateTime>, // Optional parameter that specifies end time for the exporting. #[yaserde(prefix = "trc", rename = "EndPoint")] pub end_point: Option<xs::DateTime>, // Indicates the selection criterion on the existing recordings. . #[yaserde(prefix = "trc", rename = "SearchScope")] pub search_scope: tt::SearchScope, // Indicates which export file format to be used. #[yaserde(prefix = "trc", rename = "FileFormat")] pub file_format: String, // Indicates the target storage and relative directory path. #[yaserde(prefix = "trc", rename = "StorageDestination")] pub storage_destination: tt::StorageReferencePath, } impl Validate for ExportRecordedData {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct ExportRecordedDataResponse { // Unique operation token for client to associate the relevant events. #[yaserde(prefix = "trc", rename = "OperationToken")] pub operation_token: tt::ReferenceToken, // List of exported file names. The device can also use // AsyncronousOperationStatus event to publish this list. #[yaserde(prefix = "trc", rename = "FileNames")] pub file_names: Vec<String>, #[yaserde(prefix = "trc", rename = "Extension")] pub extension: Option<export_recorded_data_response::ExtensionType>, } impl Validate for ExportRecordedDataResponse {} pub mod export_recorded_data_response { use super::*; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct ExtensionType {} impl Validate for ExtensionType {} } #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct StopExportRecordedData { // Unique ExportRecordedData operation token #[yaserde(prefix = "trc", rename = "OperationToken")] pub operation_token: tt::ReferenceToken, } impl Validate for StopExportRecordedData {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct StopExportRecordedDataResponse { // Progress percentage of ExportRecordedData operation. #[yaserde(prefix = "trc", rename = "Progress")] pub progress: f64, #[yaserde(prefix = "trc", rename = "FileProgressStatus")] pub file_progress_status: tt::ArrayOfFileProgress, } impl Validate for StopExportRecordedDataResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct GetExportRecordedDataState { // Unique ExportRecordedData operation token #[yaserde(prefix = "trc", rename = "OperationToken")] pub operation_token: tt::ReferenceToken, } impl Validate for GetExportRecordedDataState {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct GetExportRecordedDataStateResponse { // Progress percentage of ExportRecordedData operation. #[yaserde(prefix = "trc", rename = "Progress")] pub progress: f64, #[yaserde(prefix = "trc", rename = "FileProgressStatus")] pub file_progress_status: tt::ArrayOfFileProgress, } impl Validate for GetExportRecordedDataStateResponse {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct RecordingOptions { #[yaserde(prefix = "trc", rename = "Job")] pub job: JobOptions, #[yaserde(prefix = "trc", rename = "Track")] pub track: TrackOptions, } impl Validate for RecordingOptions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct JobOptions { // Number of spare jobs that can be created for the recording. #[yaserde(attribute, rename = "Spare")] pub spare: Option<i32>, // A device that supports recording of a restricted set of Media/Media2 // Service Profiles returns the list of profiles that can be recorded on the // given Recording. #[yaserde(attribute, rename = "CompatibleSources")] pub compatible_sources: Option<tt::StringAttrList>, } impl Validate for JobOptions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "trc", namespace = "trc: http://www.onvif.org/ver10/recording/wsdl" )] pub struct TrackOptions { // Total spare number of tracks that can be added to this recording. #[yaserde(attribute, rename = "SpareTotal")] pub spare_total: Option<i32>, // Number of spare Video tracks that can be added to this recording. #[yaserde(attribute, rename = "SpareVideo")] pub spare_video: Option<i32>, // Number of spare Aduio tracks that can be added to this recording. #[yaserde(attribute, rename = "SpareAudio")] pub spare_audio: Option<i32>, // Number of spare Metadata tracks that can be added to this recording. #[yaserde(attribute, rename = "SpareMetadata")] pub spare_metadata: Option<i32>, } impl Validate for TrackOptions {} // Returns the capabilities of the recording service. The result is returned in // a typed answer. pub async fn get_service_capabilities<T: transport::Transport>( transport: &T, request: &GetServiceCapabilities, ) -> Result<GetServiceCapabilitiesResponse, transport::Error> { transport::request(transport, request).await } // CreateRecording shall create a new recording. The new recording shall be // created with a track // for each supported TrackType see Recording Control Spec. pub async fn create_recording<T: transport::Transport>( transport: &T, request: &CreateRecording, ) -> Result<CreateRecordingResponse, transport::Error> { transport::request(transport, request).await } // DeleteRecording shall delete a recording object. Whenever a recording is // deleted, the device // shall delete all the tracks that are part of the recording, and it shall // delete all the Recording // Jobs that record into the recording. For each deleted recording job, the // device shall also // delete all the receiver objects associated with the recording job that are // automatically created // using the AutoCreateReceiver field of the recording job configuration // structure and are not // used in any other recording job. pub async fn delete_recording<T: transport::Transport>( transport: &T, request: &DeleteRecording, ) -> Result<DeleteRecordingResponse, transport::Error> { transport::request(transport, request).await } // GetRecordings shall return a description of all the recordings in the device. // This description // shall include a list of all the tracks for each recording. pub async fn get_recordings<T: transport::Transport>( transport: &T, request: &GetRecordings, ) -> Result<GetRecordingsResponse, transport::Error> { transport::request(transport, request).await } // SetRecordingConfiguration shall change the configuration of a recording. pub async fn set_recording_configuration<T: transport::Transport>( transport: &T, request: &SetRecordingConfiguration, ) -> Result<SetRecordingConfigurationResponse, transport::Error> { transport::request(transport, request).await } // GetRecordingConfiguration shall retrieve the recording configuration for a // recording. pub async fn get_recording_configuration<T: transport::Transport>( transport: &T, request: &GetRecordingConfiguration, ) -> Result<GetRecordingConfigurationResponse, transport::Error> { transport::request(transport, request).await } // GetRecordingOptions returns information for a recording identified by the // RecordingToken. The information includes the number of additonal tracks as // well as recording jobs that can be configured. pub async fn get_recording_options<T: transport::Transport>( transport: &T, request: &GetRecordingOptions, ) -> Result<GetRecordingOptionsResponse, transport::Error> { transport::request(transport, request).await } // This method shall create a new track within a recording. pub async fn create_track<T: transport::Transport>( transport: &T, request: &CreateTrack, ) -> Result<CreateTrackResponse, transport::Error> { transport::request(transport, request).await } // DeleteTrack shall remove a track from a recording. All the data in the track // shall be deleted. pub async fn delete_track<T: transport::Transport>( transport: &T, request: &DeleteTrack, ) -> Result<DeleteTrackResponse, transport::Error> { transport::request(transport, request).await } // GetTrackConfiguration shall retrieve the configuration for a specific track. pub async fn get_track_configuration<T: transport::Transport>( transport: &T, request: &GetTrackConfiguration, ) -> Result<GetTrackConfigurationResponse, transport::Error> { transport::request(transport, request).await } // SetTrackConfiguration shall change the configuration of a track. pub async fn set_track_configuration<T: transport::Transport>( transport: &T, request: &SetTrackConfiguration, ) -> Result<SetTrackConfigurationResponse, transport::Error> { transport::request(transport, request).await } // CreateRecordingJob shall create a new recording job. pub async fn create_recording_job<T: transport::Transport>( transport: &T, request: &CreateRecordingJob, ) -> Result<CreateRecordingJobResponse, transport::Error> { transport::request(transport, request).await } // DeleteRecordingJob removes a recording job. It shall also implicitly delete // all the receiver // objects associated with the recording job that are automatically created // using the // AutoCreateReceiver field of the recording job configuration structure and are // not used in any // other recording job. pub async fn delete_recording_job<T: transport::Transport>( transport: &T, request: &DeleteRecordingJob, ) -> Result<DeleteRecordingJobResponse, transport::Error> { transport::request(transport, request).await } // GetRecordingJobs shall return a list of all the recording jobs in the device. pub async fn get_recording_jobs<T: transport::Transport>( transport: &T, request: &GetRecordingJobs, ) -> Result<GetRecordingJobsResponse, transport::Error> { transport::request(transport, request).await } // SetRecordingJobConfiguration shall change the configuration for a recording // job. pub async fn set_recording_job_configuration<T: transport::Transport>( transport: &T, request: &SetRecordingJobConfiguration, ) -> Result<SetRecordingJobConfigurationResponse, transport::Error> { transport::request(transport, request).await } // GetRecordingJobConfiguration shall return the current configuration for a // recording job. pub async fn get_recording_job_configuration<T: transport::Transport>( transport: &T, request: &GetRecordingJobConfiguration, ) -> Result<GetRecordingJobConfigurationResponse, transport::Error> { transport::request(transport, request).await } // SetRecordingJobMode shall change the mode of the recording job. Using this // method shall be // equivalent to retrieving the recording job configuration, and writing it back // with a different // mode. pub async fn set_recording_job_mode<T: transport::Transport>( transport: &T, request: &SetRecordingJobMode, ) -> Result<SetRecordingJobModeResponse, transport::Error> { transport::request(transport, request).await } // GetRecordingJobState returns the state of a recording job. It includes an // aggregated state, // and state for each track of the recording job. pub async fn get_recording_job_state<T: transport::Transport>( transport: &T, request: &GetRecordingJobState, ) -> Result<GetRecordingJobStateResponse, transport::Error> { transport::request(transport, request).await } // Exports the selected recordings (from existing recorded data) to the given // storage target based on the requested file format. pub async fn export_recorded_data<T: transport::Transport>( transport: &T, request: &ExportRecordedData, ) -> Result<ExportRecordedDataResponse, transport::Error> { transport::request(transport, request).await } // Stops the selected ExportRecordedData operation. pub async fn stop_export_recorded_data<T: transport::Transport>( transport: &T, request: &StopExportRecordedData, ) -> Result<StopExportRecordedDataResponse, transport::Error> { transport::request(transport, request).await } // Retrieves the status of selected ExportRecordedData operation. pub async fn get_export_recorded_data_state<T: transport::Transport>( transport: &T, request: &GetExportRecordedDataState, ) -> Result<GetExportRecordedDataStateResponse, transport::Error> { transport::request(transport, request).await }
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
false
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/xsd_rs/xmlmime/src/lib.rs
xsd_rs/xmlmime/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use std::str::FromStr; use validate::Validate; use xsd_macro_utils::*; use yaserde_derive::{YaDeserialize, YaSerialize}; #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct ContentType(pub String); impl Validate for ContentType { fn validate(&self) -> Result<(), String> { if self.0.len() < "3".parse().unwrap() { return Err(format!( "MinLength validation error. \nExpected: 0 length >= 3 \nActual: 0 length == {}", self.0.len() )); } Ok(()) } } // pub type ExpectedContentTypes = String; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "xmime", namespace = "xmime: http://www.w3.org/2005/05/xmlmime" )] pub struct Base64Binary { #[yaserde(attribute, prefix = "xmime" rename = "contentType")] pub content_type: Option<ContentType>, } impl Validate for Base64Binary {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "xmime", namespace = "xmime: http://www.w3.org/2005/05/xmlmime" )] pub struct HexBinary { #[yaserde(attribute, prefix = "xmime" rename = "contentType")] pub content_type: Option<ContentType>, } impl Validate for HexBinary {}
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
false
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/xsd_rs/radiometry/src/lib.rs
xsd_rs/radiometry/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use onvif as tt; use validate::Validate; use xsd_types::types as xs; use yaserde_derive::{YaDeserialize, YaSerialize}; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "ttr", namespace = "ttr: http://www.onvif.org/ver20/analytics/radiometry" )] pub struct RadiometryModuleConfigOptions { // The total number of temperature measurement modules that can be created // on the // device, screen based or geolocated, of any type (spots or boxes). #[yaserde(prefix = "ttr", rename = "MaxMeasurementModules")] pub max_measurement_modules: i32, // The total number of spot measurement modules that can be loaded // simultaneously on the // screen by the device. A value of 0 shall be used to indicate no support // for Spots. #[yaserde(prefix = "ttr", rename = "MaxScreenSpots")] pub max_screen_spots: i32, // The total number of box measurement modules that can be loaded // simultaneously on the // screen by the device. A value of 0 shall be used to indicate no support // for Boxes. #[yaserde(prefix = "ttr", rename = "MaxScreenBoxes")] pub max_screen_boxes: i32, // Specifies valid ranges for the different radiometry parameters used for // temperature calculation. #[yaserde(prefix = "ttr", rename = "RadiometryParameterOptions")] pub radiometry_parameter_options: Option<RadiometryParameterOptions>, } impl Validate for RadiometryModuleConfigOptions {} // Describes valid ranges for the different radiometry parameters used for // accurate temperature calculation. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "ttr", namespace = "ttr: http://www.onvif.org/ver20/analytics/radiometry" )] pub struct RadiometryParameterOptions { // Valid range of temperature values, in Kelvin. #[yaserde(prefix = "ttr", rename = "ReflectedAmbientTemperature")] pub reflected_ambient_temperature: Option<tt::FloatRange>, // Valid range of emissivity values for the objects to measure. #[yaserde(prefix = "ttr", rename = "Emissivity")] pub emissivity: Option<tt::FloatRange>, // Valid range of distance between camera and object for a valid temperature // reading, in meters. #[yaserde(prefix = "ttr", rename = "DistanceToObject")] pub distance_to_object: Option<tt::FloatRange>, // Valid range of relative humidity values, in percentage. #[yaserde(prefix = "ttr", rename = "RelativeHumidity")] pub relative_humidity: Option<tt::FloatRange>, // Valid range of temperature values, in Kelvin. #[yaserde(prefix = "ttr", rename = "AtmosphericTemperature")] pub atmospheric_temperature: Option<tt::FloatRange>, // Valid range of atmospheric transmittance values. #[yaserde(prefix = "ttr", rename = "AtmosphericTransmittance")] pub atmospheric_transmittance: Option<tt::FloatRange>, // Valid range of temperature values, in Kelvin. #[yaserde(prefix = "ttr", rename = "ExtOpticsTemperature")] pub ext_optics_temperature: Option<tt::FloatRange>, // Valid range of external optics transmittance. #[yaserde(prefix = "ttr", rename = "ExtOpticsTransmittance")] pub ext_optics_transmittance: Option<tt::FloatRange>, } impl Validate for RadiometryParameterOptions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "ttr", namespace = "ttr: http://www.onvif.org/ver20/analytics/radiometry" )] pub struct RadiometrySpotModuleConfig { // Screen coordinates, if spot is currently on screen. Assumes normalized // screen limits (-1.0, 1.0). #[yaserde(prefix = "ttr", rename = "ScreenCoords")] pub screen_coords: tt::Vector, // Absolute orientation of the PTZ Vector with the Spot on screen. If no // PTZVector is present // the spot shall behave as a screen element, and stay on the same screen // coordinates as the PTZ // moves (like a head up display mask). If PTZVector is present the Spot // element shall appear on // display only when contained in the Field of View. In this case // SpotScreenCoords shall be // reported as relative to PTZVector. #[yaserde(prefix = "ttr", rename = "AbsoluteCoords")] pub absolute_coords: Option<tt::Ptzvector>, // Not present parameter means the Device shall use its value from Global // Parameters in Thermal Service. #[yaserde(prefix = "ttr", rename = "RadiometryParameters")] pub radiometry_parameters: Option<RadiometryParameters>, // Unique identifier for this Spot Temperature Measurement Analytics Module. #[yaserde(attribute, rename = "ItemID")] pub item_id: Option<tt::ReferenceToken>, // Indicates if the Temperature Measurement Item is enabled to provide // temperature readings. #[yaserde(attribute, rename = "Active")] pub active: Option<bool>, } impl Validate for RadiometrySpotModuleConfig {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "ttr", namespace = "ttr: http://www.onvif.org/ver20/analytics/radiometry" )] pub struct RadiometryBoxModuleConfig { // Screen coordinates, if box is currently on screen. Assumes normalized // screen limits (-1.0, 1.0). #[yaserde(prefix = "ttr", rename = "ScreenCoords")] pub screen_coords: tt::Rectangle, // Absolute orientation of the PTZ Vector with the Box on screen. If no // PTZVector is present // the box shall behave as a screen element, and stay on the same screen // coordinates as the PTZ // moves (like a head up display mask). If PTZVector is present the Box // element shall appear on // display only when contained in the Field of View. In this case // BoxScreenCoords shall be // reported as relative to PTZVector. #[yaserde(prefix = "ttr", rename = "AbsoluteCoords")] pub absolute_coords: Option<tt::Ptzvector>, // Not present parameter means the Device shall use its value from Global // Parameters in Thermal Service. #[yaserde(prefix = "ttr", rename = "RadiometryParameters")] pub radiometry_parameters: Option<RadiometryParameters>, // Unique identifier for this Box Temperature Measurement Analytics Module. #[yaserde(attribute, rename = "ItemID")] pub item_id: Option<tt::ReferenceToken>, // Indicates if the Temperature Measurement Item is enabled to provide // temperature readings. #[yaserde(attribute, rename = "Active")] pub active: Option<bool>, } impl Validate for RadiometryBoxModuleConfig {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "ttr", namespace = "ttr: http://www.onvif.org/ver20/analytics/radiometry" )] pub struct SpotTemperatureReading { // Not present means Global Parameters from Thermal Service are being used. #[yaserde(prefix = "ttr", rename = "RadiometryParameters")] pub radiometry_parameters: Option<RadiometryParameters>, #[yaserde(attribute, rename = "ItemID")] pub item_id: Option<tt::ReferenceToken>, #[yaserde(attribute, rename = "SpotTemperature")] pub spot_temperature: f64, } impl Validate for SpotTemperatureReading {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "ttr", namespace = "ttr: http://www.onvif.org/ver20/analytics/radiometry" )] pub struct BoxTemperatureReading { // Not present means Global Parameters from Thermal Service are being used. #[yaserde(prefix = "ttr", rename = "RadiometryParameters")] pub radiometry_parameters: Option<RadiometryParameters>, #[yaserde(attribute, rename = "ItemID")] pub item_id: tt::ReferenceToken, #[yaserde(attribute, rename = "MaxTemperature")] pub max_temperature: f64, #[yaserde(attribute, rename = "MinTemperature")] pub min_temperature: f64, #[yaserde(attribute, rename = "AverageTemperature")] pub average_temperature: Option<f64>, #[yaserde(attribute, rename = "MedianTemperature")] pub median_temperature: Option<f64>, } impl Validate for BoxTemperatureReading {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "ttr", namespace = "ttr: http://www.onvif.org/ver20/analytics/radiometry" )] pub struct RadiometryParameters { #[yaserde(prefix = "ttr", rename = "ReflectedAmbientTemperature")] pub reflected_ambient_temperature: Option<f64>, #[yaserde(prefix = "ttr", rename = "Emissivity")] pub emissivity: Option<f64>, #[yaserde(prefix = "ttr", rename = "DistanceToObject")] pub distance_to_object: Option<f64>, #[yaserde(prefix = "ttr", rename = "RelativeHumidity")] pub relative_humidity: Option<f64>, #[yaserde(prefix = "ttr", rename = "AtmosphericTemperature")] pub atmospheric_temperature: Option<f64>, #[yaserde(prefix = "ttr", rename = "AtmosphericTransmittance")] pub atmospheric_transmittance: Option<f64>, #[yaserde(prefix = "ttr", rename = "ExtOpticsTemperature")] pub ext_optics_temperature: Option<f64>, #[yaserde(prefix = "ttr", rename = "ExtOpticsTransmittance")] pub ext_optics_transmittance: Option<f64>, } impl Validate for RadiometryParameters {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "ttr", namespace = "ttr: http://www.onvif.org/ver20/analytics/radiometry" )] pub struct RadiometryRuleConfigOptions { // Specifies valid ranges for thresholds and reference parameters used for // triggering radiometric rules. #[yaserde(prefix = "ttr", rename = "RadiometryRuleOptions")] pub radiometry_rule_options: Option<RadiometryRuleOptions>, // Specifies valid rule conditions for temperature comparisions in // radiometric rules. #[yaserde(prefix = "ttr", rename = "TemperatureConditionOptions")] pub temperature_condition_options: Vec<TemperatureCondition>, // Specifies temperature measurement types provided by radiometry analytics // modules in the device. #[yaserde(prefix = "ttr", rename = "TemperatureTypeOptions")] pub temperature_type_options: Vec<TemperatureType>, } impl Validate for RadiometryRuleConfigOptions {} // Describes valid ranges for radiometric rule condition thresholds and // reference parameters. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "ttr", namespace = "ttr: http://www.onvif.org/ver20/analytics/radiometry" )] pub struct RadiometryRuleOptions { // Valid range of temperature values, in Kelvin. #[yaserde(prefix = "ttr", rename = "ThresholdTemperature")] pub threshold_temperature: tt::FloatRange, // Valid range of hysteresis time interval for temperature conditions, in // seconds. #[yaserde(prefix = "ttr", rename = "ThresholdTime")] pub threshold_time: Option<tt::FloatRange>, // Valid range of temperature hysteresis values, in Kelvin. #[yaserde(prefix = "ttr", rename = "HysteresisTemperature")] pub hysteresis_temperature: Option<tt::FloatRange>, } impl Validate for RadiometryRuleOptions {} #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum TemperatureCondition { LessThan, MoreThan, EqualTo, Change, __Unknown__(String), } impl Default for TemperatureCondition { fn default() -> TemperatureCondition { Self::__Unknown__("No valid variants".into()) } } impl Validate for TemperatureCondition {} #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum TemperatureType { MaxTemp, MinTemp, AverageTemp, StdDeviation, MedianTemp, #[yaserde(rename = "ISOCoverage")] Isocoverage, __Unknown__(String), } impl Default for TemperatureType { fn default() -> TemperatureType { Self::__Unknown__("No valid variants".into()) } } impl Validate for TemperatureType {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "ttr", namespace = "ttr: http://www.onvif.org/ver20/analytics/radiometry" )] pub struct RadiometryTemperatureRuleConfig { // Indicates which of the temperature values provided by the input Analytics // Module // shall be used by the rule. In the case of Analytics Modules providing a // single // Temperature Value (e.g. Spot) this parameter is ignored, and is therefore // optional. #[yaserde(prefix = "ttr", rename = "TemperatureType")] pub temperature_type: Option<TemperatureType>, // Indicates the type of temperature condition to check. #[yaserde(prefix = "ttr", rename = "RuleCondition")] pub rule_condition: TemperatureCondition, // Indicates the temperature reference value the rule shall be checked // against. #[yaserde(prefix = "ttr", rename = "ThresholdTemperature")] pub threshold_temperature: f64, // Indicates the time interval during which the rule condition shall be met // to trigger an event. #[yaserde(prefix = "ttr", rename = "ThresholdTime")] pub threshold_time: xs::Duration, // Indicates the width in Kelvin of the temerature hysteresis band to be // considered by the rule. #[yaserde(prefix = "ttr", rename = "HysteresisTemperature")] pub hysteresis_temperature: f64, // Reference Token to the Temperature Measurement Analytics Module providing // the Temperature on which rule is defined. #[yaserde(attribute, rename = "RadiometryModuleID")] pub radiometry_module_id: Option<tt::ReferenceToken>, // Indicates if the Temperature Rule is enabled to provide temperature alarm // events. #[yaserde(attribute, rename = "Enabled")] pub enabled: Option<bool>, } impl Validate for RadiometryTemperatureRuleConfig {}
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
false
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/xsd_rs/onvif_xsd/src/lib.rs
xsd_rs/onvif_xsd/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use b_2 as wsnt; use soap_envelope as soapenv; use std::str::FromStr; use validate::Validate; use xmlmime as xmime; use xsd_macro_utils::*; use xsd_types::types as xs; use yaserde_derive::{YaDeserialize, YaSerialize}; pub use common::*; // Base class for physical entities like inputs and outputs. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct DeviceEntity { // Unique identifier referencing the physical entity. #[yaserde(attribute, rename = "token")] pub token: ReferenceToken, } impl Validate for DeviceEntity {} // User readable name. Length up to 64 characters. #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct Name(pub String); impl Validate for Name { fn validate(&self) -> Result<(), String> { if self.0.len() > 64 { return Err(format!( "MaxLength validation error. \nExpected: 0 length <= 64 \nActual: 0 length == {}", self.0.len() )); } Ok(()) } } // Rectangle defined by lower left corner position and size. Units are pixel. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct IntRectangle { #[yaserde(attribute, rename = "x")] pub x: i32, #[yaserde(attribute, rename = "y")] pub y: i32, #[yaserde(attribute, rename = "width")] pub width: i32, #[yaserde(attribute, rename = "height")] pub height: i32, } impl Validate for IntRectangle {} // Range of a rectangle. The rectangle itself is defined by lower left corner // position and size. Units are pixel. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct IntRectangleRange { // Range of X-axis. #[yaserde(prefix = "tt", rename = "XRange")] pub x_range: IntRange, // Range of Y-axis. #[yaserde(prefix = "tt", rename = "YRange")] pub y_range: IntRange, // Range of width. #[yaserde(prefix = "tt", rename = "WidthRange")] pub width_range: IntRange, // Range of height. #[yaserde(prefix = "tt", rename = "HeightRange")] pub height_range: IntRange, } impl Validate for IntRectangleRange {} // Range of values greater equal Min value and less equal Max value. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct FloatRange { #[yaserde(prefix = "tt", rename = "Min")] pub min: f64, #[yaserde(prefix = "tt", rename = "Max")] pub max: f64, } impl Validate for FloatRange {} // Range of duration greater equal Min duration and less equal Max duration. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct DurationRange { #[yaserde(prefix = "tt", rename = "Min")] pub min: xs::Duration, #[yaserde(prefix = "tt", rename = "Max")] pub max: xs::Duration, } impl Validate for DurationRange {} // List of values. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct IntList { #[yaserde(prefix = "tt", rename = "Items")] pub items: Vec<i32>, } impl Validate for IntList {} #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct IntAttrList(pub Vec<i32>); impl Validate for IntAttrList {} #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct FloatAttrList(pub Vec<f64>); impl Validate for FloatAttrList {} #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct StringAttrList(pub Vec<String>); impl Validate for StringAttrList {} #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct ReferenceTokenList(pub Vec<ReferenceToken>); impl Validate for ReferenceTokenList {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct FloatList { #[yaserde(prefix = "tt", rename = "Items")] pub items: Vec<f64>, } impl Validate for FloatList {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct StringItems { #[yaserde(prefix = "tt", rename = "Item")] pub item: Vec<String>, } impl Validate for StringItems {} // pub type StringList = StringAttrList; // pub type IntRange = IntRange; // pub type IntList = IntAttrList; // pub type FloatRange = FloatRange; // pub type FloatList = FloatAttrList; // pub type DurationRange = DurationRange; // pub type IntRectangleRange = IntRectangleRange; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct AnyHolder {} impl Validate for AnyHolder {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct VideoSource { // Frame rate in frames per second. #[yaserde(prefix = "tt", rename = "Framerate")] pub framerate: f64, // Horizontal and vertical resolution #[yaserde(prefix = "tt", rename = "Resolution")] pub resolution: VideoResolution, // Optional configuration of the image sensor. #[yaserde(prefix = "tt", rename = "Imaging")] pub imaging: Option<ImagingSettings>, #[yaserde(prefix = "tt", rename = "Extension")] pub extension: Option<VideoSourceExtension>, // Unique identifier referencing the physical entity. #[yaserde(attribute, rename = "token")] pub token: ReferenceToken, } impl Validate for VideoSource {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct VideoSourceExtension { // Optional configuration of the image sensor. To be used if imaging service // 2.00 is supported. #[yaserde(prefix = "tt", rename = "Imaging")] pub imaging: Option<ImagingSettings20>, // `Extension` inside `Extension` causes infinite loop at deserialization // https://github.com/media-io/yaserde/issues/76 // #[yaserde(prefix = "tt", rename = "Extension")] // pub extension: Option<VideoSourceExtension2>, } impl Validate for VideoSourceExtension {} // #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] // #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] // pub struct VideoSourceExtension2 {} // // impl Validate for VideoSourceExtension2 {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct AudioSource { // number of available audio channels. (1: mono, 2: stereo) #[yaserde(prefix = "tt", rename = "Channels")] pub channels: i32, // Unique identifier referencing the physical entity. #[yaserde(attribute, rename = "token")] pub token: ReferenceToken, } impl Validate for AudioSource {} // A media profile consists of a set of media configurations. Media profiles are // used by a client // to configure properties of a media stream from an NVT. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct Profile { // User readable name of the profile. #[yaserde(prefix = "tt", rename = "Name")] pub name: Name, // Optional configuration of the Video input. #[yaserde(prefix = "tt", rename = "VideoSourceConfiguration")] pub video_source_configuration: Option<VideoSourceConfiguration>, // Optional configuration of the Audio input. #[yaserde(prefix = "tt", rename = "AudioSourceConfiguration")] pub audio_source_configuration: Option<AudioSourceConfiguration>, // Optional configuration of the Video encoder. #[yaserde(prefix = "tt", rename = "VideoEncoderConfiguration")] pub video_encoder_configuration: Option<VideoEncoderConfiguration>, // Optional configuration of the Audio encoder. #[yaserde(prefix = "tt", rename = "AudioEncoderConfiguration")] pub audio_encoder_configuration: Option<AudioEncoderConfiguration>, // Optional configuration of the video analytics module and rule engine. #[yaserde(prefix = "tt", rename = "VideoAnalyticsConfiguration")] pub video_analytics_configuration: Option<VideoAnalyticsConfiguration>, // Optional configuration of the pan tilt zoom unit. #[yaserde(prefix = "tt", rename = "PTZConfiguration")] pub ptz_configuration: Option<Ptzconfiguration>, // Optional configuration of the metadata stream. #[yaserde(prefix = "tt", rename = "MetadataConfiguration")] pub metadata_configuration: Option<MetadataConfiguration>, // Extensions defined in ONVIF 2.0 #[yaserde(prefix = "tt", rename = "Extension")] pub extension: Option<ProfileExtension>, // Unique identifier of the profile. #[yaserde(attribute, rename = "token")] pub token: ReferenceToken, // A value of true signals that the profile cannot be deleted. Default is // false. #[yaserde(attribute, rename = "fixed")] pub fixed: Option<bool>, } impl Validate for Profile {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct ProfileExtension { // Optional configuration of the Audio output. #[yaserde(prefix = "tt", rename = "AudioOutputConfiguration")] pub audio_output_configuration: Option<AudioOutputConfiguration>, // Optional configuration of the Audio decoder. #[yaserde(prefix = "tt", rename = "AudioDecoderConfiguration")] pub audio_decoder_configuration: Option<AudioDecoderConfiguration>, // `Extension` inside `Extension` causes infinite loop at deserialization // https://github.com/media-io/yaserde/issues/76 // #[yaserde(prefix = "tt", rename = "Extension")] // pub extension: Option<ProfileExtension2>, } impl Validate for ProfileExtension {} // #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] // #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] // pub struct ProfileExtension2 {} // // impl Validate for ProfileExtension2 {} // pub type VideoSourceConfiguration = VideoSourceConfiguration; // pub type AudioSourceConfiguration = AudioSourceConfiguration; // pub type VideoEncoderConfiguration = VideoEncoderConfiguration; // pub type AudioEncoderConfiguration = AudioEncoderConfiguration; // pub type VideoAnalyticsConfiguration = VideoAnalyticsConfiguration; // pub type Ptzconfiguration = Ptzconfiguration; // pub type MetadataConfiguration = MetadataConfiguration; // pub type AudioOutputConfiguration = AudioOutputConfiguration; // pub type AudioDecoderConfiguration = AudioDecoderConfiguration; // Base type defining the common properties of a configuration. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct ConfigurationEntity { // User readable name. Length up to 64 characters. #[yaserde(prefix = "tt", rename = "Name")] pub name: Name, // Number of internal references currently using this configuration. #[yaserde(prefix = "tt", rename = "UseCount")] pub use_count: i32, // Token that uniquely references this configuration. Length up to 64 // characters. #[yaserde(attribute, rename = "token")] pub token: ReferenceToken, } impl Validate for ConfigurationEntity {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct VideoSourceConfiguration { // Reference to the physical input. #[yaserde(prefix = "tt", rename = "SourceToken")] pub source_token: ReferenceToken, // Rectangle specifying the Video capturing area. The capturing area shall // not be larger than the whole Video source area. #[yaserde(prefix = "tt", rename = "Bounds")] pub bounds: IntRectangle, #[yaserde(prefix = "tt", rename = "Extension")] pub extension: Option<VideoSourceConfigurationExtension>, // Readonly parameter signalling Source configuration's view mode, for // devices supporting different view modes as defined in tt:viewModes. #[yaserde(attribute, rename = "ViewMode")] pub view_mode: Option<String>, // User readable name. Length up to 64 characters. #[yaserde(prefix = "tt", rename = "Name")] pub name: Name, // Number of internal references currently using this configuration. #[yaserde(prefix = "tt", rename = "UseCount")] pub use_count: i32, // Token that uniquely references this configuration. Length up to 64 // characters. #[yaserde(attribute, rename = "token")] pub token: ReferenceToken, } impl Validate for VideoSourceConfiguration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct VideoSourceConfigurationExtension { // Optional element to configure rotation of captured image. // What resolutions a device supports shall be unaffected by the Rotate // parameters. #[yaserde(prefix = "tt", rename = "Rotate")] pub rotate: Option<Rotate>, // `Extension` inside `Extension` causes infinite loop at deserialization // https://github.com/media-io/yaserde/issues/76 // #[yaserde(prefix = "tt", rename = "Extension")] // pub extension: Option<VideoSourceConfigurationExtension2>, } impl Validate for VideoSourceConfigurationExtension {} // #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] // #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] // pub struct VideoSourceConfigurationExtension2 { // // Optional element describing the geometric lens distortion. Multiple // // instances for future variable lens support. // #[yaserde(prefix = "tt", rename = "LensDescription")] // pub lens_description: Vec<LensDescription>, // // // Optional element describing the scene orientation in the camera’s field // // of view. // #[yaserde(prefix = "tt", rename = "SceneOrientation")] // pub scene_orientation: SceneOrientation, // } // // impl Validate for VideoSourceConfigurationExtension2 {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct Rotate { // Parameter to enable/disable Rotation feature. #[yaserde(prefix = "tt", rename = "Mode")] pub mode: RotateMode, // Optional parameter to configure how much degree of clockwise rotation of // image for On mode. Omitting this parameter for On mode means 180 degree // rotation. #[yaserde(prefix = "tt", rename = "Degree")] pub degree: Option<i32>, #[yaserde(prefix = "tt", rename = "Extension")] pub extension: Option<RotateExtension>, } impl Validate for Rotate {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct RotateExtension {} impl Validate for RotateExtension {} #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub enum RotateMode { // Enable the Rotate feature. Degree of rotation is specified Degree // parameter. #[yaserde(rename = "OFF")] Off, // Disable the Rotate feature. #[yaserde(rename = "ON")] On, // Rotate feature is automatically activated by the device. #[yaserde(rename = "AUTO")] Auto, __Unknown__(String), } impl Default for RotateMode { fn default() -> RotateMode { Self::__Unknown__("No valid variants".into()) } } impl Validate for RotateMode {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct LensProjection { // Angle of incidence. #[yaserde(prefix = "tt", rename = "Angle")] pub angle: f64, // Mapping radius as a consequence of the emergent angle. #[yaserde(prefix = "tt", rename = "Radius")] pub radius: f64, // Optional ray absorption at the given angle due to vignetting. A value of // one means no absorption. #[yaserde(prefix = "tt", rename = "Transmittance")] pub transmittance: Option<f64>, } impl Validate for LensProjection {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct LensOffset { // Optional horizontal offset of the lens center in normalized coordinates. #[yaserde(attribute, rename = "x")] pub x: Option<f64>, // Optional vertical offset of the lens center in normalized coordinates. #[yaserde(attribute, rename = "y")] pub y: Option<f64>, } impl Validate for LensOffset {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct LensDescription { // Offset of the lens center to the imager center in normalized coordinates. #[yaserde(prefix = "tt", rename = "Offset")] pub offset: LensOffset, // Radial description of the projection characteristics. The resulting curve // is defined by the B-Spline interpolation // over the given elements. The element for Radius zero shall not be // provided. The projection points shall be ordered with ascending Radius. // Items outside the last projection Radius shall be assumed to be invisible // (black). #[yaserde(prefix = "tt", rename = "Projection")] pub projection: Vec<LensProjection>, // Compensation of the x coordinate needed for the ONVIF normalized // coordinate system. #[yaserde(prefix = "tt", rename = "XFactor")] pub x_factor: f64, // Optional focal length of the optical system. #[yaserde(attribute, rename = "FocalLength")] pub focal_length: Option<f64>, } impl Validate for LensDescription {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct VideoSourceConfigurationOptions { // Supported range for the capturing area. // Device that does not support cropped streaming shall express BoundsRange // option as mentioned below // BoundsRange->XRange and BoundsRange->YRange with same Min/Max values // HeightRange and WidthRange Min/Max values same as VideoSource Height and // Width Limits. #[yaserde(prefix = "tt", rename = "BoundsRange")] pub bounds_range: IntRectangleRange, // List of physical inputs. #[yaserde(prefix = "tt", rename = "VideoSourceTokensAvailable")] pub video_source_tokens_available: Vec<ReferenceToken>, #[yaserde(prefix = "tt", rename = "Extension")] pub extension: Option<VideoSourceConfigurationOptionsExtension>, // Maximum number of profiles. #[yaserde(attribute, rename = "MaximumNumberOfProfiles")] pub maximum_number_of_profiles: Option<i32>, } impl Validate for VideoSourceConfigurationOptions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct VideoSourceConfigurationOptionsExtension { // Options of parameters for Rotation feature. #[yaserde(prefix = "tt", rename = "Rotate")] pub rotate: Option<RotateOptions>, // `Extension` inside `Extension` causes infinite loop at deserialization // https://github.com/media-io/yaserde/issues/76 // #[yaserde(prefix = "tt", rename = "Extension")] // pub extension: Option<VideoSourceConfigurationOptionsExtension2>, } impl Validate for VideoSourceConfigurationOptionsExtension {} // #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] // #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] // pub struct VideoSourceConfigurationOptionsExtension2 { // // Scene orientation modes supported by the device for this configuration. // #[yaserde(prefix = "tt", rename = "SceneOrientationMode")] // pub scene_orientation_mode: Vec<SceneOrientationMode>, // } // // impl Validate for VideoSourceConfigurationOptionsExtension2 {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct RotateOptions { // Supported options of Rotate mode parameter. #[yaserde(prefix = "tt", rename = "Mode")] pub mode: Vec<RotateMode>, // List of supported degree value for rotation. #[yaserde(prefix = "tt", rename = "DegreeList")] pub degree_list: Option<IntList>, #[yaserde(prefix = "tt", rename = "Extension")] pub extension: Option<RotateOptionsExtension>, // After setting the rotation, if a device starts to reboot this value is // true. // If a device can handle rotation setting without rebooting this value is // false. #[yaserde(attribute, rename = "Reboot")] pub reboot: Option<bool>, } impl Validate for RotateOptions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct RotateOptionsExtension {} impl Validate for RotateOptionsExtension {} #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub enum SceneOrientationMode { #[yaserde(rename = "MANUAL")] Manual, #[yaserde(rename = "AUTO")] Auto, __Unknown__(String), } impl Default for SceneOrientationMode { fn default() -> SceneOrientationMode { Self::__Unknown__("No valid variants".into()) } } impl Validate for SceneOrientationMode {} #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub enum SceneOrientationOption { Below, Horizon, Above, __Unknown__(String), } impl Default for SceneOrientationOption { fn default() -> SceneOrientationOption { Self::__Unknown__("No valid variants".into()) } } impl Validate for SceneOrientationOption {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct SceneOrientation { // Parameter to assign the way the camera determines the scene orientation. #[yaserde(prefix = "tt", rename = "Mode")] pub mode: SceneOrientationMode, // Assigned or determined scene orientation based on the Mode. When // assigning the Mode to AUTO, this field // is optional and will be ignored by the device. When assigning the Mode to // MANUAL, this field is required // and the device will return an InvalidArgs fault if missing. #[yaserde(prefix = "tt", rename = "Orientation")] pub orientation: Option<String>, } impl Validate for SceneOrientation {} // Source view modes supported by device. #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct ViewModes(pub String); impl Validate for ViewModes {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct VideoEncoderConfiguration { // Used video codec, either Jpeg, H.264 or Mpeg4 #[yaserde(prefix = "tt", rename = "Encoding")] pub encoding: VideoEncoding, // Configured video resolution #[yaserde(prefix = "tt", rename = "Resolution")] pub resolution: VideoResolution, // Relative value for the video quantizers and the quality of the video. A // high value within supported quality range means higher quality #[yaserde(prefix = "tt", rename = "Quality")] pub quality: f64, // Optional element to configure rate control related parameters. #[yaserde(prefix = "tt", rename = "RateControl")] pub rate_control: Option<VideoRateControl>, // Optional element to configure Mpeg4 related parameters. #[yaserde(prefix = "tt", rename = "MPEG4")] pub mpeg4: Option<Mpeg4Configuration>, // Optional element to configure H.264 related parameters. #[yaserde(prefix = "tt", rename = "H264")] pub h264: Option<H264Configuration>, // Defines the multicast settings that could be used for video streaming. #[yaserde(prefix = "tt", rename = "Multicast")] pub multicast: MulticastConfiguration, // The rtsp session timeout for the related video stream #[yaserde(prefix = "tt", rename = "SessionTimeout")] pub session_timeout: xs::Duration, // A value of true indicates that frame rate is a fixed value rather than an // upper limit, // and that the video encoder shall prioritize frame rate over all other // adaptable // configuration values such as bitrate. Default is false. #[yaserde(attribute, rename = "GuaranteedFrameRate")] pub guaranteed_frame_rate: Option<bool>, // User readable name. Length up to 64 characters. #[yaserde(prefix = "tt", rename = "Name")] pub name: Name, // Number of internal references currently using this configuration. #[yaserde(prefix = "tt", rename = "UseCount")] pub use_count: i32, // Token that uniquely references this configuration. Length up to 64 // characters. #[yaserde(attribute, rename = "token")] pub token: ReferenceToken, } impl Validate for VideoEncoderConfiguration {} #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub enum VideoEncoding { #[yaserde(rename = "JPEG")] Jpeg, #[yaserde(rename = "MPEG4")] Mpeg4, H264, __Unknown__(String), } impl Default for VideoEncoding { fn default() -> VideoEncoding { Self::__Unknown__("No valid variants".into()) } } impl Validate for VideoEncoding {} #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub enum Mpeg4Profile { #[yaserde(rename = "SP")] Sp, #[yaserde(rename = "ASP")] Asp, __Unknown__(String), } impl Default for Mpeg4Profile { fn default() -> Mpeg4Profile { Self::__Unknown__("No valid variants".into()) } } impl Validate for Mpeg4Profile {} #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub enum H264Profile { Baseline, Main, Extended, High, __Unknown__(String), } impl Default for H264Profile { fn default() -> H264Profile { Self::__Unknown__("No valid variants".into()) } } impl Validate for H264Profile {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct VideoResolution { // Number of the columns of the Video image. #[yaserde(prefix = "tt", rename = "Width")] pub width: i32, // Number of the lines of the Video image. #[yaserde(prefix = "tt", rename = "Height")] pub height: i32, } impl Validate for VideoResolution {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct VideoRateControl { // Maximum output framerate in fps. If an EncodingInterval is provided the // resulting encoded framerate will be reduced by the given factor. #[yaserde(prefix = "tt", rename = "FrameRateLimit")] pub frame_rate_limit: i32, // Interval at which images are encoded and transmitted. (A value of 1 means // that every frame is encoded, a value of 2 means that every 2nd frame is // encoded ...) #[yaserde(prefix = "tt", rename = "EncodingInterval")] pub encoding_interval: i32, // the maximum output bitrate in kbps #[yaserde(prefix = "tt", rename = "BitrateLimit")] pub bitrate_limit: i32, } impl Validate for VideoRateControl {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct Mpeg4Configuration { // Determines the interval in which the I-Frames will be coded. An entry of // 1 indicates I-Frames are continuously generated. An entry of 2 indicates // that every 2nd image is an I-Frame, and 3 only every 3rd frame, etc. The // frames in between are coded as P or B Frames. #[yaserde(prefix = "tt", rename = "GovLength")] pub gov_length: i32, // the Mpeg4 profile, either simple profile (SP) or advanced simple profile // (ASP) #[yaserde(prefix = "tt", rename = "Mpeg4Profile")] pub mpeg_4_profile: Mpeg4Profile, } impl Validate for Mpeg4Configuration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct H264Configuration { // Group of Video frames length. Determines typically the interval in which // the I-Frames will be coded. An entry of 1 indicates I-Frames are // continuously generated. An entry of 2 indicates that every 2nd image is // an I-Frame, and 3 only every 3rd frame, etc. The frames in between are // coded as P or B Frames. #[yaserde(prefix = "tt", rename = "GovLength")] pub gov_length: i32, // the H.264 profile, either baseline, main, extended or high #[yaserde(prefix = "tt", rename = "H264Profile")] pub h264_profile: H264Profile, } impl Validate for H264Configuration {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct VideoEncoderConfigurationOptions { // Range of the quality values. A high value means higher quality. #[yaserde(prefix = "tt", rename = "QualityRange")] pub quality_range: IntRange, // Optional JPEG encoder settings ranges (See also Extension element). #[yaserde(prefix = "tt", rename = "JPEG")] pub jpeg: Option<JpegOptions>, // Optional MPEG-4 encoder settings ranges (See also Extension element). #[yaserde(prefix = "tt", rename = "MPEG4")] pub mpeg4: Option<Mpeg4Options>, // Optional H.264 encoder settings ranges (See also Extension element). #[yaserde(prefix = "tt", rename = "H264")] pub h264: Option<H264Options>, #[yaserde(prefix = "tt", rename = "Extension")] pub extension: Option<VideoEncoderOptionsExtension>, // Indicates the support for the GuaranteedFrameRate attribute on the // VideoEncoderConfiguration element. #[yaserde(attribute, rename = "GuaranteedFrameRateSupported")] pub guaranteed_frame_rate_supported: Option<bool>, } impl Validate for VideoEncoderConfigurationOptions {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct VideoEncoderOptionsExtension { // Optional JPEG encoder settings ranges. #[yaserde(prefix = "tt", rename = "JPEG")] pub jpeg: Option<JpegOptions2>, // Optional MPEG-4 encoder settings ranges. #[yaserde(prefix = "tt", rename = "MPEG4")] pub mpeg4: Option<Mpeg4Options2>, // Optional H.264 encoder settings ranges. #[yaserde(prefix = "tt", rename = "H264")] pub h264: Option<H264Options2>, // `Extension` inside `Extension` causes infinite loop at deserialization // https://github.com/media-io/yaserde/issues/76 // #[yaserde(prefix = "tt", rename = "Extension")] // pub extension: Option<VideoEncoderOptionsExtension2>, } impl Validate for VideoEncoderOptionsExtension {} // #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] // #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] // pub struct VideoEncoderOptionsExtension2 {} // // impl Validate for VideoEncoderOptionsExtension2 {}
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
true
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/xsd_rs/rules/src/lib.rs
xsd_rs/rules/src/lib.rs
use onvif as tt; use validate::Validate; use yaserde_derive::{YaDeserialize, YaSerialize}; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "axt", namespace = "axt: http://www.onvif.org/ver20/analytics" )] pub struct MotionRegionConfigOptions { // The total number of Motion Region Detector rules that can be created on // the device. // This element is deprecated. maxInstances in the GetSupportedRules shall // be used instead. #[yaserde(prefix = "axt", rename = "MaxRegions")] pub max_regions: Option<i32>, // True if the device supports disarming a Motion Region Detector rule. #[yaserde(prefix = "axt", rename = "DisarmSupport")] pub disarm_support: Option<bool>, // True if the device supports defining a region using a Polygon instead of // a rectangle. // The rectangle points are still passed using a Polygon element if the // device does not support polygon regions. // In this case, the points provided in the Polygon element shall represent // a rectangle. #[yaserde(prefix = "axt", rename = "PolygonSupport")] pub polygon_support: Option<bool>, // For devices that support Polygons with limitations on the number of // sides, // provides the minimum and maximum number of sides that can be defined in // the // Polygon. #[yaserde(prefix = "axt", rename = "PolygonLimits")] pub polygon_limits: Option<tt::IntRange>, // Indicates the device can only support one sensitivity level for all // defines // motion detection regions. Changing the sensitivity for one region would // be // applied to all regions. #[yaserde(prefix = "axt", rename = "SingleSensitivitySupport")] pub single_sensitivity_support: Option<bool>, // True if the device will include the Name of the Rule to indicate the // region // that motion was detected in. #[yaserde(prefix = "axt", rename = "RuleNotification")] pub rule_notification: Option<bool>, // Indicates the support for PTZ preset based motion detection, if supported // Preset token can be associated with a motion region. #[yaserde(attribute, rename = "PTZPresetMotionSupport")] pub ptz_preset_motion_support: Option<bool>, } impl Validate for MotionRegionConfigOptions {} // pub type MotionRegionConfigOptions = MotionRegionConfigOptions; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde( prefix = "axt", namespace = "axt: http://www.onvif.org/ver20/analytics" )] pub struct MotionRegionConfig { // Provides the points of a Polygon in the VideoSourceConfiguration's Bounds // element. If the device does not support Polygons, this structure must // contain // four points that represent a Rectangle. #[yaserde(prefix = "tt", rename = "Polygon")] pub polygon: Option<tt::Polygon>, // Preset position associated with the motion region defined by Polygon. #[yaserde(prefix = "axt", rename = "PresetToken")] pub preset_token: Option<tt::ReferenceToken>, // Indicates if the Motion Region is Armed (detecting motion) or Disarmed // (motion is // not being detected). #[yaserde(attribute, rename = "Armed")] pub armed: Option<bool>, // Indicates the sensitivity level of the motion detector for this region. // The // sensitivity value is normalized where 0 represents the lower sensitivity // where // significant motion is required to trigger an alarm and 1 represents the // higher // sensitivity where very little motion is required to trigger an alarm. #[yaserde(attribute, rename = "Sensitivity")] pub sensitivity: Option<f64>, } impl Validate for MotionRegionConfig {}
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
false
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/xsd_rs/common/src/lib.rs
xsd_rs/common/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use std::str::FromStr; use validate::Validate; use xsd_macro_utils::*; use xsd_types::types as xs; use yaserde_derive::{YaDeserialize, YaSerialize}; // Unique identifier for a physical or logical resource. // Tokens should be assigned such that they are unique within a device. Tokens // must be at least unique within its class. // Length up to 64 characters. #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct ReferenceToken(pub String); impl Validate for ReferenceToken { fn validate(&self) -> Result<(), String> { if self.0.len() > "64".parse().unwrap() { return Err(format!( "MaxLength validation error. \nExpected: 0 length <= 64 \nActual: 0 length == {}", self.0.len() )); } Ok(()) } } // Range of values greater equal Min value and less equal Max value. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct IntRange { #[yaserde(prefix = "tt", rename = "Min")] pub min: i32, #[yaserde(prefix = "tt", rename = "Max")] pub max: i32, } impl Validate for IntRange {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct Vector2D { #[yaserde(attribute, rename = "x")] pub x: f64, #[yaserde(attribute, rename = "y")] pub y: f64, // Pan/tilt coordinate space selector. The following options are defined: #[yaserde(attribute, rename = "space")] pub space: Option<String>, } impl Validate for Vector2D {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct Vector1D { #[yaserde(attribute, rename = "x")] pub x: f64, // Zoom coordinate space selector. The following options are defined: #[yaserde(attribute, rename = "space")] pub space: Option<String>, } impl Validate for Vector1D {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct Ptzvector { // Pan and tilt position. The x component corresponds to pan and the y // component to tilt. #[yaserde(prefix = "tt", rename = "PanTilt")] pub pan_tilt: Option<Vector2D>, // A zoom position. #[yaserde(prefix = "tt", rename = "Zoom")] pub zoom: Option<Vector1D>, } impl Validate for Ptzvector {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct Ptzstatus { // Specifies the absolute position of the PTZ unit together with the Space // references. The default absolute spaces of the corresponding PTZ // configuration MUST be referenced within the Position element. #[yaserde(prefix = "tt", rename = "Position")] pub position: Option<Ptzvector>, // Indicates if the Pan/Tilt/Zoom device unit is currently moving, idle or // in an unknown state. #[yaserde(prefix = "tt", rename = "MoveStatus")] pub move_status: Option<PtzmoveStatus>, // States a current PTZ error. #[yaserde(prefix = "tt", rename = "Error")] pub error: Option<String>, // Specifies the UTC time when this status was generated. #[yaserde(prefix = "tt", rename = "UtcTime")] pub utc_time: xs::DateTime, } impl Validate for Ptzstatus {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct PtzmoveStatus { #[yaserde(prefix = "tt", rename = "PanTilt")] pub pan_tilt: Option<MoveStatus>, #[yaserde(prefix = "tt", rename = "Zoom")] pub zoom: Option<MoveStatus>, } impl Validate for PtzmoveStatus {} #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub enum MoveStatus { #[yaserde(rename = "IDLE")] Idle, #[yaserde(rename = "MOVING")] Moving, #[yaserde(rename = "UNKNOWN")] Unknown, __Unknown__(String), } impl Default for MoveStatus { fn default() -> MoveStatus { Self::__Unknown__("No valid variants".into()) } } impl Validate for MoveStatus {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct Vector { #[yaserde(attribute, rename = "x")] pub x: Option<f64>, #[yaserde(attribute, rename = "y")] pub y: Option<f64>, } impl Validate for Vector {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct Rectangle { #[yaserde(attribute, rename = "bottom")] pub bottom: Option<f64>, #[yaserde(attribute, rename = "top")] pub top: Option<f64>, #[yaserde(attribute, rename = "right")] pub right: Option<f64>, #[yaserde(attribute, rename = "left")] pub left: Option<f64>, } impl Validate for Rectangle {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct Polygon { #[yaserde(prefix = "tt", rename = "Point")] pub point: Vec<Vector>, } impl Validate for Polygon {} // pub type Polygon = Polygon; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct Color { #[yaserde(attribute, rename = "X")] pub x: f64, #[yaserde(attribute, rename = "Y")] pub y: f64, #[yaserde(attribute, rename = "Z")] pub z: f64, // Acceptable values: #[yaserde(attribute, rename = "Colorspace")] pub colorspace: Option<String>, } impl Validate for Color {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct ColorCovariance { #[yaserde(attribute, rename = "XX")] pub xx: f64, #[yaserde(attribute, rename = "YY")] pub yy: f64, #[yaserde(attribute, rename = "ZZ")] pub zz: f64, #[yaserde(attribute, rename = "XY")] pub xy: Option<f64>, #[yaserde(attribute, rename = "XZ")] pub xz: Option<f64>, #[yaserde(attribute, rename = "YZ")] pub yz: Option<f64>, // Acceptable values are the same as in tt:Color. #[yaserde(attribute, rename = "Colorspace")] pub colorspace: Option<String>, } impl Validate for ColorCovariance {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct Transformation { #[yaserde(prefix = "tt", rename = "Translate")] pub translate: Option<Vector>, #[yaserde(prefix = "tt", rename = "Scale")] pub scale: Option<Vector>, #[yaserde(prefix = "tt", rename = "Extension")] pub extension: Option<TransformationExtension>, } impl Validate for Transformation {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct TransformationExtension {} impl Validate for TransformationExtension {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct GeoLocation { // East west location as angle. #[yaserde(attribute, rename = "lon")] pub lon: Option<f64>, // North south location as angle. #[yaserde(attribute, rename = "lat")] pub lat: Option<f64>, // Hight in meters above sea level. #[yaserde(attribute, rename = "elevation")] pub elevation: Option<f64>, } impl Validate for GeoLocation {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct GeoOrientation { // Rotation around the x axis. #[yaserde(attribute, rename = "roll")] pub roll: Option<f64>, // Rotation around the y axis. #[yaserde(attribute, rename = "pitch")] pub pitch: Option<f64>, // Rotation around the z axis. #[yaserde(attribute, rename = "yaw")] pub yaw: Option<f64>, } impl Validate for GeoOrientation {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct LocalLocation { // East west location as angle. #[yaserde(attribute, rename = "x")] pub x: Option<f64>, // North south location as angle. #[yaserde(attribute, rename = "y")] pub y: Option<f64>, // Offset in meters from the sea level. #[yaserde(attribute, rename = "z")] pub z: Option<f64>, } impl Validate for LocalLocation {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct LocalOrientation { // Rotation around the y axis. #[yaserde(attribute, rename = "pan")] pub pan: Option<f64>, // Rotation around the z axis. #[yaserde(attribute, rename = "tilt")] pub tilt: Option<f64>, // Rotation around the x axis. #[yaserde(attribute, rename = "roll")] pub roll: Option<f64>, } impl Validate for LocalOrientation {} #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub enum Entity { Device, VideoSource, AudioSource, __Unknown__(String), } impl Default for Entity { fn default() -> Entity { Self::__Unknown__("No valid variants".into()) } } impl Validate for Entity {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct LocationEntity { // Location on earth. #[yaserde(prefix = "tt", rename = "GeoLocation")] pub geo_location: Option<GeoLocation>, // Orientation relative to earth. #[yaserde(prefix = "tt", rename = "GeoOrientation")] pub geo_orientation: Option<GeoOrientation>, // Indoor location offset. #[yaserde(prefix = "tt", rename = "LocalLocation")] pub local_location: Option<LocalLocation>, // Indoor orientation offset. #[yaserde(prefix = "tt", rename = "LocalOrientation")] pub local_orientation: Option<LocalOrientation>, // Entity type the entry refers to, use a value from the tt:Entity // enumeration. #[yaserde(attribute, rename = "Entity")] pub entity: Option<String>, // Optional entity token. #[yaserde(attribute, rename = "Token")] pub token: Option<ReferenceToken>, // If this value is true the entity cannot be deleted. #[yaserde(attribute, rename = "Fixed")] pub fixed: Option<bool>, // Optional reference to the XAddr of another devices DeviceManagement // service. #[yaserde(attribute, rename = "GeoSource")] pub geo_source: Option<String>, // If set the geo location is obtained internally. #[yaserde(attribute, rename = "AutoGeo")] pub auto_geo: Option<bool>, } impl Validate for LocationEntity {}
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
false
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/xsd_rs/types/src/lib.rs
xsd_rs/types/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] use std::str::FromStr; use validate::Validate; use xsd_macro_utils::*; use yaserde_derive::{YaDeserialize, YaSerialize}; // Type used to reference logical and physical entities. // Token may be extended by intermediate terminal with adding prefix to make it // global unique. // The length should be within 36 characters for generating as a local token. // See "Remote Token" section in Resource Query specification. #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct ReferenceToken(pub String); impl Validate for ReferenceToken { fn validate(&self) -> Result<(), String> { if self.0.len() > 64 { return Err(format!( "MaxLength validation error. \nExpected: 0 length <= 64 \nActual: 0 length == {}", self.0.len() )); } Ok(()) } } // General datastructure referenced by a token. // Should be used as extension base. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "pt", namespace = "pt: http://www.onvif.org/ver10/pacs")] pub struct DataEntity { // A service-unique identifier of the item. #[yaserde(attribute, rename = "token")] pub token: ReferenceToken, } impl Validate for DataEntity {} // Type used for names of logical and physical entities. #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct Name(pub String); impl Validate for Name { fn validate(&self) -> Result<(), String> { if self.0.len() > 64 { return Err(format!( "MaxLength validation error. \nExpected: 0 length <= 64 \nActual: 0 length == {}", self.0.len() )); } Ok(()) } } // Description is optional and the maximum length is device specific. // If the length is more than maximum length, it is silently chopped to the // maximum length // supported by the device/service (which may be 0). #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct Description(pub String); impl Validate for Description { fn validate(&self) -> Result<(), String> { if self.0.len() > 1024 { return Err(format!( "MaxLength validation error. \nExpected: 0 length <= 1024 \nActual: 0 length == {}", self.0.len() )); } Ok(()) } } // Type used to represent the numbers from 1 ,2 , 3,... #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct PositiveInteger(pub u32); impl Validate for PositiveInteger { fn validate(&self) -> Result<(), String> { if self.0 < "1".parse::<u32>().unwrap() { return Err(format!("MinInclusive validation error: invalid value of 0! \nExpected: 0 >= 1.\nActual: 0 == {}", self.0)); } Ok(()) } } // Attributes contains a Name and an optional Value and type. #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "pt", namespace = "pt: http://www.onvif.org/ver10/pacs")] pub struct Attribute { // Name of attribute. Key names starting with "ONVIF" (any case) are // reserved for ONVIF // use. #[yaserde(attribute, rename = "Name")] pub name: String, // Value of attribute #[yaserde(attribute, rename = "Value")] pub value: Option<String>, } impl Validate for Attribute {} // Recognition/identification types supported by ONVIF. #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct RecognitionType(pub String); impl Validate for RecognitionType {} #[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)] pub struct StringList(pub Vec<String>); impl Validate for StringList {}
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
false
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/xsd_rs/metadatastream/src/lib.rs
xsd_rs/metadatastream/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] #![allow(clippy::large_enum_variant)] use b_2 as wsnt; use common::*; use validate::Validate; use xsd_types::types as xs; use yaserde_derive::{YaDeserialize, YaSerialize}; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct Appearance { #[yaserde(prefix = "tt", rename = "Transformation")] pub transformation: Option<Transformation>, #[yaserde(prefix = "tt", rename = "Shape")] pub shape: Option<ShapeDescriptor>, #[yaserde(prefix = "tt", rename = "Color")] pub color: Option<ColorDescriptor>, #[yaserde(prefix = "tt", rename = "Class")] pub class: Option<ClassDescriptor>, #[yaserde(prefix = "tt", rename = "Extension")] pub extension: Option<AppearanceExtension>, #[yaserde(prefix = "tt", rename = "GeoLocation")] pub geo_location: Option<GeoLocation>, #[yaserde(prefix = "tt", rename = "VehicleInfo")] pub vehicle_info: Option<VehicleInfo>, #[yaserde(prefix = "tt", rename = "LicensePlateInfo")] pub license_plate_info: Option<LicensePlateInfo>, } impl Validate for Appearance {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct AppearanceExtension {} impl Validate for AppearanceExtension {} #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum VehicleType { Bus, Car, Truck, Bicycle, Motorcycle, __Unknown__(String), } impl Default for VehicleType { fn default() -> VehicleType { Self::__Unknown__("No valid variants".into()) } } impl Validate for VehicleType {} #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum PlateType { Normal, Police, Diplomat, Temporary, __Unknown__(String), } impl Default for PlateType { fn default() -> PlateType { Self::__Unknown__("No valid variants".into()) } } impl Validate for PlateType {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct VehicleInfo { #[yaserde(prefix = "tt", rename = "Type")] pub _type: StringLikelihood, #[yaserde(prefix = "tt", rename = "Brand")] pub brand: StringLikelihood, #[yaserde(prefix = "tt", rename = "Model")] pub model: StringLikelihood, } impl Validate for VehicleInfo {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct LicensePlateInfo { // A string of vehicle license plate number. #[yaserde(prefix = "tt", rename = "PlateNumber")] pub plate_number: StringLikelihood, // A description of the vehicle license plate, e.g., "Normal", "Police", // "Diplomat" #[yaserde(prefix = "tt", rename = "PlateType")] pub plate_type: StringLikelihood, // Describe the country of the license plate, in order to avoid the same // license plate number. #[yaserde(prefix = "tt", rename = "CountryCode")] pub country_code: StringLikelihood, // State province or authority that issue the license plate. #[yaserde(prefix = "tt", rename = "IssuingEntity")] pub issuing_entity: StringLikelihood, } impl Validate for LicensePlateInfo {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct ShapeDescriptor { #[yaserde(prefix = "tt", rename = "BoundingBox")] pub bounding_box: Rectangle, #[yaserde(prefix = "tt", rename = "CenterOfGravity")] pub center_of_gravity: Vector, #[yaserde(prefix = "tt", rename = "Polygon")] pub polygon: Vec<Polygon>, #[yaserde(prefix = "tt", rename = "Extension")] pub extension: Option<ShapeDescriptorExtension>, } impl Validate for ShapeDescriptor {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct ShapeDescriptorExtension {} impl Validate for ShapeDescriptorExtension {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct ColorDescriptor { #[yaserde(prefix = "tt", rename = "ColorCluster")] pub color_cluster: Vec<color_descriptor::ColorClusterType>, #[yaserde(prefix = "tt", rename = "Extension")] pub extension: Option<ColorDescriptorExtension>, } impl Validate for ColorDescriptor {} pub mod color_descriptor { use super::*; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct ColorClusterType { #[yaserde(prefix = "tt", rename = "Color")] pub color: Color, #[yaserde(prefix = "tt", rename = "Weight")] pub weight: Option<f64>, #[yaserde(prefix = "tt", rename = "Covariance")] pub covariance: Option<ColorCovariance>, } impl Validate for ColorClusterType {} } #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct ColorDescriptorExtension {} impl Validate for ColorDescriptorExtension {} #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum ClassType { Animal, Face, Human, Vehical, Other, __Unknown__(String), } impl Default for ClassType { fn default() -> ClassType { Self::__Unknown__("No valid variants".into()) } } impl Validate for ClassType {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct StringLikelihood { #[yaserde(attribute, rename = "Likelihood")] pub likelihood: Option<f64>, } impl Validate for StringLikelihood {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct ClassDescriptor { #[yaserde(prefix = "tt", rename = "ClassCandidate")] pub class_candidate: Vec<class_descriptor::ClassCandidateType>, #[yaserde(prefix = "tt", rename = "Extension")] pub extension: Option<ClassDescriptorExtension>, // ONVIF recommends to use this 'Type' element instead of 'ClassCandidate' // and 'Extension' above for new design. #[yaserde(prefix = "tt", rename = "Type")] pub _type: Vec<StringLikelihood>, } impl Validate for ClassDescriptor {} pub mod class_descriptor { use super::*; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct ClassCandidateType { #[yaserde(prefix = "tt", rename = "Type")] pub _type: ClassType, #[yaserde(prefix = "tt", rename = "Likelihood")] pub likelihood: f64, } impl Validate for ClassCandidateType {} } #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct ClassDescriptorExtension { #[yaserde(prefix = "tt", rename = "OtherTypes")] pub other_types: Vec<OtherType>, #[yaserde(prefix = "tt", rename = "Extension")] pub extension: Option<ClassDescriptorExtension2>, } impl Validate for ClassDescriptorExtension {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct ClassDescriptorExtension2 {} impl Validate for ClassDescriptorExtension2 {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct OtherType { // Object Class Type #[yaserde(prefix = "tt", rename = "Type")] pub _type: String, // A likelihood/probability that the corresponding object belongs to this // class. The sum of the likelihoods shall NOT exceed 1 #[yaserde(prefix = "tt", rename = "Likelihood")] pub likelihood: f64, } impl Validate for OtherType {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct Object { #[yaserde(prefix = "tt", rename = "Appearance")] pub appearance: Option<Appearance>, #[yaserde(prefix = "tt", rename = "Behaviour")] pub behaviour: Option<Behaviour>, #[yaserde(prefix = "tt", rename = "Extension")] pub extension: Option<ObjectExtension>, #[yaserde(attribute, rename = "ObjectId")] pub object_id: Option<xs::Integer>, } impl Validate for Object {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct ObjectExtension {} impl Validate for ObjectExtension {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct Frame { #[yaserde(prefix = "tt", rename = "PTZStatus")] pub ptz_status: Option<Ptzstatus>, #[yaserde(prefix = "tt", rename = "Transformation")] pub transformation: Option<Transformation>, #[yaserde(prefix = "tt", rename = "Object")] pub object: Vec<Object>, #[yaserde(prefix = "tt", rename = "ObjectTree")] pub object_tree: Option<ObjectTree>, #[yaserde(prefix = "tt", rename = "Extension")] pub extension: Option<FrameExtension>, #[yaserde(attribute, rename = "UtcTime")] pub utc_time: xs::DateTime, } impl Validate for Frame {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct FrameExtension { #[yaserde(prefix = "tt", rename = "MotionInCells")] pub motion_in_cells: Option<MotionInCells>, #[yaserde(prefix = "tt", rename = "Extension")] pub extension: Option<FrameExtension2>, } impl Validate for FrameExtension {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct FrameExtension2 {} impl Validate for FrameExtension2 {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct Merge { #[yaserde(prefix = "tt", rename = "from")] pub from: Vec<ObjectId>, #[yaserde(prefix = "tt", rename = "to")] pub to: ObjectId, } impl Validate for Merge {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct Split { #[yaserde(prefix = "tt", rename = "from")] pub from: ObjectId, #[yaserde(prefix = "tt", rename = "to")] pub to: Vec<ObjectId>, } impl Validate for Split {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct Rename { #[yaserde(prefix = "tt", rename = "from")] pub from: ObjectId, #[yaserde(prefix = "tt", rename = "to")] pub to: ObjectId, } impl Validate for Rename {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct ObjectId { #[yaserde(attribute, rename = "ObjectId")] pub object_id: Option<xs::Integer>, } impl Validate for ObjectId {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct Behaviour { #[yaserde(prefix = "tt", rename = "Removed")] pub removed: Option<behaviour::RemovedType>, #[yaserde(prefix = "tt", rename = "Idle")] pub idle: Option<behaviour::IdleType>, #[yaserde(prefix = "tt", rename = "Extension")] pub extension: Option<BehaviourExtension>, #[yaserde(prefix = "tt", rename = "Speed")] pub speed: Option<f64>, } impl Validate for Behaviour {} pub mod behaviour { use super::*; #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct RemovedType {} impl Validate for RemovedType {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct IdleType {} impl Validate for IdleType {} } #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct BehaviourExtension {} impl Validate for BehaviourExtension {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct ObjectTree { #[yaserde(prefix = "tt", rename = "Rename")] pub rename: Vec<Rename>, #[yaserde(prefix = "tt", rename = "Split")] pub split: Vec<Split>, #[yaserde(prefix = "tt", rename = "Merge")] pub merge: Vec<Merge>, #[yaserde(prefix = "tt", rename = "Delete")] pub delete: Vec<ObjectId>, #[yaserde(prefix = "tt", rename = "Extension")] pub extension: Option<ObjectTreeExtension>, } impl Validate for ObjectTree {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct ObjectTreeExtension {} impl Validate for ObjectTreeExtension {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct MotionInCells { // Number of columns of the cell grid (x dimension) #[yaserde(attribute, rename = "Columns")] pub columns: xs::Integer, // Number of rows of the cell grid (y dimension) #[yaserde(attribute, rename = "Rows")] pub rows: xs::Integer, // A “1” denotes a cell where motion is detected and a “0” an empty // cell. The first cell is in the upper left corner. Then the cell order // goes first from left to right and then from up to down. If the number of // cells is not a multiple of 8 the last byte is filled with zeros. The // information is run length encoded according to Packbit coding in ISO // 12369 (TIFF, Revision 6.0). #[yaserde(attribute, rename = "Cells")] pub cells: String, } impl Validate for MotionInCells {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct MetadataStream { #[yaserde(prefix = "tt", rename = "MetadataStreamChoice")] pub metadata_stream_choice: metadata_stream::MetadataStreamChoice, } impl Validate for MetadataStream {} pub mod metadata_stream { use super::*; #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum MetadataStreamChoice { VideoAnalytics(VideoAnalyticsStream), #[yaserde(rename = "PTZ")] Ptz(Ptzstream), Event(EventStream), Extension(MetadataStreamExtension), __Unknown__(String), } impl Default for MetadataStreamChoice { fn default() -> MetadataStreamChoice { Self::__Unknown__("No valid variants".into()) } } impl Validate for MetadataStreamChoice {} } #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct MetadataStreamExtension { #[yaserde(prefix = "tt", rename = "AudioAnalyticsStream")] pub audio_analytics_stream: Option<AudioAnalyticsStream>, #[yaserde(prefix = "tt", rename = "Extension")] pub extension: Option<MetadataStreamExtension2>, } impl Validate for MetadataStreamExtension {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct MetadataStreamExtension2 {} impl Validate for MetadataStreamExtension2 {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct AudioAnalyticsStream { #[yaserde(prefix = "tt", rename = "AudioDescriptor")] pub audio_descriptor: Vec<AudioDescriptor>, #[yaserde(prefix = "tt", rename = "Extension")] pub extension: Option<AudioAnalyticsStreamExtension>, } impl Validate for AudioAnalyticsStream {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct AudioDescriptor { #[yaserde(attribute, rename = "UtcTime")] pub utc_time: xs::DateTime, } impl Validate for AudioDescriptor {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct AudioAnalyticsStreamExtension {} impl Validate for AudioAnalyticsStreamExtension {} // pub type MetadataStream = MetadataStream; #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum VideoAnalyticsStreamChoice { Frame(Frame), Extension(VideoAnalyticsStreamExtension), __Unknown__(String), } impl Default for VideoAnalyticsStreamChoice { fn default() -> VideoAnalyticsStreamChoice { Self::__Unknown__("No valid variants".into()) } } impl Validate for VideoAnalyticsStreamChoice {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct VideoAnalyticsStream { #[yaserde(flatten)] pub video_analytics_stream_choice: VideoAnalyticsStreamChoice, } impl Validate for VideoAnalyticsStream {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct VideoAnalyticsStreamExtension {} impl Validate for VideoAnalyticsStreamExtension {} #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum PtzstreamChoice { #[yaserde(rename = "PTZStatus")] Ptzstatus(Ptzstatus), Extension(PtzstreamExtension), __Unknown__(String), } impl Default for PtzstreamChoice { fn default() -> PtzstreamChoice { Self::__Unknown__("No valid variants".into()) } } impl Validate for PtzstreamChoice {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct Ptzstream { #[yaserde(flatten)] pub ptz_stream_choice: PtzstreamChoice, } impl Validate for Ptzstream {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct PtzstreamExtension {} impl Validate for PtzstreamExtension {} #[derive(PartialEq, Debug, YaSerialize, YaDeserialize)] pub enum EventStreamChoice { #[yaserde(prefix = "wsnt", rename = "NotificationMessage")] NotificationMessage(wsnt::NotificationMessage), Extension(EventStreamExtension), __Unknown__(String), } impl Default for EventStreamChoice { fn default() -> EventStreamChoice { Self::__Unknown__("No valid variants".into()) } } impl Validate for EventStreamChoice {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct EventStream { #[yaserde(flatten)] pub event_stream_choice: EventStreamChoice, } impl Validate for EventStream {} #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)] #[yaserde(prefix = "tt", namespace = "tt: http://www.onvif.org/ver10/schema")] pub struct EventStreamExtension {} impl Validate for EventStreamExtension {}
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
false
lumeohq/onvif-rs
https://github.com/lumeohq/onvif-rs/blob/8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6/xsd_rs/xop/src/lib.rs
xsd_rs/xop/src/lib.rs
#![allow(clippy::derive_partial_eq_without_eq)] pub mod include; pub use include::*;
rust
MIT
8f1490e2ce5e2ddd29dbd3ab2586d7a90da0b6d6
2026-01-04T20:20:57.434821Z
false