Revenons sur les devices
This commit is contained in:
@@ -5,6 +5,7 @@ use xmltree::{Element, XMLNode};
|
||||
use crate::actions::Action;
|
||||
use crate::actions::Argument;
|
||||
use crate::actions::ArgumentSet;
|
||||
use crate::actions::ArgInstanceSet;
|
||||
use crate::actions::ActionInstance;
|
||||
use crate::UpnpInstance;
|
||||
use crate::UpnpObject;
|
||||
@@ -13,7 +14,7 @@ use crate::UpnpTypedInstance;
|
||||
use crate::UpnpObjectType;
|
||||
|
||||
impl UpnpObject for ActionInstance {
|
||||
fn to_xml_element(&self) -> Element {
|
||||
fn to_xml_element(&self) -> Element {
|
||||
let mut elem = Element::new("action");
|
||||
|
||||
// <name>
|
||||
@@ -21,8 +22,8 @@ fn to_xml_element(&self) -> Element {
|
||||
name_elem.children.push(XMLNode::Text(self.get_name().clone()));
|
||||
elem.children.push(XMLNode::Element(name_elem));
|
||||
|
||||
// déplacer tous les enfants de args_elem dans un nouvel Element
|
||||
let args_container = self.arguments_set().to_xml_element();
|
||||
// Utiliser le set d'instances d'arguments
|
||||
let args_container = self.arguments.to_xml_element();
|
||||
elem.children.push(XMLNode::Element(args_container));
|
||||
|
||||
elem
|
||||
@@ -40,12 +41,23 @@ impl UpnpInstance for ActionInstance {
|
||||
type Model = Action;
|
||||
|
||||
fn new(action: &Action) -> Self {
|
||||
// Créer les instances d'arguments
|
||||
let mut arguments = ArgInstanceSet::new();
|
||||
|
||||
for arg_model in action.arguments().all() {
|
||||
let arg_instance = Arc::new(crate::actions::ArgumentInstance::new(&*arg_model));
|
||||
if let Err(e) = arguments.insert(arg_instance) {
|
||||
tracing::error!("Failed to insert argument instance: {:?}", e);
|
||||
}
|
||||
}
|
||||
|
||||
Self {
|
||||
object: UpnpObjectType {
|
||||
name: action.get_name().clone(),
|
||||
object_type: "ActionInstance".to_string(),
|
||||
},
|
||||
model: action.clone(),
|
||||
arguments, // ⬅️ Set d'instances, pas le modèle !
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,13 +72,65 @@ impl UpnpTypedInstance for ActionInstance {
|
||||
}
|
||||
|
||||
impl ActionInstance {
|
||||
|
||||
|
||||
pub fn arguments(&self, name: &str) -> Option<Arc<Argument>> {
|
||||
self.model.arguments.get_by_name(name)
|
||||
/// Retourne une instance d'argument par son nom.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `name` - Nom de l'argument à rechercher
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// `Some(Arc<ArgumentInstance>)` si trouvé, `None` sinon.
|
||||
pub fn argument(&self, name: &str) -> Option<Arc<crate::actions::ArgumentInstance>> {
|
||||
self.arguments.get_by_name(name)
|
||||
}
|
||||
|
||||
pub fn arguments_set(&self) -> &ArgumentSet {
|
||||
&self.model.arguments
|
||||
/// Retourne le set d'instances d'arguments.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Référence vers le `ArgInstanceSet` contenant toutes les instances.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```ignore
|
||||
/// for arg_instance in action_instance.arguments_set().all() {
|
||||
/// println!("Argument: {}", arg_instance.get_name());
|
||||
/// if let Some(var) = arg_instance.get_variable_instance() {
|
||||
/// println!(" Variable: {} = {}", var.get_name(), var.value());
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
pub fn arguments_set(&self) -> &ArgInstanceSet {
|
||||
&self.arguments // ⬅️ Retourne les INSTANCES, pas les modèles !
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::actions::Action;
|
||||
use crate::UpnpInstance;
|
||||
|
||||
#[test]
|
||||
fn test_action_instance_creation() {
|
||||
let action = Action::new("Play".to_string());
|
||||
let instance = ActionInstance::new(&action);
|
||||
|
||||
assert_eq!(instance.get_name(), "Play");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_action_instance_has_argument_instances() {
|
||||
let action = Action::new("Play".to_string());
|
||||
let instance = ActionInstance::new(&action);
|
||||
|
||||
// Vérifier que arguments_set() retourne bien des instances
|
||||
assert!(instance.arguments_set().all().iter().all(|arg| {
|
||||
// Chaque argument doit être une ArgumentInstance
|
||||
arg.get_model(); // Cette méthode existe seulement sur les instances
|
||||
true
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use xmltree::{Element, XMLNode};
|
||||
|
||||
use crate::actions::ActionSet;
|
||||
use crate::UpnpObject;
|
||||
use crate::actions::{ActionInstanceSet, ActionSet};
|
||||
use crate::{UpnpModel, UpnpObject};
|
||||
|
||||
impl UpnpObject for ActionSet {
|
||||
fn to_xml_element(&self) -> Element {
|
||||
@@ -17,3 +17,7 @@ impl UpnpObject for ActionSet {
|
||||
|
||||
}
|
||||
|
||||
|
||||
impl UpnpModel for ActionSet {
|
||||
type Instance = ActionInstanceSet;
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
use std::{collections::HashMap, sync::{Arc, RwLock}};
|
||||
|
||||
use xmltree::Element;
|
||||
|
||||
use crate::{actions::{Argument, ArgumentInstance}, UpnpInstance, UpnpObject, UpnpObjectType, UpnpTyped, UpnpTypedInstance};
|
||||
use crate::{actions::{ActionInstanceSet, ActionSet, Argument, ArgumentInstance}, state_variables::StateVarInstance, UpnpInstance, UpnpObject, UpnpObjectType, UpnpTyped, UpnpTypedInstance};
|
||||
|
||||
|
||||
impl UpnpObject for ArgumentInstance {
|
||||
@@ -15,28 +17,240 @@ impl UpnpTyped for ArgumentInstance {
|
||||
}
|
||||
}
|
||||
|
||||
/// Implémentation de [`UpnpTypedInstance`] pour [`ArgumentInstance`].
|
||||
///
|
||||
/// Cette implémentation permet d'accéder au modèle [`Argument`] depuis l'instance
|
||||
/// via la méthode [`get_model()`](UpnpTypedInstance::get_model).
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```ignore
|
||||
/// use pmoupnp::UpnpTypedInstance;
|
||||
///
|
||||
/// let arg_instance = ArgumentInstance::new(&arg_model);
|
||||
///
|
||||
/// // Accéder au modèle
|
||||
/// let model = arg_instance.get_model();
|
||||
/// println!("Direction: in={}, out={}", model.is_in(), model.is_out());
|
||||
/// println!("Related variable: {}", model.state_variable().get_name());
|
||||
/// ```
|
||||
impl UpnpTypedInstance for ArgumentInstance {
|
||||
|
||||
/// Retourne une référence vers le modèle [`Argument`].
|
||||
///
|
||||
/// Permet d'accéder aux métadonnées statiques définies dans le modèle :
|
||||
/// - Direction de l'argument (in/out)
|
||||
/// - Variable d'état associée
|
||||
/// - Nom et type
|
||||
fn get_model(&self) -> &Self::Model {
|
||||
&self.model
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// Implémentation de [`UpnpInstance`] pour [`ArgumentInstance`].
|
||||
///
|
||||
/// Cette implémentation fournit le constructeur standard qui crée une instance
|
||||
/// **non liée** d'un argument. La liaison à une [`StateVarInstance`] doit être
|
||||
/// effectuée séparément via [`bind_variable`](ArgumentInstance::bind_variable).
|
||||
///
|
||||
/// # Processus de construction en deux phases
|
||||
///
|
||||
/// ```text
|
||||
/// Phase 1 (new) Phase 2 (bind_variable)
|
||||
/// ┌─────────────────┐ ┌──────────────────────┐
|
||||
/// │ ArgumentInstance│ │ StateVarInstance │
|
||||
/// │ │ │ │
|
||||
/// │ model: Arc<...> │────>│ Liaison établie │
|
||||
/// │ variable: None │ │ variable: Some(...) │
|
||||
/// └─────────────────┘ └──────────────────────┘
|
||||
/// ↓ ↓
|
||||
/// Création bind_variable(&var)
|
||||
/// ```
|
||||
///
|
||||
/// # Pourquoi deux phases ?
|
||||
///
|
||||
/// 1. **Ordre de création** : Les modèles (`Argument`) existent avant les instances
|
||||
/// 2. **Validation différée** : Les dépendances sont vérifiées après instanciation
|
||||
/// 3. **Découplage** : Permet de créer des arguments même si les variables n'existent pas encore
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```ignore
|
||||
/// use pmoupnp::actions::{Argument, ArgumentInstance};
|
||||
/// use pmoupnp::UpnpInstance;
|
||||
///
|
||||
/// let arg_model = Argument::new_in("InstanceID".to_string(), instance_id_var);
|
||||
///
|
||||
/// // Création de l'instance - Phase 1
|
||||
/// let arg_instance = ArgumentInstance::new(&arg_model);
|
||||
///
|
||||
/// // À ce stade, l'instance existe mais n'est pas encore liée
|
||||
/// assert_eq!(arg_instance.get_name(), "InstanceID");
|
||||
/// assert!(arg_instance.get_variable_instance().is_none());
|
||||
///
|
||||
/// // La liaison se fera plus tard via bind_variable()
|
||||
/// ```
|
||||
impl UpnpInstance for ArgumentInstance {
|
||||
type Model = Argument;
|
||||
|
||||
/// Crée une nouvelle instance d'argument depuis son modèle.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `from` - Référence vers le modèle [`Argument`] définissant cet argument
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Une nouvelle `ArgumentInstance` avec :
|
||||
/// - Nom copié depuis le modèle
|
||||
/// - Référence vers le modèle (clone)
|
||||
/// - `variable_instance` initialisé à `None` (liaison non établie)
|
||||
///
|
||||
/// # État initial
|
||||
///
|
||||
/// L'instance créée n'est **pas encore liée** à une variable d'état.
|
||||
/// Pour établir la liaison, appelez [`bind_variable`](ArgumentInstance::bind_variable).
|
||||
///
|
||||
/// # Thread-safety
|
||||
///
|
||||
/// L'instance retournée est thread-safe et peut être partagée via `Arc`.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```ignore
|
||||
/// use pmoupnp::UpnpInstance;
|
||||
///
|
||||
/// // Création depuis un modèle
|
||||
/// let instance = ArgumentInstance::new(&arg_model);
|
||||
///
|
||||
/// // L'instance hérite des propriétés du modèle
|
||||
/// assert_eq!(instance.get_name(), arg_model.get_name());
|
||||
/// assert_eq!(instance.is_in(), arg_model.is_in());
|
||||
///
|
||||
/// // Mais n'a pas encore de valeur runtime
|
||||
/// assert!(instance.get_variable_instance().is_none());
|
||||
/// ```
|
||||
fn new(from: &Argument) -> Self {
|
||||
Self {
|
||||
// Copie des métadonnées depuis le modèle
|
||||
object: UpnpObjectType {
|
||||
name: from.get_name().clone(),
|
||||
object_type: "UpnpInstance".to_string(),
|
||||
object_type: "ArgumentInstance".to_string(),
|
||||
},
|
||||
|
||||
|
||||
// Clone du modèle pour référence future
|
||||
model: from.clone(),
|
||||
variable_instance: None,
|
||||
}
|
||||
|
||||
// Initialisation à None - sera lié plus tard via bind_variable()
|
||||
// Arc<RwLock<...>> permet la modification thread-safe post-construction
|
||||
variable_instance: Arc::new(RwLock::new(None)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Méthodes de liaison et d'accès
|
||||
// ============================================================================
|
||||
|
||||
impl ArgumentInstance {
|
||||
/// Lie cet argument à une instance de variable d'état.
|
||||
///
|
||||
/// Cette méthode établit la connexion entre l'argument et sa variable d'état,
|
||||
/// permettant l'accès aux valeurs runtime lors de l'exécution d'actions.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `var_instance` - Instance de la variable d'état à lier
|
||||
///
|
||||
/// # Thread-safety
|
||||
///
|
||||
/// Cette méthode acquiert un **write lock** sur `variable_instance` et peut
|
||||
/// bloquer si d'autres threads lisent actuellement la valeur.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panique si le lock est empoisonné (poisoned), ce qui ne devrait jamais
|
||||
/// arriver dans un usage normal.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```ignore
|
||||
/// use std::sync::Arc;
|
||||
///
|
||||
/// let arg_instance = ArgumentInstance::new(&arg_model);
|
||||
/// let var_instance = Arc::new(StateVarInstance::new(&state_var));
|
||||
///
|
||||
/// // Établir la liaison
|
||||
/// arg_instance.bind_variable(var_instance.clone());
|
||||
///
|
||||
/// // Vérifier que la liaison est établie
|
||||
/// assert!(arg_instance.get_variable_instance().is_some());
|
||||
/// ```
|
||||
///
|
||||
/// # Note
|
||||
///
|
||||
/// Cette méthode peut être appelée plusieurs fois pour changer la variable liée,
|
||||
/// bien que ce ne soit généralement pas recommandé dans un usage normal.
|
||||
pub fn bind_variable(&self, var_instance: Arc<StateVarInstance>) {
|
||||
let mut var = self.variable_instance.write().unwrap();
|
||||
*var = Some(var_instance);
|
||||
}
|
||||
|
||||
/// Retourne l'instance de variable d'état liée, si elle existe.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// - `Some(Arc<StateVarInstance>)` si une variable est liée
|
||||
/// - `None` si aucune liaison n'a été établie via [`bind_variable`](Self::bind_variable)
|
||||
///
|
||||
/// # Thread-safety
|
||||
///
|
||||
/// Cette méthode acquiert un **read lock** sur `variable_instance`.
|
||||
/// Plusieurs threads peuvent lire simultanément sans blocage.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panique si le lock est empoisonné (poisoned).
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```ignore
|
||||
/// // Vérifier si la liaison existe
|
||||
/// if let Some(var) = arg_instance.get_variable_instance() {
|
||||
/// println!("Variable liée : {}", var.get_name());
|
||||
/// println!("Valeur actuelle : {}", var.value());
|
||||
/// } else {
|
||||
/// println!("Aucune variable liée");
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// # Usage dans l'exécution d'actions
|
||||
///
|
||||
/// ```ignore
|
||||
/// async fn execute_action(action: &ActionInstance) -> Result<(), ActionError> {
|
||||
/// for arg in action.arguments_set().all() {
|
||||
/// if let Some(var) = arg.get_variable_instance() {
|
||||
/// // Utiliser var.value() pour lire/écrire
|
||||
/// println!("Paramètre {} = {}", arg.get_name(), var.value());
|
||||
/// } else {
|
||||
/// return Err(ActionError::UnboundArgument(arg.get_name().to_string()));
|
||||
/// }
|
||||
/// }
|
||||
/// Ok(())
|
||||
/// }
|
||||
/// ```
|
||||
pub fn get_variable_instance(&self) -> Option<Arc<StateVarInstance>> {
|
||||
self.variable_instance.read().unwrap().clone()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
impl UpnpInstance for ActionInstanceSet {
|
||||
type Model = ActionSet;
|
||||
|
||||
fn new(_: &ActionSet) -> Self {
|
||||
Self {
|
||||
objects: RwLock::new(HashMap::new())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,21 @@
|
||||
mod errors;
|
||||
|
||||
mod action_methods;
|
||||
mod action_instance;
|
||||
mod action_set_methods;
|
||||
mod action_instance_set;
|
||||
mod argument_methods;
|
||||
mod arg_set_methods;
|
||||
mod action_methods;
|
||||
mod action_set_methods;
|
||||
mod arg_inst_set_methods;
|
||||
mod arg_instance_methods;
|
||||
mod arg_set_methods;
|
||||
mod argument_methods;
|
||||
|
||||
mod macros;
|
||||
|
||||
|
||||
use std::sync::Arc;
|
||||
use crate::{state_variables::{StateVarInstance, StateVariable}, UpnpObjectSet, UpnpObjectType};
|
||||
use crate::{
|
||||
UpnpObjectSet, UpnpObjectType,
|
||||
state_variables::{StateVarInstance, StateVariable},
|
||||
};
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
pub use errors::ActionError;
|
||||
|
||||
@@ -29,6 +31,7 @@ pub type ActionSet = UpnpObjectSet<Action>;
|
||||
pub struct ActionInstance {
|
||||
object: UpnpObjectType,
|
||||
model: Action,
|
||||
arguments: ArgInstanceSet,
|
||||
}
|
||||
|
||||
pub type ActionInstanceSet = UpnpObjectSet<ActionInstance>;
|
||||
@@ -43,12 +46,71 @@ pub struct Argument {
|
||||
|
||||
pub type ArgumentSet = UpnpObjectSet<Argument>;
|
||||
|
||||
|
||||
/// Instance d'un argument d'action UPnP.
|
||||
///
|
||||
/// Un `ArgumentInstance` représente un argument concret utilisé lors de l'exécution
|
||||
/// d'une action. Contrairement au modèle [`Argument`] qui définit la structure,
|
||||
/// l'instance maintient une liaison dynamique vers une [`StateVarInstance`] qui
|
||||
/// contient la valeur runtime.
|
||||
///
|
||||
/// # Cycle de vie
|
||||
///
|
||||
/// 1. **Création** : Instanciation via [`UpnpInstance::new`] avec `variable_instance = None`
|
||||
/// 2. **Liaison** : Association à une [`StateVarInstance`] via [`bind_variable`](Self::bind_variable)
|
||||
/// 3. **Utilisation** : Accès à la valeur runtime via [`get_variable_instance`](Self::get_variable_instance)
|
||||
///
|
||||
/// # Pourquoi `variable_instance` est optionnel ?
|
||||
///
|
||||
/// La liaison ne peut pas être faite dans le constructeur car :
|
||||
/// - Les `StateVarInstance` sont créées **après** les modèles
|
||||
/// - Les `ActionInstance` sont créées **avant** que toutes les variables soient disponibles
|
||||
/// - La validation des dépendances se fait en deux phases
|
||||
///
|
||||
/// # Thread-safety
|
||||
///
|
||||
/// Le champ `variable_instance` est protégé par un `RwLock` pour permettre :
|
||||
/// - La liaison après création (write lock)
|
||||
/// - L'accès concurrent en lecture (read lock)
|
||||
/// - L'utilisation dans un contexte multi-thread
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```ignore
|
||||
/// use pmoupnp::actions::{Argument, ArgumentInstance};
|
||||
/// use pmoupnp::state_variables::StateVarInstance;
|
||||
/// use std::sync::Arc;
|
||||
///
|
||||
/// // Phase 1 : Créer l'instance (sans liaison)
|
||||
/// let arg_model = Argument::new_in("Volume".to_string(), volume_var);
|
||||
/// let arg_instance = ArgumentInstance::new(&arg_model);
|
||||
/// assert!(arg_instance.get_variable_instance().is_none());
|
||||
///
|
||||
/// // Phase 2 : Lier à une variable d'état
|
||||
/// let var_instance = Arc::new(StateVarInstance::new(&volume_var));
|
||||
/// arg_instance.bind_variable(var_instance.clone());
|
||||
/// assert!(arg_instance.get_variable_instance().is_some());
|
||||
///
|
||||
/// // Phase 3 : Utiliser la valeur runtime
|
||||
/// if let Some(var) = arg_instance.get_variable_instance() {
|
||||
/// println!("Current value: {}", var.value());
|
||||
/// }
|
||||
/// ```
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ArgumentInstance {
|
||||
/// Métadonnées de l'objet UPnP
|
||||
object: UpnpObjectType,
|
||||
|
||||
/// Référence vers le modèle définissant la structure
|
||||
model: Argument,
|
||||
variable_instance: Option<Arc<StateVarInstance>>,
|
||||
|
||||
/// Liaison optionnelle vers l'instance de variable d'état.
|
||||
///
|
||||
/// - `None` : Pas encore liée (état initial après construction)
|
||||
/// - `Some(Arc<StateVarInstance>)` : Liée et prête à l'emploi
|
||||
///
|
||||
/// Protégée par `RwLock` pour permettre la liaison post-construction
|
||||
/// et l'accès concurrent en lecture.
|
||||
variable_instance: Arc<RwLock<Option<Arc<StateVarInstance>>>>,
|
||||
}
|
||||
|
||||
pub type ArgInstanceSet = UpnpObjectSet<ArgumentInstance>;
|
||||
|
||||
Reference in New Issue
Block a user