nmrs 3.0.0

A Rust library for NetworkManager over D-Bus
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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
use std::collections::HashMap;

use tokio::sync::watch;
use zbus::Connection;
use zvariant::OwnedValue;

use crate::Result;
use crate::api::models::access_point::AccessPoint;
use crate::api::models::{
    AirplaneModeState, Device, Network, NetworkInfo, RadioState, SavedConnection,
    SavedConnectionBrief, SettingsPatch, WifiDevice, WifiSecurity,
};
use crate::api::wifi_scope::WifiScope;
use crate::core::airplane;
use crate::core::bluetooth::connect_bluetooth;
use crate::core::connection::{
    connect, connect_to_bssid, connect_wired, disconnect, forget_by_name_and_type,
    get_device_by_interface, is_connected,
};
use crate::core::connection_settings::{get_saved_connection_path, has_saved_connection};
use crate::core::device::{
    is_connecting, list_bluetooth_devices, list_devices, wait_for_wifi_ready,
};
use crate::core::saved_connection as saved_profiles;
use crate::core::scan::{current_network, list_access_points, list_networks, scan_networks};
use crate::core::vpn::{
    active_vpn_connections, connect_vpn, connect_vpn_by_id, connect_vpn_by_uuid, disconnect_vpn,
    disconnect_vpn_by_uuid, get_vpn_info, list_vpn_connections,
};
use crate::core::wifi_device::{list_wifi_devices, set_wifi_enabled_for_interface};
use crate::models::{
    BluetoothDevice, BluetoothIdentity, VpnConfig, VpnConfiguration, VpnConnection,
    VpnConnectionInfo,
};
use crate::monitoring::device as device_monitor;
use crate::monitoring::info::show_details;
use crate::monitoring::network as network_monitor;
use crate::monitoring::wifi::{current_connection_info, current_ssid};
use crate::types::constants::device_type;

/// High-level interface to NetworkManager over D-Bus.
///
/// This is the main entry point for managing network connections on Linux systems.
/// It provides a safe, async Rust API over NetworkManager's D-Bus interface.
///
/// # Creating an Instance
///
/// ```no_run
/// use nmrs::NetworkManager;
///
/// # async fn example() -> nmrs::Result<()> {
/// let nm = NetworkManager::new().await?;
/// # Ok(())
/// # }
/// ```
///
/// # Capabilities
///
/// - **Device Management**: List devices, enable/disable WiFi
/// - **Network Scanning**: Discover available WiFi networks
/// - **Connection Management**: Connect to WiFi, Ethernet networks
/// - **Profile Management**: Save, retrieve, and delete connection profiles
/// - **Real-Time Monitoring**: Subscribe to network and device state changes
///
/// # Examples
///
/// ## Basic WiFi Connection
///
/// ```no_run
/// use nmrs::{NetworkManager, WifiSecurity};
///
/// # async fn example() -> nmrs::Result<()> {
/// let nm = NetworkManager::new().await?;
///
/// // Scan and list networks (None = all Wi-Fi devices)
/// let networks = nm.list_networks(None).await?;
/// for net in &networks {
///     println!("{}: {}%", net.ssid, net.strength.unwrap_or(0));
/// }
///
/// // Connect to a network on the first Wi-Fi device
/// nm.connect("MyNetwork", None, WifiSecurity::WpaPsk {
///     psk: "password".into()
/// }).await?;
/// # Ok(())
/// # }
/// ```
///
/// ## Device Management
///
/// ```no_run
/// use nmrs::NetworkManager;
///
/// # async fn example() -> nmrs::Result<()> {
/// let nm = NetworkManager::new().await?;
///
/// // List all network devices
/// let devices = nm.list_devices().await?;
///
/// // Control WiFi
/// nm.set_wireless_enabled(false).await?;  // Disable WiFi
/// nm.set_wireless_enabled(true).await?;   // Enable WiFi
///
/// // Check airplane mode
/// let state = nm.airplane_mode_state().await?;
/// println!("Airplane mode: {}", state.is_airplane_mode());
/// # Ok(())
/// # }
/// ```
///
/// ## Connection Profiles
///
/// ```no_run
/// use nmrs::NetworkManager;
///
/// # async fn example() -> nmrs::Result<()> {
/// let nm = NetworkManager::new().await?;
///
/// // Check for saved connection
/// if nm.has_saved_connection("MyNetwork").await? {
///     println!("Connection profile exists");
///     
///     // Delete it
///     nm.forget("MyNetwork").await?;
/// }
/// # Ok(())
/// # }
/// ```
///
/// # Thread Safety
///
/// `NetworkManager` is `Clone` and can be safely shared across async tasks.
/// Each clone shares the same underlying D-Bus connection.
///
/// # Concurrency
///
/// Concurrent connection operations (e.g. calling [`connect`](Self::connect)
/// from multiple tasks simultaneously) are **not supported** and may cause
/// race conditions. Use [`is_connecting`](Self::is_connecting) to check
/// whether a connection operation is already in progress before starting
/// a new one.
#[derive(Debug, Clone)]
pub struct NetworkManager {
    conn: Connection,
    timeout_config: crate::api::models::TimeoutConfig,
}

