rainmaker-components 0.1.0

Component abstractions for rainmaker
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
//! WiFi Provisioning component
//!
//! Provisioning is the process of providing WiFi credentials to a device without manually hardcoding credentials in firmware.
//! WiFi Provisioning is built upon [Protocomm] using endpoints tailored for connecting nearby WiFi networks using
//! companion phone apps.
//!
//! It is roughly based on the architecture of  WiFi provisioning component in ESP-IDF. More details can be found [here]
//!
//! It provides implementation for 2 transport methods(the initial communication between companion apps and the device):
//! - Over BLE
//! - Over SoftAP
//!
//! You can read more about each of the transports at: [WiFiProvMgrBle] and [WiFiProvMgrSoftAp]
//!
//! <b> Note: WiFi provisioning won't actually work for linux since WiFi component is WIP for linux. </b>
//!
//! Example
//! ```rust
//! let prov_config = WifiProvBleConfig {
//!     service_name: String::from("PROV_SERVICE"),
//!     ..Default::default()
//! };
//! let mut prov_mgr = WiFiProvMgrBle::new(
//!     wifi_arc_mutex.clone(),
//!     prov_config,
//!     nvs_partition,
//!     ProtocommSecurity::default(), // Will default to Sec0
//! )?;
//!
//!
//! rmaker.reg_user_mapping_ep(&mut prov_mgr);
//! prov_mgr.start()?;
//! ```
//! Provisioning will stop when `prov_mgr` is dropped.
//!
//! [Protocomm]: crate::protocomm::Protocomm
//! [here]: https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/provisioning/wifi_provisioning.html

use std::sync::mpsc::{self, Receiver, Sender};

use quick_protobuf::{MessageWrite, Writer};
use serde_json::json;
pub use uuid::Uuid;

mod base;
mod ble;
mod softap;

use crate::{
    error::Error,
    persistent_storage::{Nvs, NvsPartition},
    protocomm::{ProtocommCallbackType, ProtocommSecurity},
    utils::{wrap_in_arc_mutex, WrappedInArcMutex},
    wifi::{WifiApInfo, WifiClientConfig, WifiMgr},
};

pub use base::WiFiProvTransportTrait;

use ble::WiFiProvTransportBle;
pub use ble::WifiProvBleConfig;

pub use softap::WiFiProvSoftApConfig;
use softap::WiFiProvTransportSoftAp;

/// BLE transport for WiFi Provisioning.
///
/// Uses a GATT Service for provisioning purposes.
/// The UUID for this Service is the one provided in the config.
///
/// Each of the endpoint is a GATT Characteristic.
/// The UUID for the Characteristic is generated by masking 12th and 13th byte in Service UUID with increasing value for each endpoint registered.
///
/// Rest of the details are similar to BLE transport in [Protocomm]
///
/// <b> Note: Bluetooth needs to be turned on on Linux before running the program </b>
///
/// [Protocomm]: crate::protocomm::Protocomm
pub type WiFiProvMgrBle = WifiProvMgr<WiFiProvTransportBle>;

/// SoftAP transport for WiFi Provisioning.
///
/// It creates a WiFi access point and uses the Httpd transport provided by [Protocomm]
/// Each of the endpoint is a HTTP endpoint which can be interacted with using POST requests with necessary data.
///
/// Rest of the details are similar to SoftAP transport in [Protocomm]
///
/// <b> Note: For using SoftAp transport on linux, you'll need to allow opening port 80(or run program as sudo) and externally create a WiFi access point on linux. </b>
///
/// [Protocomm]: crate::protocomm::Protocomm
pub type WiFiProvMgrSoftAp = WifiProvMgr<WiFiProvTransportSoftAp>;

const WIFI_NAMESPACE: &str = "net80211";
const WIFI_SSID_KEY: &str = "sta.ssid";
const WIFI_PASS_KEY: &str = "sta.pswd";

