summaryrefslogtreecommitdiff
path: root/nrf-softdevice/src/softdevice.rs
blob: caad633c343fbb40406e81a3911ca78fff4a7f50 (plain)
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
use core::marker::PhantomData;
use core::ptr;
use core::sync::atomic::{AtomicBool, Ordering};

use embassy_util::Forever;

use crate::{pac, raw, RawError, SocEvent};

unsafe extern "C" fn fault_handler(id: u32, pc: u32, info: u32) {
    match (id, info) {
        (raw::NRF_FAULT_ID_SD_ASSERT, _) => panic!(
            "Softdevice assertion failed: an assertion inside the softdevice's code has failed. Most common cause is disabling interrupts for too long. Make sure you're using nrf_softdevice::interrupt::free instead of cortex_m::interrupt::free, which disables non-softdevice interrupts only. PC={:x}",
            pc
        ),
        (raw::NRF_FAULT_ID_APP_MEMACC, 0) => panic!(
            "Softdevice memory access violation. Your program accessed RAM reserved to the softdevice. PC={:x}",
            pc
        ),
        (raw::NRF_FAULT_ID_APP_MEMACC, _) => panic!(
            "Softdevice memory access violation. Your program accessed registers for a peripheral reserved to the softdevice. PC={:x} PREGION={:?}",
            pc, info
        ),
        _ => panic!(
            "Softdevice unknown fault id={:?} pc={:x} info={:?}",
            id, pc, info
        ),
    }
}

/// Singleton instance of the enabled softdevice.
///
/// The `Softdevice` instance can be obtaind by enabling it with [`Softdevice::enable`]. Once
/// enabled, it can be used to establish Bluetooth connections with [`ble::central`] and [`ble::peripheral`].
///
/// Disabling the softdevice is not supported due to the complexity of a safe implementation. Consider resetting the CPU instead.
pub struct Softdevice {
    // Prevent Send, Sync
    _private: PhantomData<*mut ()>,
    #[cfg(feature = "ble-gatt")]
    #[allow(unused)]
    pub(crate) att_mtu: u16,
    #[cfg(feature = "ble-l2cap")]
    pub(crate) l2cap_rx_mps: u16,
}

/// Softdevice configuration.
///
/// Fields set to None will use a default configuration.
#[derive(Default)]
pub struct Config {
    pub clock: Option<raw::nrf_clock_lf_cfg_t>,
    pub conn_gap: Option<raw::ble_gap_conn_cfg_t>,
    pub conn_gattc: Option<raw::ble_gattc_conn_cfg_t>,
    pub conn_gatts: Option<raw::ble_gatts_conn_cfg_t>,
    pub conn_gatt: Option<raw::ble_gatt_conn_cfg_t>,
    #[cfg(feature = "ble-l2cap")]
    pub conn_l2cap: Option<raw::ble_l2cap_conn_cfg_t>,
    pub common_vs_uuid: Option<raw::ble_common_cfg_vs_uuid_t>,
    pub gap_role_count: Option<raw::ble_gap_cfg_role_count_t>,
    pub gap_device_name: Option<raw::ble_gap_cfg_device_name_t>,
    pub gap_ppcp_incl: Option<raw::ble_gap_cfg_ppcp_incl_cfg_t>,
    pub gap_car_incl: Option<raw::ble_gap_cfg_car_incl_cfg_t>,
    pub gatts_service_changed: Option<raw::ble_gatts_cfg_service_changed_t>,
    pub gatts_attr_tab_size: Option<raw::ble_gatts_cfg_attr_tab_size_t>,
}

const APP_CONN_CFG_TAG: u8 = 1;

fn get_app_ram_base() -> u32 {
    extern "C" {
        static mut __sdata: u32;
    }

    unsafe { &mut __sdata as *mut u32 as u32 }
}

fn cfg_set(id: u32, cfg: &raw::ble_cfg_t) {
    let app_ram_base = get_app_ram_base();
    let ret = unsafe { raw::sd_ble_cfg_set(id, cfg, app_ram_base) };
    match RawError::convert(ret) {
        Ok(()) => {}
        Err(RawError::NoMem) => {}
        Err(err) => panic!("sd_ble_cfg_set {:?} err {:?}", id, err),
    }
}

static ENABLED: AtomicBool = AtomicBool::new(false);
static SOFTDEVICE: Forever<Softdevice> = Forever::new();

