1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
//! Bluetooth mesh application.

use dbus::{
    nonblock::{Proxy, SyncConnection},
    Path,
};
use dbus_crossroads::{Crossroads, IfaceBuilder, IfaceToken};
use std::{fmt, sync::Arc};
use strum::EnumString;
use tokio::sync::{broadcast, mpsc, oneshot};
use uuid::Uuid;

use super::{
    agent::{ProvisionAgent, RegisteredProvisionAgent},
    management::{AddNodeFailedReason, NodeAdded},
    provisioner::{Provisioner, RegisteredProvisioner},
};
use crate::{
    mesh::{
        element::{Element, RegisteredElement},
        PATH, SERVICE_NAME, TIMEOUT,
    },
    method_call, Error, ErrorKind, Result, SessionInner,
};

pub(crate) const INTERFACE: &str = "org.bluez.mesh.Application1";
pub(crate) const MESH_APP_PREFIX: &str = publish_path!("mesh/app/");

/// Definition of Bluetooth mesh application.
#[derive(Debug, Default)]
pub struct Application {
    /// Device ID
    pub device_id: Uuid,
    /// Application elements
    pub elements: Vec<Element>,
    /// Provisioner
    pub provisioner: Option<Provisioner>,
    /// Provisioning agent.
    pub agent: ProvisionAgent,
    /// Application properties
    pub properties: Properties,
    #[doc(hidden)]
    pub _non_exhaustive: (),
}

/// Application properties.
#[derive(Debug, Clone, Default)]
pub struct Properties {
    /// Company id.
    pub company_id: u16,
    /// Product id.
    pub product_id: u16,
    /// Version id.
    pub version_id: u16,
}

// ---------------
// D-Bus interface
// ---------------

/// Reason why node provisioning initiated by joining has failed.
#[derive(Debug, displaydoc::Display, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, EnumString)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum JoinFailedReason {
    /// timeout
    #[strum(serialize = "timeout")]
    Timeout,
    /// bad PDU
    #[strum(serialize = "bad-pdu")]
    BadPdu,
    /// confirmation failure
    #[strum(serialize = "confirmation-failed")]
    ConfirmationFailed,
    /// out of resources
    #[strum(serialize = "out-of-resources")]
    OutOfResources,
    /// decryption error
    #[strum(serialize = "decryption-error")]
    DecryptionError,
    /// unexpected error
    #[strum(serialize = "unexpected-error")]
    UnexpectedError,
    /// cannot assign addresses
    #[strum(serialize = "cannot-assign-addresses")]
    CannotAssignAddresses,
    /// Unknown reason
    Unknown,
}

impl From<JoinFailedReason> for Error {
    fn from(reason: JoinFailedReason) -> Self {
        Error::new(ErrorKind::MeshJoinFailed(reason))
    }
}

pub(crate) struct RegisteredApplication {
    inner: Arc<SessionInner>,
    device_id: Uuid,
    pub(crate) provisioner: Option<RegisteredProvisioner>,
    properties: Properties,
    join_result_tx: mpsc::Sender<std::result::Result<u64, JoinFailedReason>>,
    pub(crate) add_node_result_tx: broadcast::Sender<(Uuid, std::result::Result<NodeAdded, AddNodeFailedReason>)>,
}

impl RegisteredApplication {
    fn root_path(&self) -> String {
        format!("{}{}", MESH_APP_PREFIX, self.device_id.as_simple())
    }