// A struct for storing shared callback data between various callback functions
struct ProvisioningSharedData {
    wifi: WrappedInArcMutex<WifiMgr<'static>>,
    scan_results: Option<Vec<WifiApInfo>>,
    nvs_partition: NvsPartition,
    msg_sender: Sender<()>,
}

pub struct WifiProvMgr<T>
where
    T: WiFiProvTransportTrait,
{
    sec_ver: u8,
    pop: Option<String>,
    shared: WrappedInArcMutex<ProvisioningSharedData>,
    transport: T,
    msg_receiver: Receiver<()>,
}

impl WiFiProvMgrSoftAp {
    pub fn new(
        wifi: WrappedInArcMutex<WifiMgr<'static>>,
        config: WiFiProvSoftApConfig,
        nvs_partition: NvsPartition,
        sec: ProtocommSecurity,
    ) -> Result<WiFiProvMgrSoftAp, Error> {
        let (sec_ver, pop) = Self::get_sec_ver_and_pop(&sec);
        let transport = WiFiProvTransportSoftAp::new(config, sec, wifi.clone());
        Self::new_with_transport(wifi, nvs_partition, sec_ver, pop, transport)
    }
}

impl WiFiProvMgrBle {
    pub fn new(
        wifi: WrappedInArcMutex<WifiMgr<'static>>,
        config: WifiProvBleConfig,
        nvs_partition: NvsPartition,
        sec: ProtocommSecurity,
    ) -> Result<WiFiProvMgrBle, Error> {
        let (sec_ver, pop) = Self::get_sec_ver_and_pop(&sec);
        let transport = WiFiProvTransportBle::new(config, sec);
        Self::new_with_transport(wifi, nvs_partition, sec_ver, pop, transport)
    }
}

impl<T: WiFiProvTransportTrait> WifiProvMgr<T> {
    /// This function will block until node is not provisioned.
    /// It will return once first time WiFi connection has been established using provisioned credentials.
    pub fn wait_for_provisioning(&self) {
        self.msg_receiver.recv().unwrap()
    }

    /// Adding additional endpoints to the pre-existing WiFi provisioning endpoints.
    /// It is useful for an endpoint with application specific information and purpose.
    pub fn add_endpoint(&mut self, ep_name: &str, cb: ProtocommCallbackType) {
        self.transport.add_endpoint(ep_name, cb);
    }

    /// This starts the provisioning process.
    pub fn start(&mut self) -> Result<(), Error> {
        self.register_protocomm_endpoints();

        self.transport.start()?;
        let data = self.shared.lock().unwrap();
        let mut wifi = data.wifi.lock().unwrap();
        wifi.set_client_config(WifiClientConfig::default()).unwrap();

        // Start WiFi
        wifi.start().unwrap();

        Ok(())
    }

    /// Checkes if device is already provisioned.
    /// If provisioned, it returns the SSID and Password of provisioned WiFi network.
    pub fn is_provisioned(&self) -> Option<(String, String)> {
        let partition = self.shared.lock().unwrap().nvs_partition.clone();
        let nvs = Nvs::new(partition, WIFI_NAMESPACE).expect("Unable to open NVS partition");
        let mut buff = [0; 64];
        let ssid = nvs
            .get_string(WIFI_SSID_KEY, &mut buff)
            .expect("Unable to get SSID");
        let password = nvs
            .get_string(WIFI_PASS_KEY, &mut buff)
            .expect("Unable to get Password");

        if let (Some(ssid), Some(password)) = (ssid, password) {
            return Some((ssid, password));
        }
        None
    }

    fn new_with_transport(
        wifi: WrappedInArcMutex<WifiMgr<'static>>,
        nvs_partition: NvsPartition,
        sec_ver: u8,
        pop: Option<String>,
        transport: T,
    ) -> Result<WifiProvMgr<T>, Error> {
        let (sender, receiver) = mpsc::channel::<()>();

        let shared = wrap_in_arc_mutex(ProvisioningSharedData {
            nvs_partition,
            wifi,
            scan_results: None,
            msg_sender: sender,
        });

        Ok(WifiProvMgr {
            sec_ver,
            pop,
            shared,
            transport,
            msg_receiver: receiver,
        })
    }

