oxvif 0.7.0

Async Rust client library for the ONVIF IP camera protocol
Documentation
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
// ── Device Service ────────────────────────────────────────────────────────────

use super::OnvifClient;
use crate::error::OnvifError;
use crate::soap::{find_response, parse_soap_body};
use crate::types::{
    Capabilities, DeviceInfo, DnsInformation, Hostname, NetworkGateway, NetworkInterface,
    NetworkProtocol, NtpInfo, OnvifService, RelayOutput, StorageConfiguration, SystemDateTime,
    SystemLog, SystemUris, User, xml_escape,
};

impl OnvifClient {
    /// Retrieve service endpoint URLs from the device.
    ///
    /// This is typically the first call made after constructing a client. The
    /// returned [`Capabilities`] provides the URLs needed for all subsequent
    /// media, PTZ, events, and imaging operations.
    pub async fn get_capabilities(&self) -> Result<Capabilities, OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/GetCapabilities";
        const BODY: &str =
            "<tds:GetCapabilities><tds:Category>All</tds:Category></tds:GetCapabilities>";

        let xml = self.call(&self.device_url, ACTION, BODY).await?;
        let body = parse_soap_body(&xml)?;
        let resp = find_response(&body, "GetCapabilitiesResponse")?;
        Capabilities::from_xml(resp)
    }

    /// Retrieve all service endpoints advertised by the device.
    ///
    /// `GetServices` is the correct ONVIF mechanism for discovering every
    /// service URL, including Media2. Many devices do not include the Media2
    /// URL in `GetCapabilities` — call this as a fallback:
    ///
    /// ```no_run
    /// # use oxvif::{OnvifClient, OnvifError};
    /// # async fn run() -> Result<(), OnvifError> {
    /// let client = OnvifClient::new("http://192.168.1.1/onvif/device_service");
    /// let caps   = client.get_capabilities().await?;
    /// let media2_url = match caps.media2_url {
    ///     Some(u) => u,
    ///     None => client.get_services().await?
    ///         .into_iter()
    ///         .find(|s| s.is_media2())
    ///         .map(|s| s.url)
    ///         .expect("device does not support Media2"),
    /// };
    /// # Ok(()) }
    /// ```
    pub async fn get_services(&self) -> Result<Vec<OnvifService>, OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/GetServices";
        const BODY: &str = "<tds:GetServices><tds:IncludeCapability>false</tds:IncludeCapability></tds:GetServices>";

        let xml = self.call(&self.device_url, ACTION, BODY).await?;
        let body = parse_soap_body(&xml)?;
        let resp = find_response(&body, "GetServicesResponse")?;
        OnvifService::vec_from_xml(resp)
    }

    /// Retrieve the device clock and compute the UTC offset for WS-Security.
    ///
    /// Call this before [`with_utc_offset`](Self::with_utc_offset) when the
    /// device clock may differ from local UTC:
    ///
    /// ```no_run
    /// # use oxvif::{OnvifClient, OnvifError};
    /// # async fn run() -> Result<(), OnvifError> {
    /// let client = OnvifClient::new("http://192.168.1.1/onvif/device_service");
    /// let dt     = client.get_system_date_and_time().await?;
    /// let client = client.with_credentials("admin", "pass")
    ///                    .with_utc_offset(dt.utc_offset_secs());
    /// # Ok(()) }
    /// ```
    pub async fn get_system_date_and_time(&self) -> Result<SystemDateTime, OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/GetSystemDateAndTime";
        const BODY: &str = "<tds:GetSystemDateAndTime/>";

        let xml = self.call(&self.device_url, ACTION, BODY).await?;
        let body = parse_soap_body(&xml)?;
        let resp = find_response(&body, "GetSystemDateAndTimeResponse")?;
        SystemDateTime::from_xml(resp)
    }

    /// Retrieve manufacturer, model, firmware version, and serial number.
    pub async fn get_device_info(&self) -> Result<DeviceInfo, OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/GetDeviceInformation";
        const BODY: &str = "<tds:GetDeviceInformation/>";

        let xml = self.call(&self.device_url, ACTION, BODY).await?;
        let body = parse_soap_body(&xml)?;
        let resp = find_response(&body, "GetDeviceInformationResponse")?;
        DeviceInfo::from_xml(resp)
    }

    /// Retrieve the device hostname and whether it is assigned by DHCP.
    pub async fn get_hostname(&self) -> Result<Hostname, OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/GetHostname";
        const BODY: &str = "<tds:GetHostname/>";
        let xml = self.call(&self.device_url, ACTION, BODY).await?;
        let body_node = parse_soap_body(&xml)?;
        let resp = find_response(&body_node, "GetHostnameResponse")?;
        Hostname::from_xml(resp)
    }

    /// Set the device hostname.
    ///
    /// Most devices require a reboot for the change to take effect.
    pub async fn set_hostname(&self, name: &str) -> Result<(), OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/SetHostname";
        let name = xml_escape(name);
        let body = format!("<tds:SetHostname><tds:Name>{name}</tds:Name></tds:SetHostname>");
        let xml = self.call(&self.device_url, ACTION, &body).await?;
        let body_node = parse_soap_body(&xml)?;
        find_response(&body_node, "SetHostnameResponse")?;
        Ok(())
    }

    /// Retrieve the NTP server configuration.
    ///
    /// Returns whether servers come from DHCP and the list of manually
    /// configured server addresses.
    pub async fn get_ntp(&self) -> Result<NtpInfo, OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/GetNTP";
        const BODY: &str = "<tds:GetNTP/>";
        let xml = self.call(&self.device_url, ACTION, BODY).await?;
        let body_node = parse_soap_body(&xml)?;
        let resp = find_response(&body_node, "GetNTPResponse")?;
        NtpInfo::from_xml(resp)
    }

    /// Set the NTP server configuration.
    ///
    /// When `from_dhcp` is `true`, `servers` is ignored; DHCP provides the
    /// NTP servers. When `false`, each entry in `servers` is sent as a
    /// `NTPManual` element (accepted as either a DNS hostname or an IP
    /// address string).
    pub async fn set_ntp(&self, from_dhcp: bool, servers: &[&str]) -> Result<(), OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/SetNTP";
        let from_dhcp_str = if from_dhcp { "true" } else { "false" };
        let server_els: String = servers
            .iter()
            .map(|s| {
                format!(
                    "<tds:NTPManual>\
                       <tt:Type>DNS</tt:Type>\
                       <tt:DNSname>{}</tt:DNSname>\
                     </tds:NTPManual>",
                    xml_escape(s)
                )
            })
            .collect();
        let body = format!(
            "<tds:SetNTP>\
               <tds:FromDHCP>{from_dhcp_str}</tds:FromDHCP>\
               {server_els}\
             </tds:SetNTP>"
        );
        let xml = self.call(&self.device_url, ACTION, &body).await?;
        let body_node = parse_soap_body(&xml)?;
        find_response(&body_node, "SetNTPResponse")?;
        Ok(())
    }

    /// Initiate a device reboot.
    ///
    /// Returns the device's informational reboot message (e.g.
    /// `"Rebooting in 30 seconds"`). The connection will drop shortly after.
    pub async fn system_reboot(&self) -> Result<String, OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/SystemReboot";
        const BODY: &str = "<tds:SystemReboot/>";
        let xml = self.call(&self.device_url, ACTION, BODY).await?;
        let body_node = parse_soap_body(&xml)?;
        let resp = find_response(&body_node, "SystemRebootResponse")?;
        Ok(resp
            .child("Message")
            .map(|n| n.text().to_string())
            .unwrap_or_default())
    }

    /// Retrieve the device's scope URIs.
    ///
    /// Scopes describe device metadata such as name, location, and hardware model
    /// (e.g. `"onvif://www.onvif.org/name/Camera1"`). Use them for device
    /// filtering in WS-Discovery.
    pub async fn get_scopes(&self) -> Result<Vec<String>, OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/GetScopes";
        const BODY: &str = "<tds:GetScopes/>";

        let xml = self.call(&self.device_url, ACTION, BODY).await?;
        let body_node = parse_soap_body(&xml)?;
        let resp = find_response(&body_node, "GetScopesResponse")?;
        Ok(resp
            .children_named("Scopes")
            .filter_map(|n| n.child("ScopeItem").map(|s| s.text().to_string()))
            .collect())
    }

    /// Retrieve user accounts configured on the device.
    pub async fn get_users(&self) -> Result<Vec<User>, OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/GetUsers";
        const BODY: &str = "<tds:GetUsers/>";
        let xml = self.call(&self.device_url, ACTION, BODY).await?;
        let body_node = parse_soap_body(&xml)?;
        let resp = find_response(&body_node, "GetUsersResponse")?;
        User::vec_from_xml(resp)
    }

    /// Create one or more user accounts.
    ///
    /// Each element of `users` is `(username, password, user_level)`.
    /// `user_level` must be one of `"Administrator"`, `"Operator"`, `"User"`.
    pub async fn create_users(&self, users: &[(&str, &str, &str)]) -> Result<(), OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/CreateUsers";
        let user_els: String = users
            .iter()
            .map(|(u, p, l)| {
                format!(
                    "<tds:User>\
                       <tt:Username>{}</tt:Username>\
                       <tt:Password>{}</tt:Password>\
                       <tt:UserLevel>{}</tt:UserLevel>\
                     </tds:User>",
                    xml_escape(u),
                    xml_escape(p),
                    xml_escape(l)
                )
            })
            .collect();
        let body = format!("<tds:CreateUsers>{user_els}</tds:CreateUsers>");
        let xml = self.call(&self.device_url, ACTION, &body).await?;
        let body_node = parse_soap_body(&xml)?;
        find_response(&body_node, "CreateUsersResponse")?;
        Ok(())
    }

    /// Delete user accounts by username.
    pub async fn delete_users(&self, usernames: &[&str]) -> Result<(), OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/DeleteUsers";
        let user_els: String = usernames
            .iter()
            .map(|u| format!("<tds:Username>{}</tds:Username>", xml_escape(u)))
            .collect();
        let body = format!("<tds:DeleteUsers>{user_els}</tds:DeleteUsers>");
        let xml = self.call(&self.device_url, ACTION, &body).await?;
        let body_node = parse_soap_body(&xml)?;
        find_response(&body_node, "DeleteUsersResponse")?;
        Ok(())
    }

    /// Modify an existing user account.
    ///
    /// `password` may be `None` to leave the password unchanged.
    pub async fn set_user(
        &self,
        username: &str,
        password: Option<&str>,
        user_level: &str,
    ) -> Result<(), OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/SetUser";
        let pass_el = password
            .map(|p| format!("<tt:Password>{}</tt:Password>", xml_escape(p)))
            .unwrap_or_default();
        let body = format!(
            "<tds:SetUser>\
               <tds:User>\
                 <tt:Username>{}</tt:Username>\
                 {pass_el}\
                 <tt:UserLevel>{}</tt:UserLevel>\
               </tds:User>\
             </tds:SetUser>",
            xml_escape(username),
            xml_escape(user_level)
        );
        let xml = self.call(&self.device_url, ACTION, &body).await?;
        let body_node = parse_soap_body(&xml)?;
        find_response(&body_node, "SetUserResponse")?;
        Ok(())
    }

    /// Retrieve all network interfaces and their IPv4/IPv6 configuration.
    pub async fn get_network_interfaces(&self) -> Result<Vec<NetworkInterface>, OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/GetNetworkInterfaces";
        const BODY: &str = "<tds:GetNetworkInterfaces/>";
        let xml = self.call(&self.device_url, ACTION, BODY).await?;
        let body_node = parse_soap_body(&xml)?;
        let resp = find_response(&body_node, "GetNetworkInterfacesResponse")?;
        NetworkInterface::vec_from_xml(resp)
    }

    /// Update the IPv4 configuration of a network interface.
    ///
    /// Returns `true` if the device requires a reboot to apply the change.
    pub async fn set_network_interfaces(
        &self,
        token: &str,
        enabled: bool,
        ipv4_address: &str,
        prefix_length: u32,
        from_dhcp: bool,
    ) -> Result<bool, OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/SetNetworkInterfaces";
        let enabled_str = if enabled { "true" } else { "false" };
        let from_dhcp_str = if from_dhcp { "true" } else { "false" };
        let body = format!(
            "<tds:SetNetworkInterfaces>\
               <tds:InterfaceToken>{}</tds:InterfaceToken>\
               <tds:NetworkInterface>\
                 <tt:Enabled>{enabled_str}</tt:Enabled>\
                 <tt:IPv4>\
                   <tt:Enabled>true</tt:Enabled>\
                   <tt:DHCP>{from_dhcp_str}</tt:DHCP>\
                   <tt:Manual>\
                     <tt:Address>{}</tt:Address>\
                     <tt:PrefixLength>{prefix_length}</tt:PrefixLength>\
                   </tt:Manual>\
                 </tt:IPv4>\
               </tds:NetworkInterface>\
             </tds:SetNetworkInterfaces>",
            xml_escape(token),
            xml_escape(ipv4_address)
        );
        let xml = self.call(&self.device_url, ACTION, &body).await?;
        let body_node = parse_soap_body(&xml)?;
        let resp = find_response(&body_node, "SetNetworkInterfacesResponse")?;
        let reboot = resp
            .child("RebootNeeded")
            .map(|n| n.text() == "true" || n.text() == "1")
            .unwrap_or(false);
        Ok(reboot)
    }

    /// Retrieve the enabled network protocols (HTTP, HTTPS, RTSP, etc.).
    pub async fn get_network_protocols(&self) -> Result<Vec<NetworkProtocol>, OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/GetNetworkProtocols";
        const BODY: &str = "<tds:GetNetworkProtocols/>";
        let xml = self.call(&self.device_url, ACTION, BODY).await?;
        let body_node = parse_soap_body(&xml)?;
        let resp = find_response(&body_node, "GetNetworkProtocolsResponse")?;
        NetworkProtocol::vec_from_xml(resp)
    }

    /// Retrieve the DNS server configuration.
    pub async fn get_dns(&self) -> Result<DnsInformation, OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/GetDNS";
        const BODY: &str = "<tds:GetDNS/>";
        let xml = self.call(&self.device_url, ACTION, BODY).await?;
        let body_node = parse_soap_body(&xml)?;
        let resp = find_response(&body_node, "GetDNSResponse")?;
        DnsInformation::from_xml(resp)
    }

    /// Set the DNS server configuration.
    ///
    /// When `from_dhcp` is `true`, `servers` is ignored.
    pub async fn set_dns(&self, from_dhcp: bool, servers: &[&str]) -> Result<(), OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/SetDNS";
        let from_dhcp_str = if from_dhcp { "true" } else { "false" };
        let server_els: String = servers
            .iter()
            .map(|s| {
                format!(
                    "<tds:DNSManual>\
                       <tt:Type>IPv4</tt:Type>\
                       <tt:IPv4Address>{}</tt:IPv4Address>\
                     </tds:DNSManual>",
                    xml_escape(s)
                )
            })
            .collect();
        let body = format!(
            "<tds:SetDNS>\
               <tds:FromDHCP>{from_dhcp_str}</tds:FromDHCP>\
               {server_els}\
             </tds:SetDNS>"
        );
        let xml = self.call(&self.device_url, ACTION, &body).await?;
        let body_node = parse_soap_body(&xml)?;
        find_response(&body_node, "SetDNSResponse")?;
        Ok(())
    }

    /// Retrieve the default IPv4 and IPv6 gateway addresses.
    pub async fn get_network_default_gateway(&self) -> Result<NetworkGateway, OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/GetNetworkDefaultGateway";
        const BODY: &str = "<tds:GetNetworkDefaultGateway/>";
        let xml = self.call(&self.device_url, ACTION, BODY).await?;
        let body_node = parse_soap_body(&xml)?;
        let resp = find_response(&body_node, "GetNetworkDefaultGatewayResponse")?;
        NetworkGateway::from_xml(resp)
    }

    /// Retrieve the device system log.
    ///
    /// `log_type` is typically `"System"` or `"Access"`.
    pub async fn get_system_log(&self, log_type: &str) -> Result<SystemLog, OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/GetSystemLog";
        let body = format!(
            "<tds:GetSystemLog><tds:LogType>{}</tds:LogType></tds:GetSystemLog>",
            xml_escape(log_type)
        );
        let xml = self.call(&self.device_url, ACTION, &body).await?;
        let body_node = parse_soap_body(&xml)?;
        let resp = find_response(&body_node, "GetSystemLogResponse")?;
        SystemLog::from_xml(resp)
    }

    /// Retrieve all relay output port configurations.
    pub async fn get_relay_outputs(&self) -> Result<Vec<RelayOutput>, OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/GetRelayOutputs";
        const BODY: &str = "<tds:GetRelayOutputs/>";
        let xml = self.call(&self.device_url, ACTION, BODY).await?;
        let body_node = parse_soap_body(&xml)?;
        let resp = find_response(&body_node, "GetRelayOutputsResponse")?;
        RelayOutput::vec_from_xml(resp)
    }

    /// Configure the properties of a relay output port.
    ///
    /// - `mode`: `"Bistable"` (latching) or `"Monostable"` (timed).
    /// - `delay_time`: ISO 8601 duration for monostable mode, e.g. `"PT1S"`.
    /// - `idle_state`: `"closed"` or `"open"`.
    pub async fn set_relay_output_settings(
        &self,
        relay_token: &str,
        mode: &str,
        delay_time: &str,
        idle_state: &str,
    ) -> Result<(), OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/SetRelayOutputSettings";
        let body = format!(
            "<tds:SetRelayOutputSettings>\
               <tds:RelayOutputToken>{}</tds:RelayOutputToken>\
               <tds:Properties>\
                 <tt:Mode>{}</tt:Mode>\
                 <tt:DelayTime>{}</tt:DelayTime>\
                 <tt:IdleState>{}</tt:IdleState>\
               </tds:Properties>\
             </tds:SetRelayOutputSettings>",
            xml_escape(relay_token),
            xml_escape(mode),
            xml_escape(delay_time),
            xml_escape(idle_state)
        );
        let xml = self.call(&self.device_url, ACTION, &body).await?;
        let body_node = parse_soap_body(&xml)?;
        find_response(&body_node, "SetRelayOutputSettingsResponse")?;
        Ok(())
    }

    /// Set the electrical state of a relay output port.
    ///
    /// `state` must be `"active"` or `"inactive"`.
    pub async fn set_relay_output_state(
        &self,
        relay_token: &str,
        state: &str,
    ) -> Result<(), OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/SetRelayOutputState";
        let body = format!(
            "<tds:SetRelayOutputState>\
               <tds:RelayOutputToken>{}</tds:RelayOutputToken>\
               <tds:LogicalState>{}</tds:LogicalState>\
             </tds:SetRelayOutputState>",
            xml_escape(relay_token),
            xml_escape(state)
        );
        let xml = self.call(&self.device_url, ACTION, &body).await?;
        let body_node = parse_soap_body(&xml)?;
        find_response(&body_node, "SetRelayOutputStateResponse")?;
        Ok(())
    }

    /// Enable or disable network protocols (HTTP, HTTPS, RTSP, etc.).
    ///
    /// Each element of `protocols` is `(name, enabled, ports)`.
    /// `name` is typically `"HTTP"`, `"HTTPS"`, or `"RTSP"`.
    pub async fn set_network_protocols(
        &self,
        protocols: &[(&str, bool, &[u32])],
    ) -> Result<(), OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/SetNetworkProtocols";
        let proto_els: String = protocols
            .iter()
            .map(|(name, enabled, ports)| {
                let port_els: String = ports
                    .iter()
                    .map(|p| format!("<tt:Port>{p}</tt:Port>"))
                    .collect();
                format!(
                    "<tds:NetworkProtocols>\
                       <tt:Name>{}</tt:Name>\
                       <tt:Enabled>{enabled}</tt:Enabled>\
                       {port_els}\
                     </tds:NetworkProtocols>",
                    xml_escape(name)
                )
            })
            .collect();
        let body = format!("<tds:SetNetworkProtocols>{proto_els}</tds:SetNetworkProtocols>");
        let xml = self.call(&self.device_url, ACTION, &body).await?;
        let body_node = parse_soap_body(&xml)?;
        find_response(&body_node, "SetNetworkProtocolsResponse")?;
        Ok(())
    }

    /// Restore the device to factory defaults.
    ///
    /// `default_type` must be `"Hard"` (full reset, including network settings)
    /// or `"Soft"` (reset configuration but keep network settings).
    pub async fn set_system_factory_default(&self, default_type: &str) -> Result<(), OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/SetSystemFactoryDefault";
        let body = format!(
            "<tds:SetSystemFactoryDefault>\
               <tds:FactoryDefault>{}</tds:FactoryDefault>\
             </tds:SetSystemFactoryDefault>",
            xml_escape(default_type)
        );
        let xml = self.call(&self.device_url, ACTION, &body).await?;
        let body_node = parse_soap_body(&xml)?;
        find_response(&body_node, "SetSystemFactoryDefaultResponse")?;
        Ok(())
    }

    /// Retrieve all storage locations (SD card, NAS, etc.) configured on the device.
    pub async fn get_storage_configurations(
        &self,
    ) -> Result<Vec<StorageConfiguration>, OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/GetStorageConfigurations";
        const BODY: &str = "<tds:GetStorageConfigurations/>";
        let xml = self.call(&self.device_url, ACTION, BODY).await?;
        let body_node = parse_soap_body(&xml)?;
        let resp = find_response(&body_node, "GetStorageConfigurationsResponse")?;
        StorageConfiguration::vec_from_xml(resp)
    }

    /// Create or update a storage configuration entry.
    ///
    /// Pass `token = ""` to create a new entry; supply an existing token to
    /// update it.
    pub async fn set_storage_configuration(
        &self,
        token: &str,
        storage_type: &str,
        local_path: &str,
        storage_uri: &str,
        user: &str,
        use_anonymous: bool,
    ) -> Result<(), OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/SetStorageConfiguration";
        let token_attr = if token.is_empty() {
            String::new()
        } else {
            format!(" token=\"{}\"", xml_escape(token))
        };
        let use_anon_str = if use_anonymous { "true" } else { "false" };
        let body = format!(
            "<tds:SetStorageConfiguration>\
               <tds:StorageConfiguration{token_attr}>\
                 <tt:StorageType>{}</tt:StorageType>\
                 <tt:LocalPath>{}</tt:LocalPath>\
                 <tt:StorageUri>{}</tt:StorageUri>\
                 <tt:UserInfo>\
                   <tt:Username>{}</tt:Username>\
                   <tt:UseAnonymous>{use_anon_str}</tt:UseAnonymous>\
                 </tt:UserInfo>\
               </tds:StorageConfiguration>\
             </tds:SetStorageConfiguration>",
            xml_escape(storage_type),
            xml_escape(local_path),
            xml_escape(storage_uri),
            xml_escape(user)
        );
        let xml = self.call(&self.device_url, ACTION, &body).await?;
        let body_node = parse_soap_body(&xml)?;
        find_response(&body_node, "SetStorageConfigurationResponse")?;
        Ok(())
    }

    /// Retrieve HTTP URIs for firmware upgrade, system log, and support-info download.
    pub async fn get_system_uris(&self) -> Result<SystemUris, OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/GetSystemUris";
        const BODY: &str = "<tds:GetSystemUris/>";
        let xml = self.call(&self.device_url, ACTION, BODY).await?;
        let body_node = parse_soap_body(&xml)?;
        let resp = find_response(&body_node, "GetSystemUrisResponse")?;
        SystemUris::from_xml(resp)
    }

    /// Retrieve the current WS-Discovery mode.
    ///
    /// Returns `"Discoverable"` or `"NonDiscoverable"`.
    pub async fn get_discovery_mode(&self) -> Result<String, OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/GetDiscoveryMode";
        const BODY: &str = "<tds:GetDiscoveryMode/>";
        let xml = self.call(&self.device_url, ACTION, BODY).await?;
        let body_node = parse_soap_body(&xml)?;
        let resp = find_response(&body_node, "GetDiscoveryModeResponse")?;
        Ok(resp
            .child("DiscoveryMode")
            .map(|n| n.text().to_string())
            .unwrap_or_default())
    }

    /// Set the WS-Discovery mode.
    ///
    /// `mode` must be `"Discoverable"` or `"NonDiscoverable"`.
    pub async fn set_discovery_mode(&self, mode: &str) -> Result<(), OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/device/wsdl/SetDiscoveryMode";
        let body = format!(
            "<tds:SetDiscoveryMode>\
               <tds:DiscoveryMode>{}</tds:DiscoveryMode>\
             </tds:SetDiscoveryMode>",
            xml_escape(mode)
        );
        let xml = self.call(&self.device_url, ACTION, &body).await?;
        let body_node = parse_soap_body(&xml)?;
        find_response(&body_node, "SetDiscoveryModeResponse")?;
        Ok(())
    }
}