impl Softdevice {
    /// Enable the softdevice.
    ///
    /// This function takes ownership of the softdevice-reserved peripherals to ensure application code doesn't attempt to use them after enabling.
    ///
    /// # Panics
    /// - Panics if the requested configuration requires more memory than reserved for the softdevice. In that case, you can give more memory to the softdevice by editing the RAM start address in `memory.x`. The required start address is logged prior to panic.
    /// - Panics if the requested configuration has too high memory requirements for the softdevice. The softdevice supports a maximum dynamic memory size of 64kb.
    /// - Panics if called multiple times. Must be called at most once.
    pub fn enable(config: &Config) -> &'static mut Softdevice {
        if ENABLED
            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
            .is_err()
        {
            panic!("nrf_softdevice::enable() called multiple times.")
        }

        let p_clock_lf_cfg = config.clock.as_ref().map(|x| x as _).unwrap_or(ptr::null());
        let ret = unsafe { raw::sd_softdevice_enable(p_clock_lf_cfg, Some(fault_handler)) };
        match RawError::convert(ret) {
            Ok(()) => {}
            Err(err) => panic!("sd_softdevice_enable err {:?}", err),
        }

        let app_ram_base = get_app_ram_base();

        // Set at least one GAP config so conn_cfg_tag 1 (APP_CONN_CFG_TAG) is usable.
        // If you set none, it seems the softdevice won't let you use it, requiring a conn_cfg_tag of 0 (raw::BLE_CONN_CFG_TAG_DEFAULT) instead.
        let val = config.conn_gap.unwrap_or(raw::ble_gap_conn_cfg_t {
            conn_count: raw::BLE_GAP_CONN_COUNT_DEFAULT as u8,
            event_length: raw::BLE_GAP_EVENT_LENGTH_DEFAULT as u16,
        });
        cfg_set(
            raw::BLE_CONN_CFGS_BLE_CONN_CFG_GAP,
            &raw::ble_cfg_t {
                conn_cfg: raw::ble_conn_cfg_t {
                    conn_cfg_tag: APP_CONN_CFG_TAG,
                    params: raw::ble_conn_cfg_t__bindgen_ty_1 { gap_conn_cfg: val },
                },
            },
        );

        if let Some(val) = config.conn_gatt {
            cfg_set(
                raw::BLE_CONN_CFGS_BLE_CONN_CFG_GATT,
                &raw::ble_cfg_t {
                    conn_cfg: raw::ble_conn_cfg_t {
                        conn_cfg_tag: APP_CONN_CFG_TAG,
                        params: raw::ble_conn_cfg_t__bindgen_ty_1 { gatt_conn_cfg: val },
                    },
                },
            );
        }

        if let Some(val) = config.conn_gattc {
            cfg_set(
                raw::BLE_CONN_CFGS_BLE_CONN_CFG_GATTC,
                &raw::ble_cfg_t {
                    conn_cfg: raw::ble_conn_cfg_t {
                        conn_cfg_tag: APP_CONN_CFG_TAG,
                        params: raw::ble_conn_cfg_t__bindgen_ty_1 { gattc_conn_cfg: val },
                    },
                },
            );
        }

        if let Some(val) = config.conn_gatts {
            cfg_set(
                raw::BLE_CONN_CFGS_BLE_CONN_CFG_GATTS,
                &raw::ble_cfg_t {
                    conn_cfg: raw::ble_conn_cfg_t {
                        conn_cfg_tag: APP_CONN_CFG_TAG,
                        params: raw::ble_conn_cfg_t__bindgen_ty_1 { gatts_conn_cfg: val },
                    },
                },
            );
        }

        #[cfg(feature = "ble-l2cap")]
        if let Some(val) = config.conn_l2cap {
            cfg_set(
                raw::BLE_CONN_CFGS_BLE_CONN_CFG_L2CAP,
                &raw::ble_cfg_t {
                    conn_cfg: raw::ble_conn_cfg_t {
                        conn_cfg_tag: APP_CONN_CFG_TAG,
                        params: raw::ble_conn_cfg_t__bindgen_ty_1 { l2cap_conn_cfg: val },
                    },
                },
            );
        }

        if let Some(val) = config.common_vs_uuid {
            cfg_set(
                raw::BLE_COMMON_CFGS_BLE_COMMON_CFG_VS_UUID,
                &raw::ble_cfg_t {
                    common_cfg: raw::ble_common_cfg_t { vs_uuid_cfg: val },
                },
            );
        }

        if let Some(val) = config.gap_role_count {
            cfg_set(
                raw::BLE_GAP_CFGS_BLE_GAP_CFG_ROLE_COUNT,
                &raw::ble_cfg_t {
                    gap_cfg: raw::ble_gap_cfg_t { role_count_cfg: val },
                },
            );
        }