    fn get_sec_ver_and_pop(sec: &ProtocommSecurity) -> (u8, Option<String>) {
        let sec_ver;
        let pop;

        match &sec {
            ProtocommSecurity::Sec0(_sec0) => {
                sec_ver = 0;
                pop = None;
            }
            ProtocommSecurity::Sec1(sec1) => {
                sec_ver = 1;
                pop = sec1.pop.clone();
            }
        }

        (sec_ver, pop)
    }

    fn get_version_info(&self) -> String {
        let mut cap = vec!["wifi_scan"];

        if self.pop.is_none() {
            cap.push("no_pop");
        }

        if self.sec_ver == 0 {
            cap.push("no_sec");
        }

        json! ({
            "prov": {
                "ver": "v1.1",
                "sec_ver": self.sec_ver,
                "cap": cap
            }
        })
        .to_string()
    }

    fn register_protocomm_endpoints(&mut self) {
        let version_info = self.get_version_info();
        let shared_1 = self.shared.clone();
        let shared_2 = self.shared.clone();

        self.transport.set_version_info("proto-ver", version_info);
        self.transport.set_security_ep("prov-session");
        self.add_endpoint(
            "prov-scan",
            Box::new(move |ep, data| ep_prov_scan::prov_scan_callbak(ep, data, shared_1.clone())),
        );
        self.add_endpoint(
            "prov-config",
            Box::new(move |ep, data| {
                ep_prov_config::prov_config_callback(ep, data, shared_2.clone())
            }),
        );
    }
}

mod ep_prov_scan {
    use super::*;

    use crate::proto::{
        constants::Status,
        wifi_prov::{
            wifi_constants::WifiAuthMode,
            wifi_scan::{mod_WiFiScanPayload::OneOfpayload, *},
        },
    };

    impl From<WifiApInfo> for WiFiScanResult {
        fn from(value: WifiApInfo) -> Self {
            let auth = match value.auth {
                crate::wifi::WifiAuthMode::None => WifiAuthMode::Open,
                crate::wifi::WifiAuthMode::WEP => WifiAuthMode::WEP,
                crate::wifi::WifiAuthMode::WPA => WifiAuthMode::WPA_PSK,
                crate::wifi::WifiAuthMode::WPA2Personal => WifiAuthMode::WPA2_PSK,
                crate::wifi::WifiAuthMode::WPAWPA2Personal => WifiAuthMode::WPA_WPA2_PSK,
                crate::wifi::WifiAuthMode::WPA2Enterprise => WifiAuthMode::WPA2_ENTERPRISE,
                crate::wifi::WifiAuthMode::WPA3Personal => WifiAuthMode::WPA3_PSK,
                crate::wifi::WifiAuthMode::WPA2WPA3Personal => WifiAuthMode::WPA2_WPA3_PSK,
                _ => panic!("Unknown WiFi auth type"),
            };

            Self {
                ssid: value.ssid.into(),
                channel: value.channel as u32,
                bssid: value.bssid,
                rssi: value.signal_strength as i32,
                auth,
            }
        }
    }

