Gerer les souscription aux variables
This commit is contained in:
@@ -298,7 +298,7 @@ pub trait WebAppExt {
|
|||||||
/// # Type Parameter
|
/// # Type Parameter
|
||||||
///
|
///
|
||||||
/// * `W` - Type RustEmbed contenant les fichiers de la webapp
|
/// * `W` - Type RustEmbed contenant les fichiers de la webapp
|
||||||
fn add_webapp<W>(&mut self, path: &str) -> Pin<Box<dyn Future<Output = ()> + Send + '_>>
|
async fn add_webapp<W>(&mut self, path: &str)
|
||||||
where
|
where
|
||||||
W: RustEmbed + Clone + Send + Sync + 'static;
|
W: RustEmbed + Clone + Send + Sync + 'static;
|
||||||
|
|
||||||
@@ -311,7 +311,7 @@ pub trait WebAppExt {
|
|||||||
/// # Type Parameter
|
/// # Type Parameter
|
||||||
///
|
///
|
||||||
/// * `W` - Type RustEmbed contenant les fichiers de la webapp
|
/// * `W` - Type RustEmbed contenant les fichiers de la webapp
|
||||||
fn add_webapp_with_redirect<W>(&mut self, path: &str) -> Pin<Box<dyn Future<Output = ()> + Send + '_>>
|
async fn add_webapp_with_redirect<W>(&mut self, path: &str)
|
||||||
where
|
where
|
||||||
W: RustEmbed + Clone + Send + Sync + 'static;
|
W: RustEmbed + Clone + Send + Sync + 'static;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -30,28 +30,24 @@
|
|||||||
use crate::WebAppExt;
|
use crate::WebAppExt;
|
||||||
use pmoserver::Server;
|
use pmoserver::Server;
|
||||||
use rust_embed::RustEmbed;
|
use rust_embed::RustEmbed;
|
||||||
use std::future::Future;
|
|
||||||
use std::pin::Pin;
|
|
||||||
|
|
||||||
impl WebAppExt for Server {
|
impl WebAppExt for Server {
|
||||||
fn add_webapp<W>(&mut self, path: &str) -> Pin<Box<dyn Future<Output = ()> + Send + '_>>
|
async fn add_webapp<W>(&mut self, path: &str)
|
||||||
where
|
where
|
||||||
W: RustEmbed + Clone + Send + Sync + 'static,
|
W: RustEmbed + Clone + Send + Sync + 'static,
|
||||||
{
|
{
|
||||||
let path = path.to_string();
|
let path = path.to_string();
|
||||||
Box::pin(async move {
|
|
||||||
self.add_spa::<W>(&path).await;
|
self.add_spa::<W>(&path).await;
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn add_webapp_with_redirect<W>(&mut self, path: &str) -> Pin<Box<dyn Future<Output = ()> + Send + '_>>
|
async fn add_webapp_with_redirect<W>(&mut self, path: &str)
|
||||||
where
|
where
|
||||||
W: RustEmbed + Clone + Send + Sync + 'static,
|
W: RustEmbed + Clone + Send + Sync + 'static,
|
||||||
{
|
{
|
||||||
let path = path.to_string();
|
let path = path.to_string();
|
||||||
Box::pin(async move {
|
|
||||||
self.add_spa::<W>(&path).await;
|
self.add_spa::<W>(&path).await;
|
||||||
self.add_redirect("/", &path).await;
|
self.add_redirect("/", &path).await;
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,28 +1,28 @@
|
|||||||
//! Implémentation de ServiceInstance.
|
//! Implémentation de ServiceInstance.
|
||||||
|
|
||||||
use std::{
|
|
||||||
collections::HashMap,
|
|
||||||
sync::{Arc, Mutex, RwLock},
|
|
||||||
time::Duration,
|
|
||||||
pin::Pin,
|
|
||||||
future::Future,
|
|
||||||
};
|
|
||||||
use axum::{
|
use axum::{
|
||||||
|
body::Body,
|
||||||
extract::{Request, State},
|
extract::{Request, State},
|
||||||
http::{HeaderMap, StatusCode},
|
http::{HeaderMap, StatusCode},
|
||||||
response::{IntoResponse, Response},
|
response::{IntoResponse, Response},
|
||||||
body::Body,
|
};
|
||||||
|
use std::{
|
||||||
|
collections::HashMap,
|
||||||
|
future::Future,
|
||||||
|
pin::Pin,
|
||||||
|
sync::{Arc, Mutex, RwLock},
|
||||||
|
time::Duration,
|
||||||
};
|
};
|
||||||
use tokio::time;
|
use tokio::time;
|
||||||
use tracing::{info, warn, error};
|
use tracing::{error, info, warn};
|
||||||
use xmltree::{Element, XMLNode, EmitterConfig};
|
use xmltree::{Element, EmitterConfig, XMLNode};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
services::{Service, ServiceError},
|
UpnpInstance, UpnpObject, UpnpObjectType, UpnpTyped, UpnpTypedInstance,
|
||||||
actions::{ActionInstance, ActionInstanceSet},
|
actions::{ActionInstance, ActionInstanceSet},
|
||||||
state_variables::{StateVarInstance, StateVarInstanceSet, UpnpVariable},
|
|
||||||
devices::DeviceInstance,
|
devices::DeviceInstance,
|
||||||
UpnpObject, UpnpInstance, UpnpTyped, UpnpTypedInstance, UpnpObjectType,
|
services::{Service, ServiceError},
|
||||||
|
state_variables::{StateVarInstance, StateVarInstanceSet, UpnpVariable},
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Méthodes HTTP pour les événements UPnP.
|
/// Méthodes HTTP pour les événements UPnP.
|
||||||
@@ -96,7 +96,6 @@ pub struct ServiceInstance {
|
|||||||
seqid: Arc<Mutex<HashMap<String, u32>>>,
|
seqid: Arc<Mutex<HashMap<String, u32>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
impl std::fmt::Debug for ServiceInstance {
|
impl std::fmt::Debug for ServiceInstance {
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
f.debug_struct("ServiceInstance")
|
f.debug_struct("ServiceInstance")
|
||||||
@@ -194,7 +193,9 @@ impl UpnpObject for ServiceInstance {
|
|||||||
let mut elem = Element::new("service");
|
let mut elem = Element::new("service");
|
||||||
|
|
||||||
let mut service_type = Element::new("serviceType");
|
let mut service_type = Element::new("serviceType");
|
||||||
service_type.children.push(XMLNode::Text(self.service_type()));
|
service_type
|
||||||
|
.children
|
||||||
|
.push(XMLNode::Text(self.service_type()));
|
||||||
elem.children.push(XMLNode::Element(service_type));
|
elem.children.push(XMLNode::Element(service_type));
|
||||||
|
|
||||||
let mut service_id = Element::new("serviceId");
|
let mut service_id = Element::new("serviceId");
|
||||||
@@ -206,11 +207,15 @@ impl UpnpObject for ServiceInstance {
|
|||||||
elem.children.push(XMLNode::Element(scpd_url));
|
elem.children.push(XMLNode::Element(scpd_url));
|
||||||
|
|
||||||
let mut control_url = Element::new("controlURL");
|
let mut control_url = Element::new("controlURL");
|
||||||
control_url.children.push(XMLNode::Text(self.control_route()));
|
control_url
|
||||||
|
.children
|
||||||
|
.push(XMLNode::Text(self.control_route()));
|
||||||
elem.children.push(XMLNode::Element(control_url));
|
elem.children.push(XMLNode::Element(control_url));
|
||||||
|
|
||||||
let mut event_sub_url = Element::new("eventSubURL");
|
let mut event_sub_url = Element::new("eventSubURL");
|
||||||
event_sub_url.children.push(XMLNode::Text(self.event_route()));
|
event_sub_url
|
||||||
|
.children
|
||||||
|
.push(XMLNode::Text(self.event_route()));
|
||||||
elem.children.push(XMLNode::Element(event_sub_url));
|
elem.children.push(XMLNode::Element(event_sub_url));
|
||||||
|
|
||||||
elem
|
elem
|
||||||
@@ -306,8 +311,14 @@ impl ServiceInstance {
|
|||||||
/// Retourne une erreur si l'enregistrement des routes échoue.
|
/// Retourne une erreur si l'enregistrement des routes échoue.
|
||||||
pub async fn register_urls(&self, server: &mut pmoserver::Server) -> Result<(), ServiceError> {
|
pub async fn register_urls(&self, server: &mut pmoserver::Server) -> Result<(), ServiceError> {
|
||||||
let device = self.device.read().unwrap();
|
let device = self.device.read().unwrap();
|
||||||
let device_name = device.as_ref().map(|d| d.get_name().clone()).unwrap_or_else(|| "unknown".to_string());
|
let device_name = device
|
||||||
let server_url = device.as_ref().map(|d| d.base_url().to_string()).unwrap_or_default();
|
.as_ref()
|
||||||
|
.map(|d| d.get_name().clone())
|
||||||
|
.unwrap_or_else(|| "unknown".to_string());
|
||||||
|
let server_url = device
|
||||||
|
.as_ref()
|
||||||
|
.map(|d| d.base_url().to_string())
|
||||||
|
.unwrap_or_default();
|
||||||
drop(device);
|
drop(device);
|
||||||
|
|
||||||
info!(
|
info!(
|
||||||
@@ -320,26 +331,24 @@ impl ServiceInstance {
|
|||||||
|
|
||||||
// Handler SCPD
|
// Handler SCPD
|
||||||
let instance_scpd = self.clone();
|
let instance_scpd = self.clone();
|
||||||
server.add_handler(&self.scpd_route(), move || {
|
server
|
||||||
let instance = instance_scpd.clone();
|
.add_handler(&self.scpd_route(), move || {
|
||||||
async move { instance.scpd_handler().await }
|
let instance = instance_scpd.clone();
|
||||||
}).await;
|
async move { instance.scpd_handler().await }
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
|
||||||
// Handler control
|
// Handler control
|
||||||
let instance_control = self.clone();
|
let instance_control = self.clone();
|
||||||
server.add_post_handler_with_state(
|
server
|
||||||
&self.control_route(),
|
.add_post_handler_with_state(&self.control_route(), control_handler, instance_control)
|
||||||
control_handler,
|
.await;
|
||||||
instance_control,
|
|
||||||
).await;
|
|
||||||
|
|
||||||
// Handler événements
|
// Handler événements
|
||||||
let instance_event = self.clone();
|
let instance_event = self.clone();
|
||||||
server.add_handler_with_state(
|
server
|
||||||
&self.event_route(),
|
.add_handler_with_state(&self.event_route(), event_sub_handler, instance_event)
|
||||||
event_sub_handler,
|
.await;
|
||||||
instance_event,
|
|
||||||
).await;
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -366,16 +375,14 @@ impl ServiceInstance {
|
|||||||
|
|
||||||
// actionList
|
// actionList
|
||||||
if !self.actions.all().is_empty() {
|
if !self.actions.all().is_empty() {
|
||||||
elem.children.push(XMLNode::Element(
|
elem.children
|
||||||
self.actions.to_xml_element()
|
.push(XMLNode::Element(self.actions.to_xml_element()));
|
||||||
));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// serviceStateTable
|
// serviceStateTable
|
||||||
if !self.statevariables.all().is_empty() {
|
if !self.statevariables.all().is_empty() {
|
||||||
elem.children.push(XMLNode::Element(
|
elem.children
|
||||||
self.statevariables.to_xml_element()
|
.push(XMLNode::Element(self.statevariables.to_xml_element()));
|
||||||
));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
elem
|
elem
|
||||||
@@ -399,9 +406,13 @@ impl ServiceInstance {
|
|||||||
|
|
||||||
(
|
(
|
||||||
StatusCode::OK,
|
StatusCode::OK,
|
||||||
[(axum::http::header::CONTENT_TYPE, "text/xml; charset=\"utf-8\"")],
|
[(
|
||||||
|
axum::http::header::CONTENT_TYPE,
|
||||||
|
"text/xml; charset=\"utf-8\"",
|
||||||
|
)],
|
||||||
xml,
|
xml,
|
||||||
).into_response()
|
)
|
||||||
|
.into_response()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Ajoute un abonné aux événements.
|
/// Ajoute un abonné aux événements.
|
||||||
@@ -443,9 +454,13 @@ impl ServiceInstance {
|
|||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let callback = callback.trim().trim_matches(|c| c == '<' || c == '>');
|
let callback = callback.trim().trim_matches(|c| c == '<' || c == '>');
|
||||||
|
|
||||||
let mut body = r#"<e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">"#.to_string();
|
let mut body =
|
||||||
|
r#"<e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">"#.to_string();
|
||||||
for (name, val) in changed {
|
for (name, val) in changed {
|
||||||
body.push_str(&format!("<e:property><{0}>{1}</{0}></e:property>", name, val));
|
body.push_str(&format!(
|
||||||
|
"<e:property><{0}>{1}</{0}></e:property>",
|
||||||
|
name, val
|
||||||
|
));
|
||||||
}
|
}
|
||||||
body.push_str("</e:propertyset>");
|
body.push_str("</e:propertyset>");
|
||||||
|
|
||||||
@@ -462,7 +477,11 @@ impl ServiceInstance {
|
|||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
Ok(resp) => {
|
Ok(resp) => {
|
||||||
info!("✅ Initial event sent to {}, status={}", callback, resp.status());
|
info!(
|
||||||
|
"✅ Initial event sent to {}, status={}",
|
||||||
|
callback,
|
||||||
|
resp.status()
|
||||||
|
);
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
error!("Failed to send initial event to {}: {}", callback, e);
|
error!("Failed to send initial event to {}: {}", callback, e);
|
||||||
@@ -511,9 +530,13 @@ impl ServiceInstance {
|
|||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let callback = callback.trim().trim_matches(|c| c == '<' || c == '>');
|
let callback = callback.trim().trim_matches(|c| c == '<' || c == '>');
|
||||||
|
|
||||||
let mut body = r#"<e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">"#.to_string();
|
let mut body =
|
||||||
|
r#"<e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">"#.to_string();
|
||||||
for (name, val) in changed_clone {
|
for (name, val) in changed_clone {
|
||||||
body.push_str(&format!("<e:property><{0}>{1}</{0}></e:property>", name, val));
|
body.push_str(&format!(
|
||||||
|
"<e:property><{0}>{1}</{0}></e:property>",
|
||||||
|
name, val
|
||||||
|
));
|
||||||
}
|
}
|
||||||
body.push_str("</e:propertyset>");
|
body.push_str("</e:propertyset>");
|
||||||
|
|
||||||
@@ -565,18 +588,26 @@ impl ServiceInstance {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Handler Axum pour les événements (SUBSCRIBE/UNSUBSCRIBE).
|
/// Handler Axum pour les événements (SUBSCRIBE/UNSUBSCRIBE).
|
||||||
fn event_sub_handler(
|
async fn event_sub_handler(
|
||||||
State(instance): State<ServiceInstance>,
|
State(instance): State<ServiceInstance>,
|
||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
req: Request<Body>,
|
req: Request<Body>,
|
||||||
) -> Pin<Box<dyn Future<Output = Response> + Send>> {
|
) -> Response {
|
||||||
Box::pin(async move {
|
|
||||||
info!("📡 Event Subscription request for {}", instance.get_name());
|
info!("📡 Event Subscription request for {}", instance.get_name());
|
||||||
|
|
||||||
let method = req.method().as_str();
|
let method = req.method().as_str();
|
||||||
let sid = headers.get("SID").and_then(|v| v.to_str().ok()).unwrap_or("");
|
let sid = headers
|
||||||
let timeout = headers.get("Timeout").and_then(|v| v.to_str().ok()).unwrap_or("");
|
.get("SID")
|
||||||
let callback = headers.get("Callback").and_then(|v| v.to_str().ok()).unwrap_or("");
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.unwrap_or("");
|
||||||
|
let timeout = headers
|
||||||
|
.get("Timeout")
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.unwrap_or("");
|
||||||
|
let callback = headers
|
||||||
|
.get("Callback")
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.unwrap_or("");
|
||||||
|
|
||||||
match method {
|
match method {
|
||||||
METHOD_SUBSCRIBE => {
|
METHOD_SUBSCRIBE => {
|
||||||
@@ -584,14 +615,19 @@ fn event_sub_handler(
|
|||||||
// Nouvelle souscription
|
// Nouvelle souscription
|
||||||
let new_sid = format!("uuid:{}", uuid::Uuid::new_v4());
|
let new_sid = format!("uuid:{}", uuid::Uuid::new_v4());
|
||||||
if !callback.is_empty() {
|
if !callback.is_empty() {
|
||||||
instance.add_subscriber(new_sid.clone(), callback.to_string()).await;
|
instance
|
||||||
|
.add_subscriber(new_sid.clone(), callback.to_string())
|
||||||
|
.await;
|
||||||
}
|
}
|
||||||
let timeout_val = if timeout.is_empty() {
|
let timeout_val = if timeout.is_empty() {
|
||||||
"Second-1800"
|
"Second-1800"
|
||||||
} else {
|
} else {
|
||||||
timeout
|
timeout
|
||||||
};
|
};
|
||||||
info!("🔒 New subscription: SID={}, Callback={}, Timeout={}", new_sid, callback, timeout_val);
|
info!(
|
||||||
|
"🔒 New subscription: SID={}, Callback={}, Timeout={}",
|
||||||
|
new_sid, callback, timeout_val
|
||||||
|
);
|
||||||
|
|
||||||
let sid_clone = new_sid.clone();
|
let sid_clone = new_sid.clone();
|
||||||
let instance_clone = instance.clone();
|
let instance_clone = instance.clone();
|
||||||
@@ -612,14 +648,15 @@ fn event_sub_handler(
|
|||||||
[
|
[
|
||||||
(
|
(
|
||||||
axum::http::header::HeaderName::from_static("sid"),
|
axum::http::header::HeaderName::from_static("sid"),
|
||||||
axum::http::HeaderValue::from_str(&response_sid).unwrap()
|
axum::http::HeaderValue::from_str(&response_sid).unwrap(),
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
axum::http::header::HeaderName::from_static("timeout"),
|
axum::http::header::HeaderName::from_static("timeout"),
|
||||||
axum::http::HeaderValue::from_str(&response_timeout).unwrap()
|
axum::http::HeaderValue::from_str(&response_timeout).unwrap(),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
).into_response()
|
)
|
||||||
|
.into_response()
|
||||||
}
|
}
|
||||||
METHOD_UNSUBSCRIBE => {
|
METHOD_UNSUBSCRIBE => {
|
||||||
if !sid.is_empty() {
|
if !sid.is_empty() {
|
||||||
@@ -633,15 +670,10 @@ fn event_sub_handler(
|
|||||||
StatusCode::METHOD_NOT_ALLOWED.into_response()
|
StatusCode::METHOD_NOT_ALLOWED.into_response()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handler Axum pour le contrôle SOAP.
|
/// Handler Axum pour le contrôle SOAP.
|
||||||
fn control_handler(
|
async fn control_handler(State(instance): State<ServiceInstance>, _body: String) -> Response {
|
||||||
State(instance): State<ServiceInstance>,
|
|
||||||
_body: String,
|
|
||||||
) -> Pin<Box<dyn Future<Output = Response> + Send>> {
|
|
||||||
Box::pin(async move {
|
|
||||||
info!("📡 Control request for {}", instance.get_name());
|
info!("📡 Control request for {}", instance.get_name());
|
||||||
|
|
||||||
// TODO: Parser le SOAP et appeler l'action correspondante
|
// TODO: Parser le SOAP et appeler l'action correspondante
|
||||||
@@ -660,10 +692,13 @@ fn control_handler(
|
|||||||
|
|
||||||
(
|
(
|
||||||
StatusCode::OK,
|
StatusCode::OK,
|
||||||
[(axum::http::header::CONTENT_TYPE, "text/xml; charset=\"utf-8\"")],
|
[(
|
||||||
|
axum::http::header::CONTENT_TYPE,
|
||||||
|
"text/xml; charset=\"utf-8\"",
|
||||||
|
)],
|
||||||
response_xml,
|
response_xml,
|
||||||
).into_response()
|
)
|
||||||
})
|
.into_response()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
Reference in New Issue
Block a user