wincwifi 0.2.1

WINC1500 Wifi chip embedded driver
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
use crate::errors::Error;

use embedded_nal::nb;

use crate::error;
use crate::manager::{AccessPoint, AuthType, FirmwareInfo, IPConf, ScanResult};
use crate::manager::{Credentials, HostName, ProvisioningInfo};

use super::PingResult;
use super::StackError;
use super::WincClient;
use super::Xfer;

use crate::stack::socket_callbacks::WifiModuleState;

use crate::info;

// 1 minute max, if no other delays are added
const AP_CONNECT_TIMEOUT_MILLISECONDS: u32 = 60_000;
// 5 seconds max, assuming no additional delays
const AP_DISCONNECT_TIMEOUT_MILLISECONDS: u32 = 5_000;
// Timeout for Provisioning
#[cfg(not(test))]
const PROVISIONING_TIMEOUT: u32 = 60 * 1000;
#[cfg(test)]
const PROVISIONING_TIMEOUT: u32 = 1000;

impl<X: Xfer> WincClient<'_, X> {
    /// Call this periodically to receive network events
    ///
    /// Polls the chip for any events and changes in state,
    /// such as socket disconnects etc. This is internally
    /// called by other socket functions as well.
    pub fn heartbeat(&mut self) -> Result<(), StackError> {
        self.dispatch_events()?;
        Ok(())
    }

    /// Initializes the Wifi module - boots the firmware and
    /// does the rest of the initialization.
    ///
    /// # Returns
    ///
    /// * `()` - The Wifi module has been started.
    /// * `nb::Error::WouldBlock` - The Wifi module is still starting.
    /// * `StackError` - An error occurred while starting the Wifi module.
    pub fn start_wifi_module(&mut self) -> nb::Result<(), StackError> {
        match self.callbacks.state {
            WifiModuleState::Reset => {
                self.callbacks.state = WifiModuleState::Starting;
                self.manager.set_crc_state(true);
                self.boot = Some(Default::default());
                Err(nb::Error::WouldBlock)
            }
            WifiModuleState::Starting => {
                if let Some(state) = self.boot.as_mut() {
                    let result = self
                        .manager
                        .boot_the_chip(state)
                        .map_err(|x| nb::Error::Other(StackError::WincWifiFail(x)))?;
                    if result {
                        self.callbacks.state = WifiModuleState::Unconnected;
                        self.boot = None;
                        return Ok(());
                    }
                    Err(nb::Error::WouldBlock)
                } else {
                    Err(nb::Error::Other(StackError::InvalidState))
                }
            }
            _ => Err(nb::Error::Other(StackError::InvalidState)),
        }
    }

    fn connect_to_ap_impl(
        &mut self,
        connect_fn: impl FnOnce(&mut Self) -> Result<(), crate::errors::Error>,
    ) -> nb::Result<(), StackError> {
        match self.callbacks.state {
            WifiModuleState::Reset | WifiModuleState::Starting | WifiModuleState::Disconnecting => {
                Err(nb::Error::Other(StackError::InvalidState))
            }
            WifiModuleState::Unconnected | WifiModuleState::Provisioning => {
                self.operation_countdown = AP_CONNECT_TIMEOUT_MILLISECONDS;
                self.callbacks.state = WifiModuleState::ConnectingToAp;
                connect_fn(self).map_err(|x| nb::Error::Other(StackError::WincWifiFail(x)))?;
                Err(nb::Error::WouldBlock)
            }
            WifiModuleState::ConnectingToAp => {
                self.delay_us(self.poll_loop_delay_us); // absolute minimum delay to make timeout possible
                self.dispatch_events()?;
                self.operation_countdown -= 1;
                if self.operation_countdown == 0 {
                    return Err(nb::Error::Other(StackError::GeneralTimeout));
                }
                Err(nb::Error::WouldBlock)
            }
            WifiModuleState::ConnectionFailed => Err(nb::Error::Other(StackError::ApJoinFailed(
                self.callbacks.connection_state.conn_error.take().unwrap(),
            ))),
            WifiModuleState::ConnectedToAp => {
                info!("connect_to_ap: got Connected to AP");
                Ok(())
            }
        }
    }

    /// Connect to access point with previously saved credentials
    pub fn connect_to_saved_ap(&mut self) -> nb::Result<(), StackError> {
        self.connect_to_ap_impl(|inner_self: &mut Self| inner_self.manager.send_default_connect())
    }

    /// Connect to access point with given SSID and password, with WPA2 security
    ///
    /// # Arguments
    ///
    /// * `ssid` - The SSID of the access point to connect to.
    /// * `password` - The password of the access point to connect to.
    /// * `save_credentials` - Whether to save the credentials to the module.
    ///
    pub fn connect_to_ap(
        &mut self,
        ssid: &str,
        password: &str,
        save_credentials: bool,
    ) -> nb::Result<(), StackError> {
        self.connect_to_ap_impl(|inner_self: &mut Self| {
            inner_self.manager.send_connect(
                AuthType::WpaPSK,
                ssid,
                password,
                0xFF,
                !save_credentials,
            )
        })
    }

    /// Trigger a scan for available access points
    ///
    /// This is a non-blocking call, and takes a few seconds
    /// to complete.
    /// Results are kept in an internal buffer - retrieve
    /// them by index with [WincClient::get_scan_result]
    ///
    /// # Returns
    ///
    /// * `num_aps` - The number of access points found.
    ///
    pub fn scan(&mut self) -> nb::Result<u8, StackError> {
        match &mut self.callbacks.connection_state.scan_number_aps {
            None => {
                // This is ignored for active scan
                const PASSIVE_SCAN_TIME: u16 = 1000;
                self.manager
                    .send_scan(0xFF, PASSIVE_SCAN_TIME)
                    .map_err(|x| nb::Error::Other(StackError::WincWifiFail(x)))?;
                // Signal operation in progress
                self.callbacks.connection_state.scan_number_aps = Some(None);
            }
            Some(num_aps) => {
                if let Some(num_aps) = num_aps.take() {
                    if let Some(err) = self.callbacks.connection_state.conn_error.take() {
                        return Err(nb::Error::Other(StackError::ApScanFailed(err)));
                    }
                    self.callbacks.connection_state.scan_number_aps = None;
                    return Ok(num_aps);
                }
            }
        }

        self.dispatch_events()?;
        Err(nb::Error::WouldBlock)
    }

    /// Get the scan result for an access point
    ///
    /// # Arguments
    ///
    /// * `index` - The index of the access point to get the result for.
    ///
    /// # Returns
    ///
    /// * `ScanResult` - The scan result for the access point.
    ///
    pub fn get_scan_result(&mut self, index: u8) -> nb::Result<ScanResult, StackError> {
        match &mut self.callbacks.connection_state.scan_results {
            None => {
                self.manager
                    .send_get_scan_result(index)
                    .map_err(StackError::WincWifiFail)?;
                self.callbacks.connection_state.scan_results = Some(None);
            }
            Some(result) => {
                if let Some(result) = result.take() {
                    self.callbacks.connection_state.scan_results = None;
                    return Ok(result);
                }
            }
        }

        self.dispatch_events()?;
        Err(nb::Error::WouldBlock)
    }

    pub fn get_ip_settings(&mut self) -> nb::Result<IPConf, StackError> {
        if let Some(ip_conf) = &self.callbacks.connection_state.ip_conf {
            return Ok(ip_conf.clone());
        }

        self.dispatch_events()?;
        Err(nb::Error::WouldBlock)
    }

    /// Gets current RSSI level
    pub fn get_current_rssi(&mut self) -> nb::Result<i8, StackError> {
        match &mut self.callbacks.connection_state.rssi_level {
            None => {
                self.manager
                    .send_get_current_rssi()
                    .map_err(StackError::WincWifiFail)?;
                self.callbacks.connection_state.rssi_level = Some(None);
            }
            Some(rssi) => {
                if let Some(rssi) = rssi.take() {
                    self.callbacks.connection_state.rssi_level = None;
                    return Ok(rssi);
                }
            }
        }

        self.dispatch_events()?;
        Err(nb::Error::WouldBlock)
    }

    /// Gets current access point connection info
    ///
    /// # Returns
    ///
    /// * `ConnectionInfo` - The current connection info for the access point.
    ///
    ///
    pub fn get_connection_info(
        &mut self,
    ) -> nb::Result<crate::manager::ConnectionInfo, StackError> {
        match &mut self.callbacks.connection_state.conn_info {
            None => {
                self.manager
                    .send_get_conn_info()
                    .map_err(StackError::WincWifiFail)?;
                self.callbacks.connection_state.conn_info = Some(None);
            }
            Some(info) => {
                if let Some(info) = info.take() {
                    self.callbacks.connection_state.conn_info = None;
                    return Ok(info);
                }
            }
        }
        self.dispatch_events()?;
        Err(nb::Error::WouldBlock)
    }

    /// Get the firmware version of the Wifi module
    pub fn get_firmware_version(&mut self) -> Result<FirmwareInfo, StackError> {
        self.manager
            .get_firmware_ver_full()
            .map_err(StackError::WincWifiFail)
    }

    /// Sends a ping request to the given IP address
    ///
    /// # Arguments
    ///
    /// * `dest_ip` - The IP address to send the ping request to.
    /// * `ttl` - The time to live for the ping request.
    /// * `count` - The number of ping requests to send.
    ///
    /// # Returns
    ///
    /// * `PingResult` - The result of the ping request.
    ///
    pub fn send_ping(
        &mut self,
        dest_ip: core::net::Ipv4Addr,
        ttl: u8,
        count: u16,
    ) -> nb::Result<PingResult, StackError> {
        match &mut self.callbacks.connection_state.ping_result {
            None => {
                info!("sending ping request");
                let marker = 42; // This seems arbitrary pass through value
                self.manager
                    .send_ping_req(dest_ip, ttl, count, marker)
                    .map_err(StackError::WincWifiFail)?;
                self.callbacks.connection_state.ping_result = Some(None);
            }
            Some(result) => {
                if let Some(result) = result.take() {
                    self.callbacks.connection_state.ping_result = None;
                    return Ok(result);
                }
            }
        }

        self.dispatch_events()?;
        Err(nb::Error::WouldBlock)
    }

    /// Sends a disconnect request to the currently connected AP.
    ///
    /// This command is only applicable in station mode.
    pub fn disconnect_ap(&mut self) -> nb::Result<(), StackError> {
        match &mut self.callbacks.state {
            WifiModuleState::ConnectedToAp => {
                self.operation_countdown = AP_DISCONNECT_TIMEOUT_MILLISECONDS;
                self.callbacks.state = WifiModuleState::Disconnecting;
                self.manager
                    .send_disconnect()
                    .map_err(|x| nb::Error::Other(StackError::WincWifiFail(x)))?;
                Err(nb::Error::WouldBlock)
            }
            WifiModuleState::Disconnecting => {
                self.delay_us(self.poll_loop_delay_us); // absolute minimum delay to make timeout possible
                self.dispatch_events()?;
                self.operation_countdown -= 1;
                if self.operation_countdown == 0 {
                    return Err(nb::Error::Other(StackError::GeneralTimeout));
                }
                Err(nb::Error::WouldBlock)
            }
            _ => {
                info!("disconnect_ap: got disconnected from AP");
                Ok(())
            }
        }
    }

    /// Starts the provisioning mode. This command is only applicable when the chip is in station mode.
    ///
    /// # Arguments
    ///
    /// * `ap` - An `AccessPoint` struct containing the SSID, password, and other network details.
    /// * `hostname` - Device domain name. Must not include `.local`.
    /// * `http_redirect` - Whether HTTP redirection is enabled.
    /// * `timeout` - The timeout duration for provisioning, in minutes.
    ///
    /// # Returns
    ///
    /// * `ProvisioningInfo` - Wifi Credentials received from provisioning.
    /// * `StackError` - If an error occurs while starting provisioning mode or receiving provisioning information.
    pub fn provisioning_mode(
        &mut self,
        ap: &AccessPoint,
        hostname: &HostName,
        http_redirect: bool,
        timeout: u32,
    ) -> nb::Result<ProvisioningInfo, StackError> {
        match &mut self.callbacks.state {
            WifiModuleState::Unconnected | WifiModuleState::ConnectedToAp => {
                let auth = <Credentials as Into<AuthType>>::into(ap.key);

                if auth == AuthType::S802_1X {
                    error!("Enterprise Security in provisioning mode is not supported");
                    return Err(nb::Error::Other(StackError::InvalidParameters));
                }

                self.manager
                    .send_start_provisioning(ap, hostname, http_redirect)
                    .map_err(|x| nb::Error::Other(StackError::WincWifiFail(x)))?;

                self.callbacks.state = WifiModuleState::Provisioning;
                self.callbacks.provisioning_info = None;
            }
            WifiModuleState::Provisioning => match &mut self.callbacks.provisioning_info {
                None => {
                    self.operation_countdown = timeout * PROVISIONING_TIMEOUT;
                    self.callbacks.provisioning_info = Some(None);
                }
                Some(result) => {
                    if let Some(info) = result.take() {
                        if info.status {
                            return Ok(info);
                        }
                        return Err(nb::Error::Other(StackError::WincWifiFail(Error::Failed)));
                    } else {
                        self.delay_us(self.poll_loop_delay_us);
                        self.operation_countdown -= 1;
                        if self.operation_countdown == 0 {
                            return Err(nb::Error::Other(StackError::GeneralTimeout));
                        }
                    }
                }
            },
            _ => {
                return Err(nb::Error::Other(StackError::InvalidState));
            }
        }

        self.dispatch_events()?;
        Err(nb::Error::WouldBlock)
    }

    /// Stops provisioning mode. This command is only applicable when the chip is in provisioning mode.
    ///
    /// # Returns
    ///
    /// * `()` - If provisioning mode starts successfully.
    /// * `StackError` - If an error occurs while stopping provisioning mode.
    pub fn stop_provisioning_mode(&mut self) -> Result<(), StackError> {
        if self.callbacks.state == WifiModuleState::Provisioning {
            self.manager
                .send_stop_provisioning()
                .map_err(StackError::WincWifiFail)?;
        } else {
            return Err(StackError::InvalidState);
        }

        // change the state to unconnected
        self.callbacks.state = WifiModuleState::Unconnected;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use core::net::Ipv4Addr;

    use super::*;
    use crate::client::{test_shared::*, SocketCallbacks};
    //use crate::manager::Error::BootRomStart;
    use crate::errors::Error;
    use crate::manager::Ssid;
    use crate::manager::{EventListener, PingError, WifiConnError, WifiConnState};
    use crate::{ConnectionInfo, Credentials, S8Password, S8Username, WifiChannel, WpaKey};
    #[cfg(feature = "wep")]
    use crate::{WepKey, WepKeyIndex};

    #[test]
    fn test_heartbeat() {
        assert_eq!(make_test_client().heartbeat(), Ok(()));
    }

    #[test]
    fn test_start_wifi_module() {
        let mut client = make_test_client();
        let result = nb::block!(client.start_wifi_module());
        assert_eq!(
            result,
            Err(StackError::WincWifiFail(Error::BootRomStart).into())
        );
    }

    #[test]
    fn test_connect_to_saved_ap_invalid_state() {
        let mut client = make_test_client();
        let result = nb::block!(client.connect_to_saved_ap());
        assert_eq!(result, Err(StackError::InvalidState));
    }
    #[test]
    fn test_connect_to_saved_ap_timeout() {
        let mut client = make_test_client();
        client.callbacks.state = WifiModuleState::Unconnected;
        let result = nb::block!(client.connect_to_saved_ap());
        assert_eq!(result, Err(StackError::GeneralTimeout));
    }
    #[test]
    fn test_connect_to_saved_ap_success() {
        let mut client = make_test_client();
        client.callbacks.state = WifiModuleState::Unconnected;
        let mut my_debug = |callbacks: &mut SocketCallbacks| {
            callbacks.on_connstate_changed(WifiConnState::Connected, WifiConnError::Unhandled);
        };
        client.debug_callback = Some(&mut my_debug);
        let result = nb::block!(client.connect_to_saved_ap());
        assert_eq!(result, Ok(()));
    }
    #[test]
    fn test_connect_to_saved_ap_invalid_credentials() {
        let mut client = make_test_client();
        client.callbacks.state = WifiModuleState::Unconnected;
        let mut my_debug = |callbacks: &mut SocketCallbacks| {
            callbacks.on_connstate_changed(WifiConnState::Disconnected, WifiConnError::AuthFail);
        };
        client.debug_callback = Some(&mut my_debug);
        let result = nb::block!(client.connect_to_saved_ap());
        assert_eq!(
            result,
            Err(StackError::ApJoinFailed(WifiConnError::AuthFail))
        );
    }

    #[test]
    fn test_connect_to_ap_success() {
        let mut client = make_test_client();
        client.callbacks.state = WifiModuleState::Unconnected;
        let mut my_debug = |callbacks: &mut SocketCallbacks| {
            callbacks.on_connstate_changed(WifiConnState::Connected, WifiConnError::Unhandled);
        };
        client.debug_callback = Some(&mut my_debug);
        let result = nb::block!(client.connect_to_ap("test", "test", false));
        assert_eq!(result, Ok(()));
    }

    #[test]
    fn test_scan_ok() {
        let mut client = make_test_client();
        client.callbacks.state = WifiModuleState::Unconnected;
        let mut my_debug = |callbacks: &mut SocketCallbacks| {
            callbacks.on_scan_done(5, WifiConnError::Unhandled);
        };
        client.debug_callback = Some(&mut my_debug);
        let result = nb::block!(client.scan());
        assert_eq!(result, Ok(5));
    }

    #[test]
    fn test_get_scan_result_ok() {
        let mut client = make_test_client();
        client.callbacks.state = WifiModuleState::Unconnected;
        let mut my_debug = |callbacks: &mut SocketCallbacks| {
            callbacks.on_scan_result(ScanResult {
                index: 0,
                rssi: 0,
                auth: AuthType::Open,
                channel: 0,
                bssid: [0; 6],
                ssid: Ssid::from("test").unwrap(),
            });
        };
        client.debug_callback = Some(&mut my_debug);
        let result = nb::block!(client.get_scan_result(0));
        assert_eq!(result.unwrap().ssid, Ssid::from("test").unwrap());
    }

    #[test]
    fn test_get_current_rssi_ok() {
        let mut client = make_test_client();
        client.callbacks.state = WifiModuleState::Unconnected;
        let mut my_debug = |callbacks: &mut SocketCallbacks| {
            callbacks.on_rssi(0);
        };
        client.debug_callback = Some(&mut my_debug);
        let result = nb::block!(client.get_current_rssi());
        assert_eq!(result, Ok(0));
    }

    #[test]
    fn test_get_connection_info_ok() {
        let mut client = make_test_client();
        client.callbacks.state = WifiModuleState::Unconnected;
        let mut my_debug = |callbacks: &mut SocketCallbacks| {
            callbacks.on_connection_info(ConnectionInfo {
                ssid: Ssid::from("test").unwrap(),
                auth: AuthType::Open,
                ip: Ipv4Addr::new(192, 168, 1, 1),
                mac: [0; 6],
                rssi: 0,
            });
        };
        client.debug_callback = Some(&mut my_debug);
        let result = nb::block!(client.get_connection_info());
        assert_eq!(result.unwrap().ssid, Ssid::from("test").unwrap());
    }

    #[test]
    fn test_get_firmware_version_ok() {
        let mut client = make_test_client();
        client.callbacks.state = WifiModuleState::Unconnected;
        let result = client.get_firmware_version();
        assert_eq!(result.unwrap().chip_id, 0);
    }

    #[test]
    fn test_send_ping_ok() {
        let mut client = make_test_client();
        client.callbacks.state = WifiModuleState::Unconnected;
        let mut my_debug = |callbacks: &mut SocketCallbacks| {
            callbacks.on_ping(
                Ipv4Addr::new(192, 168, 1, 1),
                0,
                42,
                0,
                0,
                PingError::Unhandled,
            );
        };
        client.debug_callback = Some(&mut my_debug);
        let result = nb::block!(client.send_ping(Ipv4Addr::new(192, 168, 1, 1), 64, 1));
        assert!(result.is_ok());
        assert_eq!(result.unwrap().rtt, 42);
    }

    #[test]
    fn test_disconnect_success() {
        let mut client = make_test_client();
        client.callbacks.state = WifiModuleState::ConnectedToAp;

        let mut my_debug = |callbacks: &mut SocketCallbacks| {
            callbacks.on_connstate_changed(WifiConnState::Disconnected, WifiConnError::Unhandled);
        };

        client.debug_callback = Some(&mut my_debug);

        let result = nb::block!(client.disconnect_ap());

        assert!(result.is_ok());
    }

    #[test]
    fn test_disconnect_timeout() {
        let mut client = make_test_client();
        client.callbacks.state = WifiModuleState::ConnectedToAp;

        let result = nb::block!(client.disconnect_ap());

        assert_eq!(result.err(), Some(StackError::GeneralTimeout));
    }

    #[test]
    fn test_disconnect_while_not_connected() {
        let mut client = make_test_client();
        client.callbacks.state = WifiModuleState::Starting;

        let result = nb::block!(client.disconnect_ap());

        assert!(result.is_ok());
    }

    #[test]
    fn test_provisioning_mode_open_success() {
        // test client
        let mut client = make_test_client();
        // ssid for access point configuration.
        let ap_ssid = Ssid::from("ssid").unwrap();
        // access point configuration.
        let ap = AccessPoint::open(&ap_ssid);
        // hostname for access point.
        let hostname = HostName::from("admin").unwrap();
        // ssid received from provisioning.
        let test_ssid = Ssid::from("test_ssid").unwrap();
        // Wpa key passed to provisioning callback.
        // Should be empty for Open network.
        let test_key = WpaKey::new();
        // debug callback
        let mut my_debug = |callbacks: &mut SocketCallbacks| {
            callbacks.on_provisioning(test_ssid, test_key, AuthType::Open, true);
        };

        client.debug_callback = Some(&mut my_debug);
        // set the module state to unconnected.
        client.callbacks.state = WifiModuleState::Unconnected;

        let result = nb::block!(client.provisioning_mode(&ap, &hostname, false, 1));

        assert!(result.is_ok());
        if let Ok(info) = result {
            assert_eq!(info.key, Credentials::Open);
            assert_eq!(info.ssid, test_ssid);
        } else {
            assert!(false);
        }
    }

    #[test]
    fn test_provisioning_mode_wpa_success() {
        // test client
        let mut client = make_test_client();
        // ssid for access point configuration.
        let ap_ssid = Ssid::from("ssid").unwrap();
        // wpa key for access point configuration.
        let ap_key = WpaKey::from("wpa_key").unwrap();
        // Access Point Configuration.
        let ap = AccessPoint::wpa(&ap_ssid, &ap_key);
        // hostname for access point.
        let hostname = HostName::from("admin").unwrap();
        // ssid received from provisioning.
        let test_ssid = Ssid::from("test_ssid").unwrap();
        // Wpa key passed to provisioning callback.
        let test_key = WpaKey::from("test_key").unwrap();
        // debug callback
        let mut my_debug = |callbacks: &mut SocketCallbacks| {
            callbacks.on_provisioning(test_ssid, test_key, AuthType::WpaPSK, true);
        };

        client.debug_callback = Some(&mut my_debug);
        // set the module state to unconnected.
        client.callbacks.state = WifiModuleState::Unconnected;

        let result = nb::block!(client.provisioning_mode(&ap, &hostname, false, 1));

        assert!(result.is_ok());
        if let Ok(info) = result {
            assert_eq!(info.key, Credentials::WpaPSK(test_key));
            assert_eq!(info.ssid, test_ssid);
        } else {
            assert!(false);
        }
    }

    #[cfg(feature = "wep")]
    #[test]
    fn test_provisioning_mode_wep_success() {
        // test client
        let mut client = make_test_client();
        // ssid for access point configuration.
        let ap_ssid = Ssid::from("ssid").unwrap();
        // wep key for access point configuration.
        let ap_key = WepKey::from("wep_key").unwrap();
        // Wep key index
        let wep_key_index = WepKeyIndex::Key1;
        // Access Point Configuration.
        let ap = AccessPoint::wep(&ap_ssid, &ap_key, wep_key_index);
        // hostname for access point.
        let hostname = HostName::from("admin").unwrap();
        // ssid received from provisioning.
        let test_ssid = Ssid::from("test_ssid").unwrap();
        // Wpa key passed to provisioning callback.
        let test_key = WpaKey::from("test_wep_key").unwrap();
        // Wep Key received from provisioning.
        let test_wep_key = WepKey::from("test_wep_key").unwrap();
        // debug callback
        let mut my_debug = |callbacks: &mut SocketCallbacks| {
            callbacks.on_provisioning(test_ssid, test_key, AuthType::WEP, true);
        };

        client.debug_callback = Some(&mut my_debug);
        // set the module state to unconnected.
        client.callbacks.state = WifiModuleState::Unconnected;

        let result = nb::block!(client.provisioning_mode(&ap, &hostname, false, 1));

        assert!(result.is_ok());
        if let Ok(info) = result {
            assert_eq!(info.key, Credentials::Wep(test_wep_key, wep_key_index));
            assert_eq!(info.ssid, test_ssid);
        } else {
            assert!(false);
        }
    }

    #[test]
    fn test_provisioning_mode_enterprise_fail() {
        // test client
        let mut client = make_test_client();
        // ssid for access point configuration.
        let ap_ssid = Ssid::from("ssid").unwrap();
        // S802_1X Username for network credentials.
        let s8_username = S8Username::from("username").unwrap();
        // S802_1X Password for network credentials.
        let s8_password = S8Password::from("password").unwrap();
        // S802_1X network credentials.
        let ap_key = Credentials::S802_1X(s8_username, s8_password);

        // Access Point Configuration.
        let ap = AccessPoint {
            ssid: &ap_ssid,
            key: ap_key,
            channel: WifiChannel::Channel1,
            ssid_hidden: false,
            ip: Ipv4Addr::new(192, 168, 1, 1),
        };

        // hostname for access point.
        let hostname = HostName::from("admin").unwrap();

        // set the module state to unconnected.
        client.callbacks.state = WifiModuleState::Unconnected;

        let result = nb::block!(client.provisioning_mode(&ap, &hostname, false, 1));

        assert!(result.is_err());
        if let Err(error) = result {
            assert_eq!(error, StackError::InvalidParameters);
        } else {
            assert!(false);
        }
    }

    #[test]
    fn test_provisioning_invalid_state() {
        // test client
        let mut client = make_test_client();
        // ssid for access point configuration.
        let ap_ssid = Ssid::from("ssid").unwrap();
        // access point configuration.
        let ap = AccessPoint::open(&ap_ssid);
        // hostname for access point.
        let hostname = HostName::from("admin").unwrap();

        // set the module state to unconnected.
        client.callbacks.state = WifiModuleState::ConnectingToAp;

        let result = nb::block!(client.provisioning_mode(&ap, &hostname, false, 1));

        assert!(result.is_err());
        if let Err(err) = result {
            assert_eq!(err, StackError::InvalidState);
        } else {
            assert!(false);
        }
    }

    #[test]
    fn test_provisioning_timeout() {
        // test client
        let mut client = make_test_client();
        // ssid for access point configuration.
        let ap_ssid = Ssid::from("ssid").unwrap();
        // access point configuration.
        let ap = AccessPoint::open(&ap_ssid);
        // hostname for access point.
        let hostname = HostName::from("admin").unwrap();

        // set the module state to unconnected.
        client.callbacks.state = WifiModuleState::Unconnected;

        let result = nb::block!(client.provisioning_mode(&ap, &hostname, false, 1500)); // Time is in miliseconds

        assert!(result.is_err());
        if let Err(err) = result {
            assert_eq!(err, StackError::GeneralTimeout);
        } else {
            assert!(false);
        }
    }

    #[test]
    fn test_provisioning_failed() {
        // test client
        let mut client = make_test_client();
        // ssid for access point configuration.
        let ap_ssid = Ssid::from("ssid").unwrap();
        // access point configuration.
        let ap = AccessPoint::open(&ap_ssid);
        // hostname for access point.
        let hostname = HostName::from("admin").unwrap();
        // ssid received from provisioning.
        let test_ssid = Ssid::from("test_ssid").unwrap();
        // Wpa key passed to provisioning callback.
        // Should be empty for Open network.
        let test_key = WpaKey::new();
        // debug callback
        let mut my_debug = |callbacks: &mut SocketCallbacks| {
            callbacks.on_provisioning(test_ssid, test_key, AuthType::Open, false);
        };

        client.debug_callback = Some(&mut my_debug);
        // set the module state to unconnected.
        client.callbacks.state = WifiModuleState::Unconnected;

        let result = nb::block!(client.provisioning_mode(&ap, &hostname, false, 1));

        assert!(result.is_err());
        if let Err(error) = result {
            assert_eq!(error, StackError::WincWifiFail(Error::Failed));
        } else {
            assert!(false);
        }
    }

    #[test]
    fn test_stop_provisioning_success() {
        // test client
        let mut client = make_test_client();
        // set the module state to unconnected.
        client.callbacks.state = WifiModuleState::Provisioning;

        let result = client.stop_provisioning_mode();

        assert!(result.is_ok());
    }

    #[test]
    fn test_stop_provisioning_state_error() {
        // test client
        let mut client = make_test_client();
        // set the module state to unconnected.
        client.callbacks.state = WifiModuleState::Unconnected;

        let result = client.stop_provisioning_mode();

        assert!(result.is_err());
    }
}