    pub(crate) fn dbus_path(&self) -> Path<'static> {
        Path::new(self.root_path()).unwrap()
    }

    pub(crate) fn app_dbus_path(&self) -> Path<'static> {
        let app_path = format!("{}/application", self.root_path());
        Path::new(app_path).unwrap()
    }

    pub(crate) fn element_dbus_path(&self, element_idx: usize) -> Path<'static> {
        let element_path = format!("{}/ele{}", self.root_path(), element_idx);
        Path::new(element_path).unwrap()
    }

    fn proxy(&self) -> Proxy<'_, &SyncConnection> {
        Proxy::new(SERVICE_NAME, PATH, TIMEOUT, &*self.inner.connection)
    }

    dbus_interface!();
    dbus_default_interface!(INTERFACE);

    pub(crate) fn register_interface(cr: &mut Crossroads) -> IfaceToken<Arc<Self>> {
        cr.register(INTERFACE, |ib: &mut IfaceBuilder<Arc<Self>>| {
            ib.method_with_cr_async("JoinComplete", ("token",), (), |ctx, cr, (token,): (u64,)| {
                method_call(ctx, cr, move |reg: Arc<Self>| async move {
                    let _ = reg.join_result_tx.send(Ok(token)).await;
                    Ok(())
                })
            });

            ib.method_with_cr_async("JoinFailed", ("reason",), (), |ctx, cr, (reason,): (String,)| {
                method_call(ctx, cr, move |reg: Arc<Self>| async move {
                    let _ = reg
                        .join_result_tx
                        .send(Err(reason.parse::<JoinFailedReason>().unwrap_or(JoinFailedReason::Unknown)))
                        .await;
                    Ok(())
                })
            });

            cr_property!(ib, "CompanyID", reg => {
                Some(reg.properties.company_id)
            });

            cr_property!(ib, "ProductID", reg => {
                Some(reg.properties.product_id)
            });

            cr_property!(ib, "VersionID", reg => {
                Some(reg.properties.version_id)
            });
        })
    }

    pub(crate) async fn register(inner: Arc<SessionInner>, app: Application) -> Result<ApplicationHandle> {
        let Application { device_id, elements, provisioner, agent, properties, .. } = app;

        let (join_result_tx, join_result_rx) = mpsc::channel(1);
        let (add_node_result_tx, add_node_result_rx) = broadcast::channel(1024);
        let this = Arc::new(Self {
            inner: inner.clone(),
            device_id,
            provisioner: provisioner.map(|prov| RegisteredProvisioner::new(inner.clone(), prov)),
            properties,
            join_result_tx,
            add_node_result_tx,
        });
        let app_inner = Arc::new(ApplicationInner { add_node_result_rx });

        let root_path = this.dbus_path();
        log::trace!("Publishing mesh application at {}", &root_path);

        {
            let mut cr = inner.crossroads.lock().await;

            // register object manager
            let om = cr.object_manager();
            cr.insert(root_path.clone(), &[om], ());

            // register agent
            cr.insert(
                Path::from(format!("{}/{}", root_path.clone(), "agent")),
                &[inner.provision_agent_token],
                Arc::new(RegisteredProvisionAgent::new(agent, inner.clone())),
            );

            // register application
            let mut ifaces = vec![inner.application_token];
            if this.provisioner.is_some() {
                ifaces.push(inner.provisioner_token);
            }
            cr.insert(this.app_dbus_path(), &[inner.application_token], this.clone());

            // register elements
            for (element_idx, element) in elements.into_iter().enumerate() {
                let element_path = this.element_dbus_path(element_idx);
                let reg_element = RegisteredElement::new(inner.clone(), this.root_path(), element, element_idx);
                cr.insert(element_path.clone(), &[inner.element_token], Arc::new(reg_element));
            }
        }

        let (drop_tx, drop_rx) = oneshot::channel();
        let path_unreg = root_path.clone();
        tokio::spawn(async move {
            let _ = drop_rx.await;

            log::trace!("Unpublishing mesh application at {}", &path_unreg);
            let mut cr = inner.crossroads.lock().await;
            cr.remove::<Self>(&path_unreg);
        });

        Ok(ApplicationHandle {
            app_inner,
            name: root_path,
            device_id,
            token: None,
            join_result_rx,
            _drop_tx: drop_tx,
        })
    }
}

pub(crate) struct ApplicationInner {
    pub add_node_result_rx: broadcast::Receiver<(Uuid, std::result::Result<NodeAdded, AddNodeFailedReason>)>,
}

/// Handle to Bluetooth mesh application.
///
/// Drop this handle to unpublish.
pub struct ApplicationHandle {
    pub(crate) app_inner: Arc<ApplicationInner>,
    pub(crate) name: dbus::Path<'static>,
    pub(crate) device_id: Uuid,
    pub(crate) token: Option<u64>,
    pub(crate) join_result_rx: mpsc::Receiver<std::result::Result<u64, JoinFailedReason>>,
    _drop_tx: oneshot::Sender<()>,
}

impl fmt::Debug for ApplicationHandle {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("ApplicationHandle")
            .field("name", &self.name)
            .field("device_id", &self.device_id)
            .field("token", &self.token)
            .finish()
    }
}

impl ApplicationHandle {
    /// Token.
    ///
    /// Only available when application was registered using [`Network::join`](super::network::Network::join).
    ///
    /// The token parameter serves as a unique identifier of the
    /// particular node. The token must be preserved by the application
    /// in order to authenticate itself to the mesh daemon and attach to
    /// the network as a mesh node by calling Attach() method or
    /// permanently remove the identity of the mesh node by calling
    /// Leave() method.
    pub fn token(&self) -> Option<u64> {
        self.token
    }
}

impl Drop for ApplicationHandle {
    fn drop(&mut self) {
        // required for drop order
    }
}