    #[inline(always)]
    pub fn prov_scan_callbak(
        _ep: &str,
        inp: &[u8],
        shared: WrappedInArcMutex<ProvisioningSharedData>,
    ) -> Vec<u8> {
        let mut out_payload: Vec<u8> = Default::default();
        let mut writer = Writer::new(&mut out_payload);
        let mut resp = WiFiScanPayload::default();

        let inp_data = match WiFiScanPayload::try_from(inp) {
            Ok(payload) => payload,
            Err(_) => {
                resp.status = Status::InvalidProto;
                resp.write_message(&mut writer).unwrap();
                return out_payload;
            }
        };

        let resp_msg;
        let resp_payload = match inp_data.payload {
            OneOfpayload::cmd_scan_start(cmd_scan_start) => {
                resp_msg = WiFiScanMsgType::TypeRespScanStart;
                handle_scan_start(cmd_scan_start, shared)
            }
            OneOfpayload::cmd_scan_status(cmd_scan_status) => {
                resp_msg = WiFiScanMsgType::TypeRespScanStatus;
                handle_scan_status(cmd_scan_status, shared)
            }
            OneOfpayload::cmd_scan_result(cmd_scan_result) => {
                resp_msg = WiFiScanMsgType::TypeRespScanResult;
                handle_scan_result(cmd_scan_result, shared)
            }
            other => {
                log::error!("Invalid payload type {:?}", other);
                return vec![];
            }
        };

        resp.status = Status::Success;
        resp.msg = resp_msg;
        resp.payload = resp_payload;

        if resp.write_message(&mut writer).is_err() {
            log::error!("Failed to write message");
            return vec![];
        };

        out_payload
    }

    fn handle_scan_start(
        _cmd: CmdScanStart,
        _shared: WrappedInArcMutex<ProvisioningSharedData>,
    ) -> OneOfpayload {
        let resp = RespScanStart::default();
        OneOfpayload::resp_scan_start(resp)
    }

    fn handle_scan_status(
        _cmd: CmdScanStatus,
        shared: WrappedInArcMutex<ProvisioningSharedData>,
    ) -> OneOfpayload {
        let mut resp = RespScanStatus::default();

        let mut data = shared.lock().unwrap();

        let networks = data.wifi.lock().unwrap().scan().unwrap();

        resp.scan_finished = true;
        resp.result_count = networks.len() as u32;
        log::info!("Found {} WiFi network(s)", networks.len());

        data.scan_results = Some(networks);

        OneOfpayload::resp_scan_status(resp)
    }

    fn handle_scan_result(
        cmd: CmdScanResult,
        shared: WrappedInArcMutex<ProvisioningSharedData>,
    ) -> OneOfpayload {
        log::info!("Sending WiFi scan results");

        let mut resp = RespScanResult::default();

        let data = shared.lock().unwrap();
        let networks = data
            .scan_results
            .as_ref()
            .expect("WiFi scan results not found");

        let start_index = cmd.start_index as usize;
        let count = cmd.count as usize;
        let end_index = start_index + count;

        let entries = networks
            .clone()
            .drain(start_index..end_index)
            .map(|x| x.into())
            .collect();

        resp.entries = entries;
        OneOfpayload::resp_scan_result(resp)
    }
}

mod ep_prov_config {
    use mod_RespGetStatus::OneOfstate;
    use mod_WiFiConfigPayload::OneOfpayload;
    use quick_protobuf::{MessageWrite, Writer};

    use super::*;
    use crate::{
        proto::wifi_prov::{
            constants::*,
            wifi_config::*,
            wifi_constants::{WifiConnectFailedReason, WifiConnectedState, WifiStationState},
        },
        wifi::WifiClientConfig,
    };

    use super::ProvisioningSharedData;

    #[inline(always)]
    pub fn prov_config_callback(
        _ep: &str,
        inp: &[u8],
        shared: WrappedInArcMutex<ProvisioningSharedData>,
    ) -> Vec<u8> {
        let mut resp = WiFiConfigPayload::default();
        let mut out_vec = Vec::<u8>::new();
        let mut writer = Writer::new(&mut out_vec);

        let inp_payload = WiFiConfigPayload::try_from(inp).unwrap();

        let resp_payload = match inp_payload.payload {
            mod_WiFiConfigPayload::OneOfpayload::cmd_get_status(cmd_get_status) => {
                resp.msg = WiFiConfigMsgType::TypeRespGetStatus;
                handle_get_status(cmd_get_status, shared)
            }
            mod_WiFiConfigPayload::OneOfpayload::cmd_set_config(cmd_set_config) => {
                resp.msg = WiFiConfigMsgType::TypeRespSetConfig;
                handle_set_config(cmd_set_config, shared)
            }
            mod_WiFiConfigPayload::OneOfpayload::cmd_apply_config(cmd_apply_config) => {
                resp.msg = WiFiConfigMsgType::TypeRespApplyConfig;
                handle_apply_config(cmd_apply_config, shared)
            }
            _ => unreachable!(),
        };

        resp.payload = resp_payload;

        if resp.write_message(&mut writer).is_err() {
            log::error!("Failed to write wifi_config response");
            return vec![];
        };

        out_vec
    }