impl NetworkManager {
    /// Creates a new `NetworkManager` connected to the system D-Bus with default timeout configuration.
    ///
    /// Uses default timeouts of 30 seconds for connection and 10 seconds for disconnection.
    /// To customize timeouts, use [`with_config()`](Self::with_config) instead.
    pub async fn new() -> Result<Self> {
        let conn = Connection::system().await?;
        Ok(Self {
            conn,
            timeout_config: crate::api::models::TimeoutConfig::default(),
        })
    }

    /// Creates a new `NetworkManager` with custom timeout configuration.
    ///
    /// This allows you to customize how long NetworkManager will wait for
    /// various operations to complete before timing out.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nmrs::{NetworkManager, TimeoutConfig};
    /// use std::time::Duration;
    ///
    /// # async fn example() -> nmrs::Result<()> {
    /// // Configure longer timeouts for slow networks
    /// let config = TimeoutConfig::new()
    ///     .with_connection_timeout(Duration::from_secs(60))
    ///     .with_disconnect_timeout(Duration::from_secs(20));
    ///
    /// let nm = NetworkManager::with_config(config).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn with_config(timeout_config: crate::api::models::TimeoutConfig) -> Result<Self> {
        let conn = Connection::system().await?;
        Ok(Self {
            conn,
            timeout_config,
        })
    }

    /// Returns the current timeout configuration.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nmrs::NetworkManager;
    ///
    /// # async fn example() -> nmrs::Result<()> {
    /// let nm = NetworkManager::new().await?;
    /// let config = nm.timeout_config();
    /// println!("Connection timeout: {:?}", config.connection_timeout);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn timeout_config(&self) -> crate::api::models::TimeoutConfig {
        self.timeout_config
    }

    /// List all network devices managed by NetworkManager.
    pub async fn list_devices(&self) -> Result<Vec<Device>> {
        list_devices(&self.conn).await
    }

    /// List all bluetooth devices.
    pub async fn list_bluetooth_devices(&self) -> Result<Vec<BluetoothDevice>> {
        list_bluetooth_devices(&self.conn).await
    }

    /// Lists all network devices managed by NetworkManager.
    pub async fn list_wireless_devices(&self) -> Result<Vec<Device>> {
        let devices = list_devices(&self.conn).await?;
        Ok(devices.into_iter().filter(|d| d.is_wireless()).collect())
    }

    /// List all wired (Ethernet) devices.
    pub async fn list_wired_devices(&self) -> Result<Vec<Device>> {
        let devices = list_devices(&self.conn).await?;
        Ok(devices.into_iter().filter(|d| d.is_wired()).collect())
    }

    /// Lists all visible Wi-Fi networks.
    ///
    /// Networks sharing an SSID on the same device are grouped, keeping the
    /// strongest AP as the representative. Each returned [`Network`] carries
    /// `best_bssid`, `bssids`, and `security_features` from the underlying APs.
    ///
    /// Pass `interface = Some("wlan0")` to scope to a single Wi-Fi device,
    /// or `None` to enumerate across every Wi-Fi device.
    ///
    /// **3.0 break:** added the `interface` parameter. For old behavior,
    /// pass `None`.
    pub async fn list_networks(&self, interface: Option<&str>) -> Result<Vec<Network>> {
        list_networks(&self.conn, interface).await
    }

    /// Lists every managed Wi-Fi device on the system.
    ///
    /// Each [`WifiDevice`] includes its interface name, MAC, current state,
    /// and the SSID of any active connection.
    pub async fn list_wifi_devices(&self) -> Result<Vec<WifiDevice>> {
        list_wifi_devices(&self.conn).await
    }

    /// Look up a single Wi-Fi device by interface name.
    ///
    /// Returns
    /// [`WifiInterfaceNotFound`](crate::ConnectionError::WifiInterfaceNotFound)
    /// if no device matches, or
    /// [`NotAWifiDevice`](crate::ConnectionError::NotAWifiDevice) if the
    /// interface exists but isn't a Wi-Fi device.
    pub async fn wifi_device_by_interface(&self, name: &str) -> Result<WifiDevice> {
        let all = list_wifi_devices(&self.conn).await?;
        all.into_iter()
            .find(|d| d.interface == name)
            .ok_or_else(|| crate::ConnectionError::WifiInterfaceNotFound {
                interface: name.to_string(),
            })
    }

    /// Build a [`WifiScope`] pinned to the given interface.
    ///
    /// All operations on the returned scope target only that one Wi-Fi
    /// device. Useful on multi-radio systems (laptops with USB dongles,
    /// docks with a second wireless adapter).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nmrs::{NetworkManager, WifiSecurity};
    ///
    /// # async fn example() -> nmrs::Result<()> {
    /// let nm = NetworkManager::new().await?;
    /// nm.wifi("wlan1").connect(
    ///     "Guest",
    ///     WifiSecurity::WpaPsk { psk: "guestpass".into() },
    /// ).await?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn wifi(&self, interface: impl Into<String>) -> WifiScope {
        WifiScope {
            conn: self.conn.clone(),
            interface: interface.into(),
            timeout_config: self.timeout_config,
        }
    }

    /// Lists all visible access points, one entry per BSSID.
    ///
    /// Unlike [`list_networks`](Self::list_networks), this preserves
    /// duplicate BSSIDs for the same SSID and includes per-AP details
    /// like BSSID, exact frequency, bitrate, and device state.
    ///
    /// Pass `interface` to restrict to a single wireless device (e.g.
    /// `Some("wlan0")`), or `None` for all devices.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nmrs::NetworkManager;
    ///
    /// # async fn example() -> nmrs::Result<()> {
    /// let nm = NetworkManager::new().await?;
    /// let mut aps = nm.list_access_points(None).await?;
    /// aps.sort_by(|a, b| b.strength.cmp(&a.strength));
    /// for ap in &aps {
    ///     println!("{:>3}%  {:<20} {}  {} MHz",
    ///         ap.strength, ap.ssid, ap.bssid, ap.frequency_mhz);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn list_access_points(&self, interface: Option<&str>) -> Result<Vec<AccessPoint>> {
        list_access_points(&self.conn, interface).await
    }

    /// Connects to a specific access point by SSID and optional BSSID.
    ///
    /// If `bssid` is `Some`, the connection targets that specific AP rather
    /// than the strongest match for the SSID. If `None`, behaves identically
    /// to [`connect`](Self::connect).
    ///
    /// **3.0 break:** added the `interface` parameter (3rd argument). Pass
    /// `None` for the previous behavior of using the first available Wi-Fi
    /// device, or `Some("wlan1")` to pin the connection to a specific
    /// interface. For an ergonomic per-interface API, see
    /// [`wifi`](Self::wifi).
    ///
    /// # Errors
    ///
    /// Returns [`ApBssidNotFound`](crate::ConnectionError::ApBssidNotFound) if
    /// no AP matching both the SSID and BSSID is visible.
    /// Returns [`InvalidBssid`](crate::ConnectionError::InvalidBssid) if the
    /// BSSID format is invalid.
    /// Returns
    /// [`WifiInterfaceNotFound`](crate::ConnectionError::WifiInterfaceNotFound)
    /// or [`NotAWifiDevice`](crate::ConnectionError::NotAWifiDevice) if the
    /// supplied interface name is bad.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nmrs::{NetworkManager, WifiSecurity};
    ///
    /// # async fn example() -> nmrs::Result<()> {
    /// let nm = NetworkManager::new().await?;
    /// nm.connect_to_bssid(
    ///     "HomeWiFi",
    ///     Some("AA:BB:CC:DD:EE:FF"),
    ///     None,
    ///     WifiSecurity::WpaPsk { psk: "password".into() },
    /// ).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn connect_to_bssid(
        &self,
        ssid: &str,
        bssid: Option<&str>,
        interface: Option<&str>,
        creds: WifiSecurity,
    ) -> Result<()> {
        connect_to_bssid(
            &self.conn,
            ssid,
            bssid,
            creds,
            interface,
            Some(self.timeout_config),
        )
        .await
    }

    /// Connects to a Wi-Fi network with the given credentials.
    ///
    /// **3.0 break:** added the `interface` parameter (3rd argument). Pass
    /// `None` for the previous behavior of using the first available Wi-Fi
    /// device, or `Some("wlan1")` to pin the connection to a specific
    /// interface.
    ///
    /// # Errors
    ///
    /// Returns `ConnectionError::NotFound` if the network is not visible,
    /// `ConnectionError::AuthFailed` if authentication fails, or other
    /// variants for specific failure reasons.
    pub async fn connect(
        &self,
        ssid: &str,
        interface: Option<&str>,
        creds: WifiSecurity,
    ) -> Result<()> {
        connect(
            &self.conn,
            ssid,
            creds,
            interface,
            Some(self.timeout_config),
        )
        .await
    }

    /// Connects to a wired (Ethernet) device.
    ///
    /// Finds the first available wired device and either activates an existing
    /// saved connection or creates a new one. The connection will activate
    /// when a cable is plugged in.
    ///
    /// # Errors
    ///
    /// Returns `ConnectionError::NoWiredDevice` if no wired device is found.
    pub async fn connect_wired(&self) -> Result<()> {
        connect_wired(&self.conn, Some(self.timeout_config)).await
    }

    /// Connects to a bluetooth device using the provided identity.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use nmrs::{NetworkManager, models::BluetoothIdentity, models::BluetoothNetworkRole};
    ///
    /// # async fn example() -> nmrs::Result<()> {
    ///    let nm = NetworkManager::new().await?;
    ///
    ///    let identity = BluetoothIdentity::new(
    ///         "C8:1F:E8:F0:51:57".into(),
    ///         BluetoothNetworkRole::PanU,
    ///     )?;
    ///
    ///    nm.connect_bluetooth("My Phone", &identity).await?;
    ///    Ok(())
    /// }
    ///
    /// ```
    pub async fn connect_bluetooth(&self, name: &str, identity: &BluetoothIdentity) -> Result<()> {
        connect_bluetooth(&self.conn, name, identity, Some(self.timeout_config)).await
    }

    /// Connects to a VPN using the provided configuration.
    ///
    /// Supports WireGuard and OpenVPN connections. The function checks for an
    /// existing saved VPN connection by name. If found, it activates the saved
    /// connection. If not found, it creates a new VPN connection with the provided
    /// configuration.
    ///
    /// # Examples
    ///
    /// ## WireGuard
    ///
    /// ```rust
    /// use nmrs::{NetworkManager, WireGuardConfig, WireGuardPeer};
    ///
    /// # async fn example() -> nmrs::Result<()> {
    /// let nm = NetworkManager::new().await?;
    ///
    /// let peer = WireGuardPeer::new(
    ///     "peer_public_key",
    ///     "vpn.example.com:51820",
    ///     vec!["0.0.0.0/0".into()],
    /// ).with_persistent_keepalive(25);
    ///
    /// let config = WireGuardConfig::new(
    ///     "MyVPN",
    ///     "vpn.example.com:51820",
    ///     "your_private_key",
    ///     "10.0.0.2/24",
    ///     vec![peer],
    /// ).with_dns(vec!["1.1.1.1".into()]);
    ///
    /// nm.connect_vpn(config).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// ## OpenVPN
    ///
    /// ```rust
    /// use nmrs::{NetworkManager, OpenVpnConfig, OpenVpnAuthType};
    ///
    /// # async fn example() -> nmrs::Result<()> {
    /// let nm = NetworkManager::new().await?;
    ///
    /// let config = OpenVpnConfig::new("CorpVPN", "vpn.example.com", 1194, false)
    ///     .with_auth_type(OpenVpnAuthType::PasswordTls)
    ///     .with_username("user")
    ///     .with_password("secret")
    ///     .with_ca_cert("/etc/openvpn/ca.crt")
    ///     .with_client_cert("/etc/openvpn/client.crt")
    ///     .with_client_key("/etc/openvpn/client.key");
    ///
    /// nm.connect_vpn(config).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - NetworkManager is not running or accessible
    /// - The configuration is invalid or incomplete
    /// - The VPN connection fails to activate
    pub async fn connect_vpn<C>(&self, config: C) -> Result<()>
    where
        C: VpnConfig + Into<VpnConfiguration>,
    {
        connect_vpn(&self.conn, config.into(), Some(self.timeout_config)).await
    }

    /// Imports a `.ovpn` file and activates the OpenVPN connection.
    ///
    /// Parses the file, persists any inline certificates, builds the
    /// connection profile, and activates it through NetworkManager.
    ///
    /// # Arguments
    ///
    /// * `path` — Path to the `.ovpn` configuration file
    /// * `username` — Optional username for password-based authentication
    /// * `password` — Optional password for password-based authentication
    ///
    /// # Example
    ///
    /// ```no_run
    /// use nmrs::NetworkManager;
    ///
    /// # async fn example() -> nmrs::Result<()> {
    /// let nm = NetworkManager::new().await?;
    /// nm.import_ovpn("corp.ovpn", Some("user"), Some("secret")).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The file cannot be read or parsed
    /// - Inline certificate storage fails
    /// - The configuration is incomplete (e.g. TLS auth without certs)
    /// - The VPN connection fails to activate
    pub async fn import_ovpn(
        &self,
        path: impl AsRef<std::path::Path>,
        username: Option<&str>,
        password: Option<&str>,
    ) -> Result<()> {
        use crate::builders::OpenVpnBuilder;

        let mut builder = OpenVpnBuilder::from_ovpn_file(path)?;
        if let Some(u) = username {
            builder = builder.username(u);
        }
        if let Some(p) = password {
            builder = builder.password(p);
        }
        let config = builder.build()?;
        self.connect_vpn(config).await
    }

    /// Disconnects from an active VPN connection by name.
    ///
    /// Searches through active connections for a VPN matching the given name.
    /// If found, deactivates the connection. If not found or already disconnected,
    /// returns success.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use nmrs::NetworkManager;
    ///
    /// # async fn example() -> nmrs::Result<()> {
    /// let nm = NetworkManager::new().await?;
    /// nm.disconnect_vpn("MyVPN").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn disconnect_vpn(&self, name: &str) -> Result<()> {
        disconnect_vpn(&self.conn, name).await
    }

    /// Lists all saved VPN connections.
    ///
    /// Returns a list of all VPN connection profiles saved in NetworkManager,
    /// including their name, type, and current state. Returns WireGuard and
    /// OpenVPN connections.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use nmrs::NetworkManager;
    ///
    /// # async fn example() -> nmrs::Result<()> {
    /// let nm = NetworkManager::new().await?;
    /// let vpns = nm.list_vpn_connections().await?;
    ///
    /// for vpn in vpns {
    ///     println!("{}: {:?}", vpn.name, vpn.vpn_type);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn list_vpn_connections(&self) -> Result<Vec<VpnConnection>> {
        list_vpn_connections(&self.conn).await
    }

    /// Only active VPNs (subset of `list_vpn_connections` with `active = true`).
    pub async fn active_vpn_connections(&self) -> Result<Vec<VpnConnection>> {
        active_vpn_connections(&self.conn).await
    }

    /// Activate a saved VPN by UUID.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use nmrs::NetworkManager;
    ///
    /// # async fn example() -> nmrs::Result<()> {
    /// let nm = NetworkManager::new().await?;
    /// nm.connect_vpn_by_uuid("2c3f1234-abcd-5678-ef01-234567890abc").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn connect_vpn_by_uuid(&self, uuid: &str) -> Result<()> {
        connect_vpn_by_uuid(&self.conn, uuid, Some(self.timeout_config)).await
    }

    /// Activate a saved VPN by connection display name.
    ///
    /// Fails with [`VpnIdAmbiguous`](crate::ConnectionError::VpnIdAmbiguous)
    /// if multiple VPNs share the same name.
    pub async fn connect_vpn_by_id(&self, id: &str) -> Result<()> {
        connect_vpn_by_id(&self.conn, id, Some(self.timeout_config)).await
    }

    /// Disconnect a VPN by UUID.
    pub async fn disconnect_vpn_by_uuid(&self, uuid: &str) -> Result<()> {
        disconnect_vpn_by_uuid(&self.conn, uuid).await
    }

    /// Forgets (deletes) a saved VPN connection by name.
    ///
    /// Searches through saved connections for a VPN matching the given name.
    /// If found, deletes the connection profile. If currently connected, the
    /// VPN will be disconnected first before deletion.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use nmrs::NetworkManager;
    ///
    /// # async fn example() -> nmrs::Result<()> {
    /// let nm = NetworkManager::new().await?;
    /// nm.forget_vpn("MyVPN").await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error only if the operation fails unexpectedly.
    /// Returns `Ok(())` if no matching VPN connection is found.
    pub async fn forget_vpn(&self, name: &str) -> Result<()> {
        crate::core::vpn::forget_vpn(&self.conn, name).await
    }

    /// Gets detailed information about an active VPN connection.
    ///
    /// Retrieves comprehensive information about a VPN connection, including
    /// IP configuration, DNS servers, gateway, interface, and connection state.
    /// The VPN must be actively connected to retrieve this information.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use nmrs::NetworkManager;
    ///
    /// # async fn example() -> nmrs::Result<()> {
    /// let nm = NetworkManager::new().await?;
    /// let info = nm.get_vpn_info("MyVPN").await?;
    ///
    /// println!("VPN: {}", info.name);
    /// println!("Interface: {:?}", info.interface);
    /// println!("IP Address: {:?}", info.ip4_address);
    /// println!("DNS Servers: {:?}", info.dns_servers);
    /// println!("State: {:?}", info.state);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns `ConnectionError::NoVpnConnection` if the VPN is not found
    /// or not currently active.
    pub async fn get_vpn_info(&self, name: &str) -> Result<VpnConnectionInfo> {
        get_vpn_info(&self.conn, name).await
    }

    /// Returns the combined software/hardware state of the Wi-Fi radio.
    ///
    /// See [`RadioState`] for the distinction between `enabled` (software)
    /// and `hardware_enabled` (rfkill).
    pub async fn wifi_state(&self) -> Result<RadioState> {
        airplane::wifi_state(&self.conn).await
    }

    /// Returns the combined software/hardware state of the WWAN radio.
    pub async fn wwan_state(&self) -> Result<RadioState> {
        airplane::wwan_state(&self.conn).await
    }

    /// Returns the combined software/hardware state of the Bluetooth radio.
    ///
    /// Reads power state from all BlueZ adapters and cross-references rfkill.
    /// If BlueZ is not running or no adapters exist, returns
    /// `RadioState { enabled: true, hardware_enabled: false }`.
    pub async fn bluetooth_radio_state(&self) -> Result<RadioState> {
        airplane::bluetooth_radio_state(&self.conn).await
    }

    /// Returns the aggregated airplane-mode state across all radios.
    ///
    /// Fans out to Wi-Fi, WWAN, and Bluetooth concurrently and returns
    /// an [`AirplaneModeState`] snapshot.
    pub async fn airplane_mode_state(&self) -> Result<AirplaneModeState> {
        airplane::airplane_mode_state(&self.conn).await
    }

    /// Enables or disables the Wi-Fi radio (software toggle).
    ///
    /// This replaces the deprecated [`set_wifi_enabled`](Self::set_wifi_enabled).
    /// If the radio is hardware-killed, NM accepts the write but the radio
    /// remains off until hardware is unkilled.
    pub async fn set_wireless_enabled(&self, enabled: bool) -> Result<()> {
        airplane::set_wireless_enabled(&self.conn, enabled).await
    }

    /// Enables or disables the WWAN (mobile broadband) radio.
    ///
    /// Writes the `WwanEnabled` property on NetworkManager.
    pub async fn set_wwan_enabled(&self, enabled: bool) -> Result<()> {
        airplane::set_wwan_enabled(&self.conn, enabled).await
    }

    /// Enables or disables the Bluetooth radio by toggling all BlueZ adapters.
    ///
    /// Returns [`BluezUnavailable`](crate::ConnectionError::BluezUnavailable) if BlueZ is not running
    /// or no adapters exist.
    pub async fn set_bluetooth_radio_enabled(&self, enabled: bool) -> Result<()> {
        airplane::set_bluetooth_radio_enabled(&self.conn, enabled).await
    }

    /// Flips all three radios in one call.
    ///
    /// **`enabled = true` means airplane mode is on, i.e. radios are off.**
    ///
    /// Does not fail fast: attempts all three toggles concurrently and
    /// returns the first error at the end, if any.
    pub async fn set_airplane_mode(&self, enabled: bool) -> Result<()> {
        airplane::set_airplane_mode(&self.conn, enabled).await
    }

    /// Current connectivity state as NM sees it (single property read).
    ///
    /// # Example
    ///
    /// ```no_run
    /// use nmrs::NetworkManager;
    ///
    /// # async fn example() -> nmrs::Result<()> {
    /// let nm = NetworkManager::new().await?;
    /// let state = nm.connectivity().await?;
    /// println!("{state:?}");
    /// # Ok(())
    /// # }
    /// ```
    pub async fn connectivity(&self) -> Result<crate::ConnectivityState> {
        crate::core::connectivity::connectivity(&self.conn).await
    }

    /// Forces NM to re-check connectivity by probing the configured URI.
    ///
    /// Returns the new state once the check completes.
    ///
    /// # Errors
    ///
    /// Returns [`ConnectivityCheckDisabled`](crate::ConnectionError::ConnectivityCheckDisabled)
    /// if NM's connectivity checks are turned off.
    pub async fn check_connectivity(&self) -> Result<crate::ConnectivityState> {
        crate::core::connectivity::check_connectivity(&self.conn).await
    }

    /// Full connectivity report including check URI and captive-portal URL.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use nmrs::NetworkManager;
    ///
    /// # async fn example() -> nmrs::Result<()> {
    /// let nm = NetworkManager::new().await?;
    /// let report = nm.connectivity_report().await?;
    /// println!("{:?} portal={:?}", report.state, report.captive_portal_url);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn connectivity_report(&self) -> Result<crate::ConnectivityReport> {
        crate::core::connectivity::connectivity_report(&self.conn).await
    }

    /// Captive-portal URL detected by NM, if state is `Portal`.
    ///
    /// Returns `None` if NM is not in `Portal` state or if this NM version
    /// does not expose the URL.
    pub async fn captive_portal_url(&self) -> Result<Option<String>> {
        let report = crate::core::connectivity::connectivity_report(&self.conn).await?;
        Ok(report.captive_portal_url)
    }

    /// Disable or re-enable a single Wi-Fi interface.
    ///
    /// Sets `Device.Autoconnect = enabled` and, when disabling, calls
    /// `Device.Disconnect()`. This is independent of the global wireless
    /// killswitch ([`set_wireless_enabled`](Self::set_wireless_enabled)) and
    /// safe to use on multi-radio systems.
    ///
    /// # Errors
    ///
    /// Returns
    /// [`WifiInterfaceNotFound`](crate::ConnectionError::WifiInterfaceNotFound)
    /// if no device with that name exists, or
    /// [`NotAWifiDevice`](crate::ConnectionError::NotAWifiDevice) if the
    /// interface isn't a Wi-Fi device.
    pub async fn set_wifi_enabled(&self, interface: &str, enabled: bool) -> Result<()> {
        set_wifi_enabled_for_interface(&self.conn, interface, enabled).await
    }

    /// Waits for a Wi-Fi device to become ready (disconnected or activated).
    pub async fn wait_for_wifi_ready(&self) -> Result<()> {
        wait_for_wifi_ready(&self.conn).await
    }

    /// Triggers a Wi-Fi scan.
    ///
    /// **3.0 break:** added the `interface` parameter. Pass `None` to scan
    /// every Wi-Fi device, or `Some("wlan0")` to scan one. See
    /// [`wifi`](Self::wifi) for an ergonomic per-interface API.
    pub async fn scan_networks(&self, interface: Option<&str>) -> Result<()> {
        scan_networks(&self.conn, interface).await
    }

    /// Returns whether any network device is currently in a transitional state.
    ///
    /// A device is considered "connecting" when its state is one of:
    /// Prepare, Config, NeedAuth, IpConfig, IpCheck, Secondaries, or Deactivating.
    ///
    /// Use this to guard against concurrent connection attempts, which are
    /// not supported and may cause undefined behavior.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use nmrs::NetworkManager;
    ///
    /// # async fn example() -> nmrs::Result<()> {
    /// let nm = NetworkManager::new().await?;
    ///
    /// if nm.is_connecting().await? {
    ///     eprintln!("A connection operation is already in progress");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn is_connecting(&self) -> Result<bool> {
        is_connecting(&self.conn).await
    }

    /// Check if a network is connected
    pub async fn is_connected(&self, ssid: &str) -> Result<bool> {
        is_connected(&self.conn, ssid).await
    }

    /// Disconnects from the current Wi-Fi network.
    ///
    /// If currently connected to a Wi-Fi network, this deactivates the
    /// active connection on the targeted device and waits for it to reach
    /// the disconnected state.
    ///
    /// **3.0 break:** added the `interface` parameter. Pass `None` for the
    /// previous behavior (first Wi-Fi device), or `Some("wlan1")` to target
    /// a specific interface.
    ///
    /// Returns `Ok(())` if disconnected successfully or if no active
    /// connection exists.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use nmrs::NetworkManager;
    ///
    /// # async fn example() -> nmrs::Result<()> {
    /// let nm = NetworkManager::new().await?;
    /// nm.disconnect(None).await?;
    /// nm.disconnect(Some("wlan1")).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn disconnect(&self, interface: Option<&str>) -> Result<()> {
        disconnect(&self.conn, interface, Some(self.timeout_config)).await
    }

    /// Returns the full `Network` object for the currently connected WiFi network.
    ///
    /// This provides detailed information about the active connection including
    /// signal strength, frequency, security type, and BSSID.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use nmrs::NetworkManager;
    ///
    /// # async fn example() -> nmrs::Result<()> {
    /// let nm = NetworkManager::new().await?;
    /// if let Some(network) = nm.current_network().await? {
    ///     println!("Connected to: {} ({}%)", network.ssid, network.strength.unwrap_or(0));
    /// } else {
    ///     println!("Not connected");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn current_network(&self) -> Result<Option<Network>> {
        current_network(&self.conn).await
    }

    /// Lists all saved connection profiles with decoded [`SavedConnection`] summaries.
    ///
    /// Secrets are not included; use a [secret agent](crate::agent) with
    /// `GetSecrets` for passwords and keys.
    ///
    /// For a lighter call that only resolves `uuid`, `id`, and `type`, see
    /// [`Self::list_saved_connections_brief`].
    ///
    /// # Example
    ///
    /// ```no_run
    /// use nmrs::NetworkManager;
    ///
    /// # async fn example() -> nmrs::Result<()> {
    /// let nm = NetworkManager::new().await?;
    /// for c in nm.list_saved_connections().await? {
    ///     println!("{}  {}  {}", c.id, c.connection_type, c.uuid);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn list_saved_connections(&self) -> Result<Vec<SavedConnection>> {
        saved_profiles::list_saved_connections(&self.conn).await
    }

    /// Lists saved profiles with only `connection.uuid`, `id`, and `type` (still one
    /// `GetSettings` per profile, but skips building [`SettingsSummary`](crate::SettingsSummary)).
    pub async fn list_saved_connections_brief(&self) -> Result<Vec<SavedConnectionBrief>> {
        saved_profiles::list_saved_connections_brief(&self.conn).await
    }

    /// Returns the human-visible names (`connection.id`) of all saved profiles.
    ///
    /// Convenience over `list_saved_connections().map(|v| v.into_iter().map(|c| c.id).collect())`.
    pub async fn list_saved_connection_ids(&self) -> Result<Vec<String>> {
        Ok(saved_profiles::list_saved_connections_brief(&self.conn)
            .await?
            .into_iter()
            .map(|c| c.id)
            .collect())
    }

    /// Loads one saved profile by UUID with full [`SavedConnection`] decode.
    ///
    /// # Errors
    ///
    /// [`SavedConnectionNotFound`](crate::ConnectionError::SavedConnectionNotFound) if
    /// the UUID does not exist.
    pub async fn get_saved_connection(&self, uuid: &str) -> Result<SavedConnection> {
        saved_profiles::get_saved_connection(&self.conn, uuid).await
    }

    /// Raw `GetSettings` map for advanced consumers.
    pub async fn get_saved_connection_raw(
        &self,
        uuid: &str,
    ) -> Result<HashMap<String, HashMap<String, OwnedValue>>> {
        saved_profiles::get_saved_connection_raw(&self.conn, uuid).await
    }

    /// Deletes a saved profile by UUID (`Settings.Connection.Delete`).
    pub async fn delete_saved_connection(&self, uuid: &str) -> Result<()> {
        saved_profiles::delete_saved_connection(&self.conn, uuid).await
    }

    /// Merges a [`SettingsPatch`] into an existing profile (`Update` / `UpdateUnsaved`).
    pub async fn update_saved_connection(&self, uuid: &str, patch: SettingsPatch) -> Result<()> {
        saved_profiles::update_saved_connection(&self.conn, uuid, &patch).await
    }

    /// Calls `ReloadConnections` so NM re-reads profiles from disk.
    pub async fn reload_saved_connections(&self) -> Result<()> {
        saved_profiles::reload_saved_connections(&self.conn).await
    }

    /// Finds a device by its interface name (e.g., "wlan0", "eth0").
    ///
    /// Returns the D-Bus object path of the device if found.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use nmrs::NetworkManager;
    ///
    /// # async fn example() -> nmrs::Result<()> {
    /// let nm = NetworkManager::new().await?;
    /// let device_path = nm.get_device_by_interface("wlan0").await?;
    /// println!("Device path: {}", device_path.as_str());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_device_by_interface(&self, name: &str) -> Result<zvariant::OwnedObjectPath> {
        get_device_by_interface(&self.conn, name).await
    }

    /// Returns the SSID of the currently connected network, if any.
    #[must_use]
    pub async fn current_ssid(&self) -> Option<String> {
        current_ssid(&self.conn).await
    }

    /// Returns the SSID and frequency of the current connection, if any.
    #[must_use]
    pub async fn current_connection_info(&self) -> Option<(String, Option<u32>)> {
        current_connection_info(&self.conn).await
    }

    /// Returns detailed information about a specific network.
    pub async fn show_details(&self, net: &Network) -> Result<NetworkInfo> {
        show_details(&self.conn, net).await
    }

    /// Returns whether a saved connection exists for the given SSID.
    pub async fn has_saved_connection(&self, ssid: &str) -> Result<bool> {
        has_saved_connection(&self.conn, ssid).await
    }

    /// Returns the D-Bus object path of a saved connection for the given SSID.
    pub async fn get_saved_connection_path(
        &self,
        ssid: &str,
    ) -> Result<Option<zvariant::OwnedObjectPath>> {
        get_saved_connection_path(&self.conn, ssid).await
    }

    /// Forgets (deletes) a saved WiFi connection for the given SSID.
    ///
    /// If currently connected to this network, disconnects first, then deletes
    /// all saved connection profiles matching the SSID.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` if one or more connections were deleted successfully,
    /// or if no matching connections were found.
    pub async fn forget(&self, ssid: &str) -> Result<()> {
        forget_by_name_and_type(
            &self.conn,
            ssid,
            Some(device_type::WIFI),
            Some(self.timeout_config),
        )
        .await
    }

    /// Forgets (deletes) a saved Bluetooth connection.
    ///
    /// If currently connected to this device, it will disconnect first before
    /// deleting the connection profile. Can match by connection name or bdaddr.
    ///
    /// # Arguments
    ///
    /// * `name` - Connection name or bdaddr to forget
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` if the connection was deleted successfully.
    /// Returns `NoSavedConnection` if no matching connection was found.
    pub async fn forget_bluetooth(&self, name: &str) -> Result<()> {
        forget_by_name_and_type(
            &self.conn,
            name,
            Some(device_type::BLUETOOTH),
            Some(self.timeout_config),
        )
        .await
    }
    ///
    /// Subscribes to D-Bus signals for access point additions, removals, and
    /// signal strength changes on all Wi-Fi devices. Invokes the callback
    /// whenever the network list or signal data changes, enabling live UI
    /// updates without polling.
    ///
    /// This function runs indefinitely until an error occurs. Run it in a
    /// background task.
    ///
    /// # Example
    ///
    /// ```ignore
    /// # use nmrs::NetworkManager;
    /// # async fn example() -> nmrs::Result<()> {
    /// let nm = NetworkManager::new().await?;
    ///
    /// let nm_clone = nm.clone();
    /// tokio::spawn(async move {
    ///     nm_clone.monitor_network_changes(|| {
    ///         println!("Networks changed!");
    ///     }).await
    /// });
    /// # Ok(())
    /// # }
    /// ```
    pub async fn monitor_network_changes<F>(&self, callback: F) -> Result<()>
    where
        F: Fn() + Send + 'static,
    {
        let (_tx, rx) = watch::channel(());
        network_monitor::monitor_network_changes(&self.conn, rx, callback).await
    }

    /// Monitors device state changes in real-time.
    ///
    /// Subscribes to D-Bus signals for device state changes on all network
    /// devices (both wired and wireless). Invokes the callback whenever a
    /// device state changes (e.g., cable plugged in, device activated),
    /// enabling live UI updates without polling.
    ///
    /// This function runs indefinitely until an error occurs. Run it in a
    /// background task.
    ///
    /// # Example
    ///
    /// ```ignore
    /// # use nmrs::NetworkManager;
    /// # async fn example() -> nmrs::Result<()> {
    /// let nm = NetworkManager::new().await?;
    ///
    /// let nm_clone = nm.clone();
    /// tokio::spawn(async move {
    ///     nm_clone.monitor_device_changes(|| {
    ///         println!("Device state changed!");
    ///     }).await
    /// });
    /// # Ok(())
    /// # }
    /// ```
    pub async fn monitor_device_changes<F>(&self, callback: F) -> Result<()>
    where
        F: Fn() + Send + 'static,
    {
        let (_tx, rx) = watch::channel(());
        device_monitor::monitor_device_changes(&self.conn, rx, callback).await
    }
}