        if let Some(val) = config.gap_device_name {
            cfg_set(
                raw::BLE_GAP_CFGS_BLE_GAP_CFG_DEVICE_NAME,
                &raw::ble_cfg_t {
                    gap_cfg: raw::ble_gap_cfg_t { device_name_cfg: val },
                },
            );
        }

        if let Some(val) = config.gap_ppcp_incl {
            cfg_set(
                raw::BLE_GAP_CFGS_BLE_GAP_CFG_PPCP_INCL_CONFIG,
                &raw::ble_cfg_t {
                    gap_cfg: raw::ble_gap_cfg_t { ppcp_include_cfg: val },
                },
            );
        }

        if let Some(val) = config.gap_car_incl {
            cfg_set(
                raw::BLE_GAP_CFGS_BLE_GAP_CFG_CAR_INCL_CONFIG,
                &raw::ble_cfg_t {
                    gap_cfg: raw::ble_gap_cfg_t { car_include_cfg: val },
                },
            );
        }
        if let Some(val) = config.gatts_service_changed {
            cfg_set(
                raw::BLE_GATTS_CFGS_BLE_GATTS_CFG_SERVICE_CHANGED,
                &raw::ble_cfg_t {
                    gatts_cfg: raw::ble_gatts_cfg_t { service_changed: val },
                },
            );
        }
        if let Some(val) = config.gatts_attr_tab_size {
            cfg_set(
                raw::BLE_GATTS_CFGS_BLE_GATTS_CFG_ATTR_TAB_SIZE,
                &raw::ble_cfg_t {
                    gatts_cfg: raw::ble_gatts_cfg_t { attr_tab_size: val },
                },
            );
        }

        let mut wanted_app_ram_base = app_ram_base;
        let ret = unsafe { raw::sd_ble_enable(&mut wanted_app_ram_base as _) };
        info!("softdevice RAM: {:?} bytes", wanted_app_ram_base - 0x20000000);
        match RawError::convert(ret) {
            Ok(()) => {}
            Err(RawError::NoMem) => {
                if wanted_app_ram_base <= app_ram_base {
                    panic!("selected configuration has too high RAM requirements.")
                } else {
                    panic!(
                        "too little RAM for softdevice. Change your app's RAM start address to {:x}",
                        wanted_app_ram_base
                    );
                }
            }
            Err(err) => panic!("sd_ble_enable err {:?}", err),
        }

        if wanted_app_ram_base < app_ram_base {
            warn!("You're giving more RAM to the softdevice than needed. You can change your app's RAM start address to {:x}", wanted_app_ram_base);
        }

        unsafe {
            #[cfg(any(feature = "nrf52805", feature = "nrf52810", feature = "nrf52811"))]
            pac::NVIC::unmask(pac::interrupt::SWI2);
            #[cfg(not(any(feature = "nrf52805", feature = "nrf52810", feature = "nrf52811")))]
            pac::NVIC::unmask(pac::interrupt::SWI2_EGU2);
        }

        #[cfg(feature = "ble-gatt")]
        let att_mtu = config
            .conn_gatt
            .map(|x| x.att_mtu)
            .unwrap_or(raw::BLE_GATT_ATT_MTU_DEFAULT as u16);

        #[cfg(feature = "ble-l2cap")]
        let l2cap_rx_mps = config
            .conn_l2cap
            .map(|x| x.rx_mps)
            .unwrap_or(raw::BLE_L2CAP_MPS_MIN as u16);

        SOFTDEVICE.put(Softdevice {
            _private: PhantomData,

            #[cfg(feature = "ble-gatt")]
            att_mtu,

            #[cfg(feature = "ble-l2cap")]
            l2cap_rx_mps,
        })
    }

    /// Return an instance to the softdevice without checking whether
    /// it is enabled or not. This is only safe if the softdevice is enabled
    /// (a call to [`enable`] has returned without error) and no `&mut` references
    /// to the softdevice are active
    pub unsafe fn steal() -> &'static Softdevice {
        SOFTDEVICE.steal()
    }

    /// Runs the softdevice event handling loop.
    ///
    /// It must be called in its own async task after enabling the softdevice
    /// and before doing any operation. Failure to doing so will cause async operations to never finish.
    pub async fn run(&self) -> ! {
        self.run_with_callback(|_| {}).await
    }

    /// Runs the softdevice event handling loop with a callback for [`SocEvent`]s.
    ///
    /// It must be called under the same conditions as [`Softdevice::run()`]. This
    /// version allows the application to provide a callback to receive SoC events
    /// from the softdevice (other than flash events which are handled by [`Flash`](crate::flash::Flash)).
    pub async fn run_with_callback<F: FnMut(SocEvent)>(&self, f: F) -> ! {
        crate::events::run(f).await
    }
}