    fn handle_set_config(
        cmd: CmdSetConfig,
        shared: WrappedInArcMutex<ProvisioningSharedData>,
    ) -> OneOfpayload {
        let mut resp = RespSetConfig::default();

        let ssid = String::from_utf8(cmd.ssid).expect("Failed to decode WiFi SSID");
        let password = String::from_utf8(cmd.passphrase).expect("Failed to decode WiFi passphrase");
        let bssid = cmd.bssid;
        let channel = cmd.channel;

        log::info!("Received SSID={} PASSWORD={}", ssid, password);

        let wifi_config = WifiClientConfig {
            ssid,
            password,
            bssid,
            channel: channel as u8,
            ..Default::default()
        };

        // SSID and Password are saved after connection so as to deal with incorrect password

        let data = shared.lock().unwrap();
        data.wifi
            .lock()
            .unwrap()
            .set_client_config(wifi_config)
            .unwrap();

        resp.status = Status::Success;

        OneOfpayload::resp_set_config(resp)
    }

    fn handle_apply_config(
        _cmd: CmdApplyConfig,
        shared: WrappedInArcMutex<ProvisioningSharedData>,
    ) -> OneOfpayload {
        log::info!("Connecting to WiFi");
        let mut resp = RespApplyConfig::default();

        let data = shared.lock().unwrap();
        let mut wifi = data.wifi.lock().unwrap();

        if wifi.connect().is_err() {
            log::error!("Failed connecting to provided WiFi network");
        } else {
            let (client_config, _) = wifi.get_wifi_config();
            if let Some(config) = client_config {
                let ssid = config.ssid;
                let password = config.password;
                let nvs_partition = data.nvs_partition.clone();
                let nvs = Nvs::new(nvs_partition, WIFI_NAMESPACE);
                match nvs {
                    Err(_) => log::error!("Failed to open nvs for saving WiFi credentials"),
                    Ok(mut nvs) => {
                        nvs.set_str(WIFI_SSID_KEY, &ssid)
                            .expect("Failed to save SSID");
                        nvs.set_str(WIFI_PASS_KEY, &password)
                            .expect("Failed to save Password");
                    }
                }
            }
        }
        resp.status = Status::Success;

        OneOfpayload::resp_apply_config(resp)
    }

    fn handle_get_status(
        _cmd: CmdGetStatus,
        shared: WrappedInArcMutex<ProvisioningSharedData>,
    ) -> OneOfpayload {
        let mut resp = RespGetStatus::default();

        let data = shared.lock().unwrap();

        // TODO: send actual data
        let wifi = data.wifi.lock().unwrap();
        let ip_addr = wifi.get_ip_addr();

        resp.status = Status::Success;
        if wifi.is_connected() {
            resp.sta_state = WifiStationState::Connected;
            resp.state = OneOfstate::connected(WifiConnectedState {
                ip4_addr: ip_addr.to_string(),
                ..Default::default()
            });
        } else {
            resp.sta_state = WifiStationState::ConnectionFailed;
            resp.state = OneOfstate::fail_reason(WifiConnectFailedReason::AuthError);
        }

        data.msg_sender.send(()).unwrap();

        OneOfpayload::resp_get_status(resp)
    }
}