This repository has been archived by the owner on Dec 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
lib.rs
447 lines (409 loc) · 15.7 KB
/
lib.rs
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
#![no_std]
#![feature(async_fn_in_trait)]
#![allow(incomplete_features)]
#![warn(missing_docs)]
#![doc = include_str!("../README.md")]
/// The read/write interface between an embedded framework/MCU combination and a LoRa chip
pub(crate) mod interface;
/// Parameters used across the lora-phy crate to support various use cases
pub mod mod_params;
/// Traits implemented externally or internally to support control of LoRa chips
pub mod mod_traits;
/// Specific implementation to support Semtech Sx126x chips
pub mod sx1261_2;
/// Specific implementation to support Semtech Sx127x chips
pub mod sx1276_7_8_9;
pub use embedded_hal_async::delay::DelayUs;
use interface::*;
use mod_params::*;
use mod_traits::*;
// Maximum value for symbol timeout across known LoRa chips
const MAX_LORA_SYMB_NUM_TIMEOUT: u32 = 248;
/// Provides the physical layer API to support LoRa chips
pub struct LoRa<RK, DLY>
where
RK: RadioKind,
DLY: DelayUs,
{
radio_kind: RK,
delay: DLY,
radio_mode: RadioMode,
enable_public_network: bool,
rx_continuous: bool,
polling_timeout_in_ms: Option<u32>,
cold_start: bool,
calibrate_image: bool,
}
impl<RK, DLY> LoRa<RK, DLY>
where
RK: RadioKind,
DLY: DelayUs,
{
/// Build and return a new instance of the LoRa physical layer API to control an initialized LoRa radio
pub async fn new(radio_kind: RK, enable_public_network: bool, delay: DLY) -> Result<Self, RadioError> {
let mut lora = Self {
radio_kind,
delay,
radio_mode: RadioMode::Sleep,
enable_public_network,
rx_continuous: false,
polling_timeout_in_ms: None,
cold_start: true,
calibrate_image: true,
};
lora.init().await?;
Ok(lora)
}
/// Create modulation parameters for a communication channel
pub fn create_modulation_params(
&mut self,
spreading_factor: SpreadingFactor,
bandwidth: Bandwidth,
coding_rate: CodingRate,
frequency_in_hz: u32,
) -> Result<ModulationParams, RadioError> {
self.radio_kind
.create_modulation_params(spreading_factor, bandwidth, coding_rate, frequency_in_hz)
}
/// Create packet parameters for a send operation on a communication channel
pub fn create_tx_packet_params(
&mut self,
preamble_length: u16,
implicit_header: bool,
crc_on: bool,
iq_inverted: bool,
modulation_params: &ModulationParams,
) -> Result<PacketParams, RadioError> {
self.radio_kind.create_packet_params(
preamble_length,
implicit_header,
0,
crc_on,
iq_inverted,
modulation_params,
)
}
/// Create packet parameters for a receive operation on a communication channel
pub fn create_rx_packet_params(
&mut self,
preamble_length: u16,
implicit_header: bool,
max_payload_length: u8,
crc_on: bool,
iq_inverted: bool,
modulation_params: &ModulationParams,
) -> Result<PacketParams, RadioError> {
self.radio_kind.create_packet_params(
preamble_length,
implicit_header,
max_payload_length,
crc_on,
iq_inverted,
modulation_params,
)
}
/// Initialize a Semtech chip as the radio for LoRa physical layer communications
pub async fn init(&mut self) -> Result<(), RadioError> {
self.cold_start = true;
self.radio_kind.reset(&mut self.delay).await?;
self.radio_kind.ensure_ready(self.radio_mode).await?;
self.radio_kind.set_standby().await?;
self.radio_mode = RadioMode::Standby;
self.rx_continuous = false;
self.do_cold_start().await
}
async fn do_cold_start(&mut self) -> Result<(), RadioError> {
self.radio_kind.init_rf_switch().await?;
self.radio_kind.set_lora_modem(self.enable_public_network).await?;
self.radio_kind.set_oscillator().await?;
self.radio_kind.set_regulator_mode().await?;
self.radio_kind.set_tx_rx_buffer_base_address(0, 0).await?;
self.radio_kind
.set_tx_power_and_ramp_time(0, None, false, false)
.await?;
self.radio_kind.set_irq_params(Some(self.radio_mode)).await?;
self.radio_kind.update_retention_list().await?;
self.cold_start = false;
self.calibrate_image = true;
Ok(())
}
/// Place the LoRa physical layer in low power mode, specifying cold or warm start (if the Semtech chip supports it)
pub async fn sleep(&mut self, warm_start_if_possible: bool) -> Result<(), RadioError> {
if self.radio_mode != RadioMode::Sleep {
self.radio_kind.ensure_ready(self.radio_mode).await?;
self.radio_kind
.set_sleep(warm_start_if_possible, &mut self.delay)
.await?;
if !warm_start_if_possible {
self.cold_start = true;
}
self.radio_mode = RadioMode::Sleep;
}
Ok(())
}
/// Prepare the Semtech chip for a send operation
pub async fn prepare_for_tx(
&mut self,
mdltn_params: &ModulationParams,
output_power: i32,
tx_boosted_if_possible: bool,
) -> Result<(), RadioError> {
self.rx_continuous = false;
self.prepare_modem(mdltn_params).await?;
self.radio_kind.set_modulation_params(mdltn_params).await?;
self.radio_kind
.set_tx_power_and_ramp_time(output_power, Some(mdltn_params), tx_boosted_if_possible, true)
.await
}
/// Execute a send operation
pub async fn tx(
&mut self,
mdltn_params: &ModulationParams,
tx_pkt_params: &mut PacketParams,
buffer: &[u8],
timeout_in_ms: u32,
) -> Result<(), RadioError> {
self.rx_continuous = false;
self.radio_kind.ensure_ready(self.radio_mode).await?;
if self.radio_mode != RadioMode::Standby {
self.radio_kind.set_standby().await?;
self.radio_mode = RadioMode::Standby;
}
tx_pkt_params.set_payload_length(buffer.len())?;
self.radio_kind.set_packet_params(tx_pkt_params).await?;
self.radio_kind.set_channel(mdltn_params.frequency_in_hz).await?;
self.radio_kind.set_payload(buffer).await?;
self.radio_mode = RadioMode::Transmit;
self.radio_kind.set_irq_params(Some(self.radio_mode)).await?;
self.radio_kind.do_tx(timeout_in_ms).await?;
match self
.radio_kind
.process_irq(
self.radio_mode,
self.rx_continuous,
TargetIrqState::Done,
&mut self.delay,
None,
None,
)
.await
{
Ok(TargetIrqState::Done) => {
self.radio_mode = RadioMode::Standby;
Ok(())
}
Err(err) => {
self.radio_kind.ensure_ready(self.radio_mode).await?;
self.radio_kind.set_standby().await?;
self.radio_mode = RadioMode::Standby;
Err(err)
}
Ok(_) => unreachable!(),
}
}
/// Prepare the Semtech chip for a receive operation (single shot, continuous, or duty cycled) and initiate the operation
#[allow(clippy::too_many_arguments)]
pub async fn prepare_for_rx(
&mut self,
mdltn_params: &ModulationParams,
rx_pkt_params: &PacketParams,
window_in_secs: Option<u8>, // None for Rx continuous
duty_cycle_params: Option<&DutyCycleParams>,
rx_boosted_if_supported: bool,
) -> Result<(), RadioError> {
let mut symbol_timeout: u32 = 0;
match window_in_secs {
Some(window) => {
let sf = u32::from(mdltn_params.spreading_factor);
let bw = u32::from(mdltn_params.bandwidth);
let symbols_per_sec = bw / (0x01u32 << sf); // symbol rate in symbols/sec = (BW in Hz) / (2 raised to the SF power)
let window_in_ms: u32 = (window as u32).checked_mul(1000).unwrap();
symbol_timeout = (window_in_ms - 200).checked_mul(symbols_per_sec).unwrap() / 1000; // leave a gap (subtract 200ms) to allow time to set up another window
if symbol_timeout > MAX_LORA_SYMB_NUM_TIMEOUT {
symbol_timeout = MAX_LORA_SYMB_NUM_TIMEOUT;
}
self.rx_continuous = false;
// provide a safety net polling timeout while allowing reception of a packet which starts within the window but exceeds the window size
self.polling_timeout_in_ms = Some(window_in_ms.checked_mul(5).unwrap());
}
None => {
self.rx_continuous = true;
self.polling_timeout_in_ms = None;
}
}
self.prepare_modem(mdltn_params).await?;
self.radio_kind.set_modulation_params(mdltn_params).await?;
self.radio_kind.set_packet_params(rx_pkt_params).await?;
self.radio_kind.set_channel(mdltn_params.frequency_in_hz).await?;
self.radio_mode = match duty_cycle_params {
Some(&_duty_cycle) => RadioMode::ReceiveDutyCycle,
None => RadioMode::Receive,
};
self.radio_kind.set_irq_params(Some(self.radio_mode)).await?;
self.radio_kind
.do_rx(
rx_pkt_params,
duty_cycle_params,
self.rx_continuous,
rx_boosted_if_supported,
symbol_timeout as u16,
)
.await
}
/// Obtain the results of a read operation
pub async fn rx(
&mut self,
rx_pkt_params: &PacketParams,
receiving_buffer: &mut [u8],
) -> Result<(u8, PacketStatus), RadioError> {
let IrqState::RxDone(len, status) = self.rx_until_state(rx_pkt_params, receiving_buffer, TargetIrqState::Done).await? else {
unreachable!();
};
Ok((len, status))
}
/// Obtain the results of a read operation
pub async fn rx_until_state(
&mut self,
rx_pkt_params: &PacketParams,
receiving_buffer: &mut [u8],
target_rx_state: TargetIrqState,
) -> Result<IrqState, RadioError> {
match self
.radio_kind
.process_irq(
self.radio_mode,
self.rx_continuous,
target_rx_state,
&mut self.delay,
self.polling_timeout_in_ms,
None,
)
.await
{
Ok(actual_state) => match actual_state {
TargetIrqState::PreambleReceived => Ok(IrqState::PreambleReceived),
TargetIrqState::Done => {
let received_len = self.radio_kind.get_rx_payload(rx_pkt_params, receiving_buffer).await?;
let rx_pkt_status = self.radio_kind.get_rx_packet_status().await?;
Ok(IrqState::RxDone(received_len, rx_pkt_status))
}
},
Err(err) => {
// if in rx continuous mode, allow the caller to determine whether to keep receiving
if !self.rx_continuous {
self.radio_kind.ensure_ready(self.radio_mode).await?;
self.radio_kind.set_standby().await?;
self.radio_mode = RadioMode::Standby;
}
Err(err)
}
}
}
/// Prepare the Semtech chip for a channel activity detection operation and initiate the operation
pub async fn prepare_for_cad(
&mut self,
mdltn_params: &ModulationParams,
rx_boosted_if_supported: bool,
) -> Result<(), RadioError> {
self.rx_continuous = false;
self.prepare_modem(mdltn_params).await?;
self.radio_kind.set_modulation_params(mdltn_params).await?;
self.radio_kind.set_channel(mdltn_params.frequency_in_hz).await?;
self.radio_mode = RadioMode::ChannelActivityDetection;
self.radio_kind.set_irq_params(Some(self.radio_mode)).await?;
self.radio_kind.do_cad(mdltn_params, rx_boosted_if_supported).await
}
/// Obtain the results of a channel activity detection operation
pub async fn cad(&mut self) -> Result<bool, RadioError> {
let mut cad_activity_detected = false;
match self
.radio_kind
.process_irq(
self.radio_mode,
self.rx_continuous,
TargetIrqState::Done,
&mut self.delay,
None,
Some(&mut cad_activity_detected),
)
.await
{
Ok(TargetIrqState::Done) => Ok(cad_activity_detected),
Err(err) => {
self.radio_kind.ensure_ready(self.radio_mode).await?;
self.radio_kind.set_standby().await?;
self.radio_mode = RadioMode::Standby;
Err(err)
}
Ok(_) => unreachable!(),
}
}
/// Place radio in continuous wave mode, generally for regulatory testing
///
/// SemTech app note AN1200.26 “Semtech LoRa FCC 15.247 Guidance” covers usage.
///
/// Presumes that init() is called before this function
pub async fn continuous_wave(
&mut self,
mdltn_params: &ModulationParams,
output_power: i32,
tx_boosted_if_possible: bool,
) -> Result<(), RadioError> {
self.rx_continuous = false;
self.prepare_modem(mdltn_params).await?;
let tx_pkt_params = self
.radio_kind
.create_packet_params(0, false, 16, false, false, mdltn_params)?;
self.radio_kind.set_packet_params(&tx_pkt_params).await?;
self.radio_kind.set_modulation_params(mdltn_params).await?;
self.radio_kind
.set_tx_power_and_ramp_time(output_power, Some(mdltn_params), tx_boosted_if_possible, true)
.await?;
self.rx_continuous = false;
self.radio_kind.ensure_ready(self.radio_mode).await?;
if self.radio_mode != RadioMode::Standby {
self.radio_kind.set_standby().await?;
self.radio_mode = RadioMode::Standby;
}
self.radio_kind.set_channel(mdltn_params.frequency_in_hz).await?;
self.radio_mode = RadioMode::Transmit;
self.radio_kind.set_irq_params(Some(self.radio_mode)).await?;
self.radio_kind.set_tx_continuous_wave_mode().await
}
async fn prepare_modem(&mut self, mdltn_params: &ModulationParams) -> Result<(), RadioError> {
self.radio_kind.ensure_ready(self.radio_mode).await?;
if self.radio_mode != RadioMode::Standby {
self.radio_kind.set_standby().await?;
self.radio_mode = RadioMode::Standby;
}
if self.cold_start {
self.do_cold_start().await?;
}
if self.calibrate_image {
self.radio_kind.calibrate_image(mdltn_params.frequency_in_hz).await?;
self.calibrate_image = false;
}
Ok(())
}
}
impl<RK, DLY> AsyncRng for LoRa<RK, DLY>
where
RK: RngRadio,
DLY: DelayUs,
{
async fn get_random_number(&mut self) -> Result<u32, RadioError> {
self.rx_continuous = false;
self.radio_kind.ensure_ready(self.radio_mode).await?;
if self.radio_mode != RadioMode::Standby {
self.radio_kind.set_standby().await?;
self.radio_mode = RadioMode::Standby;
}
if self.cold_start {
self.do_cold_start().await?;
}
let random_number = self.radio_kind.get_random_number().await?;
self.radio_kind.set_standby().await?;
self.radio_mode = RadioMode::Standby;
Ok(random_number